From 2aed432b4b1e200b0cfa08c1681073c8136418f1 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Mon, 28 Dec 2020 12:58:06 -0800 Subject: [PATCH] Add braces to C++ single-line loops and conditionals (NFC) (#2973) This makes code easier to read and more consistent between C++ and Java. Also update clang-format settings to always add a line break (even if no braces are used). --- .clang-format | 6 +- .../src/main/native/cpp/main.cpp | 20 +- .../native/cpp/cameraserver/CameraServer.cpp | 100 ++-- .../main/native/cpp/vision/VisionRunner.cpp | 4 +- .../include/cameraserver/CameraServer.inc | 3 +- cameraserver/src/test/native/cpp/main.cpp | 4 +- cscore/examples/enum_usb/enum_usb.cpp | 7 +- cscore/examples/settings/settings.cpp | 21 +- cscore/examples/usbstream/usbstream.cpp | 3 +- cscore/examples/usbviewer/usbviewer.cpp | 8 +- cscore/src/dev/native/cpp/main.cpp | 4 +- cscore/src/main/native/cpp/CvSinkImpl.cpp | 20 +- cscore/src/main/native/cpp/CvSourceImpl.cpp | 9 +- cscore/src/main/native/cpp/Frame.cpp | 184 +++++-- cscore/src/main/native/cpp/Frame.h | 84 ++- cscore/src/main/native/cpp/HttpCameraImpl.cpp | 125 +++-- cscore/src/main/native/cpp/Instance.cpp | 19 +- cscore/src/main/native/cpp/Instance.h | 4 +- cscore/src/main/native/cpp/JpegUtil.cpp | 87 +++- .../src/main/native/cpp/MjpegServerImpl.cpp | 130 +++-- cscore/src/main/native/cpp/Notifier.cpp | 80 ++- .../src/main/native/cpp/PropertyContainer.cpp | 72 ++- .../src/main/native/cpp/PropertyContainer.h | 8 +- cscore/src/main/native/cpp/PropertyImpl.cpp | 22 +- cscore/src/main/native/cpp/RawSinkImpl.cpp | 16 +- cscore/src/main/native/cpp/SinkImpl.cpp | 59 ++- cscore/src/main/native/cpp/SourceImpl.cpp | 82 ++- cscore/src/main/native/cpp/Telemetry.cpp | 43 +- .../main/native/cpp/UnlimitedHandleResource.h | 31 +- .../main/native/cpp/UsbCameraImplCommon.cpp | 26 +- cscore/src/main/native/cpp/cscore_c.cpp | 86 ++- cscore/src/main/native/cpp/cscore_cpp.cpp | 99 +++- cscore/src/main/native/cpp/cscore_oo.cpp | 18 +- .../main/native/cpp/jni/CameraServerJNI.cpp | 172 ++++-- cscore/src/main/native/include/cscore_cpp.h | 5 +- cscore/src/main/native/include/cscore_oo.inl | 18 +- .../src/main/native/include/cscore_raw_cv.h | 20 +- .../src/main/native/linux/NetworkListener.cpp | 28 +- cscore/src/main/native/linux/NetworkUtil.cpp | 16 +- .../src/main/native/linux/UsbCameraBuffer.h | 4 +- .../src/main/native/linux/UsbCameraImpl.cpp | 318 +++++++++--- .../main/native/linux/UsbCameraProperty.cpp | 53 +- cscore/src/main/native/linux/UsbUtil.cpp | 18 +- .../src/main/native/windows/COMCreators.cpp | 11 +- .../main/native/windows/NetworkListener.cpp | 4 +- .../src/main/native/windows/NetworkUtil.cpp | 4 +- .../src/main/native/windows/UsbCameraImpl.cpp | 61 ++- .../main/native/windows/UsbCameraProperty.cpp | 18 +- .../native/windows/WindowsMessagePump.cpp | 3 +- .../app/native/cpp/NetworkTablesSettings.cpp | 11 +- glass/src/app/native/cpp/main.cpp | 14 +- glass/src/lib/native/cpp/Context.cpp | 81 ++- glass/src/lib/native/cpp/DataSource.cpp | 32 +- glass/src/lib/native/cpp/MainMenuBar.cpp | 16 +- glass/src/lib/native/cpp/Model.cpp | 4 +- glass/src/lib/native/cpp/Window.cpp | 32 +- glass/src/lib/native/cpp/WindowManager.cpp | 12 +- .../lib/native/cpp/hardware/Accelerometer.cpp | 4 +- .../lib/native/cpp/hardware/AnalogInput.cpp | 15 +- .../lib/native/cpp/hardware/AnalogOutput.cpp | 12 +- glass/src/lib/native/cpp/hardware/DIO.cpp | 16 +- glass/src/lib/native/cpp/hardware/Encoder.cpp | 11 +- glass/src/lib/native/cpp/hardware/Gyro.cpp | 3 +- .../lib/native/cpp/hardware/LEDDisplay.cpp | 22 +- glass/src/lib/native/cpp/hardware/PCM.cpp | 23 +- glass/src/lib/native/cpp/hardware/PDP.cpp | 10 +- glass/src/lib/native/cpp/hardware/PWM.cpp | 12 +- glass/src/lib/native/cpp/hardware/Relay.cpp | 29 +- .../native/cpp/hardware/SpeedController.cpp | 8 +- .../lib/native/cpp/other/CommandScheduler.cpp | 4 +- .../lib/native/cpp/other/CommandSelector.cpp | 8 +- glass/src/lib/native/cpp/other/DeviceTree.cpp | 33 +- glass/src/lib/native/cpp/other/FMS.cpp | 31 +- glass/src/lib/native/cpp/other/Field2D.cpp | 70 ++- .../lib/native/cpp/other/PIDController.cpp | 4 +- glass/src/lib/native/cpp/other/Plot.cpp | 233 ++++++--- .../lib/native/cpp/other/StringChooser.cpp | 4 +- .../native/cpp/support/ExtraGuiWidgets.cpp | 28 +- .../lib/native/cpp/support/IniSaverBase.cpp | 4 +- .../lib/native/cpp/support/IniSaverInfo.cpp | 20 +- glass/src/lib/native/include/glass/Context.h | 4 +- .../src/lib/native/include/glass/Provider.inc | 18 +- .../native/include/glass/support/IniSaver.inl | 3 +- .../include/glass/support/IniSaverVector.inl | 6 +- .../libnt/native/cpp/NTCommandScheduler.cpp | 12 +- .../libnt/native/cpp/NTCommandSelector.cpp | 6 +- glass/src/libnt/native/cpp/NTField2D.cpp | 52 +- glass/src/libnt/native/cpp/NTGyro.cpp | 6 +- .../src/libnt/native/cpp/NTPIDController.cpp | 15 +- .../libnt/native/cpp/NTSpeedController.cpp | 6 +- glass/src/libnt/native/cpp/NTSubsystem.cpp | 6 +- glass/src/libnt/native/cpp/NetworkTables.cpp | 144 +++-- .../native/cpp/NetworkTablesProvider.cpp | 46 +- hal/src/main/native/athena/Accelerometer.cpp | 12 +- .../main/native/athena/AnalogAccumulator.cpp | 3 +- hal/src/main/native/athena/AnalogGyro.cpp | 47 +- hal/src/main/native/athena/AnalogInput.cpp | 19 +- hal/src/main/native/athena/AnalogInternal.cpp | 19 +- hal/src/main/native/athena/AnalogOutput.cpp | 12 +- hal/src/main/native/athena/Counter.cpp | 5 +- hal/src/main/native/athena/DIO.cpp | 42 +- hal/src/main/native/athena/DMA.cpp | 11 +- .../main/native/athena/DigitalInternal.cpp | 27 +- hal/src/main/native/athena/DigitalInternal.h | 12 +- hal/src/main/native/athena/Encoder.cpp | 24 +- .../main/native/athena/FRCDriverStation.cpp | 31 +- hal/src/main/native/athena/HAL.cpp | 44 +- hal/src/main/native/athena/HALInitializer.cpp | 4 +- hal/src/main/native/athena/HALInitializer.h | 4 +- hal/src/main/native/athena/I2C.cpp | 12 +- hal/src/main/native/athena/Interrupts.cpp | 10 +- hal/src/main/native/athena/Notifier.cpp | 48 +- hal/src/main/native/athena/PDP.cpp | 12 +- hal/src/main/native/athena/PWM.cpp | 35 +- hal/src/main/native/athena/Ports.cpp | 80 ++- hal/src/main/native/athena/Relay.cpp | 15 +- hal/src/main/native/athena/SPI.cpp | 48 +- hal/src/main/native/athena/SerialPort.cpp | 4 +- hal/src/main/native/athena/SimDevice.cpp | 4 +- hal/src/main/native/athena/Solenoid.cpp | 24 +- hal/src/main/native/athena/Threads.cpp | 5 +- .../main/native/athena/cpp/SerialHelper.cpp | 33 +- .../athena/mockdata/AddressableLEDData.cpp | 4 +- .../native/athena/mockdata/AnalogInData.cpp | 4 +- .../athena/mockdata/AnalogTriggerData.cpp | 4 +- .../main/native/athena/mockdata/DIOData.cpp | 4 +- .../native/athena/mockdata/DigitalPWMData.cpp | 4 +- .../native/athena/mockdata/DutyCycleData.cpp | 12 +- .../native/athena/mockdata/EncoderData.cpp | 24 +- .../main/native/athena/mockdata/MockHooks.cpp | 8 +- .../native/athena/mockdata/NotifierData.cpp | 8 +- .../main/native/athena/mockdata/PCMData.cpp | 4 +- .../main/native/athena/mockdata/PDPData.cpp | 4 +- .../native/athena/mockdata/SimDeviceData.cpp | 12 +- hal/src/main/native/cpp/Main.cpp | 12 +- .../native/cpp/handles/HandlesInternal.cpp | 8 +- hal/src/main/native/cpp/jni/CANAPIJNI.cpp | 24 +- hal/src/main/native/cpp/jni/CANJNI.cpp | 8 +- hal/src/main/native/cpp/jni/HALUtil.cpp | 45 +- hal/src/main/native/cpp/jni/HALUtil.h | 16 +- hal/src/main/native/cpp/jni/InterruptJNI.cpp | 36 +- hal/src/main/native/cpp/jni/SPIJNI.cpp | 4 +- hal/src/main/native/cpp/jni/SimDeviceJNI.cpp | 20 +- .../jni/simulation/BufferCallbackStore.cpp | 8 +- .../cpp/jni/simulation/CallbackStore.cpp | 16 +- .../simulation/ConstBufferCallbackStore.cpp | 8 +- .../cpp/jni/simulation/SimDeviceDataJNI.cpp | 48 +- .../cpp/jni/simulation/SimulatorJNI.cpp | 58 ++- .../SpiReadAutoReceiveBufferCallbackStore.cpp | 4 +- hal/src/main/native/include/hal/SimDevice.h | 12 +- .../main/native/include/hal/cpp/UnsafeDIO.h | 4 +- .../hal/handles/DigitalHandleResource.h | 4 +- .../include/hal/handles/HandlesInternal.h | 20 +- .../handles/IndexedClassedHandleResource.h | 4 +- .../hal/handles/IndexedHandleResource.h | 4 +- .../handles/LimitedClassedHandleResource.h | 4 +- .../hal/handles/LimitedHandleResource.h | 4 +- .../hal/handles/UnlimitedHandleResource.h | 10 +- .../hal/simulation/SimCallbackRegistry.h | 19 +- .../include/hal/simulation/SimDataValue.h | 7 +- hal/src/main/native/sim/Accelerometer.cpp | 12 +- hal/src/main/native/sim/AddressableLED.cpp | 4 +- hal/src/main/native/sim/AnalogAccumulator.cpp | 4 +- hal/src/main/native/sim/AnalogGyro.cpp | 7 +- hal/src/main/native/sim/AnalogInput.cpp | 19 +- hal/src/main/native/sim/AnalogOutput.cpp | 7 +- hal/src/main/native/sim/AnalogTrigger.cpp | 12 +- hal/src/main/native/sim/DIO.cpp | 47 +- hal/src/main/native/sim/DMA.cpp | 8 +- hal/src/main/native/sim/DigitalInternal.cpp | 4 +- hal/src/main/native/sim/DriverStation.cpp | 43 +- hal/src/main/native/sim/DutyCycle.cpp | 8 +- hal/src/main/native/sim/Encoder.cpp | 8 +- hal/src/main/native/sim/Extensions.cpp | 14 +- hal/src/main/native/sim/HAL.cpp | 51 +- hal/src/main/native/sim/HALInitializer.cpp | 4 +- hal/src/main/native/sim/HALInitializer.h | 4 +- hal/src/main/native/sim/I2C.cpp | 4 +- hal/src/main/native/sim/Interrupts.cpp | 144 +++-- hal/src/main/native/sim/MockHooks.cpp | 52 +- hal/src/main/native/sim/Notifier.cpp | 47 +- hal/src/main/native/sim/PDP.cpp | 4 +- hal/src/main/native/sim/PWM.cpp | 35 +- hal/src/main/native/sim/Ports.cpp | 80 ++- hal/src/main/native/sim/Power.cpp | 8 +- hal/src/main/native/sim/Relay.cpp | 30 +- hal/src/main/native/sim/SPI.cpp | 8 +- hal/src/main/native/sim/SerialPort.cpp | 4 +- hal/src/main/native/sim/Solenoid.cpp | 4 +- .../sim/mockdata/AddressableLEDData.cpp | 7 +- .../native/sim/mockdata/AnalogTriggerData.cpp | 3 +- .../native/sim/mockdata/CanDataInternal.cpp | 4 +- hal/src/main/native/sim/mockdata/DIOData.cpp | 4 +- .../native/sim/mockdata/DigitalPWMData.cpp | 4 +- .../native/sim/mockdata/DriverStationData.cpp | 101 +++- .../native/sim/mockdata/DutyCycleData.cpp | 3 +- .../main/native/sim/mockdata/EncoderData.cpp | 7 +- hal/src/main/native/sim/mockdata/I2CData.cpp | 4 +- hal/src/main/native/sim/mockdata/PCMData.cpp | 4 +- hal/src/main/native/sim/mockdata/PDPData.cpp | 4 +- hal/src/main/native/sim/mockdata/PWMData.cpp | 4 +- .../main/native/sim/mockdata/RelayData.cpp | 4 +- .../main/native/sim/mockdata/RoboRioData.cpp | 4 +- hal/src/main/native/sim/mockdata/SPIData.cpp | 4 +- .../native/sim/mockdata/SimDeviceData.cpp | 156 ++++-- .../sim/mockdata/SimDeviceDataInternal.h | 32 +- myRobot/src/main/native/cpp/MyRobot.cpp | 4 +- ntcore/manualTests/native/client.cpp | 3 +- ntcore/src/main/native/cpp/CallbackManager.h | 94 +++- .../main/native/cpp/ConnectionNotifier.cpp | 4 +- ntcore/src/main/native/cpp/Dispatcher.cpp | 154 ++++-- ntcore/src/main/native/cpp/DsClient.cpp | 53 +- ntcore/src/main/native/cpp/EntryNotifier.cpp | 49 +- ntcore/src/main/native/cpp/InstanceImpl.cpp | 28 +- ntcore/src/main/native/cpp/LoggerImpl.cpp | 24 +- ntcore/src/main/native/cpp/Message.cpp | 152 ++++-- .../src/main/native/cpp/NetworkConnection.cpp | 102 +++- ntcore/src/main/native/cpp/RpcServer.cpp | 8 +- ntcore/src/main/native/cpp/SequenceNumber.cpp | 14 +- ntcore/src/main/native/cpp/SequenceNumber.h | 4 +- ntcore/src/main/native/cpp/Storage.cpp | 345 ++++++++---- ntcore/src/main/native/cpp/Storage_load.cpp | 89 +++- ntcore/src/main/native/cpp/Storage_save.cpp | 48 +- ntcore/src/main/native/cpp/Value.cpp | 35 +- ntcore/src/main/native/cpp/WireDecoder.cpp | 84 ++- ntcore/src/main/native/cpp/WireDecoder.h | 16 +- ntcore/src/main/native/cpp/WireEncoder.cpp | 62 ++- .../main/native/cpp/jni/NetworkTablesJNI.cpp | 150 ++++-- .../native/cpp/networktables/NetworkTable.cpp | 139 +++-- .../networktables/NetworkTableInstance.cpp | 10 +- ntcore/src/main/native/cpp/ntcore_c.cpp | 254 ++++++--- ntcore/src/main/native/cpp/ntcore_cpp.cpp | 491 +++++++++++++----- .../networktables/NetworkTableEntry.inl | 37 +- .../networktables/NetworkTableInstance.inl | 31 +- .../native/include/networktables/RpcCall.inl | 3 +- .../native/cpp/ConnectionListenerTest.cpp | 3 +- .../src/test/native/cpp/EntryListenerTest.cpp | 8 +- ntcore/src/test/native/cpp/MessageMatcher.cpp | 4 +- ntcore/src/test/native/cpp/StorageTest.cpp | 18 +- ntcore/src/test/native/cpp/TestPrinters.h | 8 +- .../src/test/native/cpp/WireDecoderTest.cpp | 12 +- .../src/test/native/cpp/WireEncoderTest.cpp | 28 +- .../src/clockTest/cpp/clockTest.cpp | 12 +- .../src/drive_motor/cpp/drive_motor.cpp | 7 +- .../frc_gazebo_plugins/src/gyro/cpp/gyro.cpp | 9 +- .../pneumatic_piston/cpp/pneumatic_piston.cpp | 3 +- .../src/main/native/cpp/DSCommPacket.cpp | 28 +- .../src/main/native/cpp/main.cpp | 4 +- .../src/test/native/cpp/DSCommPacketTest.cpp | 3 +- .../src/main/native/cpp/GazeboEncoder.cpp | 6 +- .../src/main/native/cpp/GazeboPCM.cpp | 6 +- .../src/main/native/cpp/GazeboPWM.cpp | 6 +- .../src/main/native/cpp/AddressableLEDGui.cpp | 16 +- .../src/main/native/cpp/AnalogInputSimGui.cpp | 4 +- .../src/main/native/cpp/DIOSimGui.cpp | 10 +- .../src/main/native/cpp/DriverStationGui.cpp | 352 +++++++++---- .../src/main/native/cpp/EncoderSimGui.cpp | 35 +- .../src/main/native/cpp/HALProvider.cpp | 35 +- .../src/main/native/cpp/Mechanism2D.cpp | 26 +- .../src/main/native/cpp/PCMSimGui.cpp | 10 +- .../src/main/native/cpp/PDPSimGui.cpp | 7 +- .../src/main/native/cpp/PWMSimGui.cpp | 7 +- .../src/main/native/cpp/RelaySimGui.cpp | 3 +- .../src/main/native/cpp/SimDeviceGui.cpp | 8 +- .../src/main/native/cpp/TimingGui.cpp | 18 +- .../halsim_gui/src/main/native/cpp/main.cpp | 4 +- .../src/main/native/include/HALDataSource.h | 3 +- .../src/main/native/cpp/WSHalProviders.cpp | 4 +- .../src/main/native/cpp/WSProvider_Analog.cpp | 12 +- .../src/main/native/cpp/WSProvider_DIO.cpp | 8 +- .../native/cpp/WSProvider_DriverStation.cpp | 8 +- .../main/native/cpp/WSProvider_Encoder.cpp | 8 +- .../main/native/cpp/WSProvider_Joystick.cpp | 12 +- .../src/main/native/cpp/WSProvider_PWM.cpp | 8 +- .../src/main/native/cpp/WSProvider_Relay.cpp | 8 +- .../main/native/cpp/WSProvider_RoboRIO.cpp | 8 +- .../main/native/cpp/WSProvider_SimDevice.cpp | 26 +- .../src/main/native/cpp/WSProvider_dPWM.cpp | 4 +- .../main/native/cpp/HALSimHttpConnection.cpp | 4 +- .../src/main/native/cpp/HALSimWeb.cpp | 4 +- .../test/native/cpp/WebServerClientTest.cpp | 4 +- wpigui/src/main/native/cpp/wpigui.cpp | 147 ++++-- .../native/directx11/wpigui_directx11.cpp | 19 +- wpigui/src/main/native/include/wpigui.h | 14 +- .../main/native/opengl3/wpigui_opengl3.cpp | 16 +- .../main/native/cpp/frc2/command/Command.cpp | 24 +- .../cpp/frc2/command/CommandScheduler.cpp | 20 +- .../native/cpp/frc2/command/CommandState.cpp | 4 +- .../cpp/frc2/command/ConditionalCommand.cpp | 8 +- .../cpp/frc2/command/FunctionalCommand.cpp | 16 +- .../cpp/frc2/command/InstantCommand.cpp | 8 +- .../frc2/command/MecanumControllerCommand.cpp | 4 +- .../cpp/frc2/command/NotifierCommand.cpp | 8 +- .../native/cpp/frc2/command/PIDCommand.cpp | 12 +- .../native/cpp/frc2/command/PIDSubsystem.cpp | 16 +- .../cpp/frc2/command/ParallelCommandGroup.cpp | 12 +- .../frc2/command/ParallelDeadlineGroup.cpp | 8 +- .../cpp/frc2/command/ParallelRaceGroup.cpp | 8 +- .../cpp/frc2/command/PerpetualCommand.cpp | 12 +- .../native/cpp/frc2/command/PrintCommand.cpp | 4 +- .../cpp/frc2/command/ProxyScheduleCommand.cpp | 4 +- .../cpp/frc2/command/RamseteCommand.cpp | 9 +- .../native/cpp/frc2/command/RunCommand.cpp | 4 +- .../cpp/frc2/command/ScheduleCommand.cpp | 8 +- .../frc2/command/SequentialCommandGroup.cpp | 4 +- .../cpp/frc2/command/StartEndCommand.cpp | 8 +- .../native/cpp/frc2/command/SubsystemBase.cpp | 8 +- .../native/cpp/frc2/command/WaitCommand.cpp | 12 +- .../cpp/frc2/command/WaitUntilCommand.cpp | 8 +- .../cpp/frc2/command/CommandTestBase.cpp | 8 +- .../native/cpp/frc2/command/ErrorConfirmer.h | 4 +- .../src/main/native/cpp/buttons/Button.cpp | 20 +- .../native/cpp/buttons/ButtonScheduler.cpp | 4 +- .../native/cpp/buttons/InternalButton.cpp | 12 +- .../native/cpp/buttons/JoystickButton.cpp | 4 +- .../src/main/native/cpp/buttons/POVButton.cpp | 4 +- .../src/main/native/cpp/buttons/Trigger.cpp | 4 +- .../src/main/native/cpp/commands/Command.cpp | 119 +++-- .../main/native/cpp/commands/CommandGroup.cpp | 64 ++- .../native/cpp/commands/CommandGroupEntry.cpp | 8 +- .../cpp/commands/ConditionalCommand.cpp | 6 +- .../native/cpp/commands/InstantCommand.cpp | 4 +- .../main/native/cpp/commands/PIDCommand.cpp | 28 +- .../main/native/cpp/commands/PIDSubsystem.cpp | 32 +- .../main/native/cpp/commands/PrintCommand.cpp | 4 +- .../main/native/cpp/commands/Scheduler.cpp | 26 +- .../main/native/cpp/commands/StartCommand.cpp | 4 +- .../main/native/cpp/commands/Subsystem.cpp | 16 +- .../main/native/cpp/commands/TimedCommand.cpp | 4 +- .../native/cpp/commands/WaitUntilCommand.cpp | 4 +- wpilibc/src/main/native/cpp/ADXL345_I2C.cpp | 24 +- wpilibc/src/main/native/cpp/ADXL345_SPI.cpp | 28 +- wpilibc/src/main/native/cpp/ADXL362.cpp | 36 +- wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp | 28 +- .../main/native/cpp/AnalogAccelerometer.cpp | 8 +- wpilibc/src/main/native/cpp/AnalogEncoder.cpp | 12 +- wpilibc/src/main/native/cpp/AnalogGyro.cpp | 36 +- wpilibc/src/main/native/cpp/AnalogInput.cpp | 84 ++- wpilibc/src/main/native/cpp/AnalogOutput.cpp | 8 +- .../main/native/cpp/AnalogPotentiometer.cpp | 4 +- wpilibc/src/main/native/cpp/AnalogTrigger.cpp | 40 +- .../main/native/cpp/AnalogTriggerOutput.cpp | 8 +- .../main/native/cpp/BuiltInAccelerometer.cpp | 12 +- wpilibc/src/main/native/cpp/CAN.cpp | 4 +- wpilibc/src/main/native/cpp/Compressor.cpp | 65 ++- wpilibc/src/main/native/cpp/Counter.cpp | 92 +++- wpilibc/src/main/native/cpp/DMA.cpp | 4 +- .../main/native/cpp/DigitalGlitchFilter.cpp | 4 +- wpilibc/src/main/native/cpp/DigitalInput.cpp | 20 +- wpilibc/src/main/native/cpp/DigitalOutput.cpp | 64 ++- .../src/main/native/cpp/DoubleSolenoid.cpp | 13 +- wpilibc/src/main/native/cpp/DriverStation.cpp | 28 +- wpilibc/src/main/native/cpp/DutyCycle.cpp | 8 +- .../src/main/native/cpp/DutyCycleEncoder.cpp | 12 +- wpilibc/src/main/native/cpp/Encoder.cpp | 75 ++- wpilibc/src/main/native/cpp/Error.cpp | 24 +- wpilibc/src/main/native/cpp/ErrorBase.cpp | 28 +- wpilibc/src/main/native/cpp/GenericHID.cpp | 21 +- wpilibc/src/main/native/cpp/I2C.cpp | 16 +- .../native/cpp/InterruptableSensorBase.cpp | 56 +- .../src/main/native/cpp/IterativeRobot.cpp | 4 +- .../main/native/cpp/IterativeRobotBase.cpp | 4 +- wpilibc/src/main/native/cpp/Joystick.cpp | 60 ++- .../src/main/native/cpp/NidecBrushless.cpp | 24 +- wpilibc/src/main/native/cpp/Notifier.cpp | 38 +- wpilibc/src/main/native/cpp/PIDBase.cpp | 19 +- wpilibc/src/main/native/cpp/PIDSource.cpp | 4 +- wpilibc/src/main/native/cpp/PWM.cpp | 56 +- .../main/native/cpp/PWMSpeedController.cpp | 20 +- .../native/cpp/PowerDistributionPanel.cpp | 4 +- wpilibc/src/main/native/cpp/Preferences.cpp | 8 +- wpilibc/src/main/native/cpp/Relay.cpp | 29 +- wpilibc/src/main/native/cpp/Resource.cpp | 4 +- wpilibc/src/main/native/cpp/RobotDrive.cpp | 42 +- wpilibc/src/main/native/cpp/RobotState.cpp | 4 +- wpilibc/src/main/native/cpp/SPI.cpp | 77 ++- wpilibc/src/main/native/cpp/SensorUtil.cpp | 4 +- wpilibc/src/main/native/cpp/SerialPort.cpp | 8 +- wpilibc/src/main/native/cpp/Servo.cpp | 20 +- wpilibc/src/main/native/cpp/Solenoid.cpp | 24 +- .../main/native/cpp/SpeedControllerGroup.cpp | 11 +- wpilibc/src/main/native/cpp/TimedRobot.cpp | 4 +- wpilibc/src/main/native/cpp/Timer.cpp | 28 +- wpilibc/src/main/native/cpp/Tracer.cpp | 12 +- wpilibc/src/main/native/cpp/Ultrasonic.cpp | 32 +- wpilibc/src/main/native/cpp/Watchdog.cpp | 41 +- .../controller/HolonomicDriveController.cpp | 4 +- .../native/cpp/controller/PIDController.cpp | 48 +- .../cpp/controller/RamseteController.cpp | 4 +- .../main/native/cpp/drive/RobotDriveBase.cpp | 16 +- .../src/main/native/cpp/drive/Vector2d.cpp | 4 +- .../src/main/native/cpp/filters/Filter.cpp | 4 +- wpilibc/src/main/native/cpp/frc2/Timer.cpp | 8 +- .../main/native/cpp/livewindow/LiveWindow.cpp | 45 +- .../native/cpp/shuffleboard/LayoutType.cpp | 4 +- .../native/cpp/shuffleboard/Shuffleboard.cpp | 12 +- .../ShuffleboardComponentBase.cpp | 4 +- .../cpp/shuffleboard/ShuffleboardTab.cpp | 4 +- .../native/cpp/shuffleboard/WidgetType.cpp | 4 +- .../cpp/simulation/AddressableLEDSim.cpp | 3 +- .../native/cpp/simulation/AnalogGyroSim.cpp | 4 +- .../native/cpp/simulation/AnalogInputSim.cpp | 4 +- .../native/cpp/simulation/AnalogOutputSim.cpp | 4 +- .../cpp/simulation/AnalogTriggerSim.cpp | 8 +- .../native/cpp/simulation/CallbackStore.cpp | 4 +- .../src/main/native/cpp/simulation/DIOSim.cpp | 20 +- .../native/cpp/simulation/DigitalPWMSim.cpp | 16 +- .../cpp/simulation/DriverStationSim.cpp | 20 +- .../native/cpp/simulation/DutyCycleSim.cpp | 8 +- .../main/native/cpp/simulation/EncoderSim.cpp | 36 +- .../native/cpp/simulation/GenericHIDSim.cpp | 8 +- .../native/cpp/simulation/JoystickSim.cpp | 8 +- .../src/main/native/cpp/simulation/PCMSim.cpp | 4 +- .../src/main/native/cpp/simulation/PDPSim.cpp | 8 +- .../src/main/native/cpp/simulation/PWMSim.cpp | 28 +- .../main/native/cpp/simulation/RelaySim.cpp | 12 +- .../main/native/cpp/simulation/RoboRioSim.cpp | 32 +- .../cpp/simulation/SPIAccelerometerSim.cpp | 4 +- .../native/cpp/simulation/SimDeviceSim.cpp | 8 +- .../main/native/cpp/simulation/SimHooks.cpp | 32 +- .../native/cpp/smartdashboard/Field2d.cpp | 8 +- .../cpp/smartdashboard/FieldObject2d.cpp | 25 +- .../cpp/smartdashboard/SendableBase.cpp | 5 +- .../smartdashboard/SendableBuilderImpl.cpp | 88 +++- .../cpp/smartdashboard/SendableRegistry.cpp | 94 ++-- .../cpp/smartdashboard/SmartDashboard.cpp | 12 +- wpilibc/src/main/native/cppcs/RobotBase.cpp | 32 +- .../src/main/native/include/frc/RobotBase.h | 9 +- .../src/main/native/include/frc/RobotDrive.h | 16 +- .../frc/shuffleboard/SendableCameraWrapper.h | 3 +- .../frc/smartdashboard/SendableBuilderImpl.h | 3 +- .../frc/smartdashboard/SendableChooser.inc | 6 +- .../src/main/native/include/frc/util/Color.h | 4 +- .../test/native/cpp/MockSpeedController.cpp | 20 +- .../cpp/simulation/SimDeviceSimTest.cpp | 4 +- .../cpp/commands/command/ReplaceMeCommand.cpp | 4 +- .../commands/command2/ReplaceMeCommand2.cpp | 4 +- .../pidcommand/ReplaceMePIDCommand.cpp | 4 +- .../ReplaceMeProfiledPIDCommand.cpp | 4 +- .../cpp/commands/trigger/ReplaceMeTrigger.cpp | 4 +- .../cpp/examples/AddressableLED/cpp/Robot.cpp | 4 +- .../cpp/examples/ArcadeDrive/cpp/Robot.cpp | 4 +- .../ArcadeDriveXboxController/cpp/Robot.cpp | 4 +- .../main/cpp/examples/ArmBot/cpp/Robot.cpp | 12 +- .../examples/ArmBot/cpp/RobotContainer.cpp | 4 +- .../ArmBot/cpp/subsystems/DriveSubsystem.cpp | 8 +- .../cpp/examples/ArmBotOffboard/cpp/Robot.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 8 +- .../cpp/examples/ArmSimulation/cpp/Robot.cpp | 4 +- .../examples/AxisCameraSample/cpp/Robot.cpp | 4 +- .../main/cpp/examples/CANPDP/cpp/Robot.cpp | 4 +- .../src/main/cpp/examples/DMA/cpp/Robot.cpp | 4 +- .../DifferentialDriveBot/cpp/Robot.cpp | 4 +- .../cpp/Robot.cpp | 4 +- .../DriveDistanceOffboard/cpp/Robot.cpp | 8 +- .../examples/DutyCycleEncoder/cpp/Robot.cpp | 4 +- .../cpp/examples/DutyCycleInput/cpp/Robot.cpp | 4 +- .../ElevatorProfiledPID/cpp/Robot.cpp | 4 +- .../examples/ElevatorSimulation/cpp/Robot.cpp | 4 +- .../ElevatorTrapezoidProfile/cpp/Robot.cpp | 4 +- .../main/cpp/examples/Encoder/cpp/Robot.cpp | 4 +- .../cpp/examples/Frisbeebot/cpp/Robot.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 8 +- .../cpp/subsystems/ShooterSubsystem.cpp | 16 +- .../main/cpp/examples/GearsBot/cpp/Robot.cpp | 8 +- .../GearsBot/cpp/commands/CloseClaw.cpp | 8 +- .../GearsBot/cpp/commands/DriveStraight.cpp | 4 +- .../GearsBot/cpp/commands/OpenClaw.cpp | 4 +- .../cpp/commands/SetDistanceToBox.cpp | 4 +- .../GearsBot/cpp/commands/TankDrive.cpp | 12 +- .../examples/GearsBot/cpp/subsystems/Claw.cpp | 20 +- .../GearsBot/cpp/subsystems/DriveTrain.cpp | 8 +- .../GearsBot/cpp/subsystems/Elevator.cpp | 12 +- .../GearsBot/cpp/subsystems/Wrist.cpp | 12 +- .../cpp/examples/GettingStarted/cpp/Robot.cpp | 4 +- .../src/main/cpp/examples/Gyro/cpp/Robot.cpp | 4 +- .../examples/GyroDriveCommands/cpp/Robot.cpp | 8 +- .../cpp/commands/TurnToAngle.cpp | 4 +- .../cpp/commands/TurnToAngleProfiled.cpp | 4 +- .../cpp/subsystems/DriveSubsystem.cpp | 8 +- .../cpp/examples/GyroMecanum/cpp/Robot.cpp | 4 +- .../examples/HatchbotInlined/cpp/Robot.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 8 +- .../HatchbotTraditional/cpp/Robot.cpp | 8 +- .../cpp/commands/DriveDistance.cpp | 8 +- .../cpp/commands/GrabHatch.cpp | 8 +- .../cpp/commands/HalveDriveSpeed.cpp | 8 +- .../cpp/commands/ReleaseHatch.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 8 +- .../main/cpp/examples/HidRumble/cpp/Robot.cpp | 4 +- .../examples/IntermediateVision/cpp/Robot.cpp | 4 +- .../cpp/examples/MecanumBot/cpp/Robot.cpp | 4 +- .../MecanumControllerCommand/cpp/Robot.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 16 +- .../cpp/examples/MecanumDrive/cpp/Robot.cpp | 4 +- .../MecanumDrivePoseEstimator/cpp/Robot.cpp | 4 +- .../cpp/examples/MotorControl/cpp/Robot.cpp | 4 +- .../MotorControlEncoder/cpp/Robot.cpp | 4 +- .../src/main/cpp/examples/PacGoat/cpp/OI.cpp | 4 +- .../main/cpp/examples/PacGoat/cpp/Robot.cpp | 12 +- .../PacGoat/cpp/commands/CheckForHotGoal.cpp | 4 +- .../PacGoat/cpp/commands/CloseClaw.cpp | 8 +- .../PacGoat/cpp/commands/DriveForward.cpp | 12 +- .../cpp/commands/DriveWithJoystick.cpp | 12 +- .../PacGoat/cpp/commands/ExtendShooter.cpp | 8 +- .../PacGoat/cpp/commands/OpenClaw.cpp | 12 +- .../cpp/commands/SetCollectionSpeed.cpp | 4 +- .../PacGoat/cpp/commands/SetPivotSetpoint.cpp | 4 +- .../PacGoat/cpp/commands/WaitForBall.cpp | 8 +- .../PacGoat/cpp/commands/WaitForPressure.cpp | 8 +- .../PacGoat/cpp/subsystems/Collector.cpp | 16 +- .../PacGoat/cpp/subsystems/DriveTrain.cpp | 16 +- .../examples/PacGoat/cpp/subsystems/Pivot.cpp | 12 +- .../PacGoat/cpp/subsystems/Shooter.cpp | 48 +- .../examples/PotentiometerPID/cpp/Robot.cpp | 4 +- .../cpp/examples/QuickVision/cpp/Robot.cpp | 4 +- .../cpp/examples/RamseteCommand/cpp/Robot.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 16 +- .../RamseteController/cpp/Drivetrain.cpp | 4 +- .../examples/RamseteController/cpp/Robot.cpp | 4 +- .../src/main/cpp/examples/Relay/cpp/Robot.cpp | 4 +- .../SchedulerEventLogging/cpp/Robot.cpp | 8 +- .../cpp/examples/SelectCommand/cpp/Robot.cpp | 8 +- .../cpp/examples/ShuffleBoard/cpp/Robot.cpp | 4 +- .../cpp/Robot.cpp | 4 +- .../main/cpp/examples/Solenoid/cpp/Robot.cpp | 4 +- .../cpp/examples/StateSpaceArm/cpp/Robot.cpp | 4 +- .../cpp/Robot.cpp | 8 +- .../cpp/RobotContainer.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 16 +- .../examples/StateSpaceElevator/cpp/Robot.cpp | 4 +- .../examples/StateSpaceFlywheel/cpp/Robot.cpp | 4 +- .../StateSpaceFlywheelSysId/cpp/Robot.cpp | 4 +- .../main/cpp/examples/SwerveBot/cpp/Robot.cpp | 4 +- .../SwerveControllerCommand/cpp/Robot.cpp | 8 +- .../cpp/subsystems/DriveSubsystem.cpp | 12 +- .../SwerveDrivePoseEstimator/cpp/Robot.cpp | 4 +- .../TankDriveXboxController/cpp/Robot.cpp | 4 +- .../cpp/examples/Ultrasonic/cpp/Robot.cpp | 4 +- .../cpp/examples/UltrasonicPID/cpp/Robot.cpp | 4 +- .../cpp/templates/commandbased/cpp/Robot.cpp | 8 +- .../templates/oldcommandbased/cpp/Robot.cpp | 16 +- .../cpp/commands/ExampleCommand.cpp | 4 +- .../cpp/commands/MyAutoCommand.cpp | 4 +- .../templates/robotbaseskeleton/cpp/Robot.cpp | 24 +- .../main/cpp/templates/timed/cpp/Robot.cpp | 4 +- .../cpp/templates/timedskeleton/cpp/Robot.cpp | 4 +- .../src/main/native/cpp/NotifierTest.cpp | 4 +- .../src/main/native/cpp/TestEnvironment.cpp | 4 +- .../main/native/cpp/command/MockCommand.cpp | 28 +- .../cpp/command/MockConditionalCommand.cpp | 24 +- .../src/main/native/cpp/mockds/MockDS.cpp | 17 +- wpimath/src/dev/native/cpp/main.cpp | 4 +- wpimath/src/main/native/cpp/MathShared.cpp | 4 +- .../main/native/cpp/geometry/Rotation2d.cpp | 4 +- .../native/cpp/geometry/Translation2d.cpp | 4 +- .../src/main/native/cpp/jni/WPIMathJNI.cpp | 3 +- .../main/native/cpp/trajectory/Trajectory.cpp | 12 +- .../cpp/trajectory/TrajectoryGenerator.cpp | 12 +- .../trajectory/TrajectoryParameterizer.cpp | 12 +- .../include/frc/estimator/AngleStatistics.h | 4 +- wpiutil/examples/webserver/webserver.cpp | 12 +- wpiutil/src/main/native/cpp/Base64.cpp | 21 +- .../src/main/native/cpp/EventLoopRunner.cpp | 24 +- wpiutil/src/main/native/cpp/HttpParser.cpp | 40 +- .../main/native/cpp/HttpServerConnection.cpp | 35 +- wpiutil/src/main/native/cpp/HttpUtil.cpp | 91 +++- wpiutil/src/main/native/cpp/PortForwarder.cpp | 30 +- wpiutil/src/main/native/cpp/SafeThread.cpp | 21 +- wpiutil/src/main/native/cpp/TCPAcceptor.cpp | 14 +- wpiutil/src/main/native/cpp/TCPConnector.cpp | 12 +- .../main/native/cpp/TCPConnector_parallel.cpp | 12 +- wpiutil/src/main/native/cpp/TCPStream.cpp | 53 +- wpiutil/src/main/native/cpp/UDPClient.cpp | 28 +- wpiutil/src/main/native/cpp/WebSocket.cpp | 198 +++++-- .../src/main/native/cpp/WebSocketServer.cpp | 54 +- wpiutil/src/main/native/cpp/future.cpp | 16 +- wpiutil/src/main/native/cpp/hostname.cpp | 8 +- .../src/main/native/cpp/jni/WPIUtilJNI.cpp | 3 +- wpiutil/src/main/native/cpp/leb128.cpp | 15 +- wpiutil/src/main/native/cpp/raw_istream.cpp | 28 +- .../main/native/cpp/raw_socket_istream.cpp | 8 +- .../main/native/cpp/raw_socket_ostream.cpp | 12 +- .../src/main/native/cpp/raw_uv_ostream.cpp | 4 +- wpiutil/src/main/native/cpp/sha1.cpp | 4 +- wpiutil/src/main/native/cpp/timestamp.cpp | 16 +- wpiutil/src/main/native/cpp/uv/Async.cpp | 5 +- wpiutil/src/main/native/cpp/uv/FsEvent.cpp | 5 +- .../src/main/native/cpp/uv/GetAddrInfo.cpp | 10 +- .../src/main/native/cpp/uv/GetNameInfo.cpp | 30 +- wpiutil/src/main/native/cpp/uv/Handle.cpp | 4 +- wpiutil/src/main/native/cpp/uv/Loop.cpp | 16 +- .../src/main/native/cpp/uv/NetworkStream.cpp | 5 +- wpiutil/src/main/native/cpp/uv/Pipe.cpp | 25 +- wpiutil/src/main/native/cpp/uv/Poll.cpp | 29 +- wpiutil/src/main/native/cpp/uv/Process.cpp | 20 +- wpiutil/src/main/native/cpp/uv/Stream.cpp | 26 +- wpiutil/src/main/native/cpp/uv/Tcp.cpp | 64 ++- wpiutil/src/main/native/cpp/uv/Timer.cpp | 4 +- wpiutil/src/main/native/cpp/uv/Udp.cpp | 45 +- wpiutil/src/main/native/cpp/uv/Work.cpp | 18 +- .../src/main/native/include/wpi/Algorithm.h | 1 + .../src/main/native/include/wpi/HttpUtil.h | 4 +- .../wpi/HttpWebSocketServerConnection.inl | 3 +- wpiutil/src/main/native/include/wpi/Logger.h | 4 +- .../src/main/native/include/wpi/UidVector.h | 8 +- .../src/main/native/include/wpi/WebSocket.h | 8 +- .../main/native/include/wpi/WorkerThread.h | 27 +- wpiutil/src/main/native/include/wpi/future.h | 81 ++- .../src/main/native/include/wpi/jni_util.h | 162 ++++-- .../src/main/native/include/wpi/raw_istream.h | 4 +- .../src/main/native/include/wpi/spinlock.h | 31 +- .../src/main/native/include/wpi/uv/Async.h | 17 +- .../native/include/wpi/uv/AsyncFunction.h | 12 +- .../src/main/native/include/wpi/uv/Buffer.h | 12 +- .../src/main/native/include/wpi/uv/Handle.h | 4 +- wpiutil/src/main/native/include/wpi/uv/Tty.h | 4 +- wpiutil/src/main/native/include/wpi/uv/util.h | 16 +- wpiutil/src/main/native/windows/Demangle.cpp | 3 +- .../src/netconsoleServer/native/cpp/main.cpp | 47 +- wpiutil/src/netconsoleTee/native/cpp/main.cpp | 35 +- wpiutil/src/test/native/cpp/Base64Test.cpp | 5 +- wpiutil/src/test/native/cpp/UidVectorTest.cpp | 4 +- .../test/native/cpp/WebSocketClientTest.cpp | 57 +- .../native/cpp/WebSocketIntegrationTest.cpp | 12 +- .../test/native/cpp/WebSocketServerTest.cpp | 16 +- wpiutil/src/test/native/cpp/WebSocketTest.cpp | 75 ++- wpiutil/src/test/native/cpp/hostname.cpp | 4 +- .../native/cpp/sigslot/signal-threaded.cpp | 28 +- .../native/cpp/sigslot/signal-tracking.cpp | 4 +- .../src/test/native/cpp/sigslot/signal.cpp | 8 +- .../native/cpp/uv/UvAsyncFunctionTest.cpp | 56 +- .../src/test/native/cpp/uv/UvAsyncTest.cpp | 24 +- .../src/test/native/cpp/uv/UvLoopWalkTest.cpp | 8 +- 634 files changed, 10716 insertions(+), 3938 deletions(-) diff --git a/.clang-format b/.clang-format index f5a95f7217..8df901fc31 100644 --- a/.clang-format +++ b/.clang-format @@ -14,10 +14,10 @@ AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All +AllowShortFunctionsOnASingleLine: Inline AllowShortLambdasOnASingleLine: All -AllowShortIfStatementsOnASingleLine: WithoutElse -AllowShortLoopsOnASingleLine: true +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: true diff --git a/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp b/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp index 6dc2f05e96..df408dee2a 100644 --- a/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp +++ b/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp @@ -143,7 +143,9 @@ bool ReadConfig() { // cameras try { for (auto&& camera : j.at("cameras")) { - if (!ReadCameraConfig(camera)) return false; + if (!ReadCameraConfig(camera)) { + return false; + } } } catch (const wpi::json::exception& e) { ParseError() << "could not read cameras: " << e.what() << '\n'; @@ -164,10 +166,14 @@ void StartCamera(const CameraConfig& config) { } // namespace int main(int argc, char* argv[]) { - if (argc >= 2) configFile = argv[1]; + if (argc >= 2) { + configFile = argv[1]; + } // read configuration - if (!ReadConfig()) return EXIT_FAILURE; + if (!ReadConfig()) { + return EXIT_FAILURE; + } // start NetworkTables auto ntinst = nt::NetworkTableInstance::GetDefault(); @@ -180,8 +186,12 @@ int main(int argc, char* argv[]) { } // start cameras - for (auto&& camera : cameras) StartCamera(camera); + for (auto&& camera : cameras) { + StartCamera(camera); + } // loop forever - for (;;) std::this_thread::sleep_for(std::chrono::seconds(10)); + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(10)); + } } diff --git a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp index 009ce0f077..ab1f1cfb78 100644 --- a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp +++ b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp @@ -71,7 +71,9 @@ static wpi::StringRef MakeSourceValue(CS_Source source, wpi::StringRef prefix{"ip:"}; buf.append(prefix.begin(), prefix.end()); auto urls = cs::GetHttpCameraUrls(source, &status); - if (!urls.empty()) buf.append(urls[0].begin(), urls[0].end()); + if (!urls.empty()) { + buf.append(urls[0].begin(), urls[0].end()); + } break; } case CS_SOURCE_CV: @@ -99,8 +101,9 @@ std::vector CameraServer::Impl::GetSinkStreamValues(CS_Sink sink) { CS_Status status = 0; // Ignore all but MjpegServer - if (cs::GetSinkKind(sink, &status) != CS_SINK_MJPEG) - return std::vector{}; + if (cs::GetSinkKind(sink, &status) != CS_SINK_MJPEG) { + return {}; + } // Get port int port = cs::GetMjpegServerPort(sink, &status); @@ -116,7 +119,9 @@ std::vector CameraServer::Impl::GetSinkStreamValues(CS_Sink sink) { values.emplace_back(MakeStreamValue(cs::GetHostname() + ".local", port)); for (const auto& addr : m_addresses) { - if (addr == "127.0.0.1") continue; // ignore localhost + if (addr == "127.0.0.1") { + continue; // ignore localhost + } values.emplace_back(MakeStreamValue(addr, port)); } } @@ -129,12 +134,15 @@ std::vector CameraServer::Impl::GetSourceStreamValues( CS_Status status = 0; // Ignore all but HttpCamera - if (cs::GetSourceKind(source, &status) != CS_SOURCE_HTTP) - return std::vector{}; + if (cs::GetSourceKind(source, &status) != CS_SOURCE_HTTP) { + return {}; + } // Generate values auto values = cs::GetHttpCameraUrls(source, &status); - for (auto& value : values) value = "mjpg:" + value; + for (auto& value : values) { + value = "mjpg:" + value; + } #ifdef __FRC_ROBORIO__ // Look to see if we have a passthrough server for this source @@ -165,16 +173,24 @@ void CameraServer::Impl::UpdateStreamValues() { // Get the source's subtable (if none exists, we're done) CS_Source source = m_fixedSources.lookup(sink); - if (source == 0) source = cs::GetSinkSource(sink, &status); - if (source == 0) continue; + if (source == 0) { + source = cs::GetSinkSource(sink, &status); + } + if (source == 0) { + continue; + } auto table = m_tables.lookup(source); if (table) { // Don't set stream values if this is a HttpCamera passthrough - if (cs::GetSourceKind(source, &status) == CS_SOURCE_HTTP) continue; + if (cs::GetSourceKind(source, &status) == CS_SOURCE_HTTP) { + continue; + } // Set table value auto values = GetSinkStreamValues(sink); - if (!values.empty()) table->GetEntry("streams").SetStringArray(values); + if (!values.empty()) { + table->GetEntry("streams").SetStringArray(values); + } } } @@ -187,7 +203,9 @@ void CameraServer::Impl::UpdateStreamValues() { if (table) { // Set table value auto values = GetSourceStreamValues(source); - if (!values.empty()) table->GetEntry("streams").SetStringArray(values); + if (!values.empty()) { + table->GetEntry("streams").SetStringArray(values); + } } } } @@ -221,8 +239,9 @@ static std::string VideoModeToString(const cs::VideoMode& mode) { static std::vector GetSourceModeValues(int source) { std::vector rv; CS_Status status = 0; - for (const auto& mode : cs::EnumerateSourceVideoModes(source, &status)) + for (const auto& mode : cs::EnumerateSourceVideoModes(source, &status)) { rv.emplace_back(VideoModeToString(mode)); + } return rv; } @@ -247,10 +266,11 @@ static void PutSourcePropertyValue(nt::NetworkTable* table, nt::NetworkTableEntry entry = table->GetEntry(name); switch (event.propertyKind) { case CS_PROP_BOOLEAN: - if (isNew) + if (isNew) { entry.SetDefaultBoolean(event.value != 0); - else + } else { entry.SetBoolean(event.value != 0); + } break; case CS_PROP_INTEGER: case CS_PROP_ENUM: @@ -269,10 +289,11 @@ static void PutSourcePropertyValue(nt::NetworkTable* table, } break; case CS_PROP_STRING: - if (isNew) + if (isNew) { entry.SetDefaultString(event.valueStr); - else + } else { entry.SetString(event.valueStr); + } break; default: break; @@ -348,30 +369,38 @@ CameraServer::Impl::Impl() } case cs::VideoEvent::kSourceDisconnected: { auto table = GetSourceTable(event.sourceHandle); - if (table) table->GetEntry("connected").SetBoolean(false); + if (table) { + table->GetEntry("connected").SetBoolean(false); + } break; } case cs::VideoEvent::kSourceVideoModesUpdated: { auto table = GetSourceTable(event.sourceHandle); - if (table) + if (table) { table->GetEntry("modes").SetStringArray( GetSourceModeValues(event.sourceHandle)); + } break; } case cs::VideoEvent::kSourceVideoModeChanged: { auto table = GetSourceTable(event.sourceHandle); - if (table) + if (table) { table->GetEntry("mode").SetString(VideoModeToString(event.mode)); + } break; } case cs::VideoEvent::kSourcePropertyCreated: { auto table = GetSourceTable(event.sourceHandle); - if (table) PutSourcePropertyValue(table.get(), event, true); + if (table) { + PutSourcePropertyValue(table.get(), event, true); + } break; } case cs::VideoEvent::kSourcePropertyValueUpdated: { auto table = GetSourceTable(event.sourceHandle); - if (table) PutSourcePropertyValue(table.get(), event, false); + if (table) { + PutSourcePropertyValue(table.get(), event, false); + } break; } case cs::VideoEvent::kSourcePropertyChoicesUpdated: { @@ -413,10 +442,14 @@ CameraServer::Impl::Impl() // get source (sourceName/...) auto subKeyIndex = relativeKey.find('/'); - if (subKeyIndex == wpi::StringRef::npos) return; + if (subKeyIndex == wpi::StringRef::npos) { + return; + } wpi::StringRef sourceName = relativeKey.slice(0, subKeyIndex); auto sourceIt = m_sources.find(sourceName); - if (sourceIt == m_sources.end()) return; + if (sourceIt == m_sources.end()) { + return; + } // get subkey relativeKey = relativeKey.substr(subKeyIndex + 1); @@ -689,7 +722,9 @@ cs::VideoSink CameraServer::GetServer(const wpi::Twine& name) { void CameraServer::AddCamera(const cs::VideoSource& camera) { std::string name = camera.GetName(); std::scoped_lock lock(m_impl->m_mutex); - if (m_impl->m_primarySourceName.empty()) m_impl->m_primarySourceName = name; + if (m_impl->m_primarySourceName.empty()) { + m_impl->m_primarySourceName = name; + } m_impl->m_sources.try_emplace(name, camera); } @@ -701,13 +736,18 @@ void CameraServer::RemoveCamera(const wpi::Twine& name) { void CameraServer::SetSize(int size) { std::scoped_lock lock(m_impl->m_mutex); - if (m_impl->m_primarySourceName.empty()) return; + if (m_impl->m_primarySourceName.empty()) { + return; + } auto it = m_impl->m_sources.find(m_impl->m_primarySourceName); - if (it == m_impl->m_sources.end()) return; - if (size == kSize160x120) + if (it == m_impl->m_sources.end()) { + return; + } + if (size == kSize160x120) { it->second.SetResolution(160, 120); - else if (size == kSize320x240) + } else if (size == kSize320x240) { it->second.SetResolution(320, 240); - else if (size == kSize640x480) + } else if (size == kSize640x480) { it->second.SetResolution(640, 480); + } } diff --git a/cameraserver/src/main/native/cpp/vision/VisionRunner.cpp b/cameraserver/src/main/native/cpp/vision/VisionRunner.cpp index 88ed92aa1d..93de7af0bc 100644 --- a/cameraserver/src/main/native/cpp/vision/VisionRunner.cpp +++ b/cameraserver/src/main/native/cpp/vision/VisionRunner.cpp @@ -53,4 +53,6 @@ void VisionRunnerBase::RunForever() { } } -void VisionRunnerBase::Stop() { m_enabled = false; } +void VisionRunnerBase::Stop() { + m_enabled = false; +} diff --git a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc b/cameraserver/src/main/native/include/cameraserver/CameraServer.inc index 293de4466a..717db29f7f 100644 --- a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc +++ b/cameraserver/src/main/native/include/cameraserver/CameraServer.inc @@ -20,7 +20,8 @@ inline cs::AxisCamera CameraServer::AddAxisCamera( const wpi::Twine& name, std::initializer_list hosts) { std::vector vec; vec.reserve(hosts.size()); - for (const auto& host : hosts) vec.emplace_back(host); + for (const auto& host : hosts) + vec.emplace_back(host); return AddAxisCamera(name, vec); } diff --git a/cameraserver/src/test/native/cpp/main.cpp b/cameraserver/src/test/native/cpp/main.cpp index 8c76519388..b36f82656c 100644 --- a/cameraserver/src/test/native/cpp/main.cpp +++ b/cameraserver/src/test/native/cpp/main.cpp @@ -2,4 +2,6 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -int main() { return 0; } +int main() { + return 0; +} diff --git a/cscore/examples/enum_usb/enum_usb.cpp b/cscore/examples/enum_usb/enum_usb.cpp index 1c773ff441..a5b7a10702 100644 --- a/cscore/examples/enum_usb/enum_usb.cpp +++ b/cscore/examples/enum_usb/enum_usb.cpp @@ -16,8 +16,9 @@ int main() { << ")\n"; if (!caminfo.otherPaths.empty()) { wpi::outs() << "Other device paths:\n"; - for (auto&& path : caminfo.otherPaths) + for (auto&& path : caminfo.otherPaths) { wpi::outs() << " " << path << '\n'; + } } cs::UsbCamera camera{"usbcam", caminfo.dev}; @@ -45,7 +46,9 @@ int main() { << "value=" << prop.Get(); auto choices = prop.GetChoices(); for (size_t i = 0; i < choices.size(); ++i) { - if (choices[i].empty()) continue; + if (choices[i].empty()) { + continue; + } wpi::outs() << "\n " << i << ": " << choices[i]; } break; diff --git a/cscore/examples/settings/settings.cpp b/cscore/examples/settings/settings.cpp index 10f9e4d2e8..7681d17121 100644 --- a/cscore/examples/settings/settings.cpp +++ b/cscore/examples/settings/settings.cpp @@ -34,18 +34,22 @@ int main(int argc, char** argv) { } else { wpi::StringRef propVal{argv[arg]}; int intVal; - if (propVal.getAsInteger(10, intVal)) + if (propVal.getAsInteger(10, intVal)) { camera.GetProperty(propName).SetString(propVal); - else + } else { camera.GetProperty(propName).Set(intVal); + } propName = wpi::StringRef{}; } } - if (arg < argc && wpi::StringRef{argv[arg]} == "--") ++arg; + if (arg < argc && wpi::StringRef{argv[arg]} == "--") { + ++arg; + } // Wait to connect - while (!camera.IsConnected()) + while (!camera.IsConnected()) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } // Set rest propName = wpi::StringRef{}; @@ -55,10 +59,11 @@ int main(int argc, char** argv) { } else { wpi::StringRef propVal{argv[arg]}; int intVal; - if (propVal.getAsInteger(10, intVal)) + if (propVal.getAsInteger(10, intVal)) { camera.GetProperty(propName).SetString(propVal); - else + } else { camera.GetProperty(propName).Set(intVal); + } propName = wpi::StringRef{}; } } @@ -88,7 +93,9 @@ int main(int argc, char** argv) { << "value=" << prop.Get(); auto choices = prop.GetChoices(); for (size_t i = 0; i < choices.size(); ++i) { - if (choices[i].empty()) continue; + if (choices[i].empty()) { + continue; + } wpi::outs() << "\n " << i << ": " << choices[i]; } break; diff --git a/cscore/examples/usbstream/usbstream.cpp b/cscore/examples/usbstream/usbstream.cpp index 28a8ae1116..f4a612e1e2 100644 --- a/cscore/examples/usbstream/usbstream.cpp +++ b/cscore/examples/usbstream/usbstream.cpp @@ -11,8 +11,9 @@ int main() { wpi::outs() << "hostname: " << cs::GetHostname() << '\n'; wpi::outs() << "IPv4 network addresses:\n"; - for (const auto& addr : cs::GetNetworkInterfaces()) + for (const auto& addr : cs::GetNetworkInterfaces()) { wpi::outs() << " " << addr << '\n'; + } cs::UsbCamera camera{"usbcam", 0}; camera.SetVideoMode(cs::VideoMode::kMJPEG, 320, 240, 30); cs::MjpegServer mjpegServer{"httpserver", 8081}; diff --git a/cscore/examples/usbviewer/usbviewer.cpp b/cscore/examples/usbviewer/usbviewer.cpp index 052e5af450..1b2ef5d44e 100644 --- a/cscore/examples/usbviewer/usbviewer.cpp +++ b/cscore/examples/usbviewer/usbviewer.cpp @@ -50,7 +50,9 @@ int main() { } else { { std::scoped_lock lock(sharedFreeListMutex); - for (auto mat : sharedFreeList) sourceFreeList.emplace_back(mat); + for (auto mat : sharedFreeList) { + sourceFreeList.emplace_back(mat); + } sharedFreeList.clear(); } if (!sourceFreeList.empty()) { @@ -68,7 +70,9 @@ int main() { auto prev = latestFrame.exchange(out); // put prev on free list - if (prev) sourceFreeList.emplace_back(prev); + if (prev) { + sourceFreeList.emplace_back(prev); + } } }); diff --git a/cscore/src/dev/native/cpp/main.cpp b/cscore/src/dev/native/cpp/main.cpp index 30acc187bd..af366144f8 100644 --- a/cscore/src/dev/native/cpp/main.cpp +++ b/cscore/src/dev/native/cpp/main.cpp @@ -6,4 +6,6 @@ #include "cscore.h" -int main() { std::cout << cs::GetHostname() << std::endl; } +int main() { + std::cout << cs::GetHostname() << std::endl; +} diff --git a/cscore/src/main/native/cpp/CvSinkImpl.cpp b/cscore/src/main/native/cpp/CvSinkImpl.cpp index 73fd69a058..8154b4b4f6 100644 --- a/cscore/src/main/native/cpp/CvSinkImpl.cpp +++ b/cscore/src/main/native/cpp/CvSinkImpl.cpp @@ -30,16 +30,22 @@ CvSinkImpl::CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger, std::function processFrame) : SinkImpl{name, logger, notifier, telemetry} {} -CvSinkImpl::~CvSinkImpl() { Stop(); } +CvSinkImpl::~CvSinkImpl() { + Stop(); +} void CvSinkImpl::Stop() { m_active = false; // wake up any waiters by forcing an empty frame to be sent - if (auto source = GetSource()) source->Wakeup(); + if (auto source = GetSource()) { + source->Wakeup(); + } // join thread - if (m_thread.joinable()) m_thread.join(); + if (m_thread.joinable()) { + m_thread.join(); + } } uint64_t CvSinkImpl::GrabFrame(cv::Mat& image) { @@ -106,7 +112,9 @@ void CvSinkImpl::ThreadMain() { } SDEBUG4("waiting for frame"); Frame frame = source->GetNextFrame(); // blocks - if (!m_active) break; + if (!m_active) { + break; + } if (!frame) { // Bad frame; sleep for 10 ms so we don't consume all processor time. std::this_thread::sleep_for(std::chrono::milliseconds(10)); @@ -240,7 +248,9 @@ uint64_t CS_GrabSinkFrameTimeoutCpp(CS_Sink sink, cv::Mat* image, char* CS_GetSinkError(CS_Sink sink, CS_Status* status) { wpi::SmallString<128> buf; auto str = cs::GetSinkError(sink, buf, status); - if (*status != 0) return nullptr; + if (*status != 0) { + return nullptr; + } return cs::ConvertToC(str); } diff --git a/cscore/src/main/native/cpp/CvSourceImpl.cpp b/cscore/src/main/native/cpp/CvSourceImpl.cpp index 9f03b8e7ef..d5a25b05c1 100644 --- a/cscore/src/main/native/cpp/CvSourceImpl.cpp +++ b/cscore/src/main/native/cpp/CvSourceImpl.cpp @@ -29,10 +29,11 @@ CvSourceImpl::~CvSourceImpl() {} void CvSourceImpl::PutFrame(cv::Mat& image) { // We only support 8-bit images; convert if necessary. cv::Mat finalImage; - if (image.depth() == CV_8U) + if (image.depth() == CV_8U) { finalImage = image; - else + } else { image.convertTo(finalImage, CV_8U); + } std::unique_ptr dest; switch (image.channels()) { @@ -224,7 +225,9 @@ void CS_SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, CS_Status* status) { wpi::SmallVector vec; vec.reserve(count); - for (int i = 0; i < count; ++i) vec.push_back(choices[i]); + for (int i = 0; i < count; ++i) { + vec.push_back(choices[i]); + } return cs::SetSourceEnumPropertyChoices(source, property, vec, status); } diff --git a/cscore/src/main/native/cpp/Frame.cpp b/cscore/src/main/native/cpp/Frame.cpp index bdff58ef57..71bd446206 100644 --- a/cscore/src/main/native/cpp/Frame.cpp +++ b/cscore/src/main/native/cpp/Frame.cpp @@ -32,22 +32,31 @@ Frame::Frame(SourceImpl& source, std::unique_ptr image, Time time) } Image* Frame::GetNearestImage(int width, int height) const { - if (!m_impl) return nullptr; + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); Image* found = nullptr; // Ideally we want the smallest image at least width/height in size for (auto i : m_impl->images) { - if (i->IsLarger(width, height) && (!found || (i->IsSmaller(*found)))) + if (i->IsLarger(width, height) && (!found || (i->IsSmaller(*found)))) { found = i; + } + } + if (found) { + return found; } - if (found) return found; // Find the largest image (will be less than width/height) for (auto i : m_impl->images) { - if (!found || (i->IsLarger(*found))) found = i; + if (!found || (i->IsLarger(*found))) { + found = i; + } + } + if (found) { + return found; } - if (found) return found; // Shouldn't reach this, but just in case... return m_impl->images.empty() ? nullptr : m_impl->images[0]; @@ -56,7 +65,9 @@ Image* Frame::GetNearestImage(int width, int height) const { Image* Frame::GetNearestImage(int width, int height, VideoMode::PixelFormat pixelFormat, int jpegQuality) const { - if (!m_impl) return nullptr; + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); Image* found = nullptr; @@ -71,19 +82,25 @@ Image* Frame::GetNearestImage(int width, int height, // 1) Same width, height, pixelFormat, and (possibly) JPEG quality // (e.g. exactly what we want) for (auto i : m_impl->images) { - if (i->Is(width, height, pixelFormat, jpegQuality)) return i; + if (i->Is(width, height, pixelFormat, jpegQuality)) { + return i; + } } // 2) Same width, height, different (but non-JPEG) pixelFormat (color conv) // 2a) If we want JPEG output, prefer BGR over other pixel formats if (pixelFormat == VideoMode::kMJPEG) { for (auto i : m_impl->images) { - if (i->Is(width, height, VideoMode::kBGR)) return i; + if (i->Is(width, height, VideoMode::kBGR)) { + return i; + } } } for (auto i : m_impl->images) { - if (i->Is(width, height) && i->pixelFormat != VideoMode::kMJPEG) return i; + if (i->Is(width, height) && i->pixelFormat != VideoMode::kMJPEG) { + return i; + } } // 3) Different width, height, same pixelFormat (only if non-JPEG) (resample) @@ -91,17 +108,23 @@ Image* Frame::GetNearestImage(int width, int height, // 3a) Smallest image at least width/height in size for (auto i : m_impl->images) { if (i->IsLarger(width, height) && i->pixelFormat == pixelFormat && - (!found || (i->IsSmaller(*found)))) + (!found || (i->IsSmaller(*found)))) { found = i; + } + } + if (found) { + return found; } - if (found) return found; // 3b) Largest image (less than width/height) for (auto i : m_impl->images) { - if (i->pixelFormat == pixelFormat && (!found || (i->IsLarger(*found)))) + if (i->pixelFormat == pixelFormat && (!found || (i->IsLarger(*found)))) { found = i; + } + } + if (found) { + return found; } - if (found) return found; } // 4) Different width, height, different (but non-JPEG) pixelFormat @@ -109,18 +132,24 @@ Image* Frame::GetNearestImage(int width, int height, // 4a) Smallest image at least width/height in size for (auto i : m_impl->images) { if (i->IsLarger(width, height) && i->pixelFormat != VideoMode::kMJPEG && - (!found || (i->IsSmaller(*found)))) + (!found || (i->IsSmaller(*found)))) { found = i; + } + } + if (found) { + return found; } - if (found) return found; // 4b) Largest image (less than width/height) for (auto i : m_impl->images) { if (i->pixelFormat != VideoMode::kMJPEG && - (!found || (i->IsLarger(*found)))) + (!found || (i->IsLarger(*found)))) { found = i; + } + } + if (found) { + return found; } - if (found) return found; // 5) Same width, height, JPEG pixelFormat (decompression). As there may be // multiple JPEG images, find the highest quality one. @@ -130,27 +159,37 @@ Image* Frame::GetNearestImage(int width, int height, found = i; // consider one without a quality setting to be the highest quality // (e.g. directly from the camera) - if (i->jpegQuality == -1) break; + if (i->jpegQuality == -1) { + break; + } } } - if (found) return found; + if (found) { + return found; + } // 6) Different width, height, JPEG pixelFormat (decompression) // 6a) Smallest image at least width/height in size for (auto i : m_impl->images) { if (i->IsLarger(width, height) && i->pixelFormat == VideoMode::kMJPEG && - (!found || (i->IsSmaller(*found)))) + (!found || (i->IsSmaller(*found)))) { found = i; + } + } + if (found) { + return found; } - if (found) return found; // 6b) Largest image (less than width/height) for (auto i : m_impl->images) { if (i->pixelFormat != VideoMode::kMJPEG && - (!found || (i->IsLarger(*found)))) + (!found || (i->IsLarger(*found)))) { found = i; + } + } + if (found) { + return found; } - if (found) return found; // Shouldn't reach this, but just in case... return m_impl->images.empty() ? nullptr : m_impl->images[0]; @@ -158,9 +197,10 @@ Image* Frame::GetNearestImage(int width, int height, Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, int requiredJpegQuality, int defaultJpegQuality) { - if (!image || - image->Is(image->width, image->height, pixelFormat, requiredJpegQuality)) + if (!image || image->Is(image->width, image->height, pixelFormat, + requiredJpegQuality)) { return image; + } Image* cur = image; // If the source image is a JPEG, we need to decode it before we can do @@ -169,7 +209,9 @@ Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, // would have returned above). if (cur->pixelFormat == VideoMode::kMJPEG) { cur = ConvertMJPEGToBGR(cur); - if (pixelFormat == VideoMode::kBGR) return cur; + if (pixelFormat == VideoMode::kBGR) { + return cur; + } } // Color convert @@ -179,17 +221,19 @@ Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, if (cur->pixelFormat == VideoMode::kYUYV) { // Check to see if BGR version already exists... if (Image* newImage = - GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { cur = newImage; - else + } else { cur = ConvertYUYVToBGR(cur); + } } else if (cur->pixelFormat == VideoMode::kGray) { // Check to see if BGR version already exists... if (Image* newImage = - GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { cur = newImage; - else + } else { cur = ConvertGrayToBGR(cur); + } } return ConvertBGRToRGB565(cur); case VideoMode::kGray: @@ -197,17 +241,19 @@ Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, if (cur->pixelFormat == VideoMode::kYUYV) { // Check to see if BGR version already exists... if (Image* newImage = - GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { cur = newImage; - else + } else { cur = ConvertYUYVToBGR(cur); + } } else if (cur->pixelFormat == VideoMode::kRGB565) { // Check to see if BGR version already exists... if (Image* newImage = - GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { cur = newImage; - else + } else { cur = ConvertRGB565ToBGR(cur); + } } return ConvertBGRToGray(cur); case VideoMode::kBGR: @@ -217,10 +263,11 @@ Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, } else if (cur->pixelFormat == VideoMode::kRGB565) { cur = ConvertRGB565ToBGR(cur); } else if (cur->pixelFormat == VideoMode::kGray) { - if (pixelFormat == VideoMode::kBGR) + if (pixelFormat == VideoMode::kBGR) { return ConvertGrayToBGR(cur); - else + } else { return ConvertGrayToMJPEG(cur, defaultJpegQuality); + } } break; case VideoMode::kYUYV: @@ -229,14 +276,17 @@ Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, } // Compress if destination is JPEG - if (pixelFormat == VideoMode::kMJPEG) + if (pixelFormat == VideoMode::kMJPEG) { cur = ConvertBGRToMJPEG(cur, defaultJpegQuality); + } return cur; } Image* Frame::ConvertMJPEGToBGR(Image* image) { - if (!image || image->pixelFormat != VideoMode::kMJPEG) return nullptr; + if (!image || image->pixelFormat != VideoMode::kMJPEG) { + return nullptr; + } // Allocate an BGR image auto newImage = @@ -257,7 +307,9 @@ Image* Frame::ConvertMJPEGToBGR(Image* image) { } Image* Frame::ConvertMJPEGToGray(Image* image) { - if (!image || image->pixelFormat != VideoMode::kMJPEG) return nullptr; + if (!image || image->pixelFormat != VideoMode::kMJPEG) { + return nullptr; + } // Allocate an grayscale image auto newImage = @@ -278,7 +330,9 @@ Image* Frame::ConvertMJPEGToGray(Image* image) { } Image* Frame::ConvertYUYVToBGR(Image* image) { - if (!image || image->pixelFormat != VideoMode::kYUYV) return nullptr; + if (!image || image->pixelFormat != VideoMode::kYUYV) { + return nullptr; + } // Allocate a BGR image auto newImage = @@ -298,7 +352,9 @@ Image* Frame::ConvertYUYVToBGR(Image* image) { } Image* Frame::ConvertBGRToRGB565(Image* image) { - if (!image || image->pixelFormat != VideoMode::kBGR) return nullptr; + if (!image || image->pixelFormat != VideoMode::kBGR) { + return nullptr; + } // Allocate a RGB565 image auto newImage = @@ -318,7 +374,9 @@ Image* Frame::ConvertBGRToRGB565(Image* image) { } Image* Frame::ConvertRGB565ToBGR(Image* image) { - if (!image || image->pixelFormat != VideoMode::kRGB565) return nullptr; + if (!image || image->pixelFormat != VideoMode::kRGB565) { + return nullptr; + } // Allocate a BGR image auto newImage = @@ -338,7 +396,9 @@ Image* Frame::ConvertRGB565ToBGR(Image* image) { } Image* Frame::ConvertBGRToGray(Image* image) { - if (!image || image->pixelFormat != VideoMode::kBGR) return nullptr; + if (!image || image->pixelFormat != VideoMode::kBGR) { + return nullptr; + } // Allocate a Grayscale image auto newImage = @@ -358,7 +418,9 @@ Image* Frame::ConvertBGRToGray(Image* image) { } Image* Frame::ConvertGrayToBGR(Image* image) { - if (!image || image->pixelFormat != VideoMode::kGray) return nullptr; + if (!image || image->pixelFormat != VideoMode::kGray) { + return nullptr; + } // Allocate a BGR image auto newImage = @@ -378,8 +440,12 @@ Image* Frame::ConvertGrayToBGR(Image* image) { } Image* Frame::ConvertBGRToMJPEG(Image* image, int quality) { - if (!image || image->pixelFormat != VideoMode::kBGR) return nullptr; - if (!m_impl) return nullptr; + if (!image || image->pixelFormat != VideoMode::kBGR) { + return nullptr; + } + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); // Allocate a JPEG image. We don't actually know what the resulting size @@ -409,8 +475,12 @@ Image* Frame::ConvertBGRToMJPEG(Image* image, int quality) { } Image* Frame::ConvertGrayToMJPEG(Image* image, int quality) { - if (!image || image->pixelFormat != VideoMode::kGray) return nullptr; - if (!m_impl) return nullptr; + if (!image || image->pixelFormat != VideoMode::kGray) { + return nullptr; + } + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); // Allocate a JPEG image. We don't actually know what the resulting size @@ -442,11 +512,14 @@ Image* Frame::ConvertGrayToMJPEG(Image* image, int quality) { Image* Frame::GetImageImpl(int width, int height, VideoMode::PixelFormat pixelFormat, int requiredJpegQuality, int defaultJpegQuality) { - if (!m_impl) return nullptr; + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); Image* cur = GetNearestImage(width, height, pixelFormat, requiredJpegQuality); - if (!cur || cur->Is(width, height, pixelFormat, requiredJpegQuality)) + if (!cur || cur->Is(width, height, pixelFormat, requiredJpegQuality)) { return cur; + } WPI_DEBUG4(Instance::GetInstance().logger, "converting image from " << cur->width << "x" << cur->height @@ -458,7 +531,9 @@ Image* Frame::GetImageImpl(int width, int height, // anything else with it. Note that if the destination format is JPEG, we // still need to do this (unless the width/height/compression were the same, // in which case we already returned the existing JPEG above). - if (cur->pixelFormat == VideoMode::kMJPEG) cur = ConvertMJPEGToBGR(cur); + if (cur->pixelFormat == VideoMode::kMJPEG) { + cur = ConvertMJPEGToBGR(cur); + } // Resize if (!cur->Is(width, height)) { @@ -482,14 +557,17 @@ Image* Frame::GetImageImpl(int width, int height, bool Frame::GetCv(cv::Mat& image, int width, int height) { Image* rawImage = GetImage(width, height, VideoMode::kBGR); - if (!rawImage) return false; + if (!rawImage) { + return false; + } rawImage->AsMat().copyTo(image); return true; } void Frame::ReleaseFrame() { - for (auto image : m_impl->images) + for (auto image : m_impl->images) { m_impl->source.ReleaseImage(std::unique_ptr(image)); + } m_impl->images.clear(); m_impl->source.ReleaseFrameImpl(std::unique_ptr(m_impl)); m_impl = nullptr; diff --git a/cscore/src/main/native/cpp/Frame.h b/cscore/src/main/native/cpp/Frame.h index 264018f066..76ff897ed5 100644 --- a/cscore/src/main/native/cpp/Frame.h +++ b/cscore/src/main/native/cpp/Frame.h @@ -49,7 +49,9 @@ class Frame { Frame(SourceImpl& source, std::unique_ptr image, Time time); Frame(const Frame& frame) noexcept : m_impl{frame.m_impl} { - if (m_impl) ++m_impl->refcount; + if (m_impl) { + ++m_impl->refcount; + } } Frame(Frame&& other) noexcept : Frame() { swap(*this, other); } @@ -71,60 +73,90 @@ class Frame { Time GetTime() const { return m_impl ? m_impl->time : 0; } wpi::StringRef GetError() const { - if (!m_impl) return wpi::StringRef{}; + if (!m_impl) { + return {}; + } return m_impl->error; } int GetOriginalWidth() const { - if (!m_impl) return 0; + if (!m_impl) { + return 0; + } std::scoped_lock lock(m_impl->mutex); - if (m_impl->images.empty()) return 0; + if (m_impl->images.empty()) { + return 0; + } return m_impl->images[0]->width; } int GetOriginalHeight() const { - if (!m_impl) return 0; + if (!m_impl) { + return 0; + } std::scoped_lock lock(m_impl->mutex); - if (m_impl->images.empty()) return 0; + if (m_impl->images.empty()) { + return 0; + } return m_impl->images[0]->height; } int GetOriginalPixelFormat() const { - if (!m_impl) return 0; + if (!m_impl) { + return 0; + } std::scoped_lock lock(m_impl->mutex); - if (m_impl->images.empty()) return 0; + if (m_impl->images.empty()) { + return 0; + } return m_impl->images[0]->pixelFormat; } int GetOriginalJpegQuality() const { - if (!m_impl) return 0; + if (!m_impl) { + return 0; + } std::scoped_lock lock(m_impl->mutex); - if (m_impl->images.empty()) return 0; + if (m_impl->images.empty()) { + return 0; + } return m_impl->images[0]->jpegQuality; } Image* GetExistingImage(size_t i = 0) const { - if (!m_impl) return nullptr; + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); - if (i >= m_impl->images.size()) return nullptr; + if (i >= m_impl->images.size()) { + return nullptr; + } return m_impl->images[i]; } Image* GetExistingImage(int width, int height) const { - if (!m_impl) return nullptr; + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); for (auto i : m_impl->images) { - if (i->Is(width, height)) return i; + if (i->Is(width, height)) { + return i; + } } return nullptr; } Image* GetExistingImage(int width, int height, VideoMode::PixelFormat pixelFormat) const { - if (!m_impl) return nullptr; + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); for (auto i : m_impl->images) { - if (i->Is(width, height, pixelFormat)) return i; + if (i->Is(width, height, pixelFormat)) { + return i; + } } return nullptr; } @@ -132,10 +164,14 @@ class Frame { Image* GetExistingImage(int width, int height, VideoMode::PixelFormat pixelFormat, int jpegQuality) const { - if (!m_impl) return nullptr; + if (!m_impl) { + return nullptr; + } std::scoped_lock lock(m_impl->mutex); for (auto i : m_impl->images) { - if (i->Is(width, height, pixelFormat, jpegQuality)) return i; + if (i->Is(width, height, pixelFormat, jpegQuality)) { + return i; + } } return nullptr; } @@ -146,7 +182,9 @@ class Frame { int jpegQuality = -1) const; Image* Convert(Image* image, VideoMode::PixelFormat pixelFormat) { - if (pixelFormat == VideoMode::kMJPEG) return nullptr; + if (pixelFormat == VideoMode::kMJPEG) { + return nullptr; + } return ConvertImpl(image, pixelFormat, -1, 80); } Image* ConvertToMJPEG(Image* image, int requiredQuality, @@ -165,7 +203,9 @@ class Frame { Image* ConvertGrayToMJPEG(Image* image, int quality); Image* GetImage(int width, int height, VideoMode::PixelFormat pixelFormat) { - if (pixelFormat == VideoMode::kMJPEG) return nullptr; + if (pixelFormat == VideoMode::kMJPEG) { + return nullptr; + } return GetImageImpl(width, height, pixelFormat, -1, 80); } Image* GetImageMJPEG(int width, int height, int requiredQuality, @@ -185,7 +225,9 @@ class Frame { Image* GetImageImpl(int width, int height, VideoMode::PixelFormat pixelFormat, int requiredJpegQuality, int defaultJpegQuality); void DecRef() { - if (m_impl && --(m_impl->refcount) == 0) ReleaseFrame(); + if (m_impl && --(m_impl->refcount) == 0) { + ReleaseFrame(); + } } void ReleaseFrame(); diff --git a/cscore/src/main/native/cpp/HttpCameraImpl.cpp b/cscore/src/main/native/cpp/HttpCameraImpl.cpp index 286f50166c..3d1c64883b 100644 --- a/cscore/src/main/native/cpp/HttpCameraImpl.cpp +++ b/cscore/src/main/native/cpp/HttpCameraImpl.cpp @@ -30,26 +30,36 @@ HttpCameraImpl::~HttpCameraImpl() { m_monitorCond.notify_one(); // join monitor thread - if (m_monitorThread.joinable()) m_monitorThread.join(); + if (m_monitorThread.joinable()) { + m_monitorThread.join(); + } // Close file if it's open { std::scoped_lock lock(m_mutex); - if (m_streamConn) m_streamConn->stream->close(); - if (m_settingsConn) m_settingsConn->stream->close(); + if (m_streamConn) { + m_streamConn->stream->close(); + } + if (m_settingsConn) { + m_settingsConn->stream->close(); + } } // force wakeup of camera thread in case it's waiting on cv m_sinkEnabledCond.notify_one(); // join camera thread - if (m_streamThread.joinable()) m_streamThread.join(); + if (m_streamThread.joinable()) { + m_streamThread.join(); + } // force wakeup of settings thread m_settingsCond.notify_one(); // join settings thread - if (m_settingsThread.joinable()) m_settingsThread.join(); + if (m_settingsThread.joinable()) { + m_settingsThread.join(); + } } void HttpCameraImpl::Start() { @@ -66,7 +76,9 @@ void HttpCameraImpl::MonitorThreadMain() { m_monitorCond.wait_for(lock, std::chrono::seconds(1), [=] { return !m_active; }); - if (!m_active) break; + if (!m_active) { + break; + } // check to see if we got any frames, and close the stream if not // (this will result in an error at the read point, and ultimately @@ -93,20 +105,28 @@ void HttpCameraImpl::StreamThreadMain() { // disconnect if not enabled if (!IsEnabled()) { std::unique_lock lock(m_mutex); - if (m_streamConn) m_streamConn->stream->close(); + if (m_streamConn) { + m_streamConn->stream->close(); + } // Wait for enable m_sinkEnabledCond.wait(lock, [=] { return !m_active || IsEnabled(); }); - if (!m_active) return; + if (!m_active) { + return; + } } // connect wpi::SmallString<64> boundary; wpi::HttpConnection* conn = DeviceStreamConnect(boundary); - if (!m_active) break; + if (!m_active) { + break; + } // keep retrying - if (!conn) continue; + if (!conn) { + continue; + } // update connected since we're actually connected SetConnected(true); @@ -134,7 +154,9 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( std::this_thread::sleep_for(std::chrono::seconds(1)); return nullptr; } - if (m_nextLocation >= m_locations.size()) m_nextLocation = 0; + if (m_nextLocation >= m_locations.size()) { + m_nextLocation = 0; + } req = wpi::HttpRequest{m_locations[m_nextLocation++], m_streamSettings}; m_streamSettingsUpdated = false; } @@ -143,7 +165,9 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( auto stream = wpi::TCPConnector::connect(req.host.c_str(), req.port, m_logger, 1); - if (!m_active || !stream) return nullptr; + if (!m_active || !stream) { + return nullptr; + } auto connPtr = std::make_unique(std::move(stream), 1); wpi::HttpConnection* conn = connPtr.get(); @@ -215,24 +239,33 @@ void HttpCameraImpl::DeviceStream(wpi::raw_istream& is, // streaming loop while (m_active && !is.has_error() && IsEnabled() && numErrors < 3 && !m_streamSettingsUpdated) { - if (!FindMultipartBoundary(is, boundary, nullptr)) break; + if (!FindMultipartBoundary(is, boundary, nullptr)) { + break; + } // Read the next two characters after the boundary (normally \r\n) // Handle just \n for LabVIEW however char eol[2]; is.read(eol, 1); - if (!m_active || is.has_error()) break; + if (!m_active || is.has_error()) { + break; + } if (eol[0] != '\n') { is.read(eol + 1, 1); - if (!m_active || is.has_error()) break; + if (!m_active || is.has_error()) { + break; + } // End-of-stream is indicated with trailing -- - if (eol[0] == '-' && eol[1] == '-') break; + if (eol[0] == '-' && eol[1] == '-') { + break; + } } - if (!DeviceStreamFrame(is, imageBuf)) + if (!DeviceStreamFrame(is, imageBuf)) { ++numErrors; - else + } else { numErrors = 0; + } } } @@ -277,7 +310,9 @@ bool HttpCameraImpl::DeviceStreamFrame(wpi::raw_istream& is, // the data directly into it. auto image = AllocImage(VideoMode::PixelFormat::kMJPEG, 0, 0, contentLength); is.read(image->data(), contentLength); - if (!m_active || is.has_error()) return false; + if (!m_active || is.has_error()) { + return false; + } int width, height; if (!GetJpegSize(image->str(), &width, &height)) { SWARNING("did not receive a JPEG image"); @@ -299,7 +334,9 @@ void HttpCameraImpl::SettingsThreadMain() { m_settingsCond.wait(lock, [=] { return !m_active || (m_prefLocation != -1 && !m_settings.empty()); }); - if (!m_active) break; + if (!m_active) { + break; + } // Build the request req = wpi::HttpRequest{m_locations[m_prefLocation], m_settings}; @@ -316,7 +353,9 @@ void HttpCameraImpl::DeviceSendSettings(wpi::HttpRequest& req) { auto stream = wpi::TCPConnector::connect(req.host.c_str(), req.port, m_logger, 1); - if (!m_active || !stream) return; + if (!m_active || !stream) { + return; + } auto connPtr = std::make_unique(std::move(stream), 1); wpi::HttpConnection* conn = connPtr.get(); @@ -329,7 +368,9 @@ void HttpCameraImpl::DeviceSendSettings(wpi::HttpRequest& req) { // Just need a handshake as settings are sent via GET parameters std::string warn; - if (!conn->Handshake(req, &warn)) SWARNING(GetName() << ": " << warn); + if (!conn->Handshake(req, &warn)) { + SWARNING(GetName() << ": " << warn); + } conn->stream->close(); } @@ -363,7 +404,9 @@ bool HttpCameraImpl::SetUrls(wpi::ArrayRef urls, std::vector HttpCameraImpl::GetUrls() const { std::scoped_lock lock(m_mutex); std::vector urls; - for (const auto& loc : m_locations) urls.push_back(loc.url); + for (const auto& loc : m_locations) { + urls.push_back(loc.url); + } return urls; } @@ -393,7 +436,9 @@ void HttpCameraImpl::CreateEnumProperty( auto& enumChoices = m_propertyData.back()->enumChoices; enumChoices.clear(); - for (const auto& choice : choices) enumChoices.emplace_back(choice); + for (const auto& choice : choices) { + enumChoices.emplace_back(choice); + } m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CREATED, name, m_propertyData.size() + 1, CS_PROP_ENUM, @@ -468,7 +513,9 @@ void HttpCameraImpl::SetExposureManual(int value, CS_Status* status) { } bool HttpCameraImpl::SetVideoMode(const VideoMode& mode, CS_Status* status) { - if (mode.pixelFormat != VideoMode::kMJPEG) return false; + if (mode.pixelFormat != VideoMode::kMJPEG) { + return false; + } std::scoped_lock lock(m_mutex); m_mode = mode; m_streamSettingsUpdated = true; @@ -527,7 +574,9 @@ CS_Source CreateHttpCamera(const wpi::Twine& name, const wpi::Twine& url, inst.notifier, inst.telemetry); break; } - if (!source->SetUrls(url.str(), status)) return 0; + if (!source->SetUrls(url.str(), status)) { + return 0; + } return inst.CreateSource(CS_SOURCE_HTTP, source); } @@ -541,7 +590,9 @@ CS_Source CreateHttpCamera(const wpi::Twine& name, } auto source = std::make_shared(name, kind, inst.logger, inst.notifier, inst.telemetry); - if (!source->SetUrls(urls, status)) return 0; + if (!source->SetUrls(urls, status)) { + return 0; + } return inst.CreateSource(CS_SOURCE_HTTP, source); } @@ -592,7 +643,9 @@ CS_Source CS_CreateHttpCameraMulti(const char* name, const char** urls, CS_Status* status) { wpi::SmallVector vec; vec.reserve(count); - for (int i = 0; i < count; ++i) vec.push_back(urls[i]); + for (int i = 0; i < count; ++i) { + vec.push_back(urls[i]); + } return cs::CreateHttpCamera(name, vec, kind, status); } @@ -604,7 +657,9 @@ void CS_SetHttpCameraUrls(CS_Source source, const char** urls, int count, CS_Status* status) { wpi::SmallVector vec; vec.reserve(count); - for (int i = 0; i < count; ++i) vec.push_back(urls[i]); + for (int i = 0; i < count; ++i) { + vec.push_back(urls[i]); + } cs::SetHttpCameraUrls(source, vec, status); } @@ -613,13 +668,19 @@ char** CS_GetHttpCameraUrls(CS_Source source, int* count, CS_Status* status) { char** out = static_cast(wpi::safe_malloc(urls.size() * sizeof(char*))); *count = urls.size(); - for (size_t i = 0; i < urls.size(); ++i) out[i] = cs::ConvertToC(urls[i]); + for (size_t i = 0; i < urls.size(); ++i) { + out[i] = cs::ConvertToC(urls[i]); + } return out; } void CS_FreeHttpCameraUrls(char** urls, int count) { - if (!urls) return; - for (int i = 0; i < count; ++i) std::free(urls[i]); + if (!urls) { + return; + } + for (int i = 0; i < count; ++i) { + std::free(urls[i]); + } std::free(urls); } diff --git a/cscore/src/main/native/cpp/Instance.cpp b/cscore/src/main/native/cpp/Instance.cpp index 4d49f473f2..ae1feb997d 100644 --- a/cscore/src/main/native/cpp/Instance.cpp +++ b/cscore/src/main/native/cpp/Instance.cpp @@ -22,14 +22,15 @@ static void def_log_func(unsigned int level, const char* file, } wpi::StringRef levelmsg; - if (level >= 50) + if (level >= 50) { levelmsg = "CRITICAL: "; - else if (level >= 40) + } else if (level >= 40) { levelmsg = "ERROR: "; - else if (level >= 30) + } else if (level >= 30) { levelmsg = "WARNING: "; - else + } else { return; + } oss << "CS: " << levelmsg << msg << " (" << wpi::sys::path::filename(file) << ':' << line << ")\n"; wpi::errs() << oss.str(); @@ -55,7 +56,9 @@ void Instance::Shutdown() { notifier.Stop(); } -void Instance::SetDefaultLogger() { logger.SetLogger(def_log_func); } +void Instance::SetDefaultLogger() { + logger.SetLogger(def_log_func); +} std::pair> Instance::FindSource( const SourceImpl& source) { @@ -84,11 +87,13 @@ CS_Sink Instance::CreateSink(CS_SinkKind kind, std::shared_ptr sink) { } void Instance::DestroySource(CS_Source handle) { - if (auto data = m_sources.Free(handle)) + if (auto data = m_sources.Free(handle)) { notifier.NotifySource(data->source->GetName(), handle, CS_SOURCE_DESTROYED); + } } void Instance::DestroySink(CS_Sink handle) { - if (auto data = m_sinks.Free(handle)) + if (auto data = m_sinks.Free(handle)) { notifier.NotifySink(data->sink->GetName(), handle, CS_SINK_DESTROYED); + } } diff --git a/cscore/src/main/native/cpp/Instance.h b/cscore/src/main/native/cpp/Instance.h index ac9f5c492a..b3e40efaa4 100644 --- a/cscore/src/main/native/cpp/Instance.h +++ b/cscore/src/main/native/cpp/Instance.h @@ -98,7 +98,9 @@ class Instance { CS_Source source, wpi::SmallVectorImpl& vec) { vec.clear(); m_sinks.ForEach([&](CS_Sink sinkHandle, const SinkData& data) { - if (source == data.sourceHandle.load()) vec.push_back(sinkHandle); + if (source == data.sourceHandle.load()) { + vec.push_back(sinkHandle); + } }); return vec; } diff --git a/cscore/src/main/native/cpp/JpegUtil.cpp b/cscore/src/main/native/cpp/JpegUtil.cpp index 8cee6bc79f..61c358153a 100644 --- a/cscore/src/main/native/cpp/JpegUtil.cpp +++ b/cscore/src/main/native/cpp/JpegUtil.cpp @@ -47,28 +47,44 @@ static const unsigned char dhtData[] = { 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa}; bool IsJpeg(wpi::StringRef data) { - if (data.size() < 11) return false; + if (data.size() < 11) { + return false; + } // Check for valid SOI auto bytes = data.bytes_begin(); - if (bytes[0] != 0xff || bytes[1] != 0xd8) return false; + if (bytes[0] != 0xff || bytes[1] != 0xd8) { + return false; + } return true; } bool GetJpegSize(wpi::StringRef data, int* width, int* height) { - if (!IsJpeg(data)) return false; + if (!IsJpeg(data)) { + return false; + } data = data.substr(2); // Get to the first block auto bytes = data.bytes_begin(); for (;;) { - if (data.size() < 4) return false; // EOF + if (data.size() < 4) { + return false; // EOF + } bytes = data.bytes_begin(); - if (bytes[0] != 0xff) return false; // not a tag - if (bytes[1] == 0xd9) return false; // EOI without finding SOF? - if (bytes[1] == 0xda) return false; // SOS without finding SOF? + if (bytes[0] != 0xff) { + return false; // not a tag + } + if (bytes[1] == 0xd9) { + return false; // EOI without finding SOF? + } + if (bytes[1] == 0xda) { + return false; // SOS without finding SOF? + } if (bytes[1] == 0xc0) { // SOF contains the file size - if (data.size() < 9) return false; + if (data.size() < 9) { + return false; + } *height = bytes[5] * 256 + bytes[6]; *width = bytes[7] * 256 + bytes[8]; return true; @@ -80,7 +96,9 @@ bool GetJpegSize(wpi::StringRef data, int* width, int* height) { bool JpegNeedsDHT(const char* data, size_t* size, size_t* locSOF) { wpi::StringRef sdata(data, *size); - if (!IsJpeg(sdata)) return false; + if (!IsJpeg(sdata)) { + return false; + } *locSOF = *size; @@ -88,12 +106,22 @@ bool JpegNeedsDHT(const char* data, size_t* size, size_t* locSOF) { sdata = sdata.substr(2); // Get to the first block auto bytes = sdata.bytes_begin(); for (;;) { - if (sdata.size() < 4) return false; // EOF + if (sdata.size() < 4) { + return false; // EOF + } bytes = sdata.bytes_begin(); - if (bytes[0] != 0xff) return false; // not a tag - if (bytes[1] == 0xda) break; // SOS - if (bytes[1] == 0xc4) return false; // DHT - if (bytes[1] == 0xc0) *locSOF = sdata.data() - data; // SOF + if (bytes[0] != 0xff) { + return false; // not a tag + } + if (bytes[1] == 0xda) { + break; // SOS + } + if (bytes[1] == 0xc4) { + return false; // DHT + } + if (bytes[1] == 0xc0) { + *locSOF = sdata.data() - data; // SOF + } // Go to the next block sdata = sdata.substr(bytes[2] * 256 + bytes[3] + 2); } @@ -126,18 +154,26 @@ bool ReadJpeg(wpi::raw_istream& is, std::string& buf, int* width, int* height) { // read SOI and first marker buf.resize(4); is.read(&(*buf.begin()), 4); - if (is.has_error()) return false; + if (is.has_error()) { + return false; + } // Check for valid SOI auto bytes = reinterpret_cast(buf.data()); - if (bytes[0] != 0xff || bytes[1] != 0xd8) return false; + if (bytes[0] != 0xff || bytes[1] != 0xd8) { + return false; + } size_t pos = 2; // point to first marker for (;;) { bytes = reinterpret_cast(buf.data() + pos); - if (bytes[0] != 0xff) return false; // not a marker + if (bytes[0] != 0xff) { + return false; // not a marker + } unsigned char marker = bytes[1]; - if (marker == 0xd9) return true; // EOI, we're done + if (marker == 0xd9) { + return true; // EOI, we're done + } if (marker == 0xda) { // SOS: need to keep reading until we reach a normal marker. @@ -147,12 +183,15 @@ bool ReadJpeg(wpi::raw_istream& is, std::string& buf, int* width, int* height) { bool maybeMarker = false; for (;;) { ReadInto(is, buf, 1); - if (is.has_error()) return false; + if (is.has_error()) { + return false; + } bytes = reinterpret_cast(buf.data() + pos); if (maybeMarker) { if (bytes[0] != 0x00 && bytes[0] != 0xff && - (bytes[0] < 0xd0 || bytes[0] > 0xd7)) + (bytes[0] < 0xd0 || bytes[0] > 0xd7)) { break; + } maybeMarker = false; } else if (bytes[0] == 0xff) { maybeMarker = true; @@ -165,7 +204,9 @@ bool ReadJpeg(wpi::raw_istream& is, std::string& buf, int* width, int* height) { // A normal block. Read the length ReadInto(is, buf, 2); // read length - if (is.has_error()) return false; + if (is.has_error()) { + return false; + } // Point to length pos += 2; @@ -174,7 +215,9 @@ bool ReadJpeg(wpi::raw_istream& is, std::string& buf, int* width, int* height) { // Read the block and the next marker size_t blockLength = bytes[0] * 256 + bytes[1]; ReadInto(is, buf, blockLength); - if (is.has_error()) return false; + if (is.has_error()) { + return false; + } bytes = reinterpret_cast(buf.data() + pos); // Special block processing diff --git a/cscore/src/main/native/cpp/MjpegServerImpl.cpp b/cscore/src/main/native/cpp/MjpegServerImpl.cpp index fa3fa137eb..a5196c1a53 100644 --- a/cscore/src/main/native/cpp/MjpegServerImpl.cpp +++ b/cscore/src/main/native/cpp/MjpegServerImpl.cpp @@ -108,13 +108,17 @@ class MjpegServerImpl::ConnThread : public wpi::SafeThread { void StartStream() { std::scoped_lock lock(m_mutex); - if (m_source) m_source->EnableSink(); + if (m_source) { + m_source->EnableSink(); + } m_streaming = true; } void StopStream() { std::scoped_lock lock(m_mutex); - if (m_source) m_source->DisableSink(); + if (m_source) { + m_source->DisableSink(); + } m_streaming = false; } }; @@ -140,7 +144,9 @@ static void SendHeader(wpi::raw_ostream& os, int code, os << "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: *\r\n"; wpi::SmallString<128> extraBuf; wpi::StringRef extraStr = extra.toStringRef(extraBuf); - if (!extraStr.empty()) os << extraStr << "\r\n"; + if (!extraStr.empty()) { + os << extraStr << "\r\n"; + } os << "\r\n"; // header ends with a blank line } @@ -198,9 +204,13 @@ bool MjpegServerImpl::ConnThread::ProcessCommand(wpi::raw_ostream& os, // split out next param and value wpi::StringRef rawParam, rawValue; std::tie(rawParam, parameters) = parameters.split('&'); - if (rawParam.empty()) continue; // ignore "&&" + if (rawParam.empty()) { + continue; // ignore "&&" + } std::tie(rawParam, rawValue) = rawParam.split('='); - if (rawParam.empty() || rawValue.empty()) continue; // ignore "param=" + if (rawParam.empty() || rawValue.empty()) { + continue; // ignore "param=" + } SDEBUG4("HTTP parameter \"" << rawParam << "\" value \"" << rawValue << "\""); @@ -282,7 +292,9 @@ bool MjpegServerImpl::ConnThread::ProcessCommand(wpi::raw_ostream& os, } // ignore name parameter - if (param == "name") continue; + if (param == "name") { + continue; + } // try to assign parameter auto prop = source.GetPropertyIndex(param); @@ -339,7 +351,9 @@ void MjpegServerImpl::ConnThread::SendHTMLHeadTitle( // Send the root html file with controls for all the settable properties. void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, SourceImpl& source, bool header) { - if (header) SendHeader(os, 200, "OK", "text/html"); + if (header) { + SendHeader(os, 200, "OK", "text/html"); + } SendHTMLHeadTitle(os); os << startRootPage; @@ -348,7 +362,9 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, for (auto prop : source.EnumerateProperties(properties_vec, &status)) { wpi::SmallString<128> name_buf; auto name = source.GetPropertyName(prop, name_buf, &status); - if (name.startswith("raw_")) continue; + if (name.startswith("raw_")) { + continue; + } auto kind = source.GetPropertyKind(prop); os << "

" << "\n"; @@ -357,10 +373,11 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, os << "\n"; - else + } else { os << " />\n"; + } break; case CS_PROP_INTEGER: { auto valI = source.GetProperty(prop, &status); @@ -381,11 +398,14 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, int j = 0; for (auto choice = choices.begin(), end = choices.end(); choice != end; ++j, ++choice) { - if (choice->empty()) continue; // skip empty choices + if (choice->empty()) { + continue; // skip empty choices + } // replace any non-printable characters in name with spaces wpi::SmallString<128> ch_name; - for (char ch : *choice) + for (char ch : *choice) { ch_name.push_back(std::isprint(ch) ? ch : ' '); + } os << "USB device path: " << info.path << '\n'; - for (auto&& path : info.otherPaths) + for (auto&& path : info.otherPaths) { os << "

Alternate device path: " << path << '\n'; + } } os << "

Supported Video Modes:

\n"; @@ -461,17 +482,20 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, // Send a JSON file which is contains information about the source parameters. void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, SourceImpl& source, bool header) { - if (header) SendHeader(os, 200, "OK", "application/json"); + if (header) { + SendHeader(os, 200, "OK", "application/json"); + } os << "{\n\"controls\": [\n"; wpi::SmallVector properties_vec; bool first = true; CS_Status status = 0; for (auto prop : source.EnumerateProperties(properties_vec, &status)) { - if (first) + if (first) { first = false; - else + } else { os << ",\n"; + } os << '{'; wpi::SmallString<128> name_buf; auto name = source.GetPropertyName(prop, name_buf, &status); @@ -511,10 +535,14 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, int j = 0; for (auto choice = choices.begin(), end = choices.end(); choice != end; ++j, ++choice) { - if (j != 0) os << ", "; + if (j != 0) { + os << ", "; + } // replace any non-printable characters in name with spaces wpi::SmallString<128> ch_name; - for (char ch : *choice) ch_name.push_back(std::isprint(ch) ? ch : ' '); + for (char ch : *choice) { + ch_name.push_back(std::isprint(ch) ? ch : ' '); + } os << '"' << j << "\": \"" << ch_name << '"'; } os << "}\n"; @@ -524,10 +552,11 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, os << "\n],\n\"modes\": [\n"; first = true; for (auto mode : source.EnumerateVideoModes(&status)) { - if (first) + if (first) { first = false; - else + } else { os << ",\n"; + } os << '{'; os << "\n\"pixelFormat\": \""; switch (mode.pixelFormat) { @@ -596,7 +625,9 @@ MjpegServerImpl::MjpegServerImpl(const wpi::Twine& name, wpi::Logger& logger, m_serverThread = std::thread(&MjpegServerImpl::ServerThreadMain, this); } -MjpegServerImpl::~MjpegServerImpl() { Stop(); } +MjpegServerImpl::~MjpegServerImpl() { + Stop(); +} void MjpegServerImpl::Stop() { m_active = false; @@ -605,18 +636,24 @@ void MjpegServerImpl::Stop() { m_acceptor->shutdown(); // join server thread - if (m_serverThread.joinable()) m_serverThread.join(); + if (m_serverThread.joinable()) { + m_serverThread.join(); + } // close streams for (auto& connThread : m_connThreads) { if (auto thr = connThread.GetThread()) { - if (thr->m_stream) thr->m_stream->close(); + if (thr->m_stream) { + thr->m_stream->close(); + } } connThread.Stop(); } // wake up connection threads by forcing an empty frame to be sent - if (auto source = GetSource()) source->Wakeup(); + if (auto source = GetSource()) { + source->Wakeup(); + } } // Send HTTP response and a stream of JPG-frames @@ -639,10 +676,14 @@ void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { Frame::Time lastFrameTime = 0; Frame::Time timePerFrame = 0; - if (m_fps != 0) timePerFrame = 1000000.0 / m_fps; + if (m_fps != 0) { + timePerFrame = 1000000.0 / m_fps; + } Frame::Time averageFrameTime = 0; Frame::Time averagePeriod = 1000000; // 1 second window - if (averagePeriod < timePerFrame) averagePeriod = timePerFrame * 10; + if (averagePeriod < timePerFrame) { + averagePeriod = timePerFrame * 10; + } StartStream(); while (m_active && !os.has_error()) { @@ -655,7 +696,9 @@ void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { } SDEBUG4("waiting for frame"); Frame frame = source->GetNextFrame(0.225); // blocks - if (!m_active) break; + if (!m_active) { + break; + } if (!frame) { // Bad frame; sleep for 20 ms so we don't consume all processor time. os << "\r\n"; // Keep connection alive @@ -804,8 +847,12 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { // The end of the request is marked by a single, empty line wpi::SmallString<128> lineBuf; for (;;) { - if (is.getline(lineBuf, 4096).startswith("\n")) break; - if (is.has_error()) return; + if (is.getline(lineBuf, 4096).startswith("\n")) { + break; + } + if (is.has_error()) { + return; + } } // Send response @@ -813,7 +860,9 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { case kStream: if (auto source = GetSource()) { SDEBUG("request for stream " << source->GetName()); - if (!ProcessCommand(os, *source, parameters, false)) return; + if (!ProcessCommand(os, *source, parameters, false)) { + return; + } } SendStream(os); break; @@ -829,10 +878,11 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { break; case kGetSettings: SDEBUG("request for JSON file"); - if (auto source = GetSource()) + if (auto source = GetSource()) { SendJSON(os, *source, true); - else + } else { SendError(os, 404, "Resource not found"); + } break; case kGetSourceConfig: SDEBUG("request for JSON file"); @@ -866,7 +916,9 @@ void MjpegServerImpl::ConnThread::Main() { while (m_active) { while (!m_stream) { m_cond.wait(lock); - if (!m_active) return; + if (!m_active) { + return; + } } lock.unlock(); ProcessRequest(); @@ -889,7 +941,9 @@ void MjpegServerImpl::ServerThreadMain() { m_active = false; return; } - if (!m_active) return; + if (!m_active) { + return; + } SDEBUG("client connection from " << stream->getPeerIP()); @@ -939,9 +993,13 @@ void MjpegServerImpl::SetSourceImpl(std::shared_ptr source) { if (auto thr = connThread.GetThread()) { if (thr->m_source != source) { bool streaming = thr->m_streaming; - if (thr->m_source && streaming) thr->m_source->DisableSink(); + if (thr->m_source && streaming) { + thr->m_source->DisableSink(); + } thr->m_source = source; - if (source && streaming) thr->m_source->EnableSink(); + if (source && streaming) { + thr->m_source->EnableSink(); + } } } } diff --git a/cscore/src/main/native/cpp/Notifier.cpp b/cscore/src/main/native/cpp/Notifier.cpp index 90960328fb..f79e0b4488 100644 --- a/cscore/src/main/native/cpp/Notifier.cpp +++ b/cscore/src/main/native/cpp/Notifier.cpp @@ -49,7 +49,9 @@ class UidVector { // one. The element is added to the freelist for later reuse. void erase(unsigned int uid) { --uid; - if (uid >= m_vector.size() || !m_vector[uid]) return; + if (uid >= m_vector.size() || !m_vector[uid]) { + return; + } m_free.push_back(uid); m_vector[uid] = T(); } @@ -88,35 +90,53 @@ class Notifier::Thread : public wpi::SafeThread { std::function m_on_exit; }; -Notifier::Notifier() { s_destroyed = false; } +Notifier::Notifier() { + s_destroyed = false; +} -Notifier::~Notifier() { s_destroyed = true; } +Notifier::~Notifier() { + s_destroyed = true; +} -void Notifier::Start() { m_owner.Start(m_on_start, m_on_exit); } +void Notifier::Start() { + m_owner.Start(m_on_start, m_on_exit); +} -void Notifier::Stop() { m_owner.Stop(); } +void Notifier::Stop() { + m_owner.Stop(); +} void Notifier::Thread::Main() { - if (m_on_start) m_on_start(); + if (m_on_start) { + m_on_start(); + } std::unique_lock lock(m_mutex); while (m_active) { while (m_notifications.empty()) { m_cond.wait(lock); - if (!m_active) goto done; + if (!m_active) { + goto done; + } } while (!m_notifications.empty()) { - if (!m_active) goto done; + if (!m_active) { + goto done; + } auto item = std::move(m_notifications.front()); m_notifications.pop(); // Use index because iterator might get invalidated. for (size_t i = 0; i < m_listeners.size(); ++i) { - if (!m_listeners[i]) continue; // removed + if (!m_listeners[i]) { + continue; // removed + } // Event type must be within requested set for this listener. - if ((item.kind & m_listeners[i].eventMask) == 0) continue; + if ((item.kind & m_listeners[i].eventMask) == 0) { + continue; + } // make a copy of the callback so we can safely release the mutex auto callback = m_listeners[i].callback; @@ -130,7 +150,9 @@ void Notifier::Thread::Main() { } done: - if (m_on_exit) m_on_exit(); + if (m_on_exit) { + m_on_exit(); + } } int Notifier::AddListener(std::function callback, @@ -142,14 +164,18 @@ int Notifier::AddListener(std::function callback, void Notifier::RemoveListener(int uid) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_listeners.erase(uid); } void Notifier::NotifySource(const wpi::Twine& name, CS_Source source, CS_EventKind kind) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_notifications.emplace(name, source, static_cast(kind)); thr->m_cond.notify_one(); } @@ -162,7 +188,9 @@ void Notifier::NotifySource(const SourceImpl& source, CS_EventKind kind) { void Notifier::NotifySourceVideoMode(const SourceImpl& source, const VideoMode& mode) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } auto handleData = Instance::GetInstance().FindSource(source); @@ -175,7 +203,9 @@ void Notifier::NotifySourceProperty(const SourceImpl& source, CS_EventKind kind, int property, CS_PropertyKind propertyKind, int value, const wpi::Twine& valueStr) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } auto handleData = Instance::GetInstance().FindSource(source); @@ -189,7 +219,9 @@ void Notifier::NotifySourceProperty(const SourceImpl& source, CS_EventKind kind, void Notifier::NotifySink(const wpi::Twine& name, CS_Sink sink, CS_EventKind kind) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_notifications.emplace(name, sink, static_cast(kind)); thr->m_cond.notify_one(); @@ -203,7 +235,9 @@ void Notifier::NotifySink(const SinkImpl& sink, CS_EventKind kind) { void Notifier::NotifySinkSourceChanged(const wpi::Twine& name, CS_Sink sink, CS_Source source) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } RawEvent event{name, sink, RawEvent::kSinkSourceChanged}; event.sourceHandle = source; @@ -217,7 +251,9 @@ void Notifier::NotifySinkProperty(const SinkImpl& sink, CS_EventKind kind, CS_PropertyKind propertyKind, int value, const wpi::Twine& valueStr) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } auto handleData = Instance::GetInstance().FindSink(sink); @@ -230,7 +266,9 @@ void Notifier::NotifySinkProperty(const SinkImpl& sink, CS_EventKind kind, void Notifier::NotifyNetworkInterfacesChanged() { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_notifications.emplace(RawEvent::kNetworkInterfacesChanged); thr->m_cond.notify_one(); @@ -238,7 +276,9 @@ void Notifier::NotifyNetworkInterfacesChanged() { void Notifier::NotifyTelemetryUpdated() { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_notifications.emplace(RawEvent::kTelemetryUpdated); thr->m_cond.notify_one(); diff --git a/cscore/src/main/native/cpp/PropertyContainer.cpp b/cscore/src/main/native/cpp/PropertyContainer.cpp index 1a26eca40c..f86280b317 100644 --- a/cscore/src/main/native/cpp/PropertyContainer.cpp +++ b/cscore/src/main/native/cpp/PropertyContainer.cpp @@ -14,7 +14,9 @@ using namespace cs; int PropertyContainer::GetPropertyIndex(const wpi::Twine& name) const { // We can't fail, so instead we create a new index if caching fails. CS_Status status = 0; - if (!m_properties_cached) CacheProperties(&status); + if (!m_properties_cached) { + CacheProperties(&status); + } std::scoped_lock lock(m_mutex); wpi::SmallVector nameBuf; int& ndx = m_properties[name.toStringRef(nameBuf)]; @@ -28,39 +30,50 @@ int PropertyContainer::GetPropertyIndex(const wpi::Twine& name) const { wpi::ArrayRef PropertyContainer::EnumerateProperties( wpi::SmallVectorImpl& vec, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) - return wpi::ArrayRef{}; + if (!m_properties_cached && !CacheProperties(status)) { + return {}; + } std::scoped_lock lock(m_mutex); for (int i = 0; i < static_cast(m_propertyData.size()); ++i) { - if (m_propertyData[i]) vec.push_back(i + 1); + if (m_propertyData[i]) { + vec.push_back(i + 1); + } } return vec; } CS_PropertyKind PropertyContainer::GetPropertyKind(int property) const { CS_Status status = 0; - if (!m_properties_cached && !CacheProperties(&status)) return CS_PROP_NONE; + if (!m_properties_cached && !CacheProperties(&status)) { + return CS_PROP_NONE; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); - if (!prop) return CS_PROP_NONE; + if (!prop) { + return CS_PROP_NONE; + } return prop->propKind; } wpi::StringRef PropertyContainer::GetPropertyName( int property, wpi::SmallVectorImpl& buf, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return wpi::StringRef{}; + if (!m_properties_cached && !CacheProperties(status)) { + return {}; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; - return wpi::StringRef{}; + return {}; } // safe to not copy because we never modify it after caching return prop->name; } int PropertyContainer::GetProperty(int property, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return 0; + if (!m_properties_cached && !CacheProperties(status)) { + return 0; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { @@ -85,7 +98,9 @@ void PropertyContainer::SetProperty(int property, int value, } // Guess it's integer if we've set before get - if (prop->propKind == CS_PROP_NONE) prop->propKind = CS_PROP_INTEGER; + if (prop->propKind == CS_PROP_NONE) { + prop->propKind = CS_PROP_INTEGER; + } if ((prop->propKind & (CS_PROP_BOOLEAN | CS_PROP_INTEGER | CS_PROP_ENUM)) == 0) { @@ -97,7 +112,9 @@ void PropertyContainer::SetProperty(int property, int value, } int PropertyContainer::GetPropertyMin(int property, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return 0; + if (!m_properties_cached && !CacheProperties(status)) { + return 0; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { @@ -108,7 +125,9 @@ int PropertyContainer::GetPropertyMin(int property, CS_Status* status) const { } int PropertyContainer::GetPropertyMax(int property, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return 0; + if (!m_properties_cached && !CacheProperties(status)) { + return 0; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { @@ -119,7 +138,9 @@ int PropertyContainer::GetPropertyMax(int property, CS_Status* status) const { } int PropertyContainer::GetPropertyStep(int property, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return 0; + if (!m_properties_cached && !CacheProperties(status)) { + return 0; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { @@ -131,7 +152,9 @@ int PropertyContainer::GetPropertyStep(int property, CS_Status* status) const { int PropertyContainer::GetPropertyDefault(int property, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return 0; + if (!m_properties_cached && !CacheProperties(status)) { + return 0; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { @@ -143,16 +166,18 @@ int PropertyContainer::GetPropertyDefault(int property, wpi::StringRef PropertyContainer::GetStringProperty( int property, wpi::SmallVectorImpl& buf, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return wpi::StringRef{}; + if (!m_properties_cached && !CacheProperties(status)) { + return {}; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; - return wpi::StringRef{}; + return {}; } if (prop->propKind != CS_PROP_STRING) { *status = CS_WRONG_PROPERTY_TYPE; - return wpi::StringRef{}; + return {}; } buf.clear(); buf.append(prop->valueStr.begin(), prop->valueStr.end()); @@ -169,7 +194,9 @@ void PropertyContainer::SetStringProperty(int property, const wpi::Twine& value, } // Guess it's string if we've set before get - if (prop->propKind == CS_PROP_NONE) prop->propKind = CS_PROP_STRING; + if (prop->propKind == CS_PROP_NONE) { + prop->propKind = CS_PROP_STRING; + } if (prop->propKind != CS_PROP_STRING) { *status = CS_WRONG_PROPERTY_TYPE; @@ -181,17 +208,18 @@ void PropertyContainer::SetStringProperty(int property, const wpi::Twine& value, std::vector PropertyContainer::GetEnumPropertyChoices( int property, CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) - return std::vector{}; + if (!m_properties_cached && !CacheProperties(status)) { + return {}; + } std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; - return std::vector{}; + return {}; } if (prop->propKind != CS_PROP_ENUM) { *status = CS_WRONG_PROPERTY_TYPE; - return std::vector{}; + return {}; } return prop->enumChoices; } diff --git a/cscore/src/main/native/cpp/PropertyContainer.h b/cscore/src/main/native/cpp/PropertyContainer.h index 49edf229bd..f1c71ea6b0 100644 --- a/cscore/src/main/native/cpp/PropertyContainer.h +++ b/cscore/src/main/native/cpp/PropertyContainer.h @@ -59,13 +59,17 @@ class PropertyContainer { protected: // Get a property; must be called with m_mutex held. PropertyImpl* GetProperty(int property) { - if (property <= 0 || static_cast(property) > m_propertyData.size()) + if (property <= 0 || + static_cast(property) > m_propertyData.size()) { return nullptr; + } return m_propertyData[property - 1].get(); } const PropertyImpl* GetProperty(int property) const { - if (property <= 0 || static_cast(property) > m_propertyData.size()) + if (property <= 0 || + static_cast(property) > m_propertyData.size()) { return nullptr; + } return m_propertyData[property - 1].get(); } // Create or update a property; must be called with m_mutex held. diff --git a/cscore/src/main/native/cpp/PropertyImpl.cpp b/cscore/src/main/native/cpp/PropertyImpl.cpp index b1b01d47f6..68977235d1 100644 --- a/cscore/src/main/native/cpp/PropertyImpl.cpp +++ b/cscore/src/main/native/cpp/PropertyImpl.cpp @@ -29,15 +29,18 @@ PropertyImpl::PropertyImpl(const wpi::Twine& name_, CS_PropertyKind kind_, void PropertyImpl::SetValue(int v) { int oldValue = value; - if (hasMinimum && v < minimum) + if (hasMinimum && v < minimum) { value = minimum; - else if (hasMaximum && v > maximum) + } else if (hasMaximum && v > maximum) { value = maximum; - else + } else { value = v; + } bool wasValueSet = valueSet; valueSet = true; - if (!wasValueSet || value != oldValue) changed(); + if (!wasValueSet || value != oldValue) { + changed(); + } } void PropertyImpl::SetValue(const wpi::Twine& v) { @@ -49,14 +52,17 @@ void PropertyImpl::SetValue(const wpi::Twine& v) { } bool wasValueSet = valueSet; valueSet = true; - if (!wasValueSet || valueChanged) changed(); + if (!wasValueSet || valueChanged) { + changed(); + } } void PropertyImpl::SetDefaultValue(int v) { - if (hasMinimum && v < minimum) + if (hasMinimum && v < minimum) { defaultValue = minimum; - else if (hasMaximum && v > maximum) + } else if (hasMaximum && v > maximum) { defaultValue = maximum; - else + } else { defaultValue = v; + } } diff --git a/cscore/src/main/native/cpp/RawSinkImpl.cpp b/cscore/src/main/native/cpp/RawSinkImpl.cpp index 52a3598e60..4dbe7818a0 100644 --- a/cscore/src/main/native/cpp/RawSinkImpl.cpp +++ b/cscore/src/main/native/cpp/RawSinkImpl.cpp @@ -22,16 +22,22 @@ RawSinkImpl::RawSinkImpl(const wpi::Twine& name, wpi::Logger& logger, std::function processFrame) : SinkImpl{name, logger, notifier, telemetry} {} -RawSinkImpl::~RawSinkImpl() { Stop(); } +RawSinkImpl::~RawSinkImpl() { + Stop(); +} void RawSinkImpl::Stop() { m_active = false; // wake up any waiters by forcing an empty frame to be sent - if (auto source = GetSource()) source->Wakeup(); + if (auto source = GetSource()) { + source->Wakeup(); + } // join thread - if (m_thread.joinable()) m_thread.join(); + if (m_thread.joinable()) { + m_thread.join(); + } } uint64_t RawSinkImpl::GrabFrame(CS_RawFrame& image) { @@ -123,7 +129,9 @@ void RawSinkImpl::ThreadMain() { } SDEBUG4("waiting for frame"); Frame frame = source->GetNextFrame(); // blocks - if (!m_active) break; + if (!m_active) { + break; + } if (!frame) { // Bad frame; sleep for 10 ms so we don't consume all processor time. std::this_thread::sleep_for(std::chrono::milliseconds(10)); diff --git a/cscore/src/main/native/cpp/SinkImpl.cpp b/cscore/src/main/native/cpp/SinkImpl.cpp index 4ccd314946..a092cb7d59 100644 --- a/cscore/src/main/native/cpp/SinkImpl.cpp +++ b/cscore/src/main/native/cpp/SinkImpl.cpp @@ -21,7 +21,9 @@ SinkImpl::SinkImpl(const wpi::Twine& name, wpi::Logger& logger, SinkImpl::~SinkImpl() { if (m_source) { - if (m_enabledCount > 0) m_source->DisableSink(); + if (m_enabledCount > 0) { + m_source->DisableSink(); + } m_source->RemoveSink(); } } @@ -41,7 +43,9 @@ void SinkImpl::Enable() { std::scoped_lock lock(m_mutex); ++m_enabledCount; if (m_enabledCount == 1) { - if (m_source) m_source->EnableSink(); + if (m_source) { + m_source->EnableSink(); + } m_notifier.NotifySink(*this, CS_SINK_ENABLED); } } @@ -50,7 +54,9 @@ void SinkImpl::Disable() { std::scoped_lock lock(m_mutex); --m_enabledCount; if (m_enabledCount == 0) { - if (m_source) m_source->DisableSink(); + if (m_source) { + m_source->DisableSink(); + } m_notifier.NotifySink(*this, CS_SINK_DISABLED); } } @@ -58,11 +64,15 @@ void SinkImpl::Disable() { void SinkImpl::SetEnabled(bool enabled) { std::scoped_lock lock(m_mutex); if (enabled && m_enabledCount == 0) { - if (m_source) m_source->EnableSink(); + if (m_source) { + m_source->EnableSink(); + } m_enabledCount = 1; m_notifier.NotifySink(*this, CS_SINK_ENABLED); } else if (!enabled && m_enabledCount > 0) { - if (m_source) m_source->DisableSink(); + if (m_source) { + m_source->DisableSink(); + } m_enabledCount = 0; m_notifier.NotifySink(*this, CS_SINK_DISABLED); } @@ -71,15 +81,21 @@ void SinkImpl::SetEnabled(bool enabled) { void SinkImpl::SetSource(std::shared_ptr source) { { std::scoped_lock lock(m_mutex); - if (m_source == source) return; + if (m_source == source) { + return; + } if (m_source) { - if (m_enabledCount > 0) m_source->DisableSink(); + if (m_enabledCount > 0) { + m_source->DisableSink(); + } m_source->RemoveSink(); } m_source = source; if (m_source) { m_source->AddSink(); - if (m_enabledCount > 0) m_source->EnableSink(); + if (m_enabledCount > 0) { + m_source->EnableSink(); + } } } SetSourceImpl(source); @@ -87,13 +103,17 @@ void SinkImpl::SetSource(std::shared_ptr source) { std::string SinkImpl::GetError() const { std::scoped_lock lock(m_mutex); - if (!m_source) return "no source connected"; + if (!m_source) { + return "no source connected"; + } return m_source->GetCurFrame().GetError(); } wpi::StringRef SinkImpl::GetError(wpi::SmallVectorImpl& buf) const { std::scoped_lock lock(m_mutex); - if (!m_source) return "no source connected"; + if (!m_source) { + return "no source connected"; + } // Make a copy as it's shared data wpi::StringRef error = m_source->GetCurFrame().GetError(); buf.clear(); @@ -115,8 +135,9 @@ bool SinkImpl::SetConfigJson(wpi::StringRef config, CS_Status* status) { } bool SinkImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { - if (config.count("properties") != 0) + if (config.count("properties") != 0) { SetPropertiesJson(config.at("properties"), m_logger, GetName(), status); + } return true; } @@ -133,7 +154,9 @@ wpi::json SinkImpl::GetConfigJsonObject(CS_Status* status) { wpi::json j; wpi::json props = GetPropertiesJsonObject(status); - if (props.is_array()) j.emplace("properties", props); + if (props.is_array()) { + j.emplace("properties", props); + } return j; } @@ -143,21 +166,25 @@ void SinkImpl::NotifyPropertyCreated(int propIndex, PropertyImpl& prop) { propIndex, prop.propKind, prop.value, prop.valueStr); // also notify choices updated event for enum types - if (prop.propKind == CS_PROP_ENUM) + if (prop.propKind == CS_PROP_ENUM) { m_notifier.NotifySinkProperty(*this, CS_SINK_PROPERTY_CHOICES_UPDATED, prop.name, propIndex, prop.propKind, prop.value, wpi::Twine{}); + } } void SinkImpl::UpdatePropertyValue(int property, bool setString, int value, const wpi::Twine& valueStr) { auto prop = GetProperty(property); - if (!prop) return; + if (!prop) { + return; + } - if (setString) + if (setString) { prop->SetValue(valueStr); - else + } else { prop->SetValue(value); + } // Only notify updates after we've notified created if (m_properties_cached) { diff --git a/cscore/src/main/native/cpp/SourceImpl.cpp b/cscore/src/main/native/cpp/SourceImpl.cpp index 9b0e8aa3cf..b764555d9d 100644 --- a/cscore/src/main/native/cpp/SourceImpl.cpp +++ b/cscore/src/main/native/cpp/SourceImpl.cpp @@ -54,10 +54,11 @@ wpi::StringRef SourceImpl::GetDescription( void SourceImpl::SetConnected(bool connected) { bool wasConnected = m_connected.exchange(connected); - if (wasConnected && !connected) + if (wasConnected && !connected) { m_notifier.NotifySource(*this, CS_SOURCE_DISCONNECTED); - else if (!wasConnected && connected) + } else if (!wasConnected && connected) { m_notifier.NotifySource(*this, CS_SOURCE_CONNECTED); + } } uint64_t SourceImpl::GetCurFrameTime() { @@ -130,7 +131,9 @@ void SourceImpl::SetExposureManual(int value, CS_Status* status) { } VideoMode SourceImpl::GetVideoMode(CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) return VideoMode{}; + if (!m_properties_cached && !CacheProperties(status)) { + return {}; + } std::scoped_lock lock(m_mutex); return m_mode; } @@ -138,14 +141,18 @@ VideoMode SourceImpl::GetVideoMode(CS_Status* status) const { bool SourceImpl::SetPixelFormat(VideoMode::PixelFormat pixelFormat, CS_Status* status) { auto mode = GetVideoMode(status); - if (!mode) return false; + if (!mode) { + return false; + } mode.pixelFormat = pixelFormat; return SetVideoMode(mode, status); } bool SourceImpl::SetResolution(int width, int height, CS_Status* status) { auto mode = GetVideoMode(status); - if (!mode) return false; + if (!mode) { + return false; + } mode.width = width; mode.height = height; return SetVideoMode(mode, status); @@ -153,7 +160,9 @@ bool SourceImpl::SetResolution(int width, int height, CS_Status* status) { bool SourceImpl::SetFPS(int fps, CS_Status* status) { auto mode = GetVideoMode(status); - if (!mode) return false; + if (!mode) { + return false; + } mode.fps = fps; return SetVideoMode(mode, status); } @@ -315,8 +324,9 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { } // properties - if (config.count("properties") != 0) + if (config.count("properties") != 0) { SetPropertiesJson(config.at("properties"), m_logger, GetName(), status); + } return true; } @@ -353,30 +363,41 @@ wpi::json SourceImpl::GetConfigJsonObject(CS_Status* status) { default: break; } - if (!pixelFormat.empty()) j.emplace("pixel format", pixelFormat); + if (!pixelFormat.empty()) { + j.emplace("pixel format", pixelFormat); + } // width - if (m_mode.width != 0) j.emplace("width", m_mode.width); + if (m_mode.width != 0) { + j.emplace("width", m_mode.width); + } // height - if (m_mode.height != 0) j.emplace("height", m_mode.height); + if (m_mode.height != 0) { + j.emplace("height", m_mode.height); + } // fps - if (m_mode.fps != 0) j.emplace("fps", m_mode.fps); + if (m_mode.fps != 0) { + j.emplace("fps", m_mode.fps); + } // TODO: output brightness, white balance, and exposure? // properties wpi::json props = GetPropertiesJsonObject(status); - if (props.is_array()) j.emplace("properties", props); + if (props.is_array()) { + j.emplace("properties", props); + } return j; } std::vector SourceImpl::EnumerateVideoModes( CS_Status* status) const { - if (!m_properties_cached && !CacheProperties(status)) - return std::vector{}; + if (!m_properties_cached && !CacheProperties(status)) { + return {}; + } std::scoped_lock lock(m_mutex); return m_videoModes; } @@ -401,10 +422,11 @@ std::unique_ptr SourceImpl::AllocImage( } // if nothing found, allocate a new buffer - if (found < 0) + if (found < 0) { image.reset(new Image{size}); - else + } else { image = std::move(m_imagesAvail[found]); + } } // Initialize image @@ -461,21 +483,25 @@ void SourceImpl::NotifyPropertyCreated(int propIndex, PropertyImpl& prop) { propIndex, prop.propKind, prop.value, prop.valueStr); // also notify choices updated event for enum types - if (prop.propKind == CS_PROP_ENUM) + if (prop.propKind == CS_PROP_ENUM) { m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CHOICES_UPDATED, prop.name, propIndex, prop.propKind, prop.value, wpi::Twine{}); + } } void SourceImpl::UpdatePropertyValue(int property, bool setString, int value, const wpi::Twine& valueStr) { auto prop = GetProperty(property); - if (!prop) return; + if (!prop) { + return; + } - if (setString) + if (setString) { prop->SetValue(valueStr); - else + } else { prop->SetValue(value); + } // Only notify updates after we've notified created if (m_properties_cached) { @@ -487,7 +513,9 @@ void SourceImpl::UpdatePropertyValue(int property, bool setString, int value, void SourceImpl::ReleaseImage(std::unique_ptr image) { std::scoped_lock lock{m_poolMutex}; - if (m_destroyFrames) return; + if (m_destroyFrames) { + return; + } // Return the frame to the pool. First try to find an empty slot, otherwise // add it to the end. auto it = std::find(m_imagesAvail.begin(), m_imagesAvail.end(), nullptr); @@ -501,7 +529,9 @@ void SourceImpl::ReleaseImage(std::unique_ptr image) { [](const std::unique_ptr& a, const std::unique_ptr& b) { return a->capacity() < b->capacity(); }); - if ((*it2)->capacity() < image->capacity()) *it2 = std::move(image); + if ((*it2)->capacity() < image->capacity()) { + *it2 = std::move(image); + } } else { m_imagesAvail.emplace_back(std::move(image)); } @@ -510,7 +540,9 @@ void SourceImpl::ReleaseImage(std::unique_ptr image) { std::unique_ptr SourceImpl::AllocFrameImpl() { std::scoped_lock lock{m_poolMutex}; - if (m_framesAvail.empty()) return std::make_unique(*this); + if (m_framesAvail.empty()) { + return std::make_unique(*this); + } auto impl = std::move(m_framesAvail.back()); m_framesAvail.pop_back(); @@ -519,6 +551,8 @@ std::unique_ptr SourceImpl::AllocFrameImpl() { void SourceImpl::ReleaseFrameImpl(std::unique_ptr impl) { std::scoped_lock lock{m_poolMutex}; - if (m_destroyFrames) return; + if (m_destroyFrames) { + return; + } m_framesAvail.push_back(std::move(impl)); } diff --git a/cscore/src/main/native/cpp/Telemetry.cpp b/cscore/src/main/native/cpp/Telemetry.cpp index 6c270a2d19..de5168d19a 100644 --- a/cscore/src/main/native/cpp/Telemetry.cpp +++ b/cscore/src/main/native/cpp/Telemetry.cpp @@ -45,22 +45,31 @@ int64_t Telemetry::Thread::GetValue(CS_Handle handle, CS_TelemetryKind kind, Telemetry::~Telemetry() {} -void Telemetry::Start() { m_owner.Start(m_notifier); } +void Telemetry::Start() { + m_owner.Start(m_notifier); +} -void Telemetry::Stop() { m_owner.Stop(); } +void Telemetry::Stop() { + m_owner.Stop(); +} void Telemetry::Thread::Main() { std::unique_lock lock(m_mutex); auto prevTime = std::chrono::steady_clock::now(); while (m_active) { double period = m_period; - if (period == 0) period = 1000.0; + if (period == 0) { + period = 1000.0; + } auto timeoutTime = prevTime + std::chrono::duration(period); while (m_active && !m_updated) { - if (m_cond.wait_until(lock, timeoutTime) == std::cv_status::timeout) + if (m_cond.wait_until(lock, timeoutTime) == std::cv_status::timeout) { break; + } + } + if (!m_active) { + break; } - if (!m_active) break; if (m_updated) { m_updated = false; continue; @@ -80,8 +89,12 @@ void Telemetry::Thread::Main() { void Telemetry::SetPeriod(double seconds) { auto thr = m_owner.GetThread(); - if (!thr) return; - if (thr->m_period == seconds) return; // no change + if (!thr) { + return; + } + if (thr->m_period == seconds) { + return; // no change + } thr->m_period = seconds; thr->m_updated = true; thr->m_cond.notify_one(); @@ -89,7 +102,9 @@ void Telemetry::SetPeriod(double seconds) { double Telemetry::GetElapsedTime() { auto thr = m_owner.GetThread(); - if (!thr) return 0; + if (!thr) { + return 0; + } return thr->m_elapsed; } @@ -110,13 +125,17 @@ double Telemetry::GetAverageValue(CS_Handle handle, CS_TelemetryKind kind, *status = CS_TELEMETRY_NOT_ENABLED; return 0; } - if (thr->m_elapsed == 0) return 0.0; + if (thr->m_elapsed == 0) { + return 0.0; + } return thr->GetValue(handle, kind, status) / thr->m_elapsed; } void Telemetry::RecordSourceBytes(const SourceImpl& source, int quantity) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } auto handleData = Instance::GetInstance().FindSource(source); thr->m_current[std::make_pair(Handle{handleData.first, Handle::kSource}, static_cast(CS_SOURCE_BYTES_RECEIVED))] += @@ -125,7 +144,9 @@ void Telemetry::RecordSourceBytes(const SourceImpl& source, int quantity) { void Telemetry::RecordSourceFrames(const SourceImpl& source, int quantity) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } auto handleData = Instance::GetInstance().FindSource(source); thr->m_current[std::make_pair(Handle{handleData.first, Handle::kSource}, static_cast(CS_SOURCE_FRAMES_RECEIVED))] += diff --git a/cscore/src/main/native/cpp/UnlimitedHandleResource.h b/cscore/src/main/native/cpp/UnlimitedHandleResource.h index 20fdc9b609..cba6399b53 100644 --- a/cscore/src/main/native/cpp/UnlimitedHandleResource.h +++ b/cscore/src/main/native/cpp/UnlimitedHandleResource.h @@ -87,7 +87,9 @@ THandle UnlimitedHandleResource::Allocate( return MakeHandle(i); } } - if (i >= THandle::kIndexMax) return 0; + if (i >= THandle::kIndexMax) { + return 0; + } m_structures.emplace_back( std::make_shared(std::forward(args)...)); @@ -105,7 +107,9 @@ THandle UnlimitedHandleResource::Allocate( return MakeHandle(i); } } - if (i >= THandle::kIndexMax) return 0; + if (i >= THandle::kIndexMax) { + return 0; + } m_structures.push_back(structure); return MakeHandle(i); @@ -117,9 +121,13 @@ UnlimitedHandleResource::Get( THandle handle) { auto index = handle.GetTypedIndex(static_cast(typeValue)); - if (index < 0) return nullptr; + if (index < 0) { + return nullptr; + } std::scoped_lock sync(m_handleMutex); - if (index >= static_cast(m_structures.size())) return nullptr; + if (index >= static_cast(m_structures.size())) { + return nullptr; + } return m_structures[index]; } @@ -129,9 +137,13 @@ UnlimitedHandleResource::Free( THandle handle) { auto index = handle.GetTypedIndex(static_cast(typeValue)); - if (index < 0) return nullptr; + if (index < 0) { + return nullptr; + } std::scoped_lock sync(m_handleMutex); - if (index >= static_cast(m_structures.size())) return nullptr; + if (index >= static_cast(m_structures.size())) { + return nullptr; + } auto rv = std::move(m_structures[index]); m_structures[index].reset(); return rv; @@ -161,7 +173,9 @@ inline void UnlimitedHandleResource::ForEach(F func) { std::scoped_lock sync(m_handleMutex); for (size_t i = 0; i < m_structures.size(); i++) { - if (m_structures[i] != nullptr) func(MakeHandle(i), *(m_structures[i])); + if (m_structures[i] != nullptr) { + func(MakeHandle(i), *(m_structures[i])); + } } } @@ -172,8 +186,9 @@ UnlimitedHandleResource::FindIf(F func) { std::scoped_lock sync(m_handleMutex); for (size_t i = 0; i < m_structures.size(); i++) { auto& structure = m_structures[i]; - if (structure != nullptr && func(*structure)) + if (structure != nullptr && func(*structure)) { return std::make_pair(MakeHandle(i), structure); + } } return std::make_pair(0, nullptr); } diff --git a/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp b/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp index 78695fb697..5731f1f1b6 100644 --- a/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp +++ b/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp @@ -16,8 +16,9 @@ static void ConvertToC(CS_UsbCameraInfo* out, const UsbCameraInfo& in) { out->otherPaths = static_cast( wpi::safe_malloc(in.otherPaths.size() * sizeof(char*))); out->otherPathsCount = in.otherPaths.size(); - for (size_t i = 0; i < in.otherPaths.size(); ++i) + for (size_t i = 0; i < in.otherPaths.size(); ++i) { out->otherPaths[i] = cs::ConvertToC(in.otherPaths[i]); + } out->vendorId = in.vendorId; out->productId = in.productId; } @@ -25,8 +26,9 @@ static void ConvertToC(CS_UsbCameraInfo* out, const UsbCameraInfo& in) { static void FreeUsbCameraInfo(CS_UsbCameraInfo* info) { std::free(info->path); std::free(info->name); - for (int i = 0; i < info->otherPathsCount; ++i) + for (int i = 0; i < info->otherPathsCount; ++i) { std::free(info->otherPaths[i]); + } std::free(info->otherPaths); } @@ -52,7 +54,9 @@ char* CS_GetUsbCameraPath(CS_Source source, CS_Status* status) { CS_UsbCameraInfo* CS_GetUsbCameraInfo(CS_Source source, CS_Status* status) { auto info = cs::GetUsbCameraInfo(source, status); - if (*status != CS_OK) return nullptr; + if (*status != CS_OK) { + return nullptr; + } CS_UsbCameraInfo* out = static_cast( wpi::safe_malloc(sizeof(CS_UsbCameraInfo))); ConvertToC(out, info); @@ -64,18 +68,26 @@ CS_UsbCameraInfo* CS_EnumerateUsbCameras(int* count, CS_Status* status) { CS_UsbCameraInfo* out = static_cast( wpi::safe_malloc(cameras.size() * sizeof(CS_UsbCameraInfo))); *count = cameras.size(); - for (size_t i = 0; i < cameras.size(); ++i) ConvertToC(&out[i], cameras[i]); + for (size_t i = 0; i < cameras.size(); ++i) { + ConvertToC(&out[i], cameras[i]); + } return out; } void CS_FreeEnumeratedUsbCameras(CS_UsbCameraInfo* cameras, int count) { - if (!cameras) return; - for (int i = 0; i < count; ++i) FreeUsbCameraInfo(&cameras[i]); + if (!cameras) { + return; + } + for (int i = 0; i < count; ++i) { + FreeUsbCameraInfo(&cameras[i]); + } std::free(cameras); } void CS_FreeUsbCameraInfo(CS_UsbCameraInfo* info) { - if (!info) return; + if (!info) { + return; + } FreeUsbCameraInfo(info); std::free(info); } diff --git a/cscore/src/main/native/cpp/cscore_c.cpp b/cscore/src/main/native/cpp/cscore_c.cpp index 3d2a04bc14..a0e35cfc94 100644 --- a/cscore/src/main/native/cpp/cscore_c.cpp +++ b/cscore/src/main/native/cpp/cscore_c.cpp @@ -24,7 +24,9 @@ CS_PropertyKind CS_GetPropertyKind(CS_Property property, CS_Status* status) { char* CS_GetPropertyName(CS_Property property, CS_Status* status) { wpi::SmallString<128> buf; auto str = cs::GetPropertyName(property, buf, status); - if (*status != 0) return nullptr; + if (*status != 0) { + return nullptr; + } return cs::ConvertToC(str); } @@ -55,7 +57,9 @@ int CS_GetPropertyDefault(CS_Property property, CS_Status* status) { char* CS_GetStringProperty(CS_Property property, CS_Status* status) { wpi::SmallString<128> buf; auto str = cs::GetStringProperty(property, buf, status); - if (*status != 0) return nullptr; + if (*status != 0) { + return nullptr; + } return cs::ConvertToC(str); } @@ -70,8 +74,9 @@ char** CS_GetEnumPropertyChoices(CS_Property property, int* count, char** out = static_cast(wpi::safe_malloc(choices.size() * sizeof(char*))); *count = choices.size(); - for (size_t i = 0; i < choices.size(); ++i) + for (size_t i = 0; i < choices.size(); ++i) { out[i] = cs::ConvertToC(choices[i]); + } return out; } @@ -82,14 +87,18 @@ CS_SourceKind CS_GetSourceKind(CS_Source source, CS_Status* status) { char* CS_GetSourceName(CS_Source source, CS_Status* status) { wpi::SmallString<128> buf; auto str = cs::GetSourceName(source, buf, status); - if (*status != 0) return nullptr; + if (*status != 0) { + return nullptr; + } return cs::ConvertToC(str); } char* CS_GetSourceDescription(CS_Source source, CS_Status* status) { wpi::SmallString<128> buf; auto str = cs::GetSourceDescription(source, buf, status); - if (*status != 0) return nullptr; + if (*status != 0) { + return nullptr; + } return cs::ConvertToC(str); } @@ -248,14 +257,18 @@ CS_SinkKind CS_GetSinkKind(CS_Sink sink, CS_Status* status) { char* CS_GetSinkName(CS_Sink sink, CS_Status* status) { wpi::SmallString<128> buf; auto str = cs::GetSinkName(sink, buf, status); - if (*status != 0) return nullptr; + if (*status != 0) { + return nullptr; + } return cs::ConvertToC(str); } char* CS_GetSinkDescription(CS_Sink sink, CS_Status* status) { wpi::SmallString<128> buf; auto str = cs::GetSinkDescription(sink, buf, status); - if (*status != 0) return nullptr; + if (*status != 0) { + return nullptr; + } return cs::ConvertToC(str); } @@ -338,9 +351,13 @@ void CS_RemoveListener(CS_Listener handle, CS_Status* status) { return cs::RemoveListener(handle, status); } -int CS_NotifierDestroyed(void) { return cs::NotifierDestroyed(); } +int CS_NotifierDestroyed(void) { + return cs::NotifierDestroyed(); +} -void CS_SetTelemetryPeriod(double seconds) { cs::SetTelemetryPeriod(seconds); } +void CS_SetTelemetryPeriod(double seconds) { + cs::SetTelemetryPeriod(seconds); +} double CS_GetTelemetryElapsedTime(void) { return cs::GetTelemetryElapsedTime(); @@ -364,7 +381,9 @@ void CS_SetDefaultLogger(unsigned int min_level) { cs::SetDefaultLogger(min_level); } -void CS_Shutdown(void) { cs::Shutdown(); } +void CS_Shutdown(void) { + cs::Shutdown(); +} CS_Source* CS_EnumerateSources(int* count, CS_Status* status) { wpi::SmallVector buf; @@ -377,10 +396,14 @@ CS_Source* CS_EnumerateSources(int* count, CS_Status* status) { } void CS_ReleaseEnumeratedSources(CS_Source* sources, int count) { - if (!sources) return; + if (!sources) { + return; + } for (int i = 0; i < count; ++i) { CS_Status status = 0; - if (sources[i] != 0) cs::ReleaseSource(sources[i], &status); + if (sources[i] != 0) { + cs::ReleaseSource(sources[i], &status); + } } std::free(sources); } @@ -396,19 +419,29 @@ CS_Sink* CS_EnumerateSinks(int* count, CS_Status* status) { } void CS_ReleaseEnumeratedSinks(CS_Sink* sinks, int count) { - if (!sinks) return; + if (!sinks) { + return; + } for (int i = 0; i < count; ++i) { CS_Status status = 0; - if (sinks[i] != 0) cs::ReleaseSink(sinks[i], &status); + if (sinks[i] != 0) { + cs::ReleaseSink(sinks[i], &status); + } } std::free(sinks); } -void CS_FreeString(char* str) { std::free(str); } +void CS_FreeString(char* str) { + std::free(str); +} void CS_FreeEnumPropertyChoices(char** choices, int count) { - if (!choices) return; - for (int i = 0; i < count; ++i) std::free(choices[i]); + if (!choices) { + return; + } + for (int i = 0; i < count; ++i) { + std::free(choices[i]); + } std::free(choices); } @@ -420,26 +453,35 @@ void CS_FreeEnumeratedVideoModes(CS_VideoMode* modes, int count) { std::free(modes); } -char* CS_GetHostname() { return cs::ConvertToC(cs::GetHostname()); } +char* CS_GetHostname() { + return cs::ConvertToC(cs::GetHostname()); +} char** CS_GetNetworkInterfaces(int* count) { auto interfaces = cs::GetNetworkInterfaces(); char** out = static_cast(wpi::safe_malloc(interfaces.size() * sizeof(char*))); *count = interfaces.size(); - for (size_t i = 0; i < interfaces.size(); ++i) + for (size_t i = 0; i < interfaces.size(); ++i) { out[i] = cs::ConvertToC(interfaces[i]); + } return out; } void CS_FreeNetworkInterfaces(char** interfaces, int count) { - if (!interfaces) return; - for (int i = 0; i < count; ++i) std::free(interfaces[i]); + if (!interfaces) { + return; + } + for (int i = 0; i < count; ++i) { + std::free(interfaces[i]); + } std::free(interfaces); } void CS_AllocateRawFrameData(CS_RawFrame* frame, int requestedSize) { - if (frame->dataLength >= requestedSize) return; + if (frame->dataLength >= requestedSize) { + return; + } if (frame->data) { frame->data = static_cast(wpi::safe_realloc(frame->data, requestedSize)); diff --git a/cscore/src/main/native/cpp/cscore_cpp.cpp b/cscore/src/main/native/cpp/cscore_cpp.cpp index e4b86e38e8..6cbfda2741 100644 --- a/cscore/src/main/native/cpp/cscore_cpp.cpp +++ b/cscore/src/main/native/cpp/cscore_cpp.cpp @@ -57,7 +57,9 @@ namespace cs { CS_PropertyKind GetPropertyKind(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return CS_PROP_NONE; + if (!container) { + return CS_PROP_NONE; + } return container->GetPropertyKind(propertyIndex); } @@ -65,7 +67,9 @@ std::string GetPropertyName(CS_Property property, CS_Status* status) { wpi::SmallString<128> buf; int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return std::string{}; + if (!container) { + return {}; + } return container->GetPropertyName(propertyIndex, buf, status); } @@ -74,49 +78,63 @@ wpi::StringRef GetPropertyName(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return wpi::StringRef{}; + if (!container) { + return {}; + } return container->GetPropertyName(propertyIndex, buf, status); } int GetProperty(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return false; + if (!container) { + return false; + } return container->GetProperty(propertyIndex, status); } void SetProperty(CS_Property property, int value, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return; + if (!container) { + return; + } container->SetProperty(propertyIndex, value, status); } int GetPropertyMin(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return 0.0; + if (!container) { + return 0.0; + } return container->GetPropertyMin(propertyIndex, status); } int GetPropertyMax(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return 0.0; + if (!container) { + return 0.0; + } return container->GetPropertyMax(propertyIndex, status); } int GetPropertyStep(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return 0.0; + if (!container) { + return 0.0; + } return container->GetPropertyStep(propertyIndex, status); } int GetPropertyDefault(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return 0.0; + if (!container) { + return 0.0; + } return container->GetPropertyDefault(propertyIndex, status); } @@ -124,7 +142,9 @@ std::string GetStringProperty(CS_Property property, CS_Status* status) { wpi::SmallString<128> buf; int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return std::string{}; + if (!container) { + return {}; + } return container->GetStringProperty(propertyIndex, buf, status); } @@ -133,7 +153,9 @@ wpi::StringRef GetStringProperty(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return wpi::StringRef{}; + if (!container) { + return {}; + } return container->GetStringProperty(propertyIndex, buf, status); } @@ -141,7 +163,9 @@ void SetStringProperty(CS_Property property, const wpi::Twine& value, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return; + if (!container) { + return; + } container->SetStringProperty(propertyIndex, value, status); } @@ -149,7 +173,9 @@ std::vector GetEnumPropertyChoices(CS_Property property, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); - if (!container) return std::vector{}; + if (!container) { + return {}; + } return container->GetEnumPropertyChoices(propertyIndex, status); } @@ -269,8 +295,9 @@ wpi::ArrayRef EnumerateSourceProperties( } wpi::SmallVector properties_buf; for (auto property : - data->source->EnumerateProperties(properties_buf, status)) + data->source->EnumerateProperties(properties_buf, status)) { vec.push_back(Handle{source, property, Handle::kProperty}); + } return vec; } @@ -383,7 +410,9 @@ wpi::ArrayRef EnumerateSourceSinks(CS_Source source, } CS_Source CopySource(CS_Source source, CS_Status* status) { - if (source == 0) return 0; + if (source == 0) { + return 0; + } auto data = Instance::GetInstance().GetSource(source); if (!data) { *status = CS_INVALID_HANDLE; @@ -394,14 +423,18 @@ CS_Source CopySource(CS_Source source, CS_Status* status) { } void ReleaseSource(CS_Source source, CS_Status* status) { - if (source == 0) return; + if (source == 0) { + return; + } auto& inst = Instance::GetInstance(); auto data = inst.GetSource(source); if (!data) { *status = CS_INVALID_HANDLE; return; } - if (data->refCount-- == 0) inst.DestroySource(source); + if (data->refCount-- == 0) { + inst.DestroySource(source); + } } // @@ -556,8 +589,10 @@ wpi::ArrayRef EnumerateSinkProperties( return 0; } wpi::SmallVector properties_buf; - for (auto property : data->sink->EnumerateProperties(properties_buf, status)) + for (auto property : + data->sink->EnumerateProperties(properties_buf, status)) { vec.push_back(Handle{sink, property, Handle::kSinkProperty}); + } return vec; } @@ -639,7 +674,9 @@ CS_Property GetSinkSourceProperty(CS_Sink sink, const wpi::Twine& name, } CS_Sink CopySink(CS_Sink sink, CS_Status* status) { - if (sink == 0) return 0; + if (sink == 0) { + return 0; + } auto data = Instance::GetInstance().GetSink(sink); if (!data) { *status = CS_INVALID_HANDLE; @@ -650,14 +687,18 @@ CS_Sink CopySink(CS_Sink sink, CS_Status* status) { } void ReleaseSink(CS_Sink sink, CS_Status* status) { - if (sink == 0) return; + if (sink == 0) { + return; + } auto& inst = Instance::GetInstance(); auto data = inst.GetSink(sink); if (!data) { *status = CS_INVALID_HANDLE; return; } - if (data->refCount-- == 0) inst.DestroySink(sink); + if (data->refCount-- == 0) { + inst.DestroySink(sink); + } } // @@ -680,7 +721,9 @@ CS_Listener AddListener(std::function callback, if ((eventMask & CS_NETWORK_INTERFACES_CHANGED) != 0) { // start network interface event listener inst.networkListener.Start(); - if (immediateNotify) inst.notifier.NotifyNetworkInterfacesChanged(); + if (immediateNotify) { + inst.notifier.NotifyNetworkInterfacesChanged(); + } } if (immediateNotify) { // TODO @@ -697,7 +740,9 @@ void RemoveListener(CS_Listener handle, CS_Status* status) { Instance::GetInstance().notifier.RemoveListener(uid); } -bool NotifierDestroyed() { return Notifier::destroyed(); } +bool NotifierDestroyed() { + return Notifier::destroyed(); +} // // Telemetry Functions @@ -741,7 +786,9 @@ void SetDefaultLogger(unsigned int min_level) { // // Shutdown Function // -void Shutdown() { Instance::GetInstance().Shutdown(); } +void Shutdown() { + Instance::GetInstance().Shutdown(); +} // // Utility Functions @@ -757,6 +804,8 @@ wpi::ArrayRef EnumerateSinkHandles(wpi::SmallVectorImpl& vec, return Instance::GetInstance().EnumerateSinkHandles(vec); } -std::string GetHostname() { return wpi::GetHostname(); } +std::string GetHostname() { + return wpi::GetHostname(); +} } // namespace cs diff --git a/cscore/src/main/native/cpp/cscore_oo.cpp b/cscore/src/main/native/cpp/cscore_oo.cpp index 40f1018b69..86e549074f 100644 --- a/cscore/src/main/native/cpp/cscore_oo.cpp +++ b/cscore/src/main/native/cpp/cscore_oo.cpp @@ -25,8 +25,9 @@ std::vector VideoSource::EnumerateProperties() const { std::vector properties; properties.reserve(handles.size()); - for (CS_Property handle : handles) + for (CS_Property handle : handles) { properties.emplace_back(VideoProperty{handle}); + } return properties; } @@ -37,7 +38,9 @@ std::vector VideoSource::EnumerateSinks() { std::vector sinks; sinks.reserve(handles.size()); - for (int handle : handles) sinks.emplace_back(VideoSink{handle}); + for (int handle : handles) { + sinks.emplace_back(VideoSink{handle}); + } return sinks; } @@ -48,7 +51,9 @@ std::vector VideoSource::EnumerateSources() { std::vector sources; sources.reserve(handles.size()); - for (int handle : handles) sources.emplace_back(VideoSource{handle}); + for (int handle : handles) { + sources.emplace_back(VideoSource{handle}); + } return sources; } @@ -59,8 +64,9 @@ std::vector VideoSink::EnumerateProperties() const { std::vector properties; properties.reserve(handles.size()); - for (CS_Property handle : handles) + for (CS_Property handle : handles) { properties.emplace_back(VideoProperty{handle}); + } return properties; } @@ -71,6 +77,8 @@ std::vector VideoSink::EnumerateSinks() { std::vector sinks; sinks.reserve(handles.size()); - for (int handle : handles) sinks.emplace_back(VideoSink{handle}); + for (int handle : handles) { + sinks.emplace_back(VideoSink{handle}); + } return sinks; } diff --git a/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp b/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp index 60c7ca132b..ef62f79070 100644 --- a/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp +++ b/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp @@ -50,22 +50,29 @@ static const JExceptionInit exceptions[] = { {"java/lang/Exception", &exceptionEx}}; static void ListenerOnStart() { - if (!jvm) return; + if (!jvm) { + return; + } JNIEnv* env; JavaVMAttachArgs args; args.version = JNI_VERSION_1_2; args.name = const_cast("CSListener"); args.group = nullptr; if (jvm->AttachCurrentThreadAsDaemon(reinterpret_cast(&env), &args) != - JNI_OK) + JNI_OK) { return; - if (!env || !env->functions) return; + } + if (!env || !env->functions) { + return; + } listenerEnv = env; } static void ListenerOnExit() { listenerEnv = nullptr; - if (!jvm) return; + if (!jvm) { + return; + } jvm->DetachCurrentThread(); } @@ -89,7 +96,9 @@ static void ThrowJavaException(JNIEnv* env, const std::exception* e) { what = "unknown exception"; } - if (!je) je = exceptionEx; + if (!je) { + je = exceptionEx; + } env->ThrowNew(je, what.c_str()); } @@ -99,18 +108,23 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { jvm = vm; JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; + } // Cache references to classes for (auto& c : classes) { *c.cls = JClass(env, c.name); - if (!*c.cls) return JNI_ERR; + if (!*c.cls) { + return JNI_ERR; + } } for (auto& c : exceptions) { *c.cls = JException(env, c.name); - if (!*c.cls) return JNI_ERR; + if (!*c.cls) { + return JNI_ERR; + } } // Initial configuration of listener start/exit @@ -124,8 +138,9 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) { cs::Shutdown(); JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return; + } // Delete global references for (auto& c : classes) { c.cls->free(env); @@ -147,20 +162,27 @@ class JCSGlobal { JCSGlobal(JNIEnv* env, T obj) : m_obj(static_cast(env->NewGlobalRef(obj))) {} ~JCSGlobal() { - if (!jvm || cs::NotifierDestroyed()) return; + if (!jvm || cs::NotifierDestroyed()) { + return; + } JNIEnv* env; bool attached = false; // don't attach and de-attach if already attached to a thread. if (jvm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) == JNI_EDETACHED) { if (jvm->AttachCurrentThread(reinterpret_cast(&env), nullptr) != - JNI_OK) + JNI_OK) { return; + } attached = true; } - if (!env || !env->functions) return; + if (!env || !env->functions) { + return; + } env->DeleteGlobalRef(m_obj); - if (attached) jvm->DetachCurrentThread(); + if (attached) { + jvm->DetachCurrentThread(); + } } operator T() { return m_obj; } T obj() { return m_obj; } @@ -170,7 +192,9 @@ class JCSGlobal { }; static void ReportError(JNIEnv* env, CS_Status status) { - if (status == CS_OK) return; + if (status == CS_OK) { + return; + } wpi::SmallString<64> msg; switch (status) { case CS_PROPERTY_WRITE_FAILED: @@ -213,7 +237,9 @@ static void ReportError(JNIEnv* env, CS_Status status) { } static inline bool CheckStatus(JNIEnv* env, CS_Status status) { - if (status != CS_OK) ReportError(env, status); + if (status != CS_OK) { + ReportError(env, status); + } return status == CS_OK; } @@ -293,7 +319,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getPropertyName CS_Status status = 0; wpi::SmallString<128> buf; auto str = cs::GetPropertyName(property, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -398,7 +426,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getStringProperty CS_Status status = 0; wpi::SmallString<128> buf; auto str = cs::GetStringProperty(property, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -431,7 +461,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getEnumPropertyChoices { CS_Status status = 0; auto arr = cs::GetEnumPropertyChoices(property, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJStringArray(env, arr); } @@ -617,7 +649,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getSourceName CS_Status status = 0; wpi::SmallString<128> buf; auto str = cs::GetSourceName(source, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -633,7 +667,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getSourceDescription CS_Status status = 0; wpi::SmallString<128> buf; auto str = cs::GetSourceDescription(source, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -729,7 +765,9 @@ Java_edu_wpi_cscore_CameraServerJNI_enumerateSourceProperties CS_Status status = 0; wpi::SmallVector buf; auto arr = cs::EnumerateSourceProperties(source, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJIntArray(env, arr); } @@ -744,7 +782,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getSourceVideoMode { CS_Status status = 0; auto val = cs::GetSourceVideoMode(source, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJObject(env, val); } @@ -855,9 +895,13 @@ Java_edu_wpi_cscore_CameraServerJNI_enumerateSourceVideoModes { CS_Status status = 0; auto arr = cs::EnumerateSourceVideoModes(source, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } jobjectArray jarr = env->NewObjectArray(arr.size(), videoModeCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal jelem{env, MakeJObject(env, arr[i])}; env->SetObjectArrayElement(jarr, i, jelem); @@ -877,7 +921,9 @@ Java_edu_wpi_cscore_CameraServerJNI_enumerateSourceSinks CS_Status status = 0; wpi::SmallVector buf; auto arr = cs::EnumerateSourceSinks(source, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJIntArray(env, arr); } @@ -1048,7 +1094,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getUsbCameraPath { CS_Status status = 0; auto str = cs::GetUsbCameraPath(source, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -1063,7 +1111,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getUsbCameraInfo { CS_Status status = 0; auto info = cs::GetUsbCameraInfo(source, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJObject(env, info); } @@ -1078,7 +1128,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getHttpCameraKind { CS_Status status = 0; auto kind = cs::GetHttpCameraKind(source, &status); - if (!CheckStatus(env, status)) return 0; + if (!CheckStatus(env, status)) { + return 0; + } return kind; } @@ -1123,7 +1175,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getHttpCameraUrls { CS_Status status = 0; auto arr = cs::GetHttpCameraUrls(source, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJStringArray(env, arr); } @@ -1381,7 +1435,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getSinkName CS_Status status = 0; wpi::SmallString<128> buf; auto str = cs::GetSinkName(sink, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -1397,7 +1453,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getSinkDescription CS_Status status = 0; wpi::SmallString<128> buf; auto str = cs::GetSinkDescription(sink, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -1432,7 +1490,9 @@ Java_edu_wpi_cscore_CameraServerJNI_enumerateSinkProperties CS_Status status = 0; wpi::SmallVector buf; auto arr = cs::EnumerateSinkProperties(source, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJIntArray(env, arr); } @@ -1555,7 +1615,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getMjpegServerListenAddress { CS_Status status = 0; auto str = cs::GetMjpegServerListenAddress(sink, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -1721,7 +1783,9 @@ Java_edu_wpi_cscore_CameraServerJNI_getSinkError CS_Status status = 0; wpi::SmallString<128> buf; auto str = cs::GetSinkError(sink, buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJString(env, str); } @@ -1760,17 +1824,23 @@ Java_edu_wpi_cscore_CameraServerJNI_addListener // cls is a temporary here; cannot be used within callback functor jclass cls = envouter->GetObjectClass(listener); - if (!cls) return 0; + if (!cls) { + return 0; + } // method ids, on the other hand, are safe to retain jmethodID mid = envouter->GetMethodID(cls, "accept", "(Ljava/lang/Object;)V"); - if (!mid) return 0; + if (!mid) { + return 0; + } CS_Status status = 0; CS_Listener handle = cs::AddListener( [=](const cs::RawEvent& event) { JNIEnv* env = listenerEnv; - if (!env || !env->functions) return; + if (!env || !env->functions) { + return; + } // get the handler auto handler = listener_global->obj(); @@ -1782,7 +1852,9 @@ Java_edu_wpi_cscore_CameraServerJNI_addListener env->ExceptionClear(); return; } - if (!jobj) return; + if (!jobj) { + return; + } env->CallVoidMethod(handler, mid, jobj.obj()); if (env->ExceptionCheck()) { @@ -1876,10 +1948,14 @@ Java_edu_wpi_cscore_CameraServerJNI_enumerateUsbCameras { CS_Status status = 0; auto arr = cs::EnumerateUsbCameras(&status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } jobjectArray jarr = env->NewObjectArray(arr.size(), usbCameraInfoCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal jelem{env, MakeJObject(env, arr[i])}; env->SetObjectArrayElement(jarr, i, jelem); @@ -1899,7 +1975,9 @@ Java_edu_wpi_cscore_CameraServerJNI_enumerateSources CS_Status status = 0; wpi::SmallVector buf; auto arr = cs::EnumerateSourceHandles(buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJIntArray(env, arr); } @@ -1915,7 +1993,9 @@ Java_edu_wpi_cscore_CameraServerJNI_enumerateSinks CS_Status status = 0; wpi::SmallVector buf; auto arr = cs::EnumerateSinkHandles(buf, &status); - if (!CheckStatus(env, status)) return nullptr; + if (!CheckStatus(env, status)) { + return nullptr; + } return MakeJIntArray(env, arr); } @@ -1991,12 +2071,16 @@ Java_edu_wpi_cscore_CameraServerJNI_setLogger } // cls is a temporary here; cannot be used within callback functor jclass cls = env->GetObjectClass(func); - if (!cls) return; + if (!cls) { + return; + } // method ids, on the other hand, are safe to retain jmethodID mid = env->GetMethodID(cls, "apply", "(ILjava/lang/String;ILjava/lang/String;)V"); - if (!mid) return; + if (!mid) { + return; + } auto& logger = LoggerJNI::GetInstance(); logger.Start(); diff --git a/cscore/src/main/native/include/cscore_cpp.h b/cscore/src/main/native/include/cscore_cpp.h index 03d7cf6c9a..e956ac4f3c 100644 --- a/cscore/src/main/native/include/cscore_cpp.h +++ b/cscore/src/main/native/include/cscore_cpp.h @@ -124,10 +124,11 @@ struct RawEvent { RawEvent(const wpi::Twine& name_, CS_Handle handle_, RawEvent::Kind kind_) : kind{kind_}, name{name_.str()} { if (kind_ == kSinkCreated || kind_ == kSinkDestroyed || - kind_ == kSinkEnabled || kind_ == kSinkDisabled) + kind_ == kSinkEnabled || kind_ == kSinkDisabled) { sinkHandle = handle_; - else + } else { sourceHandle = handle_; + } } RawEvent(const wpi::Twine& name_, CS_Source source_, const VideoMode& mode_) : kind{kSourceVideoModeChanged}, diff --git a/cscore/src/main/native/include/cscore_oo.inl b/cscore/src/main/native/include/cscore_oo.inl index 966a3bf2c0..7b4d818063 100644 --- a/cscore/src/main/native/include/cscore_oo.inl +++ b/cscore/src/main/native/include/cscore_oo.inl @@ -94,7 +94,8 @@ inline VideoSource& VideoSource::operator=(VideoSource other) noexcept { inline VideoSource::~VideoSource() { m_status = 0; - if (m_handle != 0) ReleaseSource(m_handle, &m_status); + if (m_handle != 0) + ReleaseSource(m_handle, &m_status); } inline VideoSource::Kind VideoSource::GetKind() const { @@ -309,7 +310,8 @@ inline HttpCamera::HttpCamera(const wpi::Twine& name, HttpCameraKind kind) { std::vector vec; vec.reserve(urls.size()); - for (const auto& url : urls) vec.emplace_back(url); + for (const auto& url : urls) + vec.emplace_back(url); m_handle = CreateHttpCamera( name, vec, static_cast(static_cast(kind)), &m_status); @@ -330,7 +332,8 @@ template inline void HttpCamera::SetUrls(std::initializer_list urls) { std::vector vec; vec.reserve(urls.size()); - for (const auto& url : urls) vec.emplace_back(url); + for (const auto& url : urls) + vec.emplace_back(url); m_status = 0; ::cs::SetHttpCameraUrls(m_handle, vec, &m_status); } @@ -457,7 +460,8 @@ inline void ImageSource::SetEnumPropertyChoices( const VideoProperty& property, std::initializer_list choices) { std::vector vec; vec.reserve(choices.size()); - for (const auto& choice : choices) vec.emplace_back(choice); + for (const auto& choice : choices) + vec.emplace_back(choice); m_status = 0; SetSourceEnumPropertyChoices(m_handle, property.m_handle, vec, &m_status); } @@ -476,7 +480,8 @@ inline VideoSink& VideoSink::operator=(VideoSink other) noexcept { inline VideoSink::~VideoSink() { m_status = 0; - if (m_handle != 0) ReleaseSink(m_handle, &m_status); + if (m_handle != 0) + ReleaseSink(m_handle, &m_status); } inline VideoSink::Kind VideoSink::GetKind() const { @@ -625,7 +630,8 @@ inline VideoListener& VideoListener::operator=(VideoListener&& other) noexcept { inline VideoListener::~VideoListener() { CS_Status status = 0; - if (m_handle != 0) RemoveListener(m_handle, &status); + if (m_handle != 0) + RemoveListener(m_handle, &status); } } // namespace cs diff --git a/cscore/src/main/native/include/cscore_raw_cv.h b/cscore/src/main/native/include/cscore_raw_cv.h index e3a72e1ad1..18690327a1 100644 --- a/cscore/src/main/native/include/cscore_raw_cv.h +++ b/cscore/src/main/native/include/cscore_raw_cv.h @@ -171,22 +171,22 @@ inline RawCvSink::RawCvSink(const wpi::Twine& name, : RawSink{name, processFrame} {} inline uint64_t RawCvSink::GrabFrame(cv::Mat& image, double timeout) { - cv::Mat tmpMat; - auto retVal = GrabFrameDirect(tmpMat); + cv::Mat tmpnam; + auto retVal = GrabFrameDirect(tmpnam); if (retVal <= 0) { return retVal; } - tmpMat.copyTo(image); + tmpnam.copyTo(image); return retVal; } inline uint64_t RawCvSink::GrabFrameNoTimeout(cv::Mat& image) { - cv::Mat tmpMat; - auto retVal = GrabFrameNoTimeoutDirect(tmpMat); + cv::Mat tmpnam; + auto retVal = GrabFrameNoTimeoutDirect(tmpnam); if (retVal <= 0) { return retVal; } - tmpMat.copyTo(image); + tmpnam.copyTo(image); return retVal; } @@ -195,7 +195,9 @@ inline uint64_t RawCvSink::GrabFrameDirect(cv::Mat& image, double timeout) { rawFrame.width = 0; rawFrame.pixelFormat = CS_PixelFormat::CS_PIXFMT_BGR; m_status = RawSink::GrabFrame(rawFrame, timeout); - if (m_status <= 0) return m_status; + if (m_status <= 0) { + return m_status; + } image = cv::Mat{rawFrame.height, rawFrame.width, CV_8UC3, rawFrame.data}; return m_status; } @@ -205,7 +207,9 @@ inline uint64_t RawCvSink::GrabFrameNoTimeoutDirect(cv::Mat& image) { rawFrame.width = 0; rawFrame.pixelFormat = CS_PixelFormat::CS_PIXFMT_BGR; m_status = RawSink::GrabFrameNoTimeout(rawFrame); - if (m_status <= 0) return m_status; + if (m_status <= 0) { + return m_status; + } image = cv::Mat{rawFrame.height, rawFrame.width, CV_8UC3, rawFrame.data}; return m_status; } diff --git a/cscore/src/main/native/linux/NetworkListener.cpp b/cscore/src/main/native/linux/NetworkListener.cpp index 064c9fb5a0..63f2070f37 100644 --- a/cscore/src/main/native/linux/NetworkListener.cpp +++ b/cscore/src/main/native/linux/NetworkListener.cpp @@ -47,7 +47,9 @@ class NetworkListener::Impl { NetworkListener::NetworkListener(wpi::Logger& logger, Notifier& notifier) : m_impl(std::make_unique(logger, notifier)) {} -NetworkListener::~NetworkListener() { Stop(); } +NetworkListener::~NetworkListener() { + Stop(); +} void NetworkListener::Start() { m_impl->m_owner.Start(m_impl->m_logger, m_impl->m_notifier); @@ -57,7 +59,9 @@ void NetworkListener::Stop() { // Wake up thread if (auto thr = m_impl->m_owner.GetThread()) { thr->m_active = false; - if (thr->m_command_fd >= 0) eventfd_write(thr->m_command_fd, 1); + if (thr->m_command_fd >= 0) { + eventfd_write(thr->m_command_fd, 1); + } } m_impl->m_owner.Stop(); } @@ -114,25 +118,35 @@ void NetworkListener::Impl::Thread::Main() { } // Double-check to see if we're shutting down - if (!m_active) break; + if (!m_active) { + break; + } - if (!FD_ISSET(sd, &readfds)) continue; + if (!FD_ISSET(sd, &readfds)) { + continue; + } std::memset(&addr, 0, sizeof(addr)); struct iovec iov = {buf, sizeof(buf)}; struct msghdr msg = {&addr, sizeof(addr), &iov, 1, nullptr, 0, 0}; int len = ::recvmsg(sd, &msg, 0); if (len < 0) { - if (errno == EWOULDBLOCK || errno == EAGAIN) continue; + if (errno == EWOULDBLOCK || errno == EAGAIN) { + continue; + } ERROR( "NetworkListener: could not read netlink: " << std::strerror(errno)); break; // XXX: is this the right thing to do here? } - if (len == 0) continue; // EOF? + if (len == 0) { + continue; // EOF? + } unsigned int ulen = static_cast(len); for (struct nlmsghdr* nh = reinterpret_cast(buf); NLMSG_OK(nh, ulen); nh = NLMSG_NEXT(nh, ulen)) { - if (nh->nlmsg_type == NLMSG_DONE) break; + if (nh->nlmsg_type == NLMSG_DONE) { + break; + } if (nh->nlmsg_type == RTM_NEWLINK || nh->nlmsg_type == RTM_DELLINK || nh->nlmsg_type == RTM_NEWADDR || nh->nlmsg_type == RTM_DELADDR) { m_notifier.NotifyNetworkInterfacesChanged(); diff --git a/cscore/src/main/native/linux/NetworkUtil.cpp b/cscore/src/main/native/linux/NetworkUtil.cpp index a06b963af5..43e0fa8cd1 100644 --- a/cscore/src/main/native/linux/NetworkUtil.cpp +++ b/cscore/src/main/native/linux/NetworkUtil.cpp @@ -13,17 +13,25 @@ namespace cs { std::vector GetNetworkInterfaces() { struct ifaddrs* ifa; - if (::getifaddrs(&ifa) != 0) return std::vector{}; + if (::getifaddrs(&ifa) != 0) { + return {}; + } std::vector rv; char buf[256]; for (struct ifaddrs* i = ifa; i; i = i->ifa_next) { - if (!i->ifa_addr) continue; // no address - if (i->ifa_addr->sa_family != AF_INET) continue; // only return IPv4 + if (!i->ifa_addr) { + continue; // no address + } + if (i->ifa_addr->sa_family != AF_INET) { + continue; // only return IPv4 + } struct sockaddr_in* addr_in = reinterpret_cast(i->ifa_addr); const char* addr = ::inet_ntop(addr_in->sin_family, &addr_in->sin_addr, buf, sizeof(buf)); - if (!addr) continue; // error converting address + if (!addr) { + continue; // error converting address + } rv.emplace_back(addr); } diff --git a/cscore/src/main/native/linux/UsbCameraBuffer.h b/cscore/src/main/native/linux/UsbCameraBuffer.h index 6fba7c7ff0..e816aa9f68 100644 --- a/cscore/src/main/native/linux/UsbCameraBuffer.h +++ b/cscore/src/main/native/linux/UsbCameraBuffer.h @@ -35,7 +35,9 @@ class UsbCameraBuffer { } ~UsbCameraBuffer() { - if (m_data) munmap(m_data, m_length); + if (m_data) { + munmap(m_data, m_length); + } } friend void swap(UsbCameraBuffer& first, UsbCameraBuffer& second) noexcept { diff --git a/cscore/src/main/native/linux/UsbCameraImpl.cpp b/cscore/src/main/native/linux/UsbCameraImpl.cpp index f9a8451ca6..4d75984e16 100644 --- a/cscore/src/main/native/linux/UsbCameraImpl.cpp +++ b/cscore/src/main/native/linux/UsbCameraImpl.cpp @@ -96,7 +96,9 @@ static __u32 FromPixelFormat(VideoMode::PixelFormat pixelFormat) { } static bool IsPercentageProperty(wpi::StringRef name) { - if (name.startswith("raw_")) name = name.substr(4); + if (name.startswith("raw_")) { + name = name.substr(4); + } return name == "brightness" || name == "contrast" || name == "saturation" || name == "hue" || name == "sharpness" || name == "gain" || name == "exposure_absolute" || name == "exposure_time_absolute"; @@ -122,7 +124,9 @@ int UsbCameraImpl::RawToPercentage(const UsbCameraProperty& rawProp, rawProp.minimum == 5 && rawProp.maximum == 20000) { int nelems = wpi::array_lengthof(quirkLifeCamHd3000); for (int i = 0; i < nelems; ++i) { - if (rawValue < quirkLifeCamHd3000[i]) return 100.0 * i / nelems; + if (rawValue < quirkLifeCamHd3000[i]) { + return 100.0 * i / nelems; + } } return 100; } @@ -137,8 +141,12 @@ int UsbCameraImpl::PercentageToRaw(const UsbCameraProperty& rawProp, rawProp.minimum == 5 && rawProp.maximum == 20000) { int nelems = wpi::array_lengthof(quirkLifeCamHd3000); int ndx = nelems * percentValue / 100.0; - if (ndx < 0) ndx = 0; - if (ndx >= nelems) ndx = nelems - 1; + if (ndx < 0) { + ndx = 0; + } + if (ndx >= nelems) { + ndx = nelems - 1; + } return quirkLifeCamHd3000[ndx]; } return rawProp.minimum + @@ -153,18 +161,28 @@ static bool GetVendorProduct(int dev, int* vendor, int* product) { } int fd = open(ifpath.c_str(), O_RDONLY); - if (fd < 0) return false; + if (fd < 0) { + return false; + } char readBuf[128]; ssize_t n = read(fd, readBuf, sizeof(readBuf)); close(fd); - if (n <= 0) return false; + if (n <= 0) { + return false; + } wpi::StringRef readStr{readBuf}; - if (readStr.substr(readStr.find('v')).substr(1, 4).getAsInteger(16, *vendor)) + if (readStr.substr(readStr.find('v')) + .substr(1, 4) + .getAsInteger(16, *vendor)) { return false; - if (readStr.substr(readStr.find('p')).substr(1, 4).getAsInteger(16, *product)) + } + if (readStr.substr(readStr.find('p')) + .substr(1, 4) + .getAsInteger(16, *product)) { return false; + } return true; } @@ -177,13 +195,17 @@ static bool GetDescriptionSysV4L(int dev, std::string* desc) { } int fd = open(ifpath.c_str(), O_RDONLY); - if (fd < 0) return false; + if (fd < 0) { + return false; + } char readBuf[128]; ssize_t n = read(fd, readBuf, sizeof(readBuf)); close(fd); - if (n <= 0) return false; + if (n <= 0) { + return false; + } *desc = wpi::StringRef(readBuf, n).rtrim(); return true; @@ -191,7 +213,9 @@ static bool GetDescriptionSysV4L(int dev, std::string* desc) { static bool GetDescriptionIoctl(const char* cpath, std::string* desc) { int fd = open(cpath, O_RDWR); - if (fd < 0) return false; + if (fd < 0) { + return false; + } struct v4l2_capability vcap; std::memset(&vcap, 0, sizeof(vcap)); @@ -222,7 +246,9 @@ static bool GetDescriptionIoctl(const char* cpath, std::string* desc) { static bool IsVideoCaptureDevice(const char* cpath) { int fd = open(cpath, O_RDWR); - if (fd < 0) return false; + if (fd < 0) { + return false; + } struct v4l2_capability vcap; std::memset(&vcap, 0, sizeof(vcap)); @@ -255,9 +281,13 @@ static int GetDeviceNum(const char* cpath) { } path = wpi::sys::path::filename(path); - if (!path.startswith("video")) return -1; + if (!path.startswith("video")) { + return -1; + } int dev = -1; - if (path.substr(5).getAsInteger(10, dev)) return -1; + if (path.substr(5).getAsInteger(10, dev)) { + return -1; + } return dev; } @@ -267,11 +297,15 @@ static std::string GetDescriptionImpl(const char* cpath) { int dev = GetDeviceNum(cpath); if (dev >= 0) { // Sometimes the /sys tree gives a better name. - if (GetDescriptionSysV4L(dev, &rv)) return rv; + if (GetDescriptionSysV4L(dev, &rv)) { + return rv; + } } // Otherwise use an ioctl to query the caps and get the card name - if (GetDescriptionIoctl(cpath, &rv)) return rv; + if (GetDescriptionIoctl(cpath, &rv)) { + return rv; + } return std::string{}; } @@ -305,17 +339,23 @@ UsbCameraImpl::~UsbCameraImpl() { Send(Message{Message::kNone}); // join camera thread - if (m_cameraThread.joinable()) m_cameraThread.join(); + if (m_cameraThread.joinable()) { + m_cameraThread.join(); + } // close command fd int fd = m_command_fd.exchange(-1); - if (fd >= 0) close(fd); + if (fd >= 0) { + close(fd); + } } static inline void DoFdSet(int fd, fd_set* set, int* nfds) { if (fd >= 0) { FD_SET(fd, set); - if ((fd + 1) > *nfds) *nfds = fd + 1; + if ((fd + 1) > *nfds) { + *nfds = fd + 1; + } } } @@ -357,12 +397,16 @@ void UsbCameraImpl::CameraThreadMain() { while (m_active) { // If not connected, try to reconnect - if (m_fd < 0) DeviceConnect(); + if (m_fd < 0) { + DeviceConnect(); + } // Make copies of fd's in case they go away int command_fd = m_command_fd.load(); int fd = m_fd.load(); - if (!m_active) break; + if (!m_active) { + break; + } // Reset notified flag and restart streaming if necessary if (fd >= 0) { @@ -395,7 +439,9 @@ void UsbCameraImpl::CameraThreadMain() { fd_set readfds; FD_ZERO(&readfds); DoFdSet(command_fd, &readfds, &nfds); - if (m_streaming) DoFdSet(fd, &readfds, &nfds); + if (m_streaming) { + DoFdSet(fd, &readfds, &nfds); + } DoFdSet(notify_fd, &readfds, &nfds); if (select(nfds, &readfds, nullptr, nullptr, &tv) < 0) { @@ -404,7 +450,9 @@ void UsbCameraImpl::CameraThreadMain() { } // Double-check to see if we're shutting down - if (!m_active) break; + if (!m_active) { + break; + } // Handle notify events if (notify_fd >= 0 && FD_ISSET(notify_fd, &readfds)) { @@ -508,10 +556,14 @@ void UsbCameraImpl::CameraThreadMain() { void UsbCameraImpl::DeviceDisconnect() { int fd = m_fd.exchange(-1); - if (fd < 0) return; // already disconnected + if (fd < 0) { + return; // already disconnected + } // Unmap buffers - for (int i = 0; i < kNumBuffers; ++i) m_buffers[i] = UsbCameraBuffer{}; + for (int i = 0; i < kNumBuffers; ++i) { + m_buffers[i] = UsbCameraBuffer{}; + } // Close device close(fd); @@ -521,14 +573,20 @@ void UsbCameraImpl::DeviceDisconnect() { } void UsbCameraImpl::DeviceConnect() { - if (m_fd >= 0) return; + if (m_fd >= 0) { + return; + } - if (m_connectVerbose) SINFO("Connecting to USB camera on " << m_path); + if (m_connectVerbose) { + SINFO("Connecting to USB camera on " << m_path); + } // Try to open the device SDEBUG3("opening device"); int fd = open(m_path.c_str(), O_RDWR); - if (fd < 0) return; + if (fd < 0) { + return; + } m_fd = fd; // Get capabilities @@ -537,8 +595,9 @@ void UsbCameraImpl::DeviceConnect() { std::memset(&vcap, 0, sizeof(vcap)); if (DoIoctl(fd, VIDIOC_QUERYCAP, &vcap) >= 0) { m_capabilities = vcap.capabilities; - if (m_capabilities & V4L2_CAP_DEVICE_CAPS) + if (m_capabilities & V4L2_CAP_DEVICE_CAPS) { m_capabilities = vcap.device_caps; + } } // Get or restore video mode @@ -559,10 +618,12 @@ void UsbCameraImpl::DeviceConnect() { for (size_t i = 0; i < m_propertyData.size(); ++i) { const auto prop = static_cast(m_propertyData[i].get()); - if (!prop || !prop->valueSet || !prop->device || prop->percentage) + if (!prop || !prop->valueSet || !prop->device || prop->percentage) { continue; - if (!prop->DeviceSet(lock2, m_fd)) + } + if (!prop->DeviceSet(lock2, m_fd)) { SWARNING("failed to set property " << prop->name); + } } } @@ -601,7 +662,9 @@ void UsbCameraImpl::DeviceConnect() { if (!m_buffers[i].m_data) { SWARNING("could not map buffer " << i); // release other buffers - for (int j = 0; j < i; ++j) m_buffers[j] = UsbCameraBuffer{}; + for (int j = 0; j < i; ++j) { + m_buffers[j] = UsbCameraBuffer{}; + } close(fd); m_fd = -1; return; @@ -621,9 +684,13 @@ void UsbCameraImpl::DeviceConnect() { } bool UsbCameraImpl::DeviceStreamOn() { - if (m_streaming) return false; // ignore if already enabled + if (m_streaming) { + return false; // ignore if already enabled + } int fd = m_fd.load(); - if (fd < 0) return false; + if (fd < 0) { + return false; + } // Queue buffers SDEBUG3("queuing buffers"); @@ -660,11 +727,17 @@ bool UsbCameraImpl::DeviceStreamOn() { } bool UsbCameraImpl::DeviceStreamOff() { - if (!m_streaming) return false; // ignore if already disabled + if (!m_streaming) { + return false; // ignore if already disabled + } int fd = m_fd.load(); - if (fd < 0) return false; + if (fd < 0) { + return false; + } int type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (DoIoctl(fd, VIDIOC_STREAMOFF, &type) != 0) return false; + if (DoIoctl(fd, VIDIOC_STREAMOFF, &type) != 0) { + return false; + } SDEBUG4("disabled streaming"); m_streaming = false; return true; @@ -703,12 +776,16 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetMode( m_mode = newMode; lock.unlock(); bool wasStreaming = m_streaming; - if (wasStreaming) DeviceStreamOff(); + if (wasStreaming) { + DeviceStreamOff(); + } if (m_fd >= 0) { DeviceDisconnect(); DeviceConnect(); } - if (wasStreaming) DeviceStreamOn(); + if (wasStreaming) { + DeviceStreamOn(); + } m_notifier.NotifySourceVideoMode(*this, newMode); lock.lock(); } else if (newMode.fps != m_mode.fps) { @@ -716,9 +793,13 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetMode( lock.unlock(); // Need to stop streaming to set FPS bool wasStreaming = m_streaming; - if (wasStreaming) DeviceStreamOff(); + if (wasStreaming) { + DeviceStreamOff(); + } DeviceSetFPS(); - if (wasStreaming) DeviceStreamOn(); + if (wasStreaming) { + DeviceStreamOn(); + } m_notifier.NotifySourceVideoMode(*this, newMode); lock.lock(); } @@ -735,21 +816,25 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetProperty( // Look up auto prop = static_cast(GetProperty(property)); - if (!prop) return CS_INVALID_PROPERTY; + if (!prop) { + return CS_INVALID_PROPERTY; + } // If setting before we get, guess initial type based on set if (prop->propKind == CS_PROP_NONE) { - if (setString) + if (setString) { prop->propKind = CS_PROP_STRING; - else + } else { prop->propKind = CS_PROP_INTEGER; + } } // Check kind match if ((setString && prop->propKind != CS_PROP_STRING) || - (!setString && (prop->propKind & - (CS_PROP_BOOLEAN | CS_PROP_INTEGER | CS_PROP_ENUM)) == 0)) + (!setString && (prop->propKind & (CS_PROP_BOOLEAN | CS_PROP_INTEGER | + CS_PROP_ENUM)) == 0)) { return CS_WRONG_PROPERTY_TYPE; + } // Handle percentage property int percentageProperty = prop->propPair; @@ -766,17 +851,21 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetProperty( // Actually set the new value on the device (if possible) if (!prop->device) { - if (prop->id == kPropConnectVerboseId) m_connectVerbose = value; + if (prop->id == kPropConnectVerboseId) { + m_connectVerbose = value; + } } else { - if (!prop->DeviceSet(lock, m_fd, value, valueStr)) + if (!prop->DeviceSet(lock, m_fd, value, valueStr)) { return CS_PROPERTY_WRITE_FAILED; + } } // Cache the set values UpdatePropertyValue(property, setString, value, valueStr); - if (percentageProperty != 0) + if (percentageProperty != 0) { UpdatePropertyValue(percentageProperty, setString, percentageValue, valueStr); + } return CS_OK; } @@ -787,12 +876,16 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetPath( lock.unlock(); // disconnect and reconnect bool wasStreaming = m_streaming; - if (wasStreaming) DeviceStreamOff(); + if (wasStreaming) { + DeviceStreamOff(); + } if (m_fd >= 0) { DeviceDisconnect(); DeviceConnect(); } - if (wasStreaming) DeviceStreamOn(); + if (wasStreaming) { + DeviceStreamOn(); + } lock.lock(); return CS_OK; } @@ -819,15 +912,18 @@ CS_StatusValue UsbCameraImpl::DeviceProcessCommand( void UsbCameraImpl::DeviceProcessCommands() { std::unique_lock lock(m_mutex); - if (m_commands.empty()) return; + if (m_commands.empty()) { + return; + } while (!m_commands.empty()) { auto msg = std::move(m_commands.back()); m_commands.pop_back(); CS_StatusValue status = DeviceProcessCommand(lock, msg); if (msg.kind != Message::kNumSinksChanged && - msg.kind != Message::kNumSinksEnabledChanged) + msg.kind != Message::kNumSinksEnabledChanged) { m_responses.emplace_back(msg.from, status); + } } lock.unlock(); m_responseCv.notify_all(); @@ -835,7 +931,9 @@ void UsbCameraImpl::DeviceProcessCommands() { void UsbCameraImpl::DeviceSetMode() { int fd = m_fd.load(); - if (fd < 0) return; + if (fd < 0) { + return; + } struct v4l2_format vfmt; std::memset(&vfmt, 0, sizeof(vfmt)); @@ -866,25 +964,34 @@ void UsbCameraImpl::DeviceSetMode() { void UsbCameraImpl::DeviceSetFPS() { int fd = m_fd.load(); - if (fd < 0) return; + if (fd < 0) { + return; + } struct v4l2_streamparm parm; std::memset(&parm, 0, sizeof(parm)); parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (DoIoctl(fd, VIDIOC_G_PARM, &parm) != 0) return; - if ((parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) return; + if (DoIoctl(fd, VIDIOC_G_PARM, &parm) != 0) { + return; + } + if ((parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) { + return; + } std::memset(&parm, 0, sizeof(parm)); parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; parm.parm.capture.timeperframe = FPSToFract(m_mode.fps); - if (DoIoctl(fd, VIDIOC_S_PARM, &parm) != 0) + if (DoIoctl(fd, VIDIOC_S_PARM, &parm) != 0) { SWARNING("could not set FPS to " << m_mode.fps); - else + } else { SINFO("set FPS to " << m_mode.fps); + } } void UsbCameraImpl::DeviceCacheMode() { int fd = m_fd.load(); - if (fd < 0) return; + if (fd < 0) { + return; + } // Get format struct v4l2_format vfmt; @@ -911,8 +1018,9 @@ void UsbCameraImpl::DeviceCacheMode() { std::memset(&parm, 0, sizeof(parm)); parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (TryIoctl(fd, VIDIOC_G_PARM, &parm) == 0) { - if (parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) + if (parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) { fps = FractToFPS(parm.parm.capture.timeperframe); + } } // Update format with user changes. @@ -943,7 +1051,9 @@ void UsbCameraImpl::DeviceCacheMode() { // Default to lowest known resolution (based on number of total pixels) int numPixels = width * height; for (const auto& mode : m_videoModes) { - if (mode.pixelFormat != pixelFormat) continue; + if (mode.pixelFormat != pixelFormat) { + continue; + } int numPixelsHere = mode.width * mode.height; if (numPixelsHere < numPixels) { formatChanged = true; @@ -970,8 +1080,12 @@ void UsbCameraImpl::DeviceCacheMode() { m_mode.fps = fps; } - if (formatChanged) DeviceSetMode(); - if (fpsChanged) DeviceSetFPS(); + if (formatChanged) { + DeviceSetMode(); + } + if (fpsChanged) { + DeviceSetFPS(); + } m_notifier.NotifySourceVideoMode(*this, m_mode); } @@ -1024,8 +1138,9 @@ void UsbCameraImpl::DeviceCacheProperty( rawProp->valueStr = perProp->valueStr; // copy } else { // Read current raw value and set percentage from it - if (!rawProp->DeviceGet(lock, m_fd)) + if (!rawProp->DeviceGet(lock, m_fd)) { SWARNING("failed to get property " << rawProp->name); + } if (perProp) { perProp->SetValue(RawToPercentage(*rawProp, rawProp->value)); @@ -1035,8 +1150,9 @@ void UsbCameraImpl::DeviceCacheProperty( // Set value on device if user-configured if (rawProp->valueSet) { - if (!rawProp->DeviceSet(lock, m_fd)) + if (!rawProp->DeviceSet(lock, m_fd)) { SWARNING("failed to set property " << rawProp->name); + } } // Update pointers since we released the lock @@ -1076,12 +1192,16 @@ void UsbCameraImpl::DeviceCacheProperty( } NotifyPropertyCreated(*rawIndex, *rawPropPtr); - if (perPropPtr) NotifyPropertyCreated(*perIndex, *perPropPtr); + if (perPropPtr) { + NotifyPropertyCreated(*perIndex, *perPropPtr); + } } void UsbCameraImpl::DeviceCacheProperties() { int fd = m_fd.load(); - if (fd < 0) return; + if (fd < 0) { + return; + } #ifdef V4L2_CTRL_FLAG_NEXT_COMPOUND constexpr __u32 nextFlags = @@ -1099,20 +1219,24 @@ void UsbCameraImpl::DeviceCacheProperties() { if (id == nextFlags) { // try just enumerating standard... for (id = V4L2_CID_BASE; id < V4L2_CID_LASTP1; ++id) { - if (auto prop = UsbCameraProperty::DeviceQuery(fd, &id)) + if (auto prop = UsbCameraProperty::DeviceQuery(fd, &id)) { DeviceCacheProperty(std::move(prop)); + } } // ... and custom controls std::unique_ptr prop; for (id = V4L2_CID_PRIVATE_BASE; - (prop = UsbCameraProperty::DeviceQuery(fd, &id)); ++id) + (prop = UsbCameraProperty::DeviceQuery(fd, &id)); ++id) { DeviceCacheProperty(std::move(prop)); + } } } void UsbCameraImpl::DeviceCacheVideoModes() { int fd = m_fd.load(); - if (fd < 0) return; + if (fd < 0) { + return; + } std::vector modes; @@ -1122,7 +1246,9 @@ void UsbCameraImpl::DeviceCacheVideoModes() { fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; for (fmt.index = 0; TryIoctl(fd, VIDIOC_ENUM_FMT, &fmt) >= 0; ++fmt.index) { VideoMode::PixelFormat pixelFormat = ToPixelFormat(fmt.pixelformat); - if (pixelFormat == VideoMode::kUnknown) continue; + if (pixelFormat == VideoMode::kUnknown) { + continue; + } // Frame sizes struct v4l2_frmsizeenum frmsize; @@ -1130,7 +1256,9 @@ void UsbCameraImpl::DeviceCacheVideoModes() { frmsize.pixel_format = fmt.pixelformat; for (frmsize.index = 0; TryIoctl(fd, VIDIOC_ENUM_FRAMESIZES, &frmsize) >= 0; ++frmsize.index) { - if (frmsize.type != V4L2_FRMSIZE_TYPE_DISCRETE) continue; + if (frmsize.type != V4L2_FRMSIZE_TYPE_DISCRETE) { + continue; + } // Frame intervals struct v4l2_frmivalenum frmival; @@ -1141,7 +1269,9 @@ void UsbCameraImpl::DeviceCacheVideoModes() { for (frmival.index = 0; TryIoctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival) >= 0; ++frmival.index) { - if (frmival.type != V4L2_FRMIVAL_TYPE_DISCRETE) continue; + if (frmival.type != V4L2_FRMIVAL_TYPE_DISCRETE) { + continue; + } modes.emplace_back(pixelFormat, static_cast(frmsize.discrete.width), @@ -1180,7 +1310,9 @@ void UsbCameraImpl::DeviceCacheVideoModes() { CS_StatusValue UsbCameraImpl::SendAndWait(Message&& msg) const { int fd = m_command_fd.load(); // exit early if not possible to signal - if (fd < 0) return CS_SOURCE_IS_DISCONNECTED; + if (fd < 0) { + return CS_SOURCE_IS_DISCONNECTED; + } auto from = msg.from; @@ -1191,7 +1323,9 @@ CS_StatusValue UsbCameraImpl::SendAndWait(Message&& msg) const { } // Signal the camera thread - if (eventfd_write(fd, 1) < 0) return CS_SOURCE_IS_DISCONNECTED; + if (eventfd_write(fd, 1) < 0) { + return CS_SOURCE_IS_DISCONNECTED; + } std::unique_lock lock(m_mutex); while (m_active) { @@ -1217,7 +1351,9 @@ CS_StatusValue UsbCameraImpl::SendAndWait(Message&& msg) const { void UsbCameraImpl::Send(Message&& msg) const { int fd = m_command_fd.load(); // exit early if not possible to signal - if (fd < 0) return; + if (fd < 0) { + return; + } // Add the message to the command queue { @@ -1237,7 +1373,9 @@ std::unique_ptr UsbCameraImpl::CreateEmptyProperty( bool UsbCameraImpl::CacheProperties(CS_Status* status) const { // Wake up camera thread; this will try to reconnect *status = SendAndWait(Message{Message::kNone}); - if (*status != CS_OK) return false; + if (*status != CS_OK) { + return false; + } if (!m_properties_cached) { *status = CS_SOURCE_IS_DISCONNECTED; return false; @@ -1473,7 +1611,9 @@ UsbCameraInfo GetUsbCameraInfo(CS_Source source, CS_Status* status) { path += ep->d_name; char* target = ::realpath(path.c_str(), nullptr); if (target) { - if (keypath == target) info.otherPaths.emplace_back(path.str()); + if (keypath == target) { + info.otherPaths.emplace_back(path.str()); + } std::free(target); } } @@ -1496,10 +1636,14 @@ std::vector EnumerateUsbCameras(CS_Status* status) { if (DIR* dp = ::opendir("/dev")) { while (struct dirent* ep = ::readdir(dp)) { wpi::StringRef fname{ep->d_name}; - if (!fname.startswith("video")) continue; + if (!fname.startswith("video")) { + continue; + } unsigned int dev = 0; - if (fname.substr(5).getAsInteger(10, dev)) continue; + if (fname.substr(5).getAsInteger(10, dev)) { + continue; + } UsbCameraInfo info; info.dev = dev; @@ -1508,14 +1652,20 @@ std::vector EnumerateUsbCameras(CS_Status* status) { path += fname; info.path = path.str(); - if (!IsVideoCaptureDevice(path.c_str())) continue; + if (!IsVideoCaptureDevice(path.c_str())) { + continue; + } info.name = GetDescriptionImpl(path.c_str()); - if (info.name.empty()) continue; + if (info.name.empty()) { + continue; + } GetVendorProduct(dev, &info.vendorId, &info.productId); - if (dev >= retval.size()) retval.resize(info.dev + 1); + if (dev >= retval.size()) { + retval.resize(info.dev + 1); + } retval[info.dev] = std::move(info); } ::closedir(dp); diff --git a/cscore/src/main/native/linux/UsbCameraProperty.cpp b/cscore/src/main/native/linux/UsbCameraProperty.cpp index 2103ecfded..f2ec84839d 100644 --- a/cscore/src/main/native/linux/UsbCameraProperty.cpp +++ b/cscore/src/main/native/linux/UsbCameraProperty.cpp @@ -26,7 +26,9 @@ static int GetIntCtrlIoctl(int fd, unsigned id, int type, int64_t* value) { ctrls.count = 1; ctrls.controls = &ctrl; int rc = DoIoctl(fd, VIDIOC_G_EXT_CTRLS, &ctrls); - if (rc < 0) return rc; + if (rc < 0) { + return rc; + } *value = ctrl.value; } else { // Use normal control @@ -34,7 +36,9 @@ static int GetIntCtrlIoctl(int fd, unsigned id, int type, int64_t* value) { std::memset(&ctrl, 0, sizeof(ctrl)); ctrl.id = id; int rc = DoIoctl(fd, VIDIOC_G_CTRL, &ctrl); - if (rc < 0) return rc; + if (rc < 0) { + return rc; + } *value = ctrl.value; } return 0; @@ -51,10 +55,11 @@ static int SetIntCtrlIoctl(int fd, unsigned id, int type, int64_t value) { std::memset(&ctrl, 0, sizeof(ctrl)); std::memset(&ctrls, 0, sizeof(ctrls)); ctrl.id = id; - if (type == V4L2_CTRL_TYPE_INTEGER64) + if (type == V4L2_CTRL_TYPE_INTEGER64) { ctrl.value64 = value; - else + } else { ctrl.value = static_cast<__s32>(value); + } ctrls.ctrl_class = ctrl_class; ctrls.count = 1; ctrls.controls = &ctrl; @@ -117,7 +122,9 @@ static wpi::StringRef NormalizeName(wpi::StringRef name, bool newWord = false; for (auto ch : name) { if (std::isalnum(ch)) { - if (newWord) buf.push_back('_'); + if (newWord) { + buf.push_back('_'); + } newWord = false; buf.push_back(std::tolower(ch)); } else if (!buf.empty()) { @@ -163,7 +170,9 @@ UsbCameraProperty::UsbCameraProperty(const struct v4l2_query_ext_ctrl& ctrl) // name size_t len = 0; - while (len < sizeof(ctrl.name) && ctrl.name[len] != '\0') ++len; + while (len < sizeof(ctrl.name) && ctrl.name[len] != '\0') { + ++len; + } wpi::SmallString<64> name_buf; name = NormalizeName(wpi::StringRef(ctrl.name, len), name_buf); } @@ -201,7 +210,9 @@ UsbCameraProperty::UsbCameraProperty(const struct v4l2_queryctrl& ctrl) // name size_t len = 0; - while (len < sizeof(ctrl.name) && ctrl.name[len] != '\0') ++len; + while (len < sizeof(ctrl.name) && ctrl.name[len] != '\0') { + ++len; + } wpi::SmallString<64> name_buf; name = NormalizeName( wpi::StringRef(reinterpret_cast(ctrl.name), len), name_buf); @@ -219,7 +230,9 @@ std::unique_ptr UsbCameraProperty::DeviceQuery(int fd, if (rc == 0) { *id = qc_ext.id; // copy back // We don't support array types - if (qc_ext.elems > 1 || qc_ext.nr_of_dims > 0) return nullptr; + if (qc_ext.elems > 1 || qc_ext.nr_of_dims > 0) { + return nullptr; + } prop = std::make_unique(qc_ext); } #endif @@ -230,7 +243,9 @@ std::unique_ptr UsbCameraProperty::DeviceQuery(int fd, qc.id = *id; rc = TryIoctl(fd, VIDIOC_QUERYCTRL, &qc); *id = qc.id; // copy back - if (rc != 0) return nullptr; + if (rc != 0) { + return nullptr; + } prop = std::make_unique(qc); } @@ -242,7 +257,9 @@ std::unique_ptr UsbCameraProperty::DeviceQuery(int fd, qmenu.id = *id; for (int i = prop->minimum; i <= prop->maximum; ++i) { qmenu.index = static_cast<__u32>(i); - if (TryIoctl(fd, VIDIOC_QUERYMENU, &qmenu) != 0) continue; + if (TryIoctl(fd, VIDIOC_QUERYMENU, &qmenu) != 0) { + continue; + } if (prop->intMenu) { wpi::raw_string_ostream os(prop->enumChoices[i]); os << qmenu.value; @@ -256,7 +273,9 @@ std::unique_ptr UsbCameraProperty::DeviceQuery(int fd, } bool UsbCameraProperty::DeviceGet(std::unique_lock& lock, int fd) { - if (fd < 0) return true; + if (fd < 0) { + return true; + } unsigned idCopy = id; int rv = 0; @@ -269,7 +288,9 @@ bool UsbCameraProperty::DeviceGet(std::unique_lock& lock, int fd) { lock.unlock(); rv = GetIntCtrlIoctl(fd, idCopy, typeCopy, &newValue); lock.lock(); - if (rv >= 0) value = newValue; + if (rv >= 0) { + value = newValue; + } break; } case CS_PROP_STRING: { @@ -278,7 +299,9 @@ bool UsbCameraProperty::DeviceGet(std::unique_lock& lock, int fd) { lock.unlock(); rv = GetStringCtrlIoctl(fd, idCopy, maximumCopy, &newValueStr); lock.lock(); - if (rv >= 0) valueStr = std::move(newValueStr); + if (rv >= 0) { + valueStr = std::move(newValueStr); + } break; } default: @@ -298,7 +321,9 @@ bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, int fd, int newValue, const wpi::Twine& newValueStr) const { - if (!device || fd < 0) return true; + if (!device || fd < 0) { + return true; + } unsigned idCopy = id; int rv = 0; diff --git a/cscore/src/main/native/linux/UsbUtil.cpp b/cscore/src/main/native/linux/UsbUtil.cpp index f21c8f816d..c2aff2972b 100644 --- a/cscore/src/main/native/linux/UsbUtil.cpp +++ b/cscore/src/main/native/linux/UsbUtil.cpp @@ -21,7 +21,9 @@ namespace cs { static wpi::StringRef GetUsbNameFromFile(int vendor, int product, wpi::SmallVectorImpl& buf) { int fd = open("/var/lib/usbutils/usb.ids", O_RDONLY); - if (fd < 0) return wpi::StringRef{}; + if (fd < 0) { + return {}; + } wpi::raw_svector_ostream os{buf}; wpi::raw_fd_istream is{fd, true}; @@ -37,9 +39,13 @@ static wpi::StringRef GetUsbNameFromFile(int vendor, int product, bool foundVendor = false; for (;;) { auto line = is.getline(lineBuf, 4096); - if (is.has_error()) break; + if (is.has_error()) { + break; + } - if (line.empty()) continue; + if (line.empty()) { + continue; + } // look for vendor at start of line if (line.startswith(vendorStr)) { @@ -63,14 +69,16 @@ static wpi::StringRef GetUsbNameFromFile(int vendor, int product, } } - return wpi::StringRef{}; + return {}; } wpi::StringRef GetUsbNameFromId(int vendor, int product, wpi::SmallVectorImpl& buf) { // try reading usb.ids wpi::StringRef rv = GetUsbNameFromFile(vendor, product, buf); - if (!rv.empty()) return rv; + if (!rv.empty()) { + return rv; + } // Fall back to internal database wpi::raw_svector_ostream os{buf}; diff --git a/cscore/src/main/native/windows/COMCreators.cpp b/cscore/src/main/native/windows/COMCreators.cpp index 32c4106ad5..f9f5cae8f2 100644 --- a/cscore/src/main/native/windows/COMCreators.cpp +++ b/cscore/src/main/native/windows/COMCreators.cpp @@ -56,9 +56,13 @@ STDMETHODIMP_(ULONG) SourceReaderCB::Release() { return uCount; } -STDMETHODIMP SourceReaderCB::OnEvent(DWORD, IMFMediaEvent*) { return S_OK; } +STDMETHODIMP SourceReaderCB::OnEvent(DWORD, IMFMediaEvent*) { + return S_OK; +} -STDMETHODIMP SourceReaderCB::OnFlush(DWORD) { return S_OK; } +STDMETHODIMP SourceReaderCB::OnFlush(DWORD) { + return S_OK; +} void SourceReaderCB::NotifyError(HRESULT hr) { wprintf(L"Source Reader error: 0x%X\n", hr); @@ -70,7 +74,8 @@ STDMETHODIMP SourceReaderCB::OnReadSample(HRESULT hrStatus, DWORD dwStreamIndex, IMFSample* pSample // Can be NULL ) { auto source = m_source.lock(); - if (!source) return S_OK; + if (!source) + return S_OK; if (SUCCEEDED(hrStatus)) { if (pSample) { // Prcoess sample diff --git a/cscore/src/main/native/windows/NetworkListener.cpp b/cscore/src/main/native/windows/NetworkListener.cpp index 39c9f355db..b4fbb1e310 100644 --- a/cscore/src/main/native/windows/NetworkListener.cpp +++ b/cscore/src/main/native/windows/NetworkListener.cpp @@ -44,7 +44,9 @@ static void WINAPI OnInterfaceChange(PVOID callerContext, NetworkListener::NetworkListener(wpi::Logger& logger, Notifier& notifier) : m_impl(std::make_unique(logger, notifier)) {} -NetworkListener::~NetworkListener() { Stop(); } +NetworkListener::~NetworkListener() { + Stop(); +} void NetworkListener::Start() { NotifyIpInterfaceChange(AF_INET, OnInterfaceChange, &m_impl->m_notifier, true, diff --git a/cscore/src/main/native/windows/NetworkUtil.cpp b/cscore/src/main/native/windows/NetworkUtil.cpp index c5318c926a..0faa43f2c8 100644 --- a/cscore/src/main/native/windows/NetworkUtil.cpp +++ b/cscore/src/main/native/windows/NetworkUtil.cpp @@ -21,7 +21,9 @@ std::vector GetNetworkInterfaces() { char ip[50]; for (int i = 0; i < counts; i++) { - if (adrs[i].is_internal) continue; + if (adrs[i].is_internal) { + continue; + } InetNtop(PF_INET, &(adrs[i].netmask.netmask4.sin_addr.s_addr), ip, sizeof(ip) - 1); ip[49] = '\0'; diff --git a/cscore/src/main/native/windows/UsbCameraImpl.cpp b/cscore/src/main/native/windows/UsbCameraImpl.cpp index 9e2d100dde..91944a34bd 100644 --- a/cscore/src/main/native/windows/UsbCameraImpl.cpp +++ b/cscore/src/main/native/windows/UsbCameraImpl.cpp @@ -86,7 +86,9 @@ UsbCameraImpl::UsbCameraImpl(const wpi::Twine& name, wpi::Logger& logger, StartMessagePump(); } -UsbCameraImpl::~UsbCameraImpl() { m_messagePump = nullptr; } +UsbCameraImpl::~UsbCameraImpl() { + m_messagePump = nullptr; +} void UsbCameraImpl::SetProperty(int property, int value, CS_Status* status) { Message msg{Message::kCmdSetProperty}; @@ -254,7 +256,8 @@ bool UsbCameraImpl::CheckDeviceChange(WPARAM wParam, DEV_BROADCAST_HDR* pHdr, } void UsbCameraImpl::DeviceDisconnect() { - if (m_connectVerbose) SINFO("Disconnected from " << m_path); + if (m_connectVerbose) + SINFO("Disconnected from " << m_path); m_sourceReader.Reset(); m_mediaSource.Reset(); if (m_imageCallback) { @@ -266,7 +269,8 @@ void UsbCameraImpl::DeviceDisconnect() { } static bool IsPercentageProperty(wpi::StringRef name) { - if (name.startswith("raw_")) name = name.substr(4); + if (name.startswith("raw_")) + name = name.substr(4); return name == "Brightness" || name == "Contrast" || name == "Saturation" || name == "Hue" || name == "Sharpness" || name == "Gain" || name == "Exposure"; @@ -274,14 +278,17 @@ static bool IsPercentageProperty(wpi::StringRef name) { void UsbCameraImpl::ProcessFrame(IMFSample* videoSample, const VideoMode& mode) { - if (!videoSample) return; + if (!videoSample) + return; ComPtr buf; if (!SUCCEEDED(videoSample->ConvertToContiguousBuffer(buf.GetAddressOf()))) { DWORD bcnt = 0; - if (!SUCCEEDED(videoSample->GetBufferCount(&bcnt))) return; - if (bcnt == 0) return; + if (!SUCCEEDED(videoSample->GetBufferCount(&bcnt))) + return; + if (bcnt == 0) + return; if (!SUCCEEDED(videoSample->GetBufferByIndex(0, buf.GetAddressOf()))) return; } @@ -310,7 +317,8 @@ void UsbCameraImpl::ProcessFrame(IMFSample* videoSample, return; } } - if (!ptr) return; + if (!ptr) + return; cv::Mat tmpMat; std::unique_ptr dest; @@ -451,16 +459,19 @@ static cs::VideoMode::PixelFormat GetFromGUID(const GUID& guid) { } bool UsbCameraImpl::DeviceConnect() { - if (m_mediaSource && m_sourceReader) return true; + if (m_mediaSource && m_sourceReader) + return true; - if (m_connectVerbose) SINFO("Connecting to USB camera on " << m_path); + if (m_connectVerbose) + SINFO("Connecting to USB camera on " << m_path); SDEBUG3("opening device"); const wchar_t* path = m_widePath.c_str(); m_mediaSource = CreateVideoCaptureDevice(path); - if (!m_mediaSource) return false; + if (!m_mediaSource) + return false; m_imageCallback = CreateSourceReaderCB(shared_from_this(), m_mode); m_sourceReader = @@ -510,7 +521,8 @@ bool UsbCameraImpl::CacheProperties(CS_Status* status) const { auto result = m_messagePump->SendWindowMessage( WaitForStartupMessage, nullptr, nullptr); *status = result; - if (*status != CS_OK) return false; + if (*status != CS_OK) + return false; if (!m_properties_cached) { *status = CS_SOURCE_IS_DISCONNECTED; return false; @@ -545,7 +557,8 @@ template void UsbCameraImpl::DeviceAddProperty(const wpi::Twine& name_, DeviceAddProperty(#val, CameraControl_##val, pCamControl); void UsbCameraImpl::DeviceCacheProperties() { - if (!m_sourceReader) return; + if (!m_sourceReader) + return; IAMVideoProcAmp* pProcAmp = NULL; @@ -693,7 +706,8 @@ void UsbCameraImpl::DeviceCacheProperty( } NotifyPropertyCreated(*rawIndex, *rawPropPtr); - if (perPropPtr && perIndex) NotifyPropertyCreated(*perIndex, *perPropPtr); + if (perPropPtr && perIndex) + NotifyPropertyCreated(*perIndex, *perPropPtr); } CS_StatusValue UsbCameraImpl::DeviceProcessCommand( @@ -740,7 +754,8 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetProperty( // Look up auto prop = static_cast(GetProperty(property)); - if (!prop) return CS_INVALID_PROPERTY; + if (!prop) + return CS_INVALID_PROPERTY; // If setting before we get, guess initial type based on set if (prop->propKind == CS_PROP_NONE) { @@ -771,7 +786,8 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetProperty( // Actually set the new value on the device (if possible) if (!prop->device) { - if (prop->id == kPropConnectVerboseId) m_connectVerbose = value; + if (prop->id == kPropConnectVerboseId) + m_connectVerbose = value; } else { if (!prop->DeviceSet(lock, m_sourceReader.Get())) { return CS_PROPERTY_WRITE_FAILED; @@ -855,8 +871,10 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetMode( } bool UsbCameraImpl::DeviceStreamOn() { - if (m_streaming) return false; - if (!m_deviceValid) return false; + if (m_streaming) + return false; + if (!m_deviceValid) + return false; m_streaming = true; m_sourceReader->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, NULL, NULL, NULL, NULL); @@ -869,9 +887,11 @@ bool UsbCameraImpl::DeviceStreamOff() { } void UsbCameraImpl::DeviceCacheMode() { - if (!m_sourceReader) return; + if (!m_sourceReader) + return; - if (m_windowsVideoModes.size() == 0) return; + if (m_windowsVideoModes.size() == 0) + return; if (!m_currentMode) { // First, see if our set mode is valid @@ -936,7 +956,8 @@ CS_StatusValue UsbCameraImpl::DeviceSetMode() { } void UsbCameraImpl::DeviceCacheVideoModes() { - if (!m_sourceReader) return; + if (!m_sourceReader) + return; std::vector modes; m_windowsVideoModes.clear(); diff --git a/cscore/src/main/native/windows/UsbCameraProperty.cpp b/cscore/src/main/native/windows/UsbCameraProperty.cpp index 600f1eec3c..ebd8967e48 100644 --- a/cscore/src/main/native/windows/UsbCameraProperty.cpp +++ b/cscore/src/main/native/windows/UsbCameraProperty.cpp @@ -38,7 +38,8 @@ UsbCameraProperty::UsbCameraProperty(const wpi::Twine& name_, bool UsbCameraProperty::DeviceGet(std::unique_lock& lock, IAMVideoProcAmp* pProcAmp) { - if (!pProcAmp) return true; + if (!pProcAmp) + return true; lock.unlock(); long newValue = 0, paramFlag = 0; // NOLINT(runtime/int) @@ -57,7 +58,8 @@ bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, IAMVideoProcAmp* pProcAmp, int newValue) const { - if (!pProcAmp) return true; + if (!pProcAmp) + return true; lock.unlock(); if (SUCCEEDED( @@ -100,7 +102,8 @@ UsbCameraProperty::UsbCameraProperty(const wpi::Twine& name_, bool UsbCameraProperty::DeviceGet(std::unique_lock& lock, IAMCameraControl* pProcAmp) { - if (!pProcAmp) return true; + if (!pProcAmp) + return true; lock.unlock(); long newValue = 0, paramFlag = 0; // NOLINT(runtime/int) @@ -119,7 +122,8 @@ bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, IAMCameraControl* pProcAmp, int newValue) const { - if (!pProcAmp) return true; + if (!pProcAmp) + return true; lock.unlock(); if (SUCCEEDED(pProcAmp->Set(tagCameraControl, newValue, @@ -133,7 +137,8 @@ bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, bool UsbCameraProperty::DeviceGet(std::unique_lock& lock, IMFSourceReader* sourceReader) { - if (!sourceReader) return true; + if (!sourceReader) + return true; if (isControlProperty) { ComPtr pProcAmp; @@ -162,7 +167,8 @@ bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, IMFSourceReader* sourceReader, int newValue) const { - if (!sourceReader) return true; + if (!sourceReader) + return true; if (isControlProperty) { ComPtr pProcAmp; diff --git a/cscore/src/main/native/windows/WindowsMessagePump.cpp b/cscore/src/main/native/windows/WindowsMessagePump.cpp index c2edfa4d55..4ebcc84571 100644 --- a/cscore/src/main/native/windows/WindowsMessagePump.cpp +++ b/cscore/src/main/native/windows/WindowsMessagePump.cpp @@ -99,7 +99,8 @@ WindowsMessagePump::WindowsMessagePump( WindowsMessagePump::~WindowsMessagePump() { auto res = SendMessage(hwnd, WM_CLOSE, NULL, NULL); - if (m_mainThread.joinable()) m_mainThread.join(); + if (m_mainThread.joinable()) + m_mainThread.join(); } void WindowsMessagePump::ThreadMain(HANDLE eventHandle) { diff --git a/glass/src/app/native/cpp/NetworkTablesSettings.cpp b/glass/src/app/native/cpp/NetworkTablesSettings.cpp index 618f3af46f..f9f234048c 100644 --- a/glass/src/app/native/cpp/NetworkTablesSettings.cpp +++ b/glass/src/app/native/cpp/NetworkTablesSettings.cpp @@ -26,7 +26,9 @@ NetworkTablesSettings::NetworkTablesSettings(NT_Inst inst, } void NetworkTablesSettings::Update() { - if (!m_restart) return; + if (!m_restart) { + return; + } m_restart = false; nt::StopClient(m_inst); nt::StopServer(m_inst); @@ -40,8 +42,9 @@ void NetworkTablesSettings::Update() { wpi::SmallVector serverNames; wpi::SmallVector, 4> servers; serverTeam.split(serverNames, ',', -1, false); - for (auto&& serverName : serverNames) + for (auto&& serverName : serverNames) { servers.emplace_back(serverName, NT_DEFAULT_PORT); + } nt::StartClient(m_inst, servers); } } else if (*m_pMode == 2) { @@ -64,5 +67,7 @@ void NetworkTablesSettings::Display() { default: break; } - if (ImGui::Button("Apply")) m_restart = true; + if (ImGui::Button("Apply")) { + m_restart = true; + } } diff --git a/glass/src/app/native/cpp/main.cpp b/glass/src/app/native/cpp/main.cpp index 335ee67761..393b2a578e 100644 --- a/glass/src/app/native/cpp/main.cpp +++ b/glass/src/app/native/cpp/main.cpp @@ -45,7 +45,9 @@ static void NtInitialize() { nt::AddPolledConnectionListener(poller, true); gui::AddEarlyExecute([poller] { auto win = gui::GetSystemWindow(); - if (!win) return; + if (!win) { + return; + } bool timedOut; for (auto&& event : nt::PollConnectionListener(poller, 0, &timedOut)) { if (event.connected) { @@ -118,14 +120,18 @@ int main() { ImGui::BeginMainMenuBar(); gui::EmitViewMenu(); if (ImGui::BeginMenu("View")) { - if (ImGui::MenuItem("Reset Time")) glass::ResetTime(); + if (ImGui::MenuItem("Reset Time")) { + glass::ResetTime(); + } ImGui::EndMenu(); } if (ImGui::BeginMenu("NetworkTables")) { - if (gNetworkTablesSettingsWindow) + if (gNetworkTablesSettingsWindow) { gNetworkTablesSettingsWindow->DisplayMenuItem("NetworkTables Settings"); - if (gNetworkTablesWindow) + } + if (gNetworkTablesWindow) { gNetworkTablesWindow->DisplayMenuItem("NetworkTables View"); + } ImGui::Separator(); gNtProvider->DisplayMenu(); ImGui::EndMenu(); diff --git a/glass/src/lib/native/cpp/Context.cpp b/glass/src/lib/native/cpp/Context.cpp index 0868709e19..031170fbe5 100644 --- a/glass/src/lib/native/cpp/Context.cpp +++ b/glass/src/lib/native/cpp/Context.cpp @@ -26,8 +26,9 @@ static bool ConvertInt(Storage::Value* value) { if (value->stringVal.empty()) { return false; } else { - if (wpi::StringRef{value->stringVal}.getAsInteger(10, value->intVal)) + if (wpi::StringRef{value->stringVal}.getAsInteger(10, value->intVal)) { return false; + } } return true; } @@ -37,8 +38,9 @@ static bool ConvertInt64(Storage::Value* value) { if (value->stringVal.empty()) { return false; } else { - if (wpi::StringRef{value->stringVal}.getAsInteger(10, value->int64Val)) + if (wpi::StringRef{value->stringVal}.getAsInteger(10, value->int64Val)) { return false; + } } return true; } @@ -62,8 +64,9 @@ static bool ConvertFloat(Storage::Value* value) { if (value->stringVal.empty()) { return false; } else { - if (std::sscanf(value->stringVal.c_str(), "%f", &value->floatVal) != 1) + if (std::sscanf(value->stringVal.c_str(), "%f", &value->floatVal) != 1) { return false; + } } return true; } @@ -73,8 +76,9 @@ static bool ConvertDouble(Storage::Value* value) { if (value->stringVal.empty()) { return false; } else { - if (std::sscanf(value->stringVal.c_str(), "%lf", &value->doubleVal) != 1) + if (std::sscanf(value->stringVal.c_str(), "%lf", &value->doubleVal) != 1) { return false; + } } return true; } @@ -83,7 +87,9 @@ static void* GlassStorageReadOpen(ImGuiContext*, ImGuiSettingsHandler* handler, const char* name) { auto ctx = static_cast(handler->UserData); auto& storage = ctx->storage[name]; - if (!storage) storage = std::make_unique(); + if (!storage) { + storage = std::make_unique(); + } return storage.get(); } @@ -193,25 +199,39 @@ static void Shutdown(Context* ctx) {} Context* glass::CreateContext() { Context* ctx = new Context; - if (!gContext) SetCurrentContext(ctx); + if (!gContext) { + SetCurrentContext(ctx); + } Initialize(ctx); return ctx; } void glass::DestroyContext(Context* ctx) { - if (!ctx) ctx = gContext; + if (!ctx) { + ctx = gContext; + } Shutdown(ctx); - if (gContext == ctx) SetCurrentContext(nullptr); + if (gContext == ctx) { + SetCurrentContext(nullptr); + } delete ctx; } -Context* glass::GetCurrentContext() { return gContext; } +Context* glass::GetCurrentContext() { + return gContext; +} -void glass::SetCurrentContext(Context* ctx) { gContext = ctx; } +void glass::SetCurrentContext(Context* ctx) { + gContext = ctx; +} -void glass::ResetTime() { gContext->zeroTime = wpi::Now(); } +void glass::ResetTime() { + gContext->zeroTime = wpi::Now(); +} -uint64_t glass::GetZeroTime() { return gContext->zeroTime; } +uint64_t glass::GetZeroTime() { + return gContext->zeroTime; +} Storage::Value& Storage::GetValue(wpi::StringRef key) { auto it = std::find(m_keys.begin(), m_keys.end(), key); @@ -227,10 +247,12 @@ Storage::Value& Storage::GetValue(wpi::StringRef key) { #define DEFUN(CapsName, LowerName, CType) \ CType Storage::Get##CapsName(wpi::StringRef key, CType defaultVal) const { \ auto it = std::find(m_keys.begin(), m_keys.end(), key); \ - if (it == m_keys.end()) return defaultVal; \ + if (it == m_keys.end()) \ + return defaultVal; \ Value& value = *m_values[it - m_keys.begin()]; \ if (value.type != Value::k##CapsName) { \ - if (!Convert##CapsName(&value)) value.LowerName##Val = defaultVal; \ + if (!Convert##CapsName(&value)) \ + value.LowerName##Val = defaultVal; \ } \ return value.LowerName##Val; \ } \ @@ -260,7 +282,8 @@ Storage::Value& Storage::GetValue(wpi::StringRef key) { } else { \ Value& value = *m_values[it - m_keys.begin()]; \ if (value.type != Value::k##CapsName) { \ - if (!Convert##CapsName(&value)) value.LowerName##Val = defaultVal; \ + if (!Convert##CapsName(&value)) \ + value.LowerName##Val = defaultVal; \ } \ return &value.LowerName##Val; \ } \ @@ -275,7 +298,9 @@ DEFUN(Double, double, double) std::string Storage::GetString(wpi::StringRef key, const std::string& defaultVal) const { auto it = std::find(m_keys.begin(), m_keys.end(), key); - if (it == m_keys.end()) return defaultVal; + if (it == m_keys.end()) { + return defaultVal; + } Value& value = *m_values[it - m_keys.begin()]; value.type = Value::kString; return value.stringVal; @@ -311,13 +336,17 @@ std::string* Storage::GetStringRef(wpi::StringRef key, Storage& glass::GetStorage() { auto& storage = gContext->storage[gContext->curId]; - if (!storage) storage = std::make_unique(); + if (!storage) { + storage = std::make_unique(); + } return *storage; } Storage& glass::GetStorage(wpi::StringRef id) { auto& storage = gContext->storage[id]; - if (!storage) storage = std::make_unique(); + if (!storage) { + storage = std::make_unique(); + } return *storage; } @@ -326,8 +355,12 @@ static void PushIDStack(wpi::StringRef label_id) { auto [label, id] = wpi::StringRef{label_id}.split("###"); // if no ###id, use label as id - if (id.empty()) id = label; - if (!gContext->curId.empty()) gContext->curId += "###"; + if (id.empty()) { + id = label; + } + if (!gContext->curId.empty()) { + gContext->curId += "###"; + } gContext->curId += id; } @@ -361,7 +394,9 @@ bool glass::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { wpi::SmallString<64> openKey; auto [name, id] = wpi::StringRef{label}.split("###"); // if no ###id, use name as id - if (id.empty()) id = name; + if (id.empty()) { + id = name; + } openKey = id; openKey += "###open"; @@ -376,7 +411,9 @@ bool glass::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) { bool* open = GetStorage().GetBoolRef("open"); *open = ImGui::TreeNodeEx( label, flags | (*open ? ImGuiTreeNodeFlags_DefaultOpen : 0)); - if (!*open) PopIDStack(); + if (!*open) { + PopIDStack(); + } return *open; } diff --git a/glass/src/lib/native/cpp/DataSource.cpp b/glass/src/lib/native/cpp/DataSource.cpp index cf46686675..56c7f37ef7 100644 --- a/glass/src/lib/native/cpp/DataSource.cpp +++ b/glass/src/lib/native/cpp/DataSource.cpp @@ -14,7 +14,9 @@ DataSource::DataSource(const wpi::Twine& id) : m_id{id.str()} { auto it = gContext->sources.try_emplace(m_id, this); auto& srcName = it.first->getValue(); m_name = srcName.name.get(); - if (!srcName.source) srcName.source = this; + if (!srcName.source) { + srcName.source = this; + } sourceCreated(m_id.c_str(), this); } @@ -26,18 +28,30 @@ DataSource::DataSource(const wpi::Twine& id, int index, int index2) wpi::Twine(index2) + wpi::Twine(']')} {} DataSource::~DataSource() { - if (!gContext) return; + if (!gContext) { + return; + } auto it = gContext->sources.find(m_id); - if (it == gContext->sources.end()) return; + if (it == gContext->sources.end()) { + return; + } auto& srcName = it->getValue(); - if (srcName.source == this) srcName.source = nullptr; + if (srcName.source == this) { + srcName.source = nullptr; + } } -void DataSource::SetName(const wpi::Twine& name) { m_name->SetName(name); } +void DataSource::SetName(const wpi::Twine& name) { + m_name->SetName(name); +} -const char* DataSource::GetName() const { return m_name->GetName(); } +const char* DataSource::GetName() const { + return m_name->GetName(); +} -void DataSource::PushEditNameId(int index) { m_name->PushEditNameId(index); } +void DataSource::PushEditNameId(int index) { + m_name->PushEditNameId(index); +} void DataSource::PushEditNameId(const char* name) { m_name->PushEditNameId(name); @@ -134,6 +148,8 @@ void DataSource::EmitDrag(ImGuiDragDropFlags flags) const { DataSource* DataSource::Find(wpi::StringRef id) { auto it = gContext->sources.find(id); - if (it == gContext->sources.end()) return nullptr; + if (it == gContext->sources.end()) { + return nullptr; + } return it->getValue().source; } diff --git a/glass/src/lib/native/cpp/MainMenuBar.cpp b/glass/src/lib/native/cpp/MainMenuBar.cpp index 751cb7101f..2c4d371256 100644 --- a/glass/src/lib/native/cpp/MainMenuBar.cpp +++ b/glass/src/lib/native/cpp/MainMenuBar.cpp @@ -11,11 +11,15 @@ using namespace glass; void MainMenuBar::AddMainMenu(std::function menu) { - if (menu) m_menus.emplace_back(std::move(menu)); + if (menu) { + m_menus.emplace_back(std::move(menu)); + } } void MainMenuBar::AddOptionMenu(std::function menu) { - if (menu) m_optionMenus.emplace_back(std::move(menu)); + if (menu) { + m_optionMenus.emplace_back(std::move(menu)); + } } void MainMenuBar::Display() { @@ -24,7 +28,9 @@ void MainMenuBar::Display() { if (!m_optionMenus.empty()) { if (ImGui::BeginMenu("Options")) { for (auto&& menu : m_optionMenus) { - if (menu) menu(); + if (menu) { + menu(); + } } ImGui::EndMenu(); } @@ -33,7 +39,9 @@ void MainMenuBar::Display() { wpi::gui::EmitViewMenu(); for (auto&& menu : m_menus) { - if (menu) menu(); + if (menu) { + menu(); + } } #if 0 diff --git a/glass/src/lib/native/cpp/Model.cpp b/glass/src/lib/native/cpp/Model.cpp index 7ac23d010e..bee9086c86 100644 --- a/glass/src/lib/native/cpp/Model.cpp +++ b/glass/src/lib/native/cpp/Model.cpp @@ -6,4 +6,6 @@ using namespace glass; -bool Model::IsReadOnly() { return false; } +bool Model::IsReadOnly() { + return false; +} diff --git a/glass/src/lib/native/cpp/Window.cpp b/glass/src/lib/native/cpp/Window.cpp index 601ca75268..5b13c77d70 100644 --- a/glass/src/lib/native/cpp/Window.cpp +++ b/glass/src/lib/native/cpp/Window.cpp @@ -28,7 +28,9 @@ void Window::SetVisibility(Visibility visibility) { } void Window::Display() { - if (!m_view) return; + if (!m_view) { + return; + } if (!m_visible || !m_enabled) { PushID(m_id); m_view->Hidden(); @@ -36,22 +38,32 @@ void Window::Display() { return; } - if (m_posCond != 0) ImGui::SetNextWindowPos(m_pos, m_posCond); - if (m_sizeCond != 0) ImGui::SetNextWindowSize(m_size, m_sizeCond); - if (m_setPadding) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, m_padding); + if (m_posCond != 0) { + ImGui::SetNextWindowPos(m_pos, m_posCond); + } + if (m_sizeCond != 0) { + ImGui::SetNextWindowSize(m_size, m_sizeCond); + } + if (m_setPadding) { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, m_padding); + } char label[128]; std::snprintf(label, sizeof(label), "%s###%s", m_name.empty() ? m_id.c_str() : m_name.c_str(), m_id.c_str()); if (Begin(label, &m_visible, m_flags)) { - if (m_renamePopupEnabled) PopupEditName(nullptr, &m_name); + if (m_renamePopupEnabled) { + PopupEditName(nullptr, &m_name); + } m_view->Display(); } else { m_view->Hidden(); } End(); - if (m_setPadding) ImGui::PopStyleVar(); + if (m_setPadding) { + ImGui::PopStyleVar(); + } } bool Window::DisplayMenuItem(const char* label) { @@ -83,11 +95,15 @@ void Window::IniReadLine(const char* lineStr) { m_name = value; } else if (name == "visible") { int num; - if (value.getAsInteger(10, num)) return; + if (value.getAsInteger(10, num)) { + return; + } m_visible = num; } else if (name == "enabled") { int num; - if (value.getAsInteger(10, num)) return; + if (value.getAsInteger(10, num)) { + return; + } m_enabled = num; } } diff --git a/glass/src/lib/native/cpp/WindowManager.cpp b/glass/src/lib/native/cpp/WindowManager.cpp index d89df789e6..8e7f971274 100644 --- a/glass/src/lib/native/cpp/WindowManager.cpp +++ b/glass/src/lib/native/cpp/WindowManager.cpp @@ -34,7 +34,9 @@ void WindowManager::IniSaver::IniWriteAll(ImGuiTextBuffer* out_buf) { Window* WindowManager::AddWindow(wpi::StringRef id, wpi::unique_function display) { auto win = GetOrAddWindow(id, false); - if (!win) return nullptr; + if (!win) { + return nullptr; + } if (win->HasView()) { wpi::errs() << "GUI: ignoring duplicate window '" << id << "'\n"; return nullptr; @@ -46,7 +48,9 @@ Window* WindowManager::AddWindow(wpi::StringRef id, Window* WindowManager::AddWindow(wpi::StringRef id, std::unique_ptr view) { auto win = GetOrAddWindow(id, false); - if (!win) return nullptr; + if (!win) { + return nullptr; + } if (win->HasView()) { wpi::errs() << "GUI: ignoring duplicate window '" << id << "'\n"; return nullptr; @@ -76,7 +80,9 @@ Window* WindowManager::GetWindow(wpi::StringRef id) { auto it = std::lower_bound( m_windows.begin(), m_windows.end(), id, [](const auto& elem, wpi::StringRef s) { return elem->GetId() < s; }); - if (it == m_windows.end() || (*it)->GetId() != id) return nullptr; + if (it == m_windows.end() || (*it)->GetId() != id) { + return nullptr; + } return it->get(); } diff --git a/glass/src/lib/native/cpp/hardware/Accelerometer.cpp b/glass/src/lib/native/cpp/hardware/Accelerometer.cpp index 407b173021..6a1cc03a77 100644 --- a/glass/src/lib/native/cpp/hardware/Accelerometer.cpp +++ b/glass/src/lib/native/cpp/hardware/Accelerometer.cpp @@ -10,7 +10,9 @@ using namespace glass; void glass::DisplayAccelerometerDevice(AccelerometerModel* model) { - if (!model->Exists()) return; + if (!model->Exists()) { + return; + } if (BeginDevice("BuiltInAccel")) { // Range { diff --git a/glass/src/lib/native/cpp/hardware/AnalogInput.cpp b/glass/src/lib/native/cpp/hardware/AnalogInput.cpp index fb09fae704..c0f9780361 100644 --- a/glass/src/lib/native/cpp/hardware/AnalogInput.cpp +++ b/glass/src/lib/native/cpp/hardware/AnalogInput.cpp @@ -13,7 +13,9 @@ using namespace glass; void glass::DisplayAnalogInput(AnalogInputModel* model, int index) { auto voltageData = model->GetVoltageData(); - if (!voltageData) return; + if (!voltageData) { + return; + } // build label std::string* name = GetStorage().GetStringRef("name"); @@ -34,11 +36,15 @@ void glass::DisplayAnalogInput(AnalogInputModel* model, int index) { ImGui::PopStyleColor(); } else { float val = voltageData->GetValue(); - if (voltageData->SliderFloat(label, &val, 0.0, 5.0)) model->SetVoltage(val); + if (voltageData->SliderFloat(label, &val, 0.0, 5.0)) { + model->SetVoltage(val); + } } // context menu to change name - if (PopupEditName("name", name)) voltageData->SetName(name->c_str()); + if (PopupEditName("name", name)) { + voltageData->SetName(name->c_str()); + } } void glass::DisplayAnalogInputs(AnalogInputsModel* model, @@ -58,6 +64,7 @@ void glass::DisplayAnalogInputs(AnalogInputsModel* model, PopID(); hasAny = true; }); - if (!hasAny && !noneMsg.empty()) + if (!hasAny && !noneMsg.empty()) { ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + } } diff --git a/glass/src/lib/native/cpp/hardware/AnalogOutput.cpp b/glass/src/lib/native/cpp/hardware/AnalogOutput.cpp index 937a0117a3..3a9594be4b 100644 --- a/glass/src/lib/native/cpp/hardware/AnalogOutput.cpp +++ b/glass/src/lib/native/cpp/hardware/AnalogOutput.cpp @@ -13,12 +13,16 @@ using namespace glass; void glass::DisplayAnalogOutputsDevice(AnalogOutputsModel* model) { int count = 0; model->ForEachAnalogOutput([&](auto&, int) { ++count; }); - if (count == 0) return; + if (count == 0) { + return; + } if (BeginDevice("Analog Outputs")) { model->ForEachAnalogOutput([&](auto& analogOut, int i) { auto analogOutData = analogOut.GetVoltageData(); - if (!analogOutData) return; + if (!analogOutData) { + return; + } PushID(i); // build label @@ -34,7 +38,9 @@ void glass::DisplayAnalogOutputsDevice(AnalogOutputsModel* model) { DeviceDouble(label, true, &value, analogOutData); if (PopupEditName("name", name)) { - if (analogOutData) analogOutData->SetName(name->c_str()); + if (analogOutData) { + analogOutData->SetName(name->c_str()); + } } PopID(); }); diff --git a/glass/src/lib/native/cpp/hardware/DIO.cpp b/glass/src/lib/native/cpp/hardware/DIO.cpp index e7932730d1..4d8cdf2a73 100644 --- a/glass/src/lib/native/cpp/hardware/DIO.cpp +++ b/glass/src/lib/native/cpp/hardware/DIO.cpp @@ -59,11 +59,12 @@ void DisplayDIOImpl(DIOModel* model, int index, bool outputsEnabled) { } } else { const char* name = model->GetName(); - if (name[0] != '\0') + if (name[0] != '\0') { info.GetLabel(label, sizeof(label), name); - else + } else { info.GetLabel(label, sizeof(label), model->IsInput() ? " In" : "Out", index); + } if (auto simDevice = model->GetSimDevice()) { LabelSimDevice(label, simDevice); } else { @@ -87,8 +88,12 @@ void DisplayDIOImpl(DIOModel* model, int index, bool outputsEnabled) { } } if (info.PopupEditName(index)) { - if (dpwmData) dpwmData->SetName(info.GetName()); - if (dutyCycleData) dutyCycleData->SetName(info.GetName()); + if (dpwmData) { + dpwmData->SetName(info.GetName()); + } + if (dutyCycleData) { + dutyCycleData->SetName(info.GetName()); + } } } @@ -110,6 +115,7 @@ void glass::DisplayDIOs(DIOsModel* model, bool outputsEnabled, ImGui::PopID(); }); ImGui::PopItemWidth(); - if (!hasAny && !noneMsg.empty()) + if (!hasAny && !noneMsg.empty()) { ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + } } diff --git a/glass/src/lib/native/cpp/hardware/Encoder.cpp b/glass/src/lib/native/cpp/hardware/Encoder.cpp index a3cf0df647..eca2840e5d 100644 --- a/glass/src/lib/native/cpp/hardware/Encoder.cpp +++ b/glass/src/lib/native/cpp/hardware/Encoder.cpp @@ -82,7 +82,9 @@ void glass::DisplayEncoder(EncoderModel* model) { model->SetName(name->c_str()); } - if (!open) return; + if (!open) { + return; + } ImGui::PushItemWidth(ImGui::GetFontSize() * 8); // distance per pulse @@ -94,7 +96,9 @@ void glass::DisplayEncoder(EncoderModel* model) { // count if (auto countData = model->GetCountData()) { int value = countData->GetValue(); - if (ImGui::InputInt("##input", &value)) model->SetCount(value); + if (ImGui::InputInt("##input", &value)) { + model->SetCount(value); + } ImGui::SameLine(); if (ImGui::Button("Reset")) { model->SetCount(0); @@ -157,6 +161,7 @@ void glass::DisplayEncoders(EncodersModel* model, wpi::StringRef noneMsg) { DisplayEncoder(&encoder); PopID(); }); - if (!hasAny && !noneMsg.empty()) + if (!hasAny && !noneMsg.empty()) { ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + } } diff --git a/glass/src/lib/native/cpp/hardware/Gyro.cpp b/glass/src/lib/native/cpp/hardware/Gyro.cpp index 2b717f0446..5b4c86daeb 100644 --- a/glass/src/lib/native/cpp/hardware/Gyro.cpp +++ b/glass/src/lib/native/cpp/hardware/Gyro.cpp @@ -36,8 +36,9 @@ void glass::DisplayGyro(GyroModel* m) { m->IsReadOnly() ? ImGuiInputTextFlags_ReadOnly : ImGuiInputTextFlags_None; auto value = angle->GetValue(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); - if (ImGui::InputDouble("Gyro Angle (Deg)", &value, 0.0, 0.0, "%.4f", flags)) + if (ImGui::InputDouble("Gyro Angle (Deg)", &value, 0.0, 0.0, "%.4f", flags)) { m->SetAngle(value); + } // Draw the gyro indicator. ImDrawList* draw = ImGui::GetWindowDrawList(); diff --git a/glass/src/lib/native/cpp/hardware/LEDDisplay.cpp b/glass/src/lib/native/cpp/hardware/LEDDisplay.cpp index fd074fb972..c32e3df1a3 100644 --- a/glass/src/lib/native/cpp/hardware/LEDDisplay.cpp +++ b/glass/src/lib/native/cpp/hardware/LEDDisplay.cpp @@ -42,7 +42,9 @@ void glass::DisplayLEDDisplay(LEDDisplayModel* model, int index) { ImGui::Combo("Start", start, options, 4); } ImGui::Checkbox("Serpentine", serpentine); - if (*numColumns < 1) *numColumns = 1; + if (*numColumns < 1) { + *numColumns = 1; + } ImGui::PopItemWidth(); // show as LED indicators @@ -51,13 +53,17 @@ void glass::DisplayLEDDisplay(LEDDisplayModel* model, int index) { storage.SetData(std::make_shared()); iData = storage.GetData(); } - if (length > static_cast(iData->values.size())) + if (length > static_cast(iData->values.size())) { iData->values.resize(length); - if (length > static_cast(iData->colors.size())) + } + if (length > static_cast(iData->colors.size())) { iData->colors.resize(length); + } if (!running) { iData->colors[0] = IM_COL32(128, 128, 128, 255); - for (int j = 0; j < length; ++j) iData->values[j] = -1; + for (int j = 0; j < length; ++j) { + iData->values[j] = -1; + } } else { for (int j = 0; j < length; ++j) { iData->values[j] = j + 1; @@ -79,10 +85,14 @@ void glass::DisplayLEDDisplays(LEDDisplaysModel* model) { model->ForEachLEDDisplay([&](LEDDisplayModel& display, int i) { hasAny = true; - if (model->GetNumLEDDisplays() > 1) ImGui::Text("LEDs[%d]", i); + if (model->GetNumLEDDisplays() > 1) { + ImGui::Text("LEDs[%d]", i); + } PushID(i); DisplayLEDDisplay(&display, i); PopID(); }); - if (!hasAny) ImGui::Text("No addressable LEDs"); + if (!hasAny) { + ImGui::Text("No addressable LEDs"); + } } diff --git a/glass/src/lib/native/cpp/hardware/PCM.cpp b/glass/src/lib/native/cpp/hardware/PCM.cpp index 0664512363..400df689ba 100644 --- a/glass/src/lib/native/cpp/hardware/PCM.cpp +++ b/glass/src/lib/native/cpp/hardware/PCM.cpp @@ -23,16 +23,22 @@ bool glass::DisplayPCMSolenoids(PCMModel* model, int index, wpi::SmallVector channels; model->ForEachSolenoid([&](SolenoidModel& solenoid, int j) { if (auto data = solenoid.GetOutputData()) { - if (j >= static_cast(channels.size())) channels.resize(j + 1); + if (j >= static_cast(channels.size())) { + channels.resize(j + 1); + } channels[j] = (outputsEnabled && data->GetValue()) ? 1 : -1; } }); - if (channels.empty()) return false; + if (channels.empty()) { + return false; + } // show nonexistent channels as empty for (auto&& ch : channels) { - if (ch == 0) ch = -2; + if (ch == 0) { + ch = -2; + } } // build header label @@ -81,17 +87,22 @@ void glass::DisplayPCMsSolenoids(PCMsModel* model, bool outputsEnabled, bool hasAny = false; model->ForEachPCM([&](PCMModel& pcm, int i) { PushID(i); - if (DisplayPCMSolenoids(&pcm, i, outputsEnabled)) hasAny = true; + if (DisplayPCMSolenoids(&pcm, i, outputsEnabled)) { + hasAny = true; + } PopID(); }); - if (!hasAny && !noneMsg.empty()) + if (!hasAny && !noneMsg.empty()) { ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + } } void glass::DisplayCompressorDevice(PCMModel* model, int index, bool outputsEnabled) { auto compressor = model->GetCompressor(); - if (!compressor || !compressor->Exists()) return; + if (!compressor || !compressor->Exists()) { + return; + } DisplayCompressorDevice(compressor, index, outputsEnabled); } diff --git a/glass/src/lib/native/cpp/hardware/PDP.cpp b/glass/src/lib/native/cpp/hardware/PDP.cpp index 3eadb9f0ac..23871cabc2 100644 --- a/glass/src/lib/native/cpp/hardware/PDP.cpp +++ b/glass/src/lib/native/cpp/hardware/PDP.cpp @@ -24,8 +24,9 @@ static float DisplayChannel(PDPModel& pdp, int channel) { leftInfo.GetLabel(name, sizeof(name), "", channel); double val = currentData->GetValue(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - if (currentData->InputDouble(name, &val, 0, 0, "%.3f")) + if (currentData->InputDouble(name, &val, 0, 0, "%.3f")) { pdp.SetCurrent(channel, val); + } width = ImGui::GetItemRectSize().x; leftInfo.PopupEditName(channel); ImGui::PopID(); @@ -69,7 +70,9 @@ void glass::DisplayPDP(PDPModel* model, int index) { float width = (std::max)(leftWidth, rightWidth) * 2 + ImGui::GetFontSize() * 4; - if (width > maxWidth) maxWidth = width; + if (width > maxWidth) { + maxWidth = width; + } } ImGui::Columns(1); ImGui::Dummy(ImVec2(maxWidth, 0)); @@ -84,6 +87,7 @@ void glass::DisplayPDPs(PDPsModel* model, wpi::StringRef noneMsg) { DisplayPDP(&pdp, i); PopID(); }); - if (!hasAny && !noneMsg.empty()) + if (!hasAny && !noneMsg.empty()) { ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + } } diff --git a/glass/src/lib/native/cpp/hardware/PWM.cpp b/glass/src/lib/native/cpp/hardware/PWM.cpp index 840f11302a..6fbc6243b5 100644 --- a/glass/src/lib/native/cpp/hardware/PWM.cpp +++ b/glass/src/lib/native/cpp/hardware/PWM.cpp @@ -13,7 +13,9 @@ using namespace glass; void glass::DisplayPWM(PWMModel* model, int index, bool outputsEnabled) { auto data = model->GetSpeedData(); - if (!data) return; + if (!data) { + return; + } // build label std::string* name = GetStorage().GetStringRef("name"); @@ -46,14 +48,16 @@ void glass::DisplayPWMs(PWMsModel* model, bool outputsEnabled, hasAny = true; PushID(i); - if (!first) + if (!first) { ImGui::Separator(); - else + } else { first = false; + } DisplayPWM(&pwm, i, outputsEnabled); PopID(); }); - if (!hasAny && !noneMsg.empty()) + if (!hasAny && !noneMsg.empty()) { ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + } } diff --git a/glass/src/lib/native/cpp/hardware/Relay.cpp b/glass/src/lib/native/cpp/hardware/Relay.cpp index a7de1b4b97..f0dbbf7209 100644 --- a/glass/src/lib/native/cpp/hardware/Relay.cpp +++ b/glass/src/lib/native/cpp/hardware/Relay.cpp @@ -23,20 +23,29 @@ void glass::DisplayRelay(RelayModel* model, int index, bool outputsEnabled) { bool forward = false; bool reverse = false; if (outputsEnabled) { - if (forwardData) forward = forwardData->GetValue(); - if (reverseData) reverse = reverseData->GetValue(); + if (forwardData) { + forward = forwardData->GetValue(); + } + if (reverseData) { + reverse = reverseData->GetValue(); + } } std::string* name = GetStorage().GetStringRef("name"); ImGui::PushID("name"); - if (!name->empty()) + if (!name->empty()) { ImGui::Text("%s [%d]", name->c_str(), index); - else + } else { ImGui::Text("Relay[%d]", index); + } ImGui::PopID(); if (PopupEditName("name", name)) { - if (forwardData) forwardData->SetName(name->c_str()); - if (reverseData) reverseData->SetName(name->c_str()); + if (forwardData) { + forwardData->SetName(name->c_str()); + } + if (reverseData) { + reverseData->SetName(name->c_str()); + } } ImGui::SameLine(); @@ -57,15 +66,17 @@ void glass::DisplayRelays(RelaysModel* model, bool outputsEnabled, model->ForEachRelay([&](RelayModel& relay, int i) { hasAny = true; - if (!first) + if (!first) { ImGui::Separator(); - else + } else { first = false; + } PushID(i); DisplayRelay(&relay, i, outputsEnabled); PopID(); }); - if (!hasAny && !noneMsg.empty()) + if (!hasAny && !noneMsg.empty()) { ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + } } diff --git a/glass/src/lib/native/cpp/hardware/SpeedController.cpp b/glass/src/lib/native/cpp/hardware/SpeedController.cpp index 8f749afaf8..2c3181f2d2 100644 --- a/glass/src/lib/native/cpp/hardware/SpeedController.cpp +++ b/glass/src/lib/native/cpp/hardware/SpeedController.cpp @@ -23,11 +23,15 @@ void glass::DisplaySpeedController(SpeedControllerModel* m) { } // Add button to zero output. - if (ImGui::Button("Zero")) m->SetPercent(0.0); + if (ImGui::Button("Zero")) { + m->SetPercent(0.0); + } ImGui::SameLine(); // Display a slider for the data. float value = dc->GetValue(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); - if (dc->SliderFloat("% Output", &value, -1.0f, 1.0f)) m->SetPercent(value); + if (dc->SliderFloat("% Output", &value, -1.0f, 1.0f)) { + m->SetPercent(value); + } } diff --git a/glass/src/lib/native/cpp/other/CommandScheduler.cpp b/glass/src/lib/native/cpp/other/CommandScheduler.cpp index b5b04f8d7b..83e4118631 100644 --- a/glass/src/lib/native/cpp/other/CommandScheduler.cpp +++ b/glass/src/lib/native/cpp/other/CommandScheduler.cpp @@ -27,7 +27,9 @@ void glass::DisplayCommandScheduler(CommandSchedulerModel* m) { ImGui::SameLine(pos); ImGui::PushID(i); - if (ImGui::Button("Cancel")) m->CancelCommand(i); + if (ImGui::Button("Cancel")) { + m->CancelCommand(i); + } ImGui::PopID(); } } else { diff --git a/glass/src/lib/native/cpp/other/CommandSelector.cpp b/glass/src/lib/native/cpp/other/CommandSelector.cpp index 8154489090..d2124c39fa 100644 --- a/glass/src/lib/native/cpp/other/CommandSelector.cpp +++ b/glass/src/lib/native/cpp/other/CommandSelector.cpp @@ -12,7 +12,9 @@ using namespace glass; void glass::DisplayCommandSelector(CommandSelectorModel* m) { - if (auto name = m->GetName()) ImGui::Text("%s", name); + if (auto name = m->GetName()) { + ImGui::Text("%s", name); + } if (m->Exists()) { if (auto run = m->GetRunningData()) { bool running = run->GetValue(); @@ -21,7 +23,9 @@ void glass::DisplayCommandSelector(CommandSelectorModel* m) { m->SetRunning(running); } ImGui::SameLine(); - if (running) ImGui::Text("Running..."); + if (running) { + ImGui::Text("Running..."); + } } } else { ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(96, 96, 96, 255)); diff --git a/glass/src/lib/native/cpp/other/DeviceTree.cpp b/glass/src/lib/native/cpp/other/DeviceTree.cpp index ba3b828ae7..cd69eb7d20 100644 --- a/glass/src/lib/native/cpp/other/DeviceTree.cpp +++ b/glass/src/lib/native/cpp/other/DeviceTree.cpp @@ -16,27 +16,37 @@ using namespace glass; void DeviceTreeModel::Update() { for (auto&& display : m_displays) { - if (display.first) display.first->Update(); + if (display.first) { + display.first->Update(); + } } } bool DeviceTreeModel::Exists() { for (auto&& display : m_displays) { - if (display.first && display.first->Exists()) return true; + if (display.first && display.first->Exists()) { + return true; + } } return false; } void DeviceTreeModel::Display() { for (auto&& display : m_displays) { - if (display.second) display.second(display.first); + if (display.second) { + display.second(display.first); + } } } -void glass::HideDevice(const char* id) { gContext->deviceHidden[id] = true; } +void glass::HideDevice(const char* id) { + gContext->deviceHidden[id] = true; +} bool glass::BeginDevice(const char* id, ImGuiTreeNodeFlags flags) { - if (gContext->deviceHidden[id]) return false; + if (gContext->deviceHidden[id]) { + return false; + } PushID(id); @@ -49,11 +59,15 @@ bool glass::BeginDevice(const char* id, ImGuiTreeNodeFlags flags) { bool open = CollapsingHeader(label, flags); PopupEditName("name", name); - if (!open) PopID(); + if (!open) { + PopID(); + } return open; } -void glass::EndDevice() { PopID(); } +void glass::EndDevice() { + PopID(); +} static bool DeviceBooleanImpl(const char* name, bool readonly, bool* value) { if (readonly) { @@ -82,10 +96,11 @@ static bool DeviceDoubleImpl(const char* name, bool readonly, double* value) { static bool DeviceEnumImpl(const char* name, bool readonly, int* value, const char** options, int32_t numOptions) { if (readonly) { - if (*value < 0 || *value >= numOptions) + if (*value < 0 || *value >= numOptions) { ImGui::LabelText(name, "%d (unknown)", *value); - else + } else { ImGui::LabelText(name, "%s", options[*value]); + } return false; } else { return ImGui::Combo(name, value, options, numOptions); diff --git a/glass/src/lib/native/cpp/other/FMS.cpp b/glass/src/lib/native/cpp/other/FMS.cpp index f6b9b6fd7c..a19cad453a 100644 --- a/glass/src/lib/native/cpp/other/FMS.cpp +++ b/glass/src/lib/native/cpp/other/FMS.cpp @@ -15,19 +15,25 @@ static const char* stations[] = {"Red 1", "Red 2", "Red 3", "Blue 1", "Blue 2", "Blue 3"}; void glass::DisplayFMS(FMSModel* model, bool* matchTimeEnabled) { - if (!model->Exists() || model->IsReadOnly()) return DisplayFMSReadOnly(model); + if (!model->Exists() || model->IsReadOnly()) { + return DisplayFMSReadOnly(model); + } // FMS Attached if (auto data = model->GetFmsAttachedData()) { bool val = data->GetValue(); - if (ImGui::Checkbox("FMS Attached", &val)) model->SetFmsAttached(val); + if (ImGui::Checkbox("FMS Attached", &val)) { + model->SetFmsAttached(val); + } data->EmitDrag(); } // DS Attached if (auto data = model->GetDsAttachedData()) { bool val = data->GetValue(); - if (ImGui::Checkbox("DS Attached", &val)) model->SetDsAttached(val); + if (ImGui::Checkbox("DS Attached", &val)) { + model->SetDsAttached(val); + } data->EmitDrag(); } @@ -35,15 +41,17 @@ void glass::DisplayFMS(FMSModel* model, bool* matchTimeEnabled) { if (auto data = model->GetAllianceStationIdData()) { int val = data->GetValue(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); - if (ImGui::Combo("Alliance Station", &val, stations, 6)) + if (ImGui::Combo("Alliance Station", &val, stations, 6)) { model->SetAllianceStationId(val); + } data->EmitDrag(); } // Match Time if (auto data = model->GetMatchTimeData()) { - if (matchTimeEnabled) + if (matchTimeEnabled) { ImGui::Checkbox("Match Time Enabled", matchTimeEnabled); + } double val = data->GetValue(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); @@ -74,7 +82,9 @@ void glass::DisplayFMS(FMSModel* model, bool* matchTimeEnabled) { void glass::DisplayFMSReadOnly(FMSModel* model) { bool exists = model->Exists(); - if (!exists) ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(96, 96, 96, 255)); + if (!exists) { + ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(96, 96, 96, 255)); + } if (auto data = model->GetEStopData()) { ImGui::Selectable("E-Stopped: "); @@ -123,15 +133,18 @@ void glass::DisplayFMSReadOnly(FMSModel* model) { ImGui::Selectable("Match Time: "); data->EmitDrag(); ImGui::SameLine(); - if (exists) + if (exists) { ImGui::Text("%.1f", data->GetValue()); - else + } else { ImGui::TextUnformatted("?"); + } } wpi::SmallString<64> gameSpecificMessage; model->GetGameSpecificMessage(gameSpecificMessage); ImGui::Text("Game Specific: %s", exists ? gameSpecificMessage.c_str() : "?"); - if (!exists) ImGui::PopStyleColor(); + if (!exists) { + ImGui::PopStyleColor(); + } } diff --git a/glass/src/lib/native/cpp/other/Field2D.cpp b/glass/src/lib/native/cpp/other/Field2D.cpp index fc9aa02748..dd73172101 100644 --- a/glass/src/lib/native/cpp/other/Field2D.cpp +++ b/glass/src/lib/native/cpp/other/Field2D.cpp @@ -182,7 +182,9 @@ void FieldInfo::LoadImage() { m_fileOpener.reset(); } if (!m_texture && !m_pFilename->empty()) { - if (!LoadImageImpl(m_pFilename->c_str())) m_pFilename->clear(); + if (!LoadImageImpl(m_pFilename->c_str())) { + m_pFilename->clear(); + } } } @@ -264,7 +266,9 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { wpi::sys::path::append(pathname, image); // load field image - if (!LoadImageImpl(pathname.c_str())) return; + if (!LoadImageImpl(pathname.c_str())) { + return; + } // save to field info *m_pFilename = pathname.str(); @@ -292,8 +296,9 @@ bool FieldInfo::LoadImageImpl(const char* fn) { FieldFrameData FieldInfo::GetFrameData(ImVec2 min, ImVec2 max) const { // fit the image into the window - if (m_texture && m_imageHeight != 0 && m_imageWidth != 0) + if (m_texture && m_imageHeight != 0 && m_imageWidth != 0) { gui::MaxFit(&min, &max, m_imageWidth, m_imageHeight); + } FieldFrameData ffd; ffd.imageMin = min; @@ -340,11 +345,15 @@ void ObjectGroupInfo::Reset() { void ObjectGroupInfo::LoadImage() { if (m_fileOpener && m_fileOpener->ready(0)) { auto result = m_fileOpener->result(); - if (!result.empty()) LoadImageImpl(result[0].c_str()); + if (!result.empty()) { + LoadImageImpl(result[0].c_str()); + } m_fileOpener.reset(); } if (!m_texture && !m_pFilename->empty()) { - if (!LoadImageImpl(m_pFilename->c_str())) m_pFilename->clear(); + if (!LoadImageImpl(m_pFilename->c_str())) { + m_pFilename->clear(); + } } } @@ -368,10 +377,15 @@ ObjectFrameData::ObjectFrameData(FieldObjectModel& model, m_width2(ffd.scale * width / 2), m_length2(ffd.scale * length / 2), m_hitRadius((std::min)(m_width2, m_length2) / 2) { - if (auto xData = model.GetXData()) m_x = xData->GetValue(); - if (auto yData = model.GetYData()) m_y = yData->GetValue(); - if (auto rotationData = model.GetRotationData()) + if (auto xData = model.GetXData()) { + m_x = xData->GetValue(); + } + if (auto yData = model.GetYData()) { + m_y = yData->GetValue(); + } + if (auto rotationData = model.GetRotationData()) { m_rot = rotationData->GetValue(); + } UpdateFrameData(); } @@ -418,22 +432,25 @@ int ObjectFrameData::IsHovered(const ImVec2& cursor) const { // only allow initiation of dragging when invisible button is hovered; // this prevents the window resize handles from simultaneously activating // the drag functionality - if (!ImGui::IsItemHovered()) return 0; + if (!ImGui::IsItemHovered()) { + return 0; + } float hitRadiusSquared = m_hitRadius * m_hitRadius; // it's within the hit radius of the center? - if (gui::GetDistSquared(cursor, m_center) < hitRadiusSquared) + if (gui::GetDistSquared(cursor, m_center) < hitRadiusSquared) { return 1; - else if (gui::GetDistSquared(cursor, m_corners[0]) < hitRadiusSquared) + } else if (gui::GetDistSquared(cursor, m_corners[0]) < hitRadiusSquared) { return 2; - else if (gui::GetDistSquared(cursor, m_corners[1]) < hitRadiusSquared) + } else if (gui::GetDistSquared(cursor, m_corners[1]) < hitRadiusSquared) { return 3; - else if (gui::GetDistSquared(cursor, m_corners[2]) < hitRadiusSquared) + } else if (gui::GetDistSquared(cursor, m_corners[2]) < hitRadiusSquared) { return 4; - else if (gui::GetDistSquared(cursor, m_corners[3]) < hitRadiusSquared) + } else if (gui::GetDistSquared(cursor, m_corners[3]) < hitRadiusSquared) { return 5; - else + } else { return 0; + } } bool ObjectFrameData::HandleDrag(const ImVec2& cursor, int hitCorner, @@ -525,10 +542,14 @@ void glass::DisplayField2DSettings(Field2DModel* model) { } model->ForEachFieldObjectGroup([&](auto& groupModel, auto name) { - if (!groupModel.Exists()) return; + if (!groupModel.Exists()) { + return; + } PushID(name); auto& objGroupRef = field->m_objectGroups[name]; - if (!objGroupRef) objGroupRef = std::make_unique(); + if (!objGroupRef) { + objGroupRef = std::make_unique(); + } auto objGroup = objGroupRef.get(); wpi::SmallString<64> nameBuf = name; @@ -565,7 +586,9 @@ void glass::DisplayField2D(Field2DModel* model, const ImVec2& contentSize) { // for dragging to work, there needs to be a button (otherwise the window is // dragged) - if (contentSize.x <= 0 || contentSize.y <= 0) return; + if (contentSize.x <= 0 || contentSize.y <= 0) { + return; + } ImVec2 cursorPos = windowPos + ImGui::GetCursorPos(); // screen coords ImGui::InvisibleButton("field", contentSize); @@ -576,10 +599,14 @@ void glass::DisplayField2D(Field2DModel* model, const ImVec2& contentSize) { field->Draw(drawList, ffd); model->ForEachFieldObjectGroup([&](auto& groupModel, auto name) { - if (!groupModel.Exists()) return; + if (!groupModel.Exists()) { + return; + } PushID(name); auto& objGroupRef = field->m_objectGroups[name]; - if (!objGroupRef) objGroupRef = std::make_unique(); + if (!objGroupRef) { + objGroupRef = std::make_unique(); + } auto objGroup = objGroupRef.get(); objGroup->LoadImage(); @@ -593,8 +620,9 @@ void glass::DisplayField2D(Field2DModel* model, const ImVec2& contentSize) { if (objGroup->m_dragState.object == 0 || objGroup->m_dragState.object == i) { hitCorner = ofd.IsHovered(mousePos); - if (ofd.HandleDrag(mousePos, hitCorner, &objGroup->m_dragState)) + if (ofd.HandleDrag(mousePos, hitCorner, &objGroup->m_dragState)) { objGroup->m_dragState.object = i; + } } // draw diff --git a/glass/src/lib/native/cpp/other/PIDController.cpp b/glass/src/lib/native/cpp/other/PIDController.cpp index ad5d12a3d3..30a3e8a569 100644 --- a/glass/src/lib/native/cpp/other/PIDController.cpp +++ b/glass/src/lib/native/cpp/other/PIDController.cpp @@ -23,7 +23,9 @@ void glass::DisplayPIDController(PIDControllerModel* m) { auto createTuningParameter = [](const char* name, double* v, std::function callback) { ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - if (ImGui::InputDouble(name, v, 0.0, 0.0, "%.3f")) callback(*v); + if (ImGui::InputDouble(name, v, 0.0, 0.0, "%.3f")) { + callback(*v); + } }; if (auto p = m->GetPData()) { diff --git a/glass/src/lib/native/cpp/other/Plot.cpp b/glass/src/lib/native/cpp/other/Plot.cpp index d0fc1b50ac..23b720ab4e 100644 --- a/glass/src/lib/native/cpp/other/Plot.cpp +++ b/glass/src/lib/native/cpp/other/Plot.cpp @@ -237,17 +237,23 @@ bool PlotSeries::ReadIni(wpi::StringRef name, wpi::StringRef value) { } if (name == "yAxis") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_yAxis = num; return true; } else if (name == "color") { unsigned int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_color = ImColor(num); return true; } else if (name == "marker") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_marker = num; return true; } else if (name == "weight") { @@ -255,17 +261,23 @@ bool PlotSeries::ReadIni(wpi::StringRef name, wpi::StringRef value) { return true; } else if (name == "digital") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_digital = num; return true; } else if (name == "digitalBitHeight") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_digitalBitHeight = num; return true; } else if (name == "digitalBitGap") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_digitalBitGap = num; return true; } @@ -281,10 +293,14 @@ void PlotSeries::WriteIni(ImGuiTextBuffer* out) { } const char* PlotSeries::GetName() const { - if (!m_name.empty()) return m_name.c_str(); + if (!m_name.empty()) { + return m_name.c_str(); + } if (m_newValueConn.connected()) { auto sourceName = m_source->GetName(); - if (sourceName[0] != '\0') return sourceName; + if (sourceName[0] != '\0') { + return sourceName; + } } return m_id.c_str(); } @@ -311,19 +327,23 @@ PlotSeries::Action PlotSeries::EmitPlot(PlotView& view, double now, size_t i, GetterData getterData = {now, GetZeroTime() * 1.0e-6, m_data, size, offset}; auto getter = [](void* data, int idx) { auto d = static_cast(data); - if (idx == d->size) + if (idx == d->size) { return ImPlotPoint{ d->now - d->zeroTime, d->data[d->offset == 0 ? d->size - 1 : d->offset - 1].y}; + } ImPlotPoint* point; - if (d->offset + idx < d->size) + if (d->offset + idx < d->size) { point = &d->data[d->offset + idx]; - else + } else { point = &d->data[d->offset + idx - d->size]; + } return ImPlotPoint{point->x - d->zeroTime, point->y}; }; - if (m_color.w == IMPLOT_AUTO_COL.w) m_color = ImPlot::GetColormapColor(i); + if (m_color.w == IMPLOT_AUTO_COL.w) { + m_color = ImPlot::GetColormapColor(i); + } ImPlot::SetNextLineStyle(m_color, m_weight); if (IsDigital()) { ImPlot::PushStyleVar(ImPlotStyleVar_DigitalBitHeight, m_digitalBitHeight); @@ -346,7 +366,9 @@ PlotSeries::Action PlotSeries::EmitPlot(PlotView& view, double now, size_t i, // Edit settings via popup Action rv = kNone; if (ImPlot::BeginLegendPopup(label)) { - if (ImGui::Button("Close")) ImGui::CloseCurrentPopup(); + if (ImGui::Button("Close")) { + ImGui::CloseCurrentPopup(); + } ImGui::Text("Edit series name:"); ImGui::InputText("##editname", &m_name); if (ImGui::Button("Move Up")) { @@ -382,7 +404,9 @@ void PlotSeries::EmitSettings(size_t i) { { ImGui::ColorEdit3("Color", &m_color.x, ImGuiColorEditFlags_NoInputs); ImGui::SameLine(); - if (ImGui::Button("Default")) m_color = ImPlot::GetColormapColor(i); + if (ImGui::Button("Default")) { + m_color = ImPlot::GetColormapColor(i); + } } // Line weight @@ -443,76 +467,107 @@ bool Plot::ReadIni(wpi::StringRef name, wpi::StringRef value) { return true; } else if (name == "visible") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_visible = num != 0; return true; } else if (name == "showPause") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_showPause = num != 0; return true; } else if (name == "lockPrevX") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_lockPrevX = num != 0; return true; } else if (name == "legend") { int num; - if (value.getAsInteger(10, num)) return true; - if (num == 0) + if (value.getAsInteger(10, num)) { + return true; + } + if (num == 0) { m_plotFlags &= ~ImPlotFlags_Legend; - else + } else { m_plotFlags |= ImPlotFlags_Legend; + } return true; } else if (name == "yaxis2") { int num; - if (value.getAsInteger(10, num)) return true; - if (num == 0) + if (value.getAsInteger(10, num)) { + return true; + } + if (num == 0) { m_plotFlags &= ~ImPlotFlags_YAxis2; - else + } else { m_plotFlags |= ImPlotFlags_YAxis2; + } return true; } else if (name == "yaxis3") { int num; - if (value.getAsInteger(10, num)) return true; - if (num == 0) + if (value.getAsInteger(10, num)) { + return true; + } + if (num == 0) { m_plotFlags &= ~ImPlotFlags_YAxis3; - else + } else { m_plotFlags |= ImPlotFlags_YAxis3; + } return true; } else if (name == "viewTime") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_viewTime = num / 1000.0; return true; } else if (name == "height") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_height = num; return true; } else if (name.startswith("y")) { auto [yAxisStr, yName] = name.split('_'); int yAxis; - if (yAxisStr.substr(1).getAsInteger(10, yAxis)) return false; - if (yAxis < 0 || yAxis > 3) return false; + if (yAxisStr.substr(1).getAsInteger(10, yAxis)) { + return false; + } + if (yAxis < 0 || yAxis > 3) { + return false; + } if (yName == "min") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_axisRange[yAxis].min = num / 1000.0; return true; } else if (yName == "max") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_axisRange[yAxis].max = num / 1000.0; return true; } else if (yName == "lockMin") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_axisRange[yAxis].lockMin = num != 0; return true; } else if (yName == "lockMax") { int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_axisRange[yAxis].lockMax = num != 0; return true; } @@ -539,7 +594,9 @@ void Plot::WriteIni(ImGuiTextBuffer* out) { } void Plot::DragDropTarget(PlotView& view, size_t i, bool inPlot) { - if (!ImGui::BeginDragDropTarget()) return; + if (!ImGui::BeginDragDropTarget()) { + return; + } // handle dragging onto a specific Y axis int yAxis = -1; if (inPlot) { @@ -576,12 +633,15 @@ void Plot::DragDropTarget(PlotView& view, size_t i, bool inPlot) { } void Plot::EmitPlot(PlotView& view, double now, bool paused, size_t i) { - if (!m_visible) return; + if (!m_visible) { + return; + } bool lockX = (i != 0 && m_lockPrevX); - if (!lockX && m_showPause && ImGui::Button(m_paused ? "Resume" : "Pause")) + if (!lockX && m_showPause && ImGui::Button(m_paused ? "Resume" : "Pause")) { m_paused = !m_paused; + } char label[128]; std::snprintf(label, sizeof(label), "%s##plot", m_name.c_str()); @@ -606,8 +666,12 @@ void Plot::EmitPlot(PlotView& view, double now, bool paused, size_t i) { m_axisRange[i].min, m_axisRange[i].max, m_axisRange[i].apply ? ImGuiCond_Always : ImGuiCond_Once, i); m_axisRange[i].apply = false; - if (m_axisRange[i].lockMin) yFlags[i] |= ImPlotAxisFlags_LockMin; - if (m_axisRange[i].lockMax) yFlags[i] |= ImPlotAxisFlags_LockMax; + if (m_axisRange[i].lockMin) { + yFlags[i] |= ImPlotAxisFlags_LockMin; + } + if (m_axisRange[i].lockMax) { + yFlags[i] |= ImPlotAxisFlags_LockMax; + } } if (ImPlot::BeginPlot(label, nullptr, nullptr, ImVec2(-1, m_height), @@ -617,11 +681,14 @@ void Plot::EmitPlot(PlotView& view, double now, bool paused, size_t i) { ImGui::PushID(j); switch (m_series[j]->EmitPlot(view, now, j, i)) { case PlotSeries::kMoveUp: - if (j > 0) std::swap(m_series[j - 1], m_series[j]); + if (j > 0) { + std::swap(m_series[j - 1], m_series[j]); + } break; case PlotSeries::kMoveDown: - if (j < (m_series.size() - 1)) + if (j < (m_series.size() - 1)) { std::swap(m_series[j], m_series[j + 1]); + } break; case PlotSeries::kDelete: m_series.erase(m_series.begin() + j); @@ -647,7 +714,9 @@ void Plot::EmitSettingsLimits(int axis) { ImGui::SetNextItemWidth(ImGui::GetFontSize() * 3.5); ImGui::InputDouble("Max", &m_axisRange[axis].max, 0, 0, "%.3f"); ImGui::SameLine(); - if (ImGui::Button("Apply")) m_axisRange[axis].apply = true; + if (ImGui::Button("Apply")) { + m_axisRange[axis].apply = true; + } ImGui::TextUnformatted("Lock Axis"); ImGui::SameLine(); @@ -665,35 +734,45 @@ void Plot::EmitSettings(size_t i) { ImGui::Checkbox("Visible", &m_visible); ImGui::Checkbox("Show Pause Button", &m_showPause); ImGui::CheckboxFlags("Show Legend", &m_plotFlags, ImPlotFlags_Legend); - if (i != 0) ImGui::Checkbox("Lock X-axis to previous plot", &m_lockPrevX); + if (i != 0) { + ImGui::Checkbox("Lock X-axis to previous plot", &m_lockPrevX); + } ImGui::TextUnformatted("Primary Y-Axis"); EmitSettingsLimits(0); ImGui::CheckboxFlags("2nd Y-Axis", &m_plotFlags, ImPlotFlags_YAxis2); - if ((m_plotFlags & ImPlotFlags_YAxis2) != 0) EmitSettingsLimits(1); + if ((m_plotFlags & ImPlotFlags_YAxis2) != 0) { + EmitSettingsLimits(1); + } ImGui::CheckboxFlags("3rd Y-Axis", &m_plotFlags, ImPlotFlags_YAxis3); - if ((m_plotFlags & ImPlotFlags_YAxis3) != 0) EmitSettingsLimits(2); + if ((m_plotFlags & ImPlotFlags_YAxis3) != 0) { + EmitSettingsLimits(2); + } ImGui::SetNextItemWidth(ImGui::GetFontSize() * 6); ImGui::InputFloat("View Time (s)", &m_viewTime, 0.1f, 1.0f, "%.1f"); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 6); if (ImGui::InputInt("Height", &m_height, 10)) { - if (m_height < 0) m_height = 0; + if (m_height < 0) { + m_height = 0; + } } } void PlotView::Display() { if (ImGui::BeginPopupContextItem()) { - if (ImGui::Button("Add plot")) + if (ImGui::Button("Add plot")) { m_plots.emplace_back(std::make_unique()); + } for (size_t i = 0; i < m_plots.size(); ++i) { auto& plot = m_plots[i]; ImGui::PushID(i); char name[64]; - if (!plot->GetName().empty()) + if (!plot->GetName().empty()) { std::snprintf(name, sizeof(name), "%s", plot->GetName().c_str()); - else + } else { std::snprintf(name, sizeof(name), "Plot %d", static_cast(i)); + } char label[90]; std::snprintf(label, sizeof(label), "%s###header%d", name, @@ -712,12 +791,16 @@ void PlotView::Display() { if (open) { if (ImGui::Button("Move Up")) { - if (i > 0) std::swap(m_plots[i - 1], plot); + if (i > 0) { + std::swap(m_plots[i - 1], plot); + } } ImGui::SameLine(); if (ImGui::Button("Move Down")) { - if (i < (m_plots.size() - 1)) std::swap(plot, m_plots[i + 1]); + if (i < (m_plots.size() - 1)) { + std::swap(plot, m_plots[i + 1]); + } } ImGui::SameLine(); @@ -737,11 +820,14 @@ void PlotView::Display() { } if (m_plots.empty()) { - if (ImGui::Button("Add plot")) + if (ImGui::Button("Add plot")) { m_plots.emplace_back(std::make_unique()); + } // Make "add plot" button a DND target for Plot - if (!ImGui::BeginDragDropTarget()) return; + if (!ImGui::BeginDragDropTarget()) { + return; + } if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Plot")) { auto ref = static_cast(payload->Data); MovePlot(ref->view, ref->plotIndex, 0); @@ -758,7 +844,9 @@ void PlotView::Display() { void PlotView::MovePlot(PlotView* fromView, size_t fromIndex, size_t toIndex) { if (fromView == this) { - if (fromIndex == toIndex) return; + if (fromIndex == toIndex) { + return; + } auto val = std::move(m_plots[fromIndex]); m_plots.insert(m_plots.begin() + toIndex, std::move(val)); m_plots.erase(m_plots.begin() + fromIndex + (fromIndex > toIndex ? 1 : 0)); @@ -778,7 +866,9 @@ void PlotView::MovePlotSeries(PlotView* fromView, size_t fromPlotIndex, auto& plotSeries = m_plots[fromPlotIndex]->m_series; auto val = std::move(plotSeries[fromSeriesIndex]); // only set Y-axis if actually set - if (yAxis != -1) val->SetYAxis(yAxis); + if (yAxis != -1) { + val->SetYAxis(yAxis); + } plotSeries.insert(plotSeries.begin() + toSeriesIndex, std::move(val)); plotSeries.erase(plotSeries.begin() + fromSeriesIndex + (fromSeriesIndex > toSeriesIndex ? 1 : 0)); @@ -833,7 +923,9 @@ void PlotProvider::DisplayMenu() { void PlotProvider::DisplayWindows() { // create views if not already created for (auto&& window : m_windows) { - if (!window->HasView()) window->SetView(std::make_unique(this)); + if (!window->HasView()) { + window->SetView(std::make_unique(this)); + } } WindowManager::DisplayWindows(); } @@ -847,14 +939,20 @@ void* PlotProvider::IniSaver::IniReadOpen(const char* name) { wpi::StringRef seriesId; if (m_forSeries) { std::tie(plotNumStr, seriesId) = plotNumStr.split('#'); - if (seriesId.empty()) return nullptr; + if (seriesId.empty()) { + return nullptr; + } } unsigned int plotNum; - if (plotNumStr.getAsInteger(10, plotNum)) return nullptr; + if (plotNumStr.getAsInteger(10, plotNum)) { + return nullptr; + } // get or create window auto win = m_provider->GetOrAddWindow(viewId, true); - if (!win) return nullptr; + if (!win) { + return nullptr; + } // get or create view auto view = static_cast(win->GetView()); @@ -864,12 +962,18 @@ void* PlotProvider::IniSaver::IniReadOpen(const char* name) { } // get or create plot - if (view->m_plots.size() <= plotNum) view->m_plots.resize(plotNum + 1); + if (view->m_plots.size() <= plotNum) { + view->m_plots.resize(plotNum + 1); + } auto& plot = view->m_plots[plotNum]; - if (!plot) plot = std::make_unique(); + if (!plot) { + plot = std::make_unique(); + } // early exit for plot data - if (!m_forSeries) return plot.get(); + if (!m_forSeries) { + return plot.get(); + } // get or create series return plot->m_series.emplace_back(std::make_unique(seriesId)) @@ -880,10 +984,11 @@ void PlotProvider::IniSaver::IniReadLine(void* entry, const char* lineStr) { auto [name, value] = wpi::StringRef{lineStr}.split('='); name = name.trim(); value = value.trim(); - if (m_forSeries) + if (m_forSeries) { static_cast(entry)->ReadIni(name, value); - else + } else { static_cast(entry)->ReadIni(name, value); + } } void PlotProvider::IniSaver::IniWriteAll(ImGuiTextBuffer* out_buf) { diff --git a/glass/src/lib/native/cpp/other/StringChooser.cpp b/glass/src/lib/native/cpp/other/StringChooser.cpp index fa9fa957c9..98bd3417d9 100644 --- a/glass/src/lib/native/cpp/other/StringChooser.cpp +++ b/glass/src/lib/native/cpp/other/StringChooser.cpp @@ -31,7 +31,9 @@ void glass::DisplayStringChooser(StringChooserModel* model) { if (ImGui::Selectable(option.c_str(), isSelected)) { model->SetSelected(option); } - if (isSelected) ImGui::SetItemDefaultFocus(); + if (isSelected) { + ImGui::SetItemDefaultFocus(); + } ImGui::PopID(); } ImGui::EndCombo(); diff --git a/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp b/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp index 2618f6e990..af9b0ca24b 100644 --- a/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp +++ b/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp @@ -14,9 +14,15 @@ namespace glass { void DrawLEDSources(const int* values, DataSource** sources, int numValues, int cols, const ImU32* colors, float size, float spacing, const LEDConfig& config) { - if (numValues == 0 || cols < 1) return; - if (size == 0) size = ImGui::GetFontSize() / 2.0; - if (spacing == 0) spacing = ImGui::GetFontSize() / 3.0; + if (numValues == 0 || cols < 1) { + return; + } + if (size == 0) { + size = ImGui::GetFontSize() / 2.0; + } + if (spacing == 0) { + spacing = ImGui::GetFontSize() / 3.0; + } int rows = (numValues + cols - 1) / cols; float inc = size + spacing; @@ -73,12 +79,13 @@ void DrawLEDSources(const int* values, DataSource** sources, int numValues, x += xinc; } } - if (values[i] > 0) + if (values[i] > 0) { drawList->AddRectFilled(ImVec2(x, y), ImVec2(x + size, y + size), colors[values[i] - 1]); - else if (values[i] < 0) + } else if (values[i] < 0) { drawList->AddRect(ImVec2(x, y), ImVec2(x + size, y + size), colors[-values[i] - 1], 0.0f, 0, 1.0); + } if (sources) { ImGui::SetCursorScreenPos(ImVec2(x - sized2, y - sized2)); if (sources[i]) { @@ -97,7 +104,9 @@ void DrawLEDSources(const int* values, DataSource** sources, int numValues, } } - if (!sources) ImGui::Dummy(ImVec2(inc * cols, inc * rows)); + if (!sources) { + ImGui::Dummy(ImVec2(inc * cols, inc * rows)); + } } void DrawLEDs(const int* values, int numValues, int cols, const ImU32* colors, @@ -120,15 +129,18 @@ bool DeleteButton(ImGuiID id, const ImVec2& pos) { bool hovered, held; bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held); - if (is_clipped) return pressed; + if (is_clipped) { + return pressed; + } // Render ImU32 col = ImGui::GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); ImVec2 center = bb.GetCenter(); - if (hovered) + if (hovered) { window->DrawList->AddCircleFilled( center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col, 12); + } ImU32 cross_col = ImGui::GetColorU32(ImGuiCol_Text); window->DrawList->AddCircle(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), diff --git a/glass/src/lib/native/cpp/support/IniSaverBase.cpp b/glass/src/lib/native/cpp/support/IniSaverBase.cpp index c348860d22..e222818d03 100644 --- a/glass/src/lib/native/cpp/support/IniSaverBase.cpp +++ b/glass/src/lib/native/cpp/support/IniSaverBase.cpp @@ -58,4 +58,6 @@ IniSaverBase::IniSaverBase(const wpi::Twine& typeName, IniSaverBackend* backend) : m_typeName(typeName.str()), m_backend{backend ? backend : GetSaverInstance()} {} -IniSaverBase::~IniSaverBase() { m_backend->Unregister(this); } +IniSaverBase::~IniSaverBase() { + m_backend->Unregister(this); +} diff --git a/glass/src/lib/native/cpp/support/IniSaverInfo.cpp b/glass/src/lib/native/cpp/support/IniSaverInfo.cpp index 5373fa61cf..32911da255 100644 --- a/glass/src/lib/native/cpp/support/IniSaverInfo.cpp +++ b/glass/src/lib/native/cpp/support/IniSaverInfo.cpp @@ -75,7 +75,9 @@ void NameInfo::GetLabel(char* buf, size_t size, const char* defaultName, } bool NameInfo::ReadIni(wpi::StringRef name, wpi::StringRef value) { - if (name != "name") return false; + if (name != "name") { + return false; + } size_t len = (std::min)(value.size(), sizeof(m_name) - 1); std::memcpy(m_name, value.data(), len); m_name[len] = '\0'; @@ -139,9 +141,13 @@ bool NameInfo::InputTextName(const char* label_id, ImGuiInputTextFlags flags) { } bool OpenInfo::ReadIni(wpi::StringRef name, wpi::StringRef value) { - if (name != "open") return false; + if (name != "open") { + return false; + } int num; - if (value.getAsInteger(10, num)) return true; + if (value.getAsInteger(10, num)) { + return true; + } m_open = num; return true; } @@ -151,8 +157,12 @@ void OpenInfo::WriteIni(ImGuiTextBuffer* out) { } bool NameOpenInfo::ReadIni(wpi::StringRef name, wpi::StringRef value) { - if (NameInfo::ReadIni(name, value)) return true; - if (OpenInfo::ReadIni(name, value)) return true; + if (NameInfo::ReadIni(name, value)) { + return true; + } + if (OpenInfo::ReadIni(name, value)) { + return true; + } return false; } diff --git a/glass/src/lib/native/include/glass/Context.h b/glass/src/lib/native/include/glass/Context.h index 1911c8d889..bb3c0209e2 100644 --- a/glass/src/lib/native/include/glass/Context.h +++ b/glass/src/lib/native/include/glass/Context.h @@ -141,7 +141,9 @@ void PushID(const char* str_id); void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). -inline void PushID(wpi::StringRef str) { PushID(str.begin(), str.end()); } +inline void PushID(wpi::StringRef str) { + PushID(str.begin(), str.end()); +} // push integer into the ID stack (will hash integer). void PushID(int int_id); diff --git a/glass/src/lib/native/include/glass/Provider.inc b/glass/src/lib/native/include/glass/Provider.inc index 789f12af9f..fbedb093c5 100644 --- a/glass/src/lib/native/include/glass/Provider.inc +++ b/glass/src/lib/native/include/glass/Provider.inc @@ -17,9 +17,11 @@ void Provider::GlobalInit() { template void Provider::ShowDefault(wpi::StringRef name) { auto win = GetWindow(name); - if (win) return; + if (win) + return; auto it = FindViewEntry(name); - if (it == m_viewEntries.end() || (*it)->name != name) return; + if (it == m_viewEntries.end() || (*it)->name != name) + return; this->Show(it->get(), (*it)->window); } @@ -36,7 +38,8 @@ void Provider::RegisterModel(wpi::StringRef name, ExistsFunc exists, CreateModelFunc createModel) { auto it = FindModelEntry(name); // ignore if exists - if (it != m_modelEntries.end() && (*it)->name == name) return; + if (it != m_modelEntries.end() && (*it)->name == name) + return; // insert in sorted location m_modelEntries.emplace( it, MakeModelEntry(name, std::move(exists), std::move(createModel))); @@ -49,11 +52,13 @@ void Provider::RegisterView(wpi::StringRef name, CreateViewFunc createView) { // find model; if model doesn't exist, ignore auto modelIt = FindModelEntry(modelName); - if (modelIt == m_modelEntries.end() || (*modelIt)->name != modelName) return; + if (modelIt == m_modelEntries.end() || (*modelIt)->name != modelName) + return; auto viewIt = FindViewEntry(name); // ignore if exists - if (viewIt != m_viewEntries.end() && (*viewIt)->name == name) return; + if (viewIt != m_viewEntries.end() && (*viewIt)->name == name) + return; // insert in sorted location m_viewEntries.emplace(viewIt, MakeViewEntry(name, modelIt->get(), std::move(exists), @@ -64,7 +69,8 @@ template void Provider::Update() { // update entries for (auto&& entry : m_modelEntries) { - if (entry->model) entry->model->Update(); + if (entry->model) + entry->model->Update(); } } diff --git a/glass/src/lib/native/include/glass/support/IniSaver.inl b/glass/src/lib/native/include/glass/support/IniSaver.inl index 4f5d5cb80d..d873532c1e 100644 --- a/glass/src/lib/native/include/glass/support/IniSaver.inl +++ b/glass/src/lib/native/include/glass/support/IniSaver.inl @@ -11,7 +11,8 @@ namespace glass { template void* IniSaver::IniReadOpen(const char* name) { int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) return nullptr; + if (wpi::StringRef{name}.getAsInteger(10, num)) + return nullptr; return &m_map[num]; } diff --git a/glass/src/lib/native/include/glass/support/IniSaverVector.inl b/glass/src/lib/native/include/glass/support/IniSaverVector.inl index 379d44c528..9137fc84a8 100644 --- a/glass/src/lib/native/include/glass/support/IniSaverVector.inl +++ b/glass/src/lib/native/include/glass/support/IniSaverVector.inl @@ -11,8 +11,10 @@ namespace glass { template void* IniSaverVector::IniReadOpen(const char* name) { unsigned int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) return nullptr; - if (num >= this->size()) this->resize(num + 1); + if (wpi::StringRef{name}.getAsInteger(10, num)) + return nullptr; + if (num >= this->size()) + this->resize(num + 1); return &(*this)[num]; } diff --git a/glass/src/libnt/native/cpp/NTCommandScheduler.cpp b/glass/src/libnt/native/cpp/NTCommandScheduler.cpp index 6fd308ee9c..0a46bf9ad9 100644 --- a/glass/src/libnt/native/cpp/NTCommandScheduler.cpp +++ b/glass/src/libnt/native/cpp/NTCommandScheduler.cpp @@ -27,22 +27,26 @@ NTCommandSchedulerModel::NTCommandSchedulerModel(NT_Inst instance, } void NTCommandSchedulerModel::CancelCommand(size_t index) { - if (index < m_idsValue.size()) + if (index < m_idsValue.size()) { nt::SetEntryValue( m_cancel, nt::NetworkTableValue::MakeDoubleArray({m_idsValue[index]})); + } } void NTCommandSchedulerModel::Update() { for (auto&& event : m_nt.PollListener()) { if (event.entry == m_name) { - if (event.value && event.value->IsString()) + if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); + } } else if (event.entry == m_commands) { - if (event.value && event.value->IsStringArray()) + if (event.value && event.value->IsStringArray()) { m_commandsValue = event.value->GetStringArray(); + } } else if (event.entry == m_ids) { - if (event.value && event.value->IsDoubleArray()) + if (event.value && event.value->IsDoubleArray()) { m_idsValue = event.value->GetDoubleArray(); + } } } } diff --git a/glass/src/libnt/native/cpp/NTCommandSelector.cpp b/glass/src/libnt/native/cpp/NTCommandSelector.cpp index be4d89938e..7ee2c35ebd 100644 --- a/glass/src/libnt/native/cpp/NTCommandSelector.cpp +++ b/glass/src/libnt/native/cpp/NTCommandSelector.cpp @@ -29,11 +29,13 @@ void NTCommandSelectorModel::SetRunning(bool run) { void NTCommandSelectorModel::Update() { for (auto&& event : m_nt.PollListener()) { if (event.entry == m_running) { - if (event.value && event.value->IsBoolean()) + if (event.value && event.value->IsBoolean()) { m_runningData.SetValue(event.value->GetBoolean()); + } } else if (event.entry == m_name) { - if (event.value && event.value->IsString()) + if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); + } } } } diff --git a/glass/src/libnt/native/cpp/NTField2D.cpp b/glass/src/libnt/native/cpp/NTField2D.cpp index 827fbf00ea..d3e986708e 100644 --- a/glass/src/libnt/native/cpp/NTField2D.cpp +++ b/glass/src/libnt/native/cpp/NTField2D.cpp @@ -24,7 +24,9 @@ class NTField2DModel::GroupModel : public FieldObjectGroupModel { void NTUpdate(const nt::Value& value); void Update() override { - if (auto value = nt::GetEntryValue(m_entry)) NTUpdate(*value); + if (auto value = nt::GetEntryValue(m_entry)) { + NTUpdate(*value); + } } bool Exists() override { return nt::GetEntryType(m_entry) != NT_UNASSIGNED; } bool IsReadOnly() override { return false; } @@ -96,12 +98,14 @@ void NTField2DModel::GroupModel::NTUpdate(const nt::Value& value) { m_count = arr.size() / 3; if (m_count > m_objects.size()) { m_objects.reserve(m_count); - for (size_t i = m_objects.size(); i < m_count; ++i) + for (size_t i = m_objects.size(); i < m_count; ++i) { m_objects.emplace_back(std::make_unique(m_name, m_entry, i)); + } } if (m_count < m_objects.size()) { - for (size_t i = m_count; i < m_objects.size(); ++i) + for (size_t i = m_count; i < m_objects.size(); ++i) { m_objects[i]->SetExists(false); + } } for (size_t i = 0; i < m_count; ++i) { @@ -139,19 +143,31 @@ void NTField2DModel::GroupModel::ObjectModel::SetPoseImpl(double x, double y, bool setRot) { // get from NT, validate type and size auto value = nt::GetEntryValue(m_entry); - if (!value || !value->IsDoubleArray()) return; + if (!value || !value->IsDoubleArray()) { + return; + } auto origArr = value->GetDoubleArray(); - if (origArr.size() < static_cast((m_index + 1) * 3)) return; + if (origArr.size() < static_cast((m_index + 1) * 3)) { + return; + } // copy existing array wpi::SmallVector arr; arr.reserve(origArr.size()); - for (auto&& elem : origArr) arr.emplace_back(elem); + for (auto&& elem : origArr) { + arr.emplace_back(elem); + } // update value - if (setX) arr[m_index * 3 + 0] = x; - if (setY) arr[m_index * 3 + 1] = y; - if (setRot) arr[m_index * 3 + 2] = rot; + if (setX) { + arr[m_index * 3 + 0] = x; + } + if (setY) { + arr[m_index * 3 + 1] = y; + } + if (setRot) { + arr[m_index * 3 + 2] = rot; + } // set back to NT nt::SetEntryValue(m_entry, nt::Value::MakeDoubleArray(arr)); @@ -194,19 +210,24 @@ void NTField2DModel::Update() { // handle create/delete if (wpi::StringRef{event.name}.startswith(m_path)) { auto name = wpi::StringRef{event.name}.drop_front(m_path.size()); - if (name.empty() || name[0] == '.') continue; + if (name.empty() || name[0] == '.') { + continue; + } auto it = std::lower_bound(m_groups.begin(), m_groups.end(), name, [](const auto& e, wpi::StringRef name) { return e->GetName() < name; }); bool match = (it != m_groups.end() && (*it)->GetName() == name); if (event.flags & NT_NOTIFY_DELETE) { - if (match) m_groups.erase(it); + if (match) { + m_groups.erase(it); + } continue; } else if (event.flags & NT_NOTIFY_NEW) { - if (!match) + if (!match) { it = m_groups.emplace( it, std::make_unique(event.name, event.entry)); + } } else if (!match) { continue; } @@ -221,13 +242,16 @@ bool NTField2DModel::Exists() { return m_nt.IsConnected() && nt::GetEntryType(m_name) != NT_UNASSIGNED; } -bool NTField2DModel::IsReadOnly() { return false; } +bool NTField2DModel::IsReadOnly() { + return false; +} void NTField2DModel::ForEachFieldObjectGroup( wpi::function_ref func) { for (auto&& group : m_groups) { - if (group->Exists()) + if (group->Exists()) { func(*group, wpi::StringRef{group->GetName()}.drop_front(m_path.size())); + } } } diff --git a/glass/src/libnt/native/cpp/NTGyro.cpp b/glass/src/libnt/native/cpp/NTGyro.cpp index c2f99ef9d1..db5fb41e1f 100644 --- a/glass/src/libnt/native/cpp/NTGyro.cpp +++ b/glass/src/libnt/native/cpp/NTGyro.cpp @@ -23,11 +23,13 @@ NTGyroModel::NTGyroModel(NT_Inst instance, wpi::StringRef path) void NTGyroModel::Update() { for (auto&& event : m_nt.PollListener()) { if (event.entry == m_angle) { - if (event.value && event.value->IsDouble()) + if (event.value && event.value->IsDouble()) { m_angleData.SetValue(event.value->GetDouble()); + } } else if (event.entry == m_name) { - if (event.value && event.value->IsString()) + if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); + } } } } diff --git a/glass/src/libnt/native/cpp/NTPIDController.cpp b/glass/src/libnt/native/cpp/NTPIDController.cpp index 0b9e63a62b..0edb565f04 100644 --- a/glass/src/libnt/native/cpp/NTPIDController.cpp +++ b/glass/src/libnt/native/cpp/NTPIDController.cpp @@ -49,20 +49,25 @@ void NTPIDControllerModel::SetSetpoint(double value) { void NTPIDControllerModel::Update() { for (auto&& event : m_nt.PollListener()) { if (event.entry == m_name) { - if (event.value && event.value->IsString()) + if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); + } } else if (event.entry == m_p) { - if (event.value && event.value->IsDouble()) + if (event.value && event.value->IsDouble()) { m_pData.SetValue(event.value->GetDouble()); + } } else if (event.entry == m_i) { - if (event.value && event.value->IsDouble()) + if (event.value && event.value->IsDouble()) { m_iData.SetValue(event.value->GetDouble()); + } } else if (event.entry == m_d) { - if (event.value && event.value->IsDouble()) + if (event.value && event.value->IsDouble()) { m_dData.SetValue(event.value->GetDouble()); + } } else if (event.entry == m_setpoint) { - if (event.value && event.value->IsDouble()) + if (event.value && event.value->IsDouble()) { m_setpointData.SetValue(event.value->GetDouble()); + } } } } diff --git a/glass/src/libnt/native/cpp/NTSpeedController.cpp b/glass/src/libnt/native/cpp/NTSpeedController.cpp index 0048c0c899..3ca3a35f4b 100644 --- a/glass/src/libnt/native/cpp/NTSpeedController.cpp +++ b/glass/src/libnt/native/cpp/NTSpeedController.cpp @@ -28,11 +28,13 @@ void NTSpeedControllerModel::SetPercent(double value) { void NTSpeedControllerModel::Update() { for (auto&& event : m_nt.PollListener()) { if (event.entry == m_value) { - if (event.value && event.value->IsDouble()) + if (event.value && event.value->IsDouble()) { m_valueData.SetValue(event.value->GetDouble()); + } } else if (event.entry == m_name) { - if (event.value && event.value->IsString()) + if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); + } } } } diff --git a/glass/src/libnt/native/cpp/NTSubsystem.cpp b/glass/src/libnt/native/cpp/NTSubsystem.cpp index 5b8c7273bf..0254f849be 100644 --- a/glass/src/libnt/native/cpp/NTSubsystem.cpp +++ b/glass/src/libnt/native/cpp/NTSubsystem.cpp @@ -23,11 +23,13 @@ NTSubsystemModel::NTSubsystemModel(NT_Inst instance, wpi::StringRef path) void NTSubsystemModel::Update() { for (auto&& event : m_nt.PollListener()) { if (event.entry == m_name) { - if (event.value && event.value->IsString()) + if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); + } } else if (event.entry == m_defaultCommand) { - if (event.value && event.value->IsString()) + if (event.value && event.value->IsString()) { m_defaultCommandValue = event.value->GetString(); + } } else if (event.entry == m_currentCommand) { if (event.value && event.value->IsString()) { m_currentCommandValue = event.value->GetString(); diff --git a/glass/src/libnt/native/cpp/NetworkTables.cpp b/glass/src/libnt/native/cpp/NetworkTables.cpp index db83ce7ce9..0b2ec66dbf 100644 --- a/glass/src/libnt/native/cpp/NetworkTables.cpp +++ b/glass/src/libnt/native/cpp/NetworkTables.cpp @@ -32,12 +32,15 @@ static std::string BooleanArrayToString(wpi::ArrayRef in) { os << '['; bool first = true; for (auto v : in) { - if (!first) os << ','; + if (!first) { + os << ','; + } first = false; - if (v) + if (v) { os << "true"; - else + } else { os << "false"; + } } os << ']'; return rv; @@ -49,7 +52,9 @@ static std::string DoubleArrayToString(wpi::ArrayRef in) { os << '['; bool first = true; for (auto v : in) { - if (!first) os << ','; + if (!first) { + os << ','; + } first = false; os << wpi::format("%.6f", v); } @@ -63,7 +68,9 @@ static std::string StringArrayToString(wpi::ArrayRef in) { os << '['; bool first = true; for (auto&& v : in) { - if (!first) os << ','; + if (!first) { + os << ','; + } first = false; os << '"'; os.write_escaped(v); @@ -99,14 +106,16 @@ NetworkTablesModel::Entry::Entry(nt::EntryNotification&& event) void NetworkTablesModel::Entry::UpdateValue() { switch (value->type()) { case NT_BOOLEAN: - if (!source) + if (!source) { source = std::make_unique(wpi::Twine{"NT:"} + name); + } source->SetValue(value->GetBoolean() ? 1 : 0); source->SetDigital(true); break; case NT_DOUBLE: - if (!source) + if (!source) { source = std::make_unique(wpi::Twine{"NT:"} + name); + } source->SetValue(value->GetDouble()); source->SetDigital(false); break; @@ -136,12 +145,16 @@ void NetworkTablesModel::Update() { updateTree = true; } } - if (!entry) continue; + if (!entry) { + continue; + } if (event.flags & NT_NOTIFY_DELETE) { auto it = std::find(m_sortedEntries.begin(), m_sortedEntries.end(), entry.get()); // will be removed completely below - if (it != m_sortedEntries.end()) *it = nullptr; + if (it != m_sortedEntries.end()) { + *it = nullptr; + } m_entries.erase(event.entry); updateTree = true; continue; @@ -156,7 +169,9 @@ void NetworkTablesModel::Update() { } // shortcut common case (updates) - if (!updateTree) return; + if (!updateTree) { + return; + } // remove deleted entries m_sortedEntries.erase( @@ -204,15 +219,22 @@ void NetworkTablesModel::Update() { } } -bool NetworkTablesModel::Exists() { return nt::IsConnected(m_inst); } +bool NetworkTablesModel::Exists() { + return nt::IsConnected(m_inst); +} static std::shared_ptr StringToBooleanArray(wpi::StringRef in) { in = in.trim(); - if (in.empty()) + if (in.empty()) { return nt::NetworkTableValue::MakeBooleanArray( std::initializer_list{}); - if (in.front() == '[') in = in.drop_front(); - if (in.back() == ']') in = in.drop_back(); + } + if (in.front() == '[') { + in = in.drop_front(); + } + if (in.back() == ']') { + in = in.drop_back(); + } in = in.trim(); wpi::SmallVector inSplit; @@ -237,11 +259,16 @@ static std::shared_ptr StringToBooleanArray(wpi::StringRef in) { static std::shared_ptr StringToDoubleArray(wpi::StringRef in) { in = in.trim(); - if (in.empty()) + if (in.empty()) { return nt::NetworkTableValue::MakeBooleanArray( std::initializer_list{}); - if (in.front() == '[') in = in.drop_front(); - if (in.back() == ']') in = in.drop_back(); + } + if (in.front() == '[') { + in = in.drop_front(); + } + if (in.back() == ']') { + in = in.drop_back(); + } in = in.trim(); wpi::SmallVector inSplit; @@ -265,12 +292,13 @@ static std::shared_ptr StringToDoubleArray(wpi::StringRef in) { } static int fromxdigit(char ch) { - if (ch >= 'a' && ch <= 'f') + if (ch >= 'a' && ch <= 'f') { return (ch - 'a' + 10); - else if (ch >= 'A' && ch <= 'F') + } else if (ch >= 'A' && ch <= 'F') { return (ch - 'A' + 10); - else + } else { return ch - '0'; + } } static wpi::StringRef UnescapeString(wpi::StringRef source, @@ -313,11 +341,16 @@ static wpi::StringRef UnescapeString(wpi::StringRef source, static std::shared_ptr StringToStringArray(wpi::StringRef in) { in = in.trim(); - if (in.empty()) + if (in.empty()) { return nt::NetworkTableValue::MakeStringArray( std::initializer_list{}); - if (in.front() == '[') in = in.drop_front(); - if (in.back() == ']') in = in.drop_back(); + } + if (in.front() == '[') { + in = in.drop_front(); + } + if (in.back() == ']') { + in = in.drop_back(); + } in = in.trim(); wpi::SmallVector inSplit; @@ -327,7 +360,9 @@ static std::shared_ptr StringToStringArray(wpi::StringRef in) { in.split(inSplit, ',', -1, false); for (auto val : inSplit) { val = val.trim(); - if (val.empty()) continue; + if (val.empty()) { + continue; + } if (val.front() != '"' || val.back() != '"') { wpi::errs() << "GUI: NetworkTables: Could not understand value '" << val << "'\n"; @@ -341,7 +376,9 @@ static std::shared_ptr StringToStringArray(wpi::StringRef in) { static void EmitEntryValueReadonly(NetworkTablesModel::Entry& entry) { auto& val = entry.value; - if (!val) return; + if (!val) { + return; + } switch (val->type()) { case NT_BOOLEAN: @@ -388,37 +425,43 @@ static char* GetTextBuffer(wpi::StringRef in) { static void EmitEntryValueEditable(NetworkTablesModel::Entry& entry) { auto& val = entry.value; - if (!val) return; + if (!val) { + return; + } ImGui::PushID(entry.name.c_str()); switch (val->type()) { case NT_BOOLEAN: { static const char* boolOptions[] = {"false", "true"}; int v = val->GetBoolean() ? 1 : 0; - if (ImGui::Combo("boolean", &v, boolOptions, 2)) + if (ImGui::Combo("boolean", &v, boolOptions, 2)) { nt::SetEntryValue(entry.entry, nt::NetworkTableValue::MakeBoolean(v)); + } break; } case NT_DOUBLE: { double v = val->GetDouble(); if (ImGui::InputDouble("double", &v, 0, 0, "%.6f", - ImGuiInputTextFlags_EnterReturnsTrue)) + ImGuiInputTextFlags_EnterReturnsTrue)) { nt::SetEntryValue(entry.entry, nt::NetworkTableValue::MakeDouble(v)); + } break; } case NT_STRING: { char* v = GetTextBuffer(val->GetString()); if (ImGui::InputText("string", v, kTextBufferSize, - ImGuiInputTextFlags_EnterReturnsTrue)) + ImGuiInputTextFlags_EnterReturnsTrue)) { nt::SetEntryValue(entry.entry, nt::NetworkTableValue::MakeString(v)); + } break; } case NT_BOOLEAN_ARRAY: { char* v = GetTextBuffer(entry.valueStr); if (ImGui::InputText("boolean[]", v, kTextBufferSize, ImGuiInputTextFlags_EnterReturnsTrue)) { - if (auto outv = StringToBooleanArray(v)) + if (auto outv = StringToBooleanArray(v)) { nt::SetEntryValue(entry.entry, std::move(outv)); + } } break; } @@ -426,8 +469,9 @@ static void EmitEntryValueEditable(NetworkTablesModel::Entry& entry) { char* v = GetTextBuffer(entry.valueStr); if (ImGui::InputText("double[]", v, kTextBufferSize, ImGuiInputTextFlags_EnterReturnsTrue)) { - if (auto outv = StringToDoubleArray(v)) + if (auto outv = StringToDoubleArray(v)) { nt::SetEntryValue(entry.entry, std::move(outv)); + } } break; } @@ -435,8 +479,9 @@ static void EmitEntryValueEditable(NetworkTablesModel::Entry& entry) { char* v = GetTextBuffer(entry.valueStr); if (ImGui::InputText("string[]", v, kTextBufferSize, ImGuiInputTextFlags_EnterReturnsTrue)) { - if (auto outv = StringToStringArray(v)) + if (auto outv = StringToStringArray(v)) { nt::SetEntryValue(entry.entry, std::move(outv)); + } } break; } @@ -463,26 +508,29 @@ static void EmitEntry(NetworkTablesModel::Entry& entry, const char* name, } ImGui::NextColumn(); - if (flags & NetworkTablesFlags_ReadOnly) + if (flags & NetworkTablesFlags_ReadOnly) { EmitEntryValueReadonly(entry); - else + } else { EmitEntryValueEditable(entry); + } ImGui::NextColumn(); if (flags & NetworkTablesFlags_ShowFlags) { - if ((entry.flags & NT_PERSISTENT) != 0) + if ((entry.flags & NT_PERSISTENT) != 0) { ImGui::Text("Persistent"); - else if (entry.flags != 0) + } else if (entry.flags != 0) { ImGui::Text("%02x", entry.flags); + } ImGui::NextColumn(); } if (flags & NetworkTablesFlags_ShowTimestamp) { - if (entry.value) + if (entry.value) { ImGui::Text("%f", (entry.value->last_change() * 1.0e-6) - (GetZeroTime() * 1.0e-6)); - else + } else { ImGui::TextUnformatted(""); + } ImGui::NextColumn(); } ImGui::Separator(); @@ -500,8 +548,12 @@ static void EmitTree(const std::vector& tree, TreeNodeEx(node.name.c_str(), ImGuiTreeNodeFlags_SpanFullWidth); ImGui::NextColumn(); ImGui::NextColumn(); - if (flags & NetworkTablesFlags_ShowFlags) ImGui::NextColumn(); - if (flags & NetworkTablesFlags_ShowTimestamp) ImGui::NextColumn(); + if (flags & NetworkTablesFlags_ShowFlags) { + ImGui::NextColumn(); + } + if (flags & NetworkTablesFlags_ShowTimestamp) { + ImGui::NextColumn(); + } ImGui::Separator(); if (open) { EmitTree(node.children, flags); @@ -543,7 +595,9 @@ void glass::DisplayNetworkTables(NetworkTablesModel* model, ImGui::Columns(); } - if (!CollapsingHeader("Values", ImGuiTreeNodeFlags_DefaultOpen)) return; + if (!CollapsingHeader("Values", ImGuiTreeNodeFlags_DefaultOpen)) { + return; + } } const bool showFlags = (flags & NetworkTablesFlags_ShowFlags); @@ -551,13 +605,17 @@ void glass::DisplayNetworkTables(NetworkTablesModel* model, static bool first = true; ImGui::Columns(2 + (showFlags ? 1 : 0) + (showTimestamp ? 1 : 0), "values"); - if (first) ImGui::SetColumnWidth(-1, 0.5f * ImGui::GetWindowWidth()); + if (first) { + ImGui::SetColumnWidth(-1, 0.5f * ImGui::GetWindowWidth()); + } ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Value"); ImGui::NextColumn(); if (showFlags) { - if (first) ImGui::SetColumnWidth(-1, 12 * ImGui::GetFontSize()); + if (first) { + ImGui::SetColumnWidth(-1, 12 * ImGui::GetFontSize()); + } ImGui::Text("Flags"); ImGui::NextColumn(); } diff --git a/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp b/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp index 3aaf7595ad..bfe135e062 100644 --- a/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp +++ b/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp @@ -57,7 +57,9 @@ void NetworkTablesProvider::DisplayMenu() { } } - for (; depth > 0; --depth) ImGui::EndMenu(); + for (; depth > 0; --depth) { + ImGui::EndMenu(); + } } } @@ -69,13 +71,16 @@ void NetworkTablesProvider::Update() { // look for .type fields wpi::StringRef eventName{event.name}; if (!eventName.endswith("/.type") || !event.value || - !event.value->IsString()) + !event.value->IsString()) { continue; + } auto tableName = eventName.drop_back(6); // only handle ones where we have a builder auto builderIt = m_typeMap.find(event.value->GetString()); - if (builderIt == m_typeMap.end()) continue; + if (builderIt == m_typeMap.end()) { + continue; + } if (event.flags & NT_NOTIFY_DELETE) { auto it = std::find_if( @@ -96,18 +101,26 @@ void NetworkTablesProvider::Update() { // check for visible windows that need displays (typically this is due to // file loading) for (auto&& window : m_windows) { - if (!window->IsVisible() || window->HasView()) continue; + if (!window->IsVisible() || window->HasView()) { + continue; + } auto id = window->GetId(); auto typeIt = m_typeCache.find(id); - if (typeIt == m_typeCache.end()) continue; + if (typeIt == m_typeCache.end()) { + continue; + } // only handle ones where we have a builder auto builderIt = m_typeMap.find(typeIt->second.GetName()); - if (builderIt == m_typeMap.end()) continue; + if (builderIt == m_typeMap.end()) { + continue; + } auto entry = GetOrCreateView( builderIt->second, nt::GetEntry(m_nt.GetInstance(), id + "/.type"), id); - if (entry) Show(entry, window.get()); + if (entry) { + Show(entry, window.get()); + } } } @@ -125,20 +138,29 @@ void NetworkTablesProvider::Show(ViewEntry* entry, Window* window) { } // get or create model - if (!entry->modelEntry->model) + if (!entry->modelEntry->model) { entry->modelEntry->model = entry->modelEntry->createModel(m_nt.GetInstance(), entry->name.c_str()); - if (!entry->modelEntry->model) return; + } + if (!entry->modelEntry->model) { + return; + } // the window might exist and we're just not associated to it yet - if (!window) window = GetOrAddWindow(entry->name, true); - if (!window) return; + if (!window) { + window = GetOrAddWindow(entry->name, true); + } + if (!window) { + return; + } entry->window = window; // create view auto view = entry->createView(window, entry->modelEntry->model.get(), entry->name.c_str()); - if (!view) return; + if (!view) { + return; + } window->SetView(std::move(view)); entry->window->SetVisible(true); diff --git a/hal/src/main/native/athena/Accelerometer.cpp b/hal/src/main/native/athena/Accelerometer.cpp index bebcaae181..cd24dc21c1 100644 --- a/hal/src/main/native/athena/Accelerometer.cpp +++ b/hal/src/main/native/athena/Accelerometer.cpp @@ -123,7 +123,8 @@ static void writeRegister(Register reg, uint8_t data) { // Execute and wait until it's done (up to a millisecond) initialTime = HAL_GetFPGATime(&status); while (accel->readSTAT(&status) & 1) { - if (HAL_GetFPGATime(&status) > initialTime + 1000) break; + if (HAL_GetFPGATime(&status) > initialTime + 1000) + break; } // Send a stop transmit/receive message with the data @@ -134,7 +135,8 @@ static void writeRegister(Register reg, uint8_t data) { // Execute and wait until it's done (up to a millisecond) initialTime = HAL_GetFPGATime(&status); while (accel->readSTAT(&status) & 1) { - if (HAL_GetFPGATime(&status) > initialTime + 1000) break; + if (HAL_GetFPGATime(&status) > initialTime + 1000) + break; } } @@ -151,7 +153,8 @@ static uint8_t readRegister(Register reg) { // Execute and wait until it's done (up to a millisecond) initialTime = HAL_GetFPGATime(&status); while (accel->readSTAT(&status) & 1) { - if (HAL_GetFPGATime(&status) > initialTime + 1000) break; + if (HAL_GetFPGATime(&status) > initialTime + 1000) + break; } // Receive a message with the data and stop @@ -162,7 +165,8 @@ static uint8_t readRegister(Register reg) { // Execute and wait until it's done (up to a millisecond) initialTime = HAL_GetFPGATime(&status); while (accel->readSTAT(&status) & 1) { - if (HAL_GetFPGATime(&status) > initialTime + 1000) break; + if (HAL_GetFPGATime(&status) > initialTime + 1000) + break; } return accel->readDATI(&status); diff --git a/hal/src/main/native/athena/AnalogAccumulator.cpp b/hal/src/main/native/athena/AnalogAccumulator.cpp index 807c056ab3..9b80463e53 100644 --- a/hal/src/main/native/athena/AnalogAccumulator.cpp +++ b/hal/src/main/native/athena/AnalogAccumulator.cpp @@ -25,7 +25,8 @@ HAL_Bool HAL_IsAccumulatorChannel(HAL_AnalogInputHandle analogPortHandle, return false; } for (int32_t i = 0; i < kNumAccumulators; i++) { - if (port->channel == kAccumulatorChannels[i]) return true; + if (port->channel == kAccumulatorChannels[i]) + return true; } return false; } diff --git a/hal/src/main/native/athena/AnalogGyro.cpp b/hal/src/main/native/athena/AnalogGyro.cpp index d530455cd7..342a31e212 100644 --- a/hal/src/main/native/athena/AnalogGyro.cpp +++ b/hal/src/main/native/athena/AnalogGyro.cpp @@ -48,7 +48,9 @@ void InitializeAnalogGyro() { } // namespace hal static void Wait(double seconds) { - if (seconds < 0.0) return; + if (seconds < 0.0) { + return; + } std::this_thread::sleep_for(std::chrono::duration(seconds)); } @@ -69,8 +71,9 @@ HAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analogHandle, auto handle = analogGyroHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } // Initialize port structure auto gyro = analogGyroHandles->Get(handle); @@ -97,17 +100,25 @@ void HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) { gyro->voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; HAL_SetAnalogAverageBits(gyro->handle, kAverageBits, status); - if (*status != 0) return; + if (*status != 0) { + return; + } HAL_SetAnalogOversampleBits(gyro->handle, kOversampleBits, status); - if (*status != 0) return; + if (*status != 0) { + return; + } double sampleRate = kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits)); HAL_SetAnalogSampleRate(sampleRate, status); - if (*status != 0) return; + if (*status != 0) { + return; + } Wait(0.1); HAL_SetAnalogGyroDeadband(handle, 0.0, status); - if (*status != 0) return; + if (*status != 0) { + return; + } } void HAL_FreeAnalogGyro(HAL_GyroHandle handle) { @@ -148,14 +159,18 @@ void HAL_ResetAnalogGyro(HAL_GyroHandle handle, int32_t* status) { return; } HAL_ResetAccumulator(gyro->handle, status); - if (*status != 0) return; + if (*status != 0) { + return; + } const double sampleTime = 1.0 / HAL_GetAnalogSampleRate(status); const double overSamples = 1 << HAL_GetAnalogOversampleBits(gyro->handle, status); const double averageSamples = 1 << HAL_GetAnalogAverageBits(gyro->handle, status); - if (*status != 0) return; + if (*status != 0) { + return; + } Wait(sampleTime * overSamples * averageSamples); } @@ -167,7 +182,9 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) { } HAL_InitAccumulator(gyro->handle, status); - if (*status != 0) return; + if (*status != 0) { + return; + } wpi::outs() << "Calibrating analog gyro for " << kCalibrationSampleTime << " seconds." << '\n'; Wait(kCalibrationSampleTime); @@ -175,7 +192,9 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) { int64_t value; int64_t count; HAL_GetAccumulatorOutput(gyro->handle, &value, &count, status); - if (*status != 0) return; + if (*status != 0) { + return; + } gyro->center = static_cast( static_cast(value) / static_cast(count) + 0.5); @@ -183,7 +202,9 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) { gyro->offset = static_cast(value) / static_cast(count) - static_cast(gyro->center); HAL_SetAccumulatorCenter(gyro->handle, gyro->center, status); - if (*status != 0) return; + if (*status != 0) { + return; + } HAL_ResetAnalogGyro(handle, status); } @@ -197,7 +218,9 @@ void HAL_SetAnalogGyroDeadband(HAL_GyroHandle handle, double volts, int32_t deadband = static_cast( volts * 1e9 / HAL_GetAnalogLSBWeight(gyro->handle, status) * (1 << HAL_GetAnalogOversampleBits(gyro->handle, status))); - if (*status != 0) return; + if (*status != 0) { + return; + } HAL_SetAccumulatorDeadband(gyro->handle, deadband, status); } diff --git a/hal/src/main/native/athena/AnalogInput.cpp b/hal/src/main/native/athena/AnalogInput.cpp index cda6343b9e..62bcb5fe0f 100644 --- a/hal/src/main/native/athena/AnalogInput.cpp +++ b/hal/src/main/native/athena/AnalogInput.cpp @@ -28,7 +28,9 @@ HAL_AnalogInputHandle HAL_InitializeAnalogInputPort(HAL_PortHandle portHandle, hal::init::CheckInit(); initializeAnalog(status); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex) { @@ -38,8 +40,9 @@ HAL_AnalogInputHandle HAL_InitializeAnalogInputPort(HAL_PortHandle portHandle, HAL_AnalogInputHandle handle = analogInputHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } // Initialize port structure auto analog_port = analogInputHandles->Get(handle); @@ -66,7 +69,9 @@ void HAL_FreeAnalogInputPort(HAL_AnalogInputHandle analogPortHandle) { analogInputHandles->Free(analogPortHandle); } -HAL_Bool HAL_CheckAnalogModule(int32_t module) { return module == 1; } +HAL_Bool HAL_CheckAnalogModule(int32_t module) { + return module == 1; +} HAL_Bool HAL_CheckAnalogInputChannel(int32_t channel) { return channel < kNumAnalogInputs && channel >= 0; @@ -80,13 +85,17 @@ void HAL_SetAnalogSampleRate(double samplesPerSecond, int32_t* status) { // TODO: Need double comparison with epsilon. // wpi_assert(!sampleRateSet || GetSampleRate() == samplesPerSecond); initializeAnalog(status); - if (*status != 0) return; + if (*status != 0) { + return; + } setAnalogSampleRate(samplesPerSecond, status); } double HAL_GetAnalogSampleRate(int32_t* status) { initializeAnalog(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } uint32_t ticksPerConversion = analogInputSystem->readLoopTiming(status); uint32_t ticksPerSample = ticksPerConversion * getAnalogNumActiveChannels(status); diff --git a/hal/src/main/native/athena/AnalogInternal.cpp b/hal/src/main/native/athena/AnalogInternal.cpp index b2b483bb9d..7ae6adc2b5 100644 --- a/hal/src/main/native/athena/AnalogInternal.cpp +++ b/hal/src/main/native/athena/AnalogInternal.cpp @@ -40,9 +40,13 @@ void InitializeAnalogInternal() { void initializeAnalog(int32_t* status) { hal::init::CheckInit(); - if (analogSystemInitialized) return; + if (analogSystemInitialized) { + return; + } std::scoped_lock lock(analogRegisterWindowMutex); - if (analogSystemInitialized) return; + if (analogSystemInitialized) { + return; + } analogInputSystem.reset(tAI::create(status)); analogOutputSystem.reset(tAO::create(status)); setAnalogNumChannelsToActivate(kNumAnalogInputs); @@ -52,7 +56,9 @@ void initializeAnalog(int32_t* status) { int32_t getAnalogNumActiveChannels(int32_t* status) { int32_t scanSize = analogInputSystem->readConfig_ScanSize(status); - if (scanSize == 0) return 8; + if (scanSize == 0) { + return 8; + } return scanSize; } @@ -61,8 +67,9 @@ void setAnalogNumChannelsToActivate(int32_t channels) { } int32_t getAnalogNumChannelsToActivate(int32_t* status) { - if (analogNumChannelsToActivate == 0) + if (analogNumChannelsToActivate == 0) { return getAnalogNumActiveChannels(status); + } return analogNumChannelsToActivate; } @@ -79,7 +86,9 @@ void setAnalogSampleRate(double samplesPerSecond, int32_t* status) { ticksPerSample / getAnalogNumChannelsToActivate(status); // ticksPerConversion must be at least 80 if (ticksPerConversion < 80) { - if ((*status) >= 0) *status = SAMPLE_RATE_TOO_HIGH; + if ((*status) >= 0) { + *status = SAMPLE_RATE_TOO_HIGH; + } ticksPerConversion = 80; } diff --git a/hal/src/main/native/athena/AnalogOutput.cpp b/hal/src/main/native/athena/AnalogOutput.cpp index 0eaf9ed910..25e2d92f10 100644 --- a/hal/src/main/native/athena/AnalogOutput.cpp +++ b/hal/src/main/native/athena/AnalogOutput.cpp @@ -43,7 +43,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle, hal::init::CheckInit(); initializeAnalog(status); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex) { @@ -54,8 +56,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle, HAL_AnalogOutputHandle handle = analogOutputHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = analogOutputHandles->Get(handle); if (port == nullptr) { // would only error on thread issue @@ -82,10 +85,11 @@ void HAL_SetAnalogOutput(HAL_AnalogOutputHandle analogOutputHandle, uint16_t rawValue = static_cast(voltage / 5.0 * 0x1000); - if (voltage < 0.0) + if (voltage < 0.0) { rawValue = 0; - else if (voltage > 5.0) + } else if (voltage > 5.0) { rawValue = 0x1000; + } analogOutputSystem->writeMXP(port->channel, rawValue, status); } diff --git a/hal/src/main/native/athena/Counter.cpp b/hal/src/main/native/athena/Counter.cpp index 8e1a473cd5..7577da248d 100644 --- a/hal/src/main/native/athena/Counter.cpp +++ b/hal/src/main/native/athena/Counter.cpp @@ -359,10 +359,11 @@ void HAL_SetCounterReverseDirection(HAL_CounterHandle counterHandle, } if (counter->counter->readConfig_Mode(status) == HAL_Counter_kExternalDirection) { - if (reverseDirection) + if (reverseDirection) { HAL_SetCounterDownSourceEdge(counterHandle, true, true, status); - else + } else { HAL_SetCounterDownSourceEdge(counterHandle, false, true, status); + } } } diff --git a/hal/src/main/native/athena/DIO.cpp b/hal/src/main/native/athena/DIO.cpp index 2c19975c8b..ba818f48ce 100644 --- a/hal/src/main/native/athena/DIO.cpp +++ b/hal/src/main/native/athena/DIO.cpp @@ -44,7 +44,9 @@ HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle, hal::init::CheckInit(); initializeDigital(status); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex || channel >= kNumDigitalChannels) { @@ -55,8 +57,9 @@ HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle, auto handle = digitalChannelHandles->Allocate(channel, HAL_HandleEnum::DIO, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO); if (port == nullptr) { // would only occur on thread issue. @@ -124,7 +127,8 @@ HAL_Bool HAL_CheckDIOChannel(int32_t channel) { void HAL_FreeDIOPort(HAL_DigitalHandle dioPortHandle) { auto port = digitalChannelHandles->Get(dioPortHandle, HAL_HandleEnum::DIO); // no status, so no need to check for a proper free. - if (port == nullptr) return; + if (port == nullptr) + return; digitalChannelHandles->Free(dioPortHandle, HAL_HandleEnum::DIO); // Wait for no other object to hold this handle. @@ -186,7 +190,9 @@ void HAL_SetDigitalPWMRate(double rate, int32_t* status) { // higher freq. // TODO: Round in the linear rate domain. initializeDigital(status); - if (*status != 0) return; + if (*status != 0) { + return; + } uint16_t pwmPeriodPower = static_cast( std::log(1.0 / (16 * 1.0E-6 * rate)) / std::log(2.0) + 0.5); digitalSystem->writePWMPeriodPower(pwmPeriodPower, status); @@ -200,10 +206,16 @@ void HAL_SetDigitalPWMDutyCycle(HAL_DigitalPWMHandle pwmGenerator, return; } int32_t id = *port; - if (dutyCycle > 1.0) dutyCycle = 1.0; - if (dutyCycle < 0.0) dutyCycle = 0.0; + if (dutyCycle > 1.0) { + dutyCycle = 1.0; + } + if (dutyCycle < 0.0) { + dutyCycle = 0.0; + } double rawDutyCycle = 256.0 * dutyCycle; - if (rawDutyCycle > 255.5) rawDutyCycle = 255.5; + if (rawDutyCycle > 255.5) { + rawDutyCycle = 255.5; + } { std::scoped_lock lock(digitalPwmMutex); uint16_t pwmPeriodPower = digitalSystem->readPWMPeriodPower(status); @@ -248,7 +260,9 @@ void HAL_SetDIO(HAL_DigitalHandle dioPortHandle, HAL_Bool value, return; } if (value != 0 && value != 1) { - if (value != 0) value = 1; + if (value != 0) { + value = 1; + } } { std::scoped_lock lock(digitalDIOMutex); @@ -407,7 +421,9 @@ HAL_Bool HAL_IsPulsing(HAL_DigitalHandle dioPortHandle, int32_t* status) { HAL_Bool HAL_IsAnyPulsing(int32_t* status) { initializeDigital(status); - if (*status != 0) return false; + if (*status != 0) { + return false; + } tDIO::tPulse pulseRegister = digitalSystem->readPulse(status); return pulseRegister.Headers != 0 && pulseRegister.MXP != 0 && pulseRegister.SPIPort != 0; @@ -456,7 +472,9 @@ int32_t HAL_GetFilterSelect(HAL_DigitalHandle dioPortHandle, int32_t* status) { void HAL_SetFilterPeriod(int32_t filterIndex, int64_t value, int32_t* status) { initializeDigital(status); - if (*status != 0) return; + if (*status != 0) { + return; + } std::scoped_lock lock(digitalDIOMutex); digitalSystem->writeFilterPeriodHdr(filterIndex, value, status); if (*status == 0) { @@ -466,7 +484,9 @@ void HAL_SetFilterPeriod(int32_t filterIndex, int64_t value, int32_t* status) { int64_t HAL_GetFilterPeriod(int32_t filterIndex, int32_t* status) { initializeDigital(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } uint32_t hdrPeriod = 0; uint32_t mxpPeriod = 0; { diff --git a/hal/src/main/native/athena/DMA.cpp b/hal/src/main/native/athena/DMA.cpp index 0eeda392bf..166f8eda65 100644 --- a/hal/src/main/native/athena/DMA.cpp +++ b/hal/src/main/native/athena/DMA.cpp @@ -124,7 +124,8 @@ void HAL_FreeDMA(HAL_DMAHandle handle) { auto dma = dmaHandles->Get(handle); dmaHandles->Free(handle); - if (!dma) return; + if (!dma) + return; int32_t status = 0; if (dma->manager) { @@ -514,7 +515,9 @@ void HAL_SetDMAExternalTrigger(HAL_DMAHandle handle, auto isExternalClock = dma->aDMA->readConfig_ExternalClock(status); if (*status == 0 && !isExternalClock) { dma->aDMA->writeConfig_ExternalClock(true, status); - if (*status != 0) return; + if (*status != 0) { + return; + } } else if (*status != 0) { return; } @@ -554,7 +557,9 @@ void HAL_StartDMA(HAL_DMAHandle handle, int32_t queueDepth, int32_t* status) { } tDMA::tConfig config = dma->aDMA->readConfig(status); - if (*status != 0) return; + if (*status != 0) { + return; + } { size_t accum_size = 0; diff --git a/hal/src/main/native/athena/DigitalInternal.cpp b/hal/src/main/native/athena/DigitalInternal.cpp index 6b1b3f00df..d47cedfb45 100644 --- a/hal/src/main/native/athena/DigitalInternal.cpp +++ b/hal/src/main/native/athena/DigitalInternal.cpp @@ -43,8 +43,12 @@ void InitializeDigitalInternal() { } // namespace init namespace detail { -wpi::mutex& UnsafeGetDIOMutex() { return digitalDIOMutex; } -tDIO* UnsafeGetDigialSystem() { return digitalSystem.get(); } +wpi::mutex& UnsafeGetDIOMutex() { + return digitalDIOMutex; +} +tDIO* UnsafeGetDigialSystem() { + return digitalSystem.get(); +} int32_t ComputeDigitalMask(HAL_DigitalHandle handle, int32_t* status) { auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO); if (port == nullptr) { @@ -69,11 +73,15 @@ void initializeDigital(int32_t* status) { static std::atomic_bool initialized{false}; static wpi::mutex initializeMutex; // Initial check, as if it's true initialization has finished - if (initialized) return; + if (initialized) { + return; + } std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting - if (initialized) return; + if (initialized) { + return; + } digitalSystem.reset(tDIO::create(status)); @@ -89,7 +97,8 @@ void initializeDigital(int32_t* status) { // Make sure that the 9403 IONode has had a chance to initialize before // continuing. - while (pwmSystem->readLoopTiming(status) == 0) std::this_thread::yield(); + while (pwmSystem->readLoopTiming(status) == 0) + std::this_thread::yield(); if (pwmSystem->readLoopTiming(status) != kExpectedLoopTiming) { *status = LOOP_TIMING_ERROR; // NOTE: Doesn't display the error @@ -160,7 +169,9 @@ bool remapDigitalSource(HAL_Handle digitalSourceHandle, } } -int32_t remapMXPChannel(int32_t channel) { return channel - 10; } +int32_t remapMXPChannel(int32_t channel) { + return channel - 10; +} int32_t remapMXPPWMChannel(int32_t channel) { if (channel < 14) { @@ -170,7 +181,9 @@ int32_t remapMXPPWMChannel(int32_t channel) { } } -int32_t remapSPIChannel(int32_t channel) { return channel - 26; } +int32_t remapSPIChannel(int32_t channel) { + return channel - 26; +} } // namespace hal diff --git a/hal/src/main/native/athena/DigitalInternal.h b/hal/src/main/native/athena/DigitalInternal.h index 9cd327ac77..79656ad5e2 100644 --- a/hal/src/main/native/athena/DigitalInternal.h +++ b/hal/src/main/native/athena/DigitalInternal.h @@ -98,13 +98,15 @@ bool remapDigitalSource(HAL_Handle digitalSourceHandle, */ constexpr int32_t remapDigitalChannelToBitfieldChannel(int32_t channel) { // First 10 are headers - if (channel < kNumDigitalHeaders) return channel; - // 2nd group of 16 are mxp. So if mxp port, add 6, since they start at 10 - else if (channel < kNumDigitalMXPChannels) + if (channel < kNumDigitalHeaders) { + return channel; + // 2nd group of 16 are mxp. So if mxp port, add 6, since they start at 10 + } else if (channel < kNumDigitalMXPChannels) { return channel + 6; - // Assume SPI, so remove MXP channels - else + // Assume SPI, so remove MXP channels + } else { return channel - kNumDigitalMXPChannels; + } } /** diff --git a/hal/src/main/native/athena/Encoder.cpp b/hal/src/main/native/athena/Encoder.cpp index 5f86d42f50..5e04e8ade8 100644 --- a/hal/src/main/native/athena/Encoder.cpp +++ b/hal/src/main/native/athena/Encoder.cpp @@ -60,15 +60,23 @@ void Encoder::SetupCounter(HAL_Handle digitalSourceHandleA, m_encodingScale = encodingType == HAL_Encoder_k1X ? 1 : 2; m_counter = HAL_InitializeCounter(HAL_Counter_kExternalDirection, &m_index, status); - if (*status != 0) return; + if (*status != 0) { + return; + } HAL_SetCounterMaxPeriod(m_counter, 0.5, status); - if (*status != 0) return; + if (*status != 0) { + return; + } HAL_SetCounterUpSource(m_counter, digitalSourceHandleA, analogTriggerTypeA, status); - if (*status != 0) return; + if (*status != 0) { + return; + } HAL_SetCounterDownSource(m_counter, digitalSourceHandleB, analogTriggerTypeB, status); - if (*status != 0) return; + if (*status != 0) { + return; + } if (encodingType == HAL_Encoder_k1X) { HAL_SetCounterUpSourceEdge(m_counter, true, false, status); HAL_SetCounterAverageSize(m_counter, 1, status); @@ -240,7 +248,9 @@ bool GetEncoderBaseHandle(HAL_EncoderHandle handle, HAL_FPGAEncoderHandle* fpgaHandle, HAL_CounterHandle* counterHandle) { auto encoder = encoderHandles->Get(handle); - if (!handle) return false; + if (!handle) { + return false; + } *fpgaHandle = encoder->m_encoder; *counterHandle = encoder->m_counter; @@ -258,7 +268,9 @@ HAL_EncoderHandle HAL_InitializeEncoder( auto encoder = std::make_shared( digitalSourceHandleA, analogTriggerTypeA, digitalSourceHandleB, analogTriggerTypeB, reverseDirection, encodingType, status); - if (*status != 0) return HAL_kInvalidHandle; // return in creation error + if (*status != 0) { + return HAL_kInvalidHandle; // return in creation error + } auto handle = encoderHandles->Allocate(encoder); if (handle == HAL_kInvalidHandle) { *status = NO_AVAILABLE_RESOURCES; diff --git a/hal/src/main/native/athena/FRCDriverStation.cpp b/hal/src/main/native/athena/FRCDriverStation.cpp index 74cfdc654d..2e09c8d732 100644 --- a/hal/src/main/native/athena/FRCDriverStation.cpp +++ b/hal/src/main/native/athena/FRCDriverStation.cpp @@ -158,7 +158,8 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, auto curTime = std::chrono::steady_clock::now(); int i; for (i = 0; i < KEEP_MSGS; ++i) { - if (prevMsg[i] == details) break; + if (prevMsg[i] == details) + break; } int retval = 0; if (i == KEEP_MSGS || (curTime - prevMsgTime[i]) >= std::chrono::seconds(1)) { @@ -304,7 +305,9 @@ char* HAL_GetJoystickName(int32_t joystickNum) { } } -void HAL_FreeJoystickName(char* name) { std::free(name); } +void HAL_FreeJoystickName(char* name) { + std::free(name); +} int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) { HAL_JoystickDescriptor joystickDesc; @@ -360,7 +363,9 @@ HAL_Bool HAL_IsNewControlData(void) { std::scoped_lock lock{*newDSDataAvailableMutex}; int& lastCount = GetThreadLocalLastCount(); int currentCount = newDSDataAvailableCounter; - if (lastCount == currentCount) return false; + if (lastCount == currentCount) { + return false; + } lastCount = currentCount; return true; } @@ -368,7 +373,9 @@ HAL_Bool HAL_IsNewControlData(void) { /** * Waits for the newest DS packet to arrive. Note that this is a blocking call. */ -void HAL_WaitForDSData(void) { HAL_WaitForDSDataTimeout(0); } +void HAL_WaitForDSData(void) { + HAL_WaitForDSDataTimeout(0); +} /** * Waits for the newest DS packet to arrive. If timeout is <= 0, this will wait @@ -406,7 +413,9 @@ constexpr int32_t refNumber = 42; static void newDataOccur(uint32_t refNum) { // Since we could get other values, require our specific handle // to signal our threads - if (refNum != refNumber) return; + if (refNum != refNumber) { + return; + } std::scoped_lock lock{*newDSDataAvailableMutex}; // Notify all threads ++newDSDataAvailableCounter; @@ -422,11 +431,15 @@ void HAL_InitializeDriverStation(void) { static std::atomic_bool initialized{false}; static wpi::mutex initializeMutex; // Initial check, as if it's true initialization has finished - if (initialized) return; + if (initialized) { + return; + } std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting - if (initialized) return; + if (initialized) { + return; + } // Set up the occur function internally with NetComm NetCommRPCProxy_SetOccurFuncPointer(newDataOccur); @@ -440,6 +453,8 @@ void HAL_InitializeDriverStation(void) { * Releases the DS Mutex to allow proper shutdown of any threads that are * waiting on it. */ -void HAL_ReleaseDSMutex(void) { newDataOccur(refNumber); } +void HAL_ReleaseDSMutex(void) { + newDataOccur(refNumber); +} } // extern "C" diff --git a/hal/src/main/native/athena/HAL.cpp b/hal/src/main/native/athena/HAL.cpp index 464e3df15f..fcee49897f 100644 --- a/hal/src/main/native/athena/HAL.cpp +++ b/hal/src/main/native/athena/HAL.cpp @@ -92,14 +92,20 @@ extern "C" { HAL_PortHandle HAL_GetPort(int32_t channel) { // Dont allow a number that wouldn't fit in a uint8_t - if (channel < 0 || channel >= 255) return HAL_kInvalidHandle; + if (channel < 0 || channel >= 255) { + return HAL_kInvalidHandle; + } return createPortHandle(channel, 1); } HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel) { // Dont allow a number that wouldn't fit in a uint8_t - if (channel < 0 || channel >= 255) return HAL_kInvalidHandle; - if (module < 0 || module >= 255) return HAL_kInvalidHandle; + if (channel < 0 || channel >= 255) { + return HAL_kInvalidHandle; + } + if (module < 0 || module >= 255) { + return HAL_kInvalidHandle; + } return createPortHandle(channel, module); } @@ -232,7 +238,9 @@ const char* HAL_GetErrorMessage(int32_t code) { } } -HAL_RuntimeType HAL_GetRuntimeType(void) { return HAL_Athena; } +HAL_RuntimeType HAL_GetRuntimeType(void) { + return HAL_Athena; +} int32_t HAL_GetFPGAVersion(int32_t* status) { if (!global) { @@ -259,11 +267,15 @@ uint64_t HAL_GetFPGATime(int32_t* status) { uint64_t upper1 = global->readLocalTimeUpper(status); uint32_t lower = global->readLocalTime(status); uint64_t upper2 = global->readLocalTimeUpper(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } if (upper1 != upper2) { // Rolled over between the lower call, reread lower lower = global->readLocalTime(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } } return (upper2 << 32) + lower; } @@ -272,7 +284,9 @@ uint64_t HAL_ExpandFPGATime(uint32_t unexpanded_lower, int32_t* status) { // Capture the current FPGA time. This will give us the upper half of the // clock. uint64_t fpga_time = HAL_GetFPGATime(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } // Now, we need to detect the case where the lower bits rolled over after we // sampled. In that case, the upper bits will be 1 bigger than they should @@ -319,7 +333,9 @@ static bool killExistingProgram(int timeout, int mode) { std::fstream fs; // By making this both in/out, it won't give us an error if it doesnt exist fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out); - if (fs.bad()) return false; + if (fs.bad()) { + return false; + } pid_t pid = 0; if (!fs.eof() && !fs.fail()) { @@ -359,11 +375,15 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { static std::atomic_bool initialized{false}; static wpi::mutex initializeMutex; // Initial check, as if it's true initialization has finished - if (initialized) return true; + if (initialized) { + return true; + } std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting - if (initialized) return true; + if (initialized) { + return true; + } hal::init::InitializeHAL(); @@ -394,7 +414,9 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { global.reset(tGlobal::create(&status)); watchdog.reset(tSysWatchdog::create(&status)); - if (status != 0) return false; + if (status != 0) { + return false; + } HAL_InitializeDriverStation(); diff --git a/hal/src/main/native/athena/HALInitializer.cpp b/hal/src/main/native/athena/HALInitializer.cpp index 654adf5cda..1905c9b1d6 100644 --- a/hal/src/main/native/athena/HALInitializer.cpp +++ b/hal/src/main/native/athena/HALInitializer.cpp @@ -9,6 +9,8 @@ namespace hal { namespace init { std::atomic_bool HAL_IsInitialized{false}; -void RunInitialize() { HAL_Initialize(500, 0); } +void RunInitialize() { + HAL_Initialize(500, 0); +} } // namespace init } // namespace hal diff --git a/hal/src/main/native/athena/HALInitializer.h b/hal/src/main/native/athena/HALInitializer.h index 6d7bf71259..eb7fbafd8a 100644 --- a/hal/src/main/native/athena/HALInitializer.h +++ b/hal/src/main/native/athena/HALInitializer.h @@ -11,7 +11,9 @@ namespace init { extern std::atomic_bool HAL_IsInitialized; extern void RunInitialize(); static inline void CheckInit() { - if (HAL_IsInitialized.load(std::memory_order_relaxed)) return; + if (HAL_IsInitialized.load(std::memory_order_relaxed)) { + return; + } RunInitialize(); } diff --git a/hal/src/main/native/athena/I2C.cpp b/hal/src/main/native/athena/I2C.cpp index a7cf0d14e0..9f4216e30d 100644 --- a/hal/src/main/native/athena/I2C.cpp +++ b/hal/src/main/native/athena/I2C.cpp @@ -41,7 +41,9 @@ extern "C" { void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { hal::init::CheckInit(); initializeDigital(status); - if (*status != 0) return; + if (*status != 0) { + return; + } if (port < 0 || port > 1) { // Set port out of range error here @@ -51,7 +53,9 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { if (port == HAL_I2C_kOnboard) { std::scoped_lock lock(digitalI2COnBoardMutex); i2COnboardObjCount++; - if (i2COnboardObjCount > 1) return; + if (i2COnboardObjCount > 1) { + return; + } int handle = open("/dev/i2c-2", O_RDWR); if (handle < 0) { std::printf("Failed to open onboard i2c bus: %s\n", std::strerror(errno)); @@ -61,7 +65,9 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { } else { std::scoped_lock lock(digitalI2CMXPMutex); i2CMXPObjCount++; - if (i2CMXPObjCount > 1) return; + if (i2CMXPObjCount > 1) { + return; + } if ((i2CMXPDigitalHandle1 = HAL_InitializeDIOPort( HAL_GetPort(24), false, status)) == HAL_kInvalidHandle) { return; diff --git a/hal/src/main/native/athena/Interrupts.cpp b/hal/src/main/native/athena/Interrupts.cpp index c7fc161a11..7cdac4e0f4 100644 --- a/hal/src/main/native/athena/Interrupts.cpp +++ b/hal/src/main/native/athena/Interrupts.cpp @@ -28,7 +28,9 @@ class InterruptThread : public wpi::SafeThread { std::unique_lock lock(m_mutex); while (m_active) { m_cond.wait(lock, [&] { return !m_active || m_notify; }); - if (!m_active) break; + if (!m_active) { + break; + } m_notify = false; HAL_InterruptHandlerFunction handler = m_handler; uint32_t mask = m_mask; @@ -49,14 +51,16 @@ class InterruptThreadOwner : public wpi::SafeThreadOwner { public: void SetFunc(HAL_InterruptHandlerFunction handler, void* param) { auto thr = GetThread(); - if (!thr) return; + if (!thr) + return; thr->m_handler = handler; thr->m_param = param; } void Notify(uint32_t mask) { auto thr = GetThread(); - if (!thr) return; + if (!thr) + return; thr->m_mask = mask; thr->m_notify = true; thr->m_cond.notify_one(); diff --git a/hal/src/main/native/athena/Notifier.cpp b/hal/src/main/native/athena/Notifier.cpp index d606290cc9..c4778e86b1 100644 --- a/hal/src/main/native/athena/Notifier.cpp +++ b/hal/src/main/native/athena/Notifier.cpp @@ -75,8 +75,10 @@ static void alarmCallback() { // process all notifiers notifierHandles->ForEach([&](HAL_NotifierHandle handle, Notifier* notifier) { - if (notifier->triggerTime == UINT64_MAX) return; - if (currentTime == 0) currentTime = HAL_GetFPGATime(&status); + if (notifier->triggerTime == UINT64_MAX) + return; + if (currentTime == 0) + currentTime = HAL_GetFPGATime(&status); std::unique_lock lock(notifier->mutex); if (notifier->triggerTime < currentTime) { notifier->triggerTime = UINT64_MAX; @@ -102,19 +104,25 @@ static void notifierThreadMain() { tInterruptManager manager{1 << kTimerInterruptNumber, true, &status}; while (notifierRunning) { auto triggeredMask = manager.watch(10000, false, &status); - if (!notifierRunning) break; - if (triggeredMask == 0) continue; + if (!notifierRunning) { + break; + } + if (triggeredMask == 0) + continue; alarmCallback(); } } static void cleanupNotifierAtExit() { int32_t status = 0; - if (notifierAlarm) notifierAlarm->writeEnable(false, &status); + if (notifierAlarm) + notifierAlarm->writeEnable(false, &status); notifierAlarm = nullptr; notifierRunning = false; hal::ReleaseFPGAInterrupt(kTimerInterruptNumber); - if (notifierThread.joinable()) notifierThread.join(); + if (notifierThread.joinable()) { + notifierThread.join(); + } } namespace hal { @@ -130,8 +138,9 @@ extern "C" { HAL_NotifierHandle HAL_InitializeNotifier(int32_t* status) { hal::init::CheckInit(); - if (!notifierAtexitRegistered.test_and_set()) + if (!notifierAtexitRegistered.test_and_set()) { std::atexit(cleanupNotifierAtExit); + } if (notifierRefCount.fetch_add(1) == 0) { std::scoped_lock lock(notifierMutex); @@ -154,7 +163,8 @@ void HAL_SetNotifierName(HAL_NotifierHandle notifierHandle, const char* name, void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return; + if (!notifier) + return; { std::scoped_lock lock(notifier->mutex); @@ -167,7 +177,8 @@ void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Free(notifierHandle); - if (!notifier) return; + if (!notifier) + return; // Just in case HAL_StopNotifier() wasn't called... { @@ -184,10 +195,13 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { // here (the atomic fetch_sub will prevent multiple parallel entries // into this function) - if (notifierAlarm) notifierAlarm->writeEnable(false, status); + if (notifierAlarm) + notifierAlarm->writeEnable(false, status); notifierRunning = false; hal::ReleaseFPGAInterrupt(kTimerInterruptNumber); - if (notifierThread.joinable()) notifierThread.join(); + if (notifierThread.joinable()) { + notifierThread.join(); + } std::scoped_lock lock(notifierMutex); notifierAlarm = nullptr; @@ -198,7 +212,8 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle, uint64_t triggerTime, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return; + if (!notifier) + return; { std::scoped_lock lock(notifier->mutex); @@ -215,14 +230,16 @@ void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle, notifierAlarm->writeTriggerTime(static_cast(closestTrigger), status); // Enable the alarm. - if (!wasActive) notifierAlarm->writeEnable(true, status); + if (!wasActive) + notifierAlarm->writeEnable(true, status); } } void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return; + if (!notifier) + return; { std::scoped_lock lock(notifier->mutex); @@ -233,7 +250,8 @@ void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle, uint64_t HAL_WaitForNotifierAlarm(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return 0; + if (!notifier) + return 0; std::unique_lock lock(notifier->mutex); notifier->cond.wait(lock, [&] { return !notifier->active || notifier->triggeredTime != UINT64_MAX; diff --git a/hal/src/main/native/athena/PDP.cpp b/hal/src/main/native/athena/PDP.cpp index 203317e380..4739780b72 100644 --- a/hal/src/main/native/athena/PDP.cpp +++ b/hal/src/main/native/athena/PDP.cpp @@ -306,15 +306,21 @@ void HAL_GetPDPAllChannelCurrents(HAL_PDPHandle handle, double* currents, PdpStatus1 pdpStatus; HAL_ReadCANPacketTimeout(handle, Status1, pdpStatus.data, &length, &receivedTimestamp, TimeoutMs, status); - if (*status != 0) return; + if (*status != 0) { + return; + } PdpStatus2 pdpStatus2; HAL_ReadCANPacketTimeout(handle, Status2, pdpStatus2.data, &length, &receivedTimestamp, TimeoutMs, status); - if (*status != 0) return; + if (*status != 0) { + return; + } PdpStatus3 pdpStatus3; HAL_ReadCANPacketTimeout(handle, Status3, pdpStatus3.data, &length, &receivedTimestamp, TimeoutMs, status); - if (*status != 0) return; + if (*status != 0) { + return; + } currents[0] = ((static_cast(pdpStatus.bits.chan1_h8) << 2) | pdpStatus.bits.chan1_l2) * diff --git a/hal/src/main/native/athena/PWM.cpp b/hal/src/main/native/athena/PWM.cpp index dcbe2cec10..730a786a9d 100644 --- a/hal/src/main/native/athena/PWM.cpp +++ b/hal/src/main/native/athena/PWM.cpp @@ -71,7 +71,9 @@ HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle, hal::init::CheckInit(); initializeDigital(status); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex || channel >= kNumPWMChannels) { @@ -90,8 +92,9 @@ HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle, auto handle = digitalChannelHandles->Allocate(channel, HAL_HandleEnum::PWM, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::PWM); if (port == nullptr) { // would only occur on thread issue. @@ -160,7 +163,9 @@ void HAL_SetPWMConfig(HAL_DigitalHandle pwmPortHandle, double max, // calculate the loop time in milliseconds double loopTime = HAL_GetPWMLoopTiming(status) / (kSystemClockTicksPerMicrosecond * 1e3); - if (*status != 0) return; + if (*status != 0) { + return; + } int32_t maxPwm = static_cast((max - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1); @@ -356,7 +361,9 @@ double HAL_GetPWMSpeed(HAL_DigitalHandle pwmPortHandle, int32_t* status) { } int32_t value = HAL_GetPWMRaw(pwmPortHandle, status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } DigitalPort* dPort = port.get(); if (value == kPwmDisabled) { @@ -388,7 +395,9 @@ double HAL_GetPWMPosition(HAL_DigitalHandle pwmPortHandle, int32_t* status) { } int32_t value = HAL_GetPWMRaw(pwmPortHandle, status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } DigitalPort* dPort = port.get(); if (value < GetMinNegativePwm(dPort)) { @@ -430,22 +439,30 @@ void HAL_SetPWMPeriodScale(HAL_DigitalHandle pwmPortHandle, int32_t squelchMask, int32_t HAL_GetPWMLoopTiming(int32_t* status) { initializeDigital(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } return pwmSystem->readLoopTiming(status); } uint64_t HAL_GetPWMCycleStartTime(int32_t* status) { initializeDigital(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } uint64_t upper1 = pwmSystem->readCycleStartTimeUpper(status); uint32_t lower = pwmSystem->readCycleStartTime(status); uint64_t upper2 = pwmSystem->readCycleStartTimeUpper(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } if (upper1 != upper2) { // Rolled over between the lower call, reread lower lower = pwmSystem->readCycleStartTime(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } } return (upper2 << 32) + lower; } diff --git a/hal/src/main/native/athena/Ports.cpp b/hal/src/main/native/athena/Ports.cpp index 833ac03ee1..148e15d3b2 100644 --- a/hal/src/main/native/athena/Ports.cpp +++ b/hal/src/main/native/athena/Ports.cpp @@ -16,25 +16,65 @@ void InitializePorts() {} extern "C" { -int32_t HAL_GetNumAccumulators(void) { return kNumAccumulators; } -int32_t HAL_GetNumAnalogTriggers(void) { return kNumAnalogTriggers; } -int32_t HAL_GetNumAnalogInputs(void) { return kNumAnalogInputs; } -int32_t HAL_GetNumAnalogOutputs(void) { return kNumAnalogOutputs; } -int32_t HAL_GetNumCounters(void) { return kNumCounters; } -int32_t HAL_GetNumDigitalHeaders(void) { return kNumDigitalHeaders; } -int32_t HAL_GetNumPWMHeaders(void) { return kNumPWMHeaders; } -int32_t HAL_GetNumDigitalChannels(void) { return kNumDigitalChannels; } -int32_t HAL_GetNumPWMChannels(void) { return kNumPWMChannels; } -int32_t HAL_GetNumDigitalPWMOutputs(void) { return kNumDigitalPWMOutputs; } -int32_t HAL_GetNumEncoders(void) { return kNumEncoders; } -int32_t HAL_GetNumInterrupts(void) { return kNumInterrupts; } -int32_t HAL_GetNumRelayChannels(void) { return kNumRelayChannels; } -int32_t HAL_GetNumRelayHeaders(void) { return kNumRelayHeaders; } -int32_t HAL_GetNumPCMModules(void) { return kNumPCMModules; } -int32_t HAL_GetNumSolenoidChannels(void) { return kNumSolenoidChannels; } -int32_t HAL_GetNumPDPModules(void) { return kNumPDPModules; } -int32_t HAL_GetNumPDPChannels(void) { return kNumPDPChannels; } -int32_t HAL_GetNumDutyCycles(void) { return kNumDutyCycles; } -int32_t HAL_GetNumAddressableLEDs(void) { return kNumAddressableLEDs; } +int32_t HAL_GetNumAccumulators(void) { + return kNumAccumulators; +} +int32_t HAL_GetNumAnalogTriggers(void) { + return kNumAnalogTriggers; +} +int32_t HAL_GetNumAnalogInputs(void) { + return kNumAnalogInputs; +} +int32_t HAL_GetNumAnalogOutputs(void) { + return kNumAnalogOutputs; +} +int32_t HAL_GetNumCounters(void) { + return kNumCounters; +} +int32_t HAL_GetNumDigitalHeaders(void) { + return kNumDigitalHeaders; +} +int32_t HAL_GetNumPWMHeaders(void) { + return kNumPWMHeaders; +} +int32_t HAL_GetNumDigitalChannels(void) { + return kNumDigitalChannels; +} +int32_t HAL_GetNumPWMChannels(void) { + return kNumPWMChannels; +} +int32_t HAL_GetNumDigitalPWMOutputs(void) { + return kNumDigitalPWMOutputs; +} +int32_t HAL_GetNumEncoders(void) { + return kNumEncoders; +} +int32_t HAL_GetNumInterrupts(void) { + return kNumInterrupts; +} +int32_t HAL_GetNumRelayChannels(void) { + return kNumRelayChannels; +} +int32_t HAL_GetNumRelayHeaders(void) { + return kNumRelayHeaders; +} +int32_t HAL_GetNumPCMModules(void) { + return kNumPCMModules; +} +int32_t HAL_GetNumSolenoidChannels(void) { + return kNumSolenoidChannels; +} +int32_t HAL_GetNumPDPModules(void) { + return kNumPDPModules; +} +int32_t HAL_GetNumPDPChannels(void) { + return kNumPDPChannels; +} +int32_t HAL_GetNumDutyCycles(void) { + return kNumDutyCycles; +} +int32_t HAL_GetNumAddressableLEDs(void) { + return kNumAddressableLEDs; +} } // extern "C" diff --git a/hal/src/main/native/athena/Relay.cpp b/hal/src/main/native/athena/Relay.cpp index b169aa2003..f6f8819a94 100644 --- a/hal/src/main/native/athena/Relay.cpp +++ b/hal/src/main/native/athena/Relay.cpp @@ -44,7 +44,9 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd, hal::init::CheckInit(); initializeDigital(status); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex) { @@ -52,12 +54,15 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd, return HAL_kInvalidHandle; } - if (!fwd) channel += kNumRelayHeaders; // add 4 to reverse channels + if (!fwd) { + channel += kNumRelayHeaders; // add 4 to reverse channels + } auto handle = relayHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = relayHandles->Get(handle); if (port == nullptr) { // would only occur on thread issue. @@ -105,7 +110,9 @@ void HAL_SetRelay(HAL_RelayHandle relayPortHandle, HAL_Bool on, relays = relaySystem->readValue_Reverse(status); } - if (*status != 0) return; // bad status read + if (*status != 0) { + return; // bad status read + } if (on) { relays |= 1 << port->channel; diff --git a/hal/src/main/native/athena/SPI.cpp b/hal/src/main/native/athena/SPI.cpp index 90a51ec277..b8ab439b2f 100644 --- a/hal/src/main/native/athena/SPI.cpp +++ b/hal/src/main/native/athena/SPI.cpp @@ -51,7 +51,9 @@ static bool SPIInUseByAuto(HAL_SPIPort port) { // SPI engine conflicts with any other chip selects on the same SPI device. // There are two SPI devices: one for ports 0-3 (onboard), the other for port // 4 (MXP). - if (!spiAutoRunning) return false; + if (!spiAutoRunning) { + return false; + } std::scoped_lock lock(spiAutoMutex); return (spiAutoPort >= 0 && spiAutoPort <= 3 && port >= 0 && port <= 3) || (spiAutoPort == 4 && port == 4); @@ -70,7 +72,9 @@ static void CommonSPIPortInit(int32_t* status) { if (spiPortCount.fetch_add(1) == 0) { // Have not been initialized yet initializeDigital(status); - if (*status != 0) return; + if (*status != 0) { + return; + } // MISO if ((digitalHandles[3] = HAL_InitializeDIOPort(createPortHandleForSPI(29), false, status)) == @@ -105,11 +109,15 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { } int handle; - if (HAL_GetSPIHandle(port) != 0) return; + if (HAL_GetSPIHandle(port) != 0) { + return; + } switch (port) { case HAL_SPI_kOnboardCS0: CommonSPIPortInit(status); - if (*status != 0) return; + if (*status != 0) { + return; + } // CS0 is not a DIO port, so nothing to allocate handle = open("/dev/spidev0.0", O_RDWR); if (handle < 0) { @@ -122,7 +130,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { break; case HAL_SPI_kOnboardCS1: CommonSPIPortInit(status); - if (*status != 0) return; + if (*status != 0) { + return; + } // CS1, Allocate if ((digitalHandles[0] = HAL_InitializeDIOPort(createPortHandleForSPI(26), false, status)) == @@ -143,7 +153,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { break; case HAL_SPI_kOnboardCS2: CommonSPIPortInit(status); - if (*status != 0) return; + if (*status != 0) { + return; + } // CS2, Allocate if ((digitalHandles[1] = HAL_InitializeDIOPort(createPortHandleForSPI(27), false, status)) == @@ -164,7 +176,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { break; case HAL_SPI_kOnboardCS3: CommonSPIPortInit(status); - if (*status != 0) return; + if (*status != 0) { + return; + } // CS3, Allocate if ((digitalHandles[2] = HAL_InitializeDIOPort(createPortHandleForSPI(28), false, status)) == @@ -185,7 +199,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { break; case HAL_SPI_kMXP: initializeDigital(status); - if (*status != 0) return; + if (*status != 0) { + return; + } if ((digitalHandles[5] = HAL_InitializeDIOPort(createPortHandleForSPI(14), false, status)) == HAL_kInvalidHandle) { @@ -242,7 +258,9 @@ int32_t HAL_TransactionSPI(HAL_SPIPort port, const uint8_t* dataToSend, return -1; } - if (SPIInUseByAuto(port)) return -1; + if (SPIInUseByAuto(port)) { + return -1; + } struct spi_ioc_transfer xfer; std::memset(&xfer, 0, sizeof(xfer)); @@ -260,7 +278,9 @@ int32_t HAL_WriteSPI(HAL_SPIPort port, const uint8_t* dataToSend, return -1; } - if (SPIInUseByAuto(port)) return -1; + if (SPIInUseByAuto(port)) { + return -1; + } struct spi_ioc_transfer xfer; std::memset(&xfer, 0, sizeof(xfer)); @@ -276,7 +296,9 @@ int32_t HAL_ReadSPI(HAL_SPIPort port, uint8_t* buffer, int32_t count) { return -1; } - if (SPIInUseByAuto(port)) return -1; + if (SPIInUseByAuto(port)) { + return -1; + } struct spi_ioc_transfer xfer; std::memset(&xfer, 0, sizeof(xfer)); @@ -468,7 +490,9 @@ void HAL_FreeSPIAuto(HAL_SPIPort port, int32_t* status) { } std::scoped_lock lock(spiAutoMutex); - if (spiAutoPort != port) return; + if (spiAutoPort != port) { + return; + } spiAutoPort = kSpiMaxHandles; // disable by setting to internal clock and setting rate=0 diff --git a/hal/src/main/native/athena/SerialPort.cpp b/hal/src/main/native/athena/SerialPort.cpp index 057e01a6de..bd26281587 100644 --- a/hal/src/main/native/athena/SerialPort.cpp +++ b/hal/src/main/native/athena/SerialPort.cpp @@ -414,7 +414,9 @@ int32_t HAL_GetSerialBytesReceived(HAL_SerialPortHandle handle, int32_t HAL_ReadSerial(HAL_SerialPortHandle handle, char* buffer, int32_t count, int32_t* status) { // Don't do anything if 0 bytes were requested - if (count == 0) return 0; + if (count == 0) { + return 0; + } auto port = serialPortHandles->Get(handle); if (!port) { diff --git a/hal/src/main/native/athena/SimDevice.cpp b/hal/src/main/native/athena/SimDevice.cpp index 37c7fab11c..b92d792819 100644 --- a/hal/src/main/native/athena/SimDevice.cpp +++ b/hal/src/main/native/athena/SimDevice.cpp @@ -6,7 +6,9 @@ extern "C" { -HAL_SimDeviceHandle HAL_CreateSimDevice(const char* name) { return 0; } +HAL_SimDeviceHandle HAL_CreateSimDevice(const char* name) { + return 0; +} void HAL_FreeSimDevice(HAL_SimDeviceHandle handle) {} diff --git a/hal/src/main/native/athena/Solenoid.cpp b/hal/src/main/native/athena/Solenoid.cpp index 3f2ad87ab4..dea191f7aa 100644 --- a/hal/src/main/native/athena/Solenoid.cpp +++ b/hal/src/main/native/athena/Solenoid.cpp @@ -105,7 +105,9 @@ HAL_Bool HAL_GetSolenoid(HAL_SolenoidHandle solenoidPortHandle, } int32_t HAL_GetAllSolenoids(int32_t module, int32_t* status) { - if (!checkPCMInit(module, status)) return 0; + if (!checkPCMInit(module, status)) { + return 0; + } uint8_t value; *status = PCM_modules[module]->GetAllSolenoids(value); @@ -125,13 +127,17 @@ void HAL_SetSolenoid(HAL_SolenoidHandle solenoidPortHandle, HAL_Bool value, } void HAL_SetAllSolenoids(int32_t module, int32_t state, int32_t* status) { - if (!checkPCMInit(module, status)) return; + if (!checkPCMInit(module, status)) { + return; + } *status = PCM_modules[module]->SetAllSolenoids(state); } int32_t HAL_GetPCMSolenoidBlackList(int32_t module, int32_t* status) { - if (!checkPCMInit(module, status)) return 0; + if (!checkPCMInit(module, status)) { + return 0; + } uint8_t value; *status = PCM_modules[module]->GetSolenoidBlackList(value); @@ -139,7 +145,9 @@ int32_t HAL_GetPCMSolenoidBlackList(int32_t module, int32_t* status) { return value; } HAL_Bool HAL_GetPCMSolenoidVoltageStickyFault(int32_t module, int32_t* status) { - if (!checkPCMInit(module, status)) return 0; + if (!checkPCMInit(module, status)) { + return 0; + } bool value; *status = PCM_modules[module]->GetSolenoidStickyFault(value); @@ -147,7 +155,9 @@ HAL_Bool HAL_GetPCMSolenoidVoltageStickyFault(int32_t module, int32_t* status) { return value; } HAL_Bool HAL_GetPCMSolenoidVoltageFault(int32_t module, int32_t* status) { - if (!checkPCMInit(module, status)) return false; + if (!checkPCMInit(module, status)) { + return false; + } bool value; *status = PCM_modules[module]->GetSolenoidFault(value); @@ -155,7 +165,9 @@ HAL_Bool HAL_GetPCMSolenoidVoltageFault(int32_t module, int32_t* status) { return value; } void HAL_ClearAllPCMStickyFaults(int32_t module, int32_t* status) { - if (!checkPCMInit(module, status)) return; + if (!checkPCMInit(module, status)) { + return; + } *status = PCM_modules[module]->ClearStickyFaults(); } diff --git a/hal/src/main/native/athena/Threads.cpp b/hal/src/main/native/athena/Threads.cpp index 4f2dbf126f..76204f5196 100644 --- a/hal/src/main/native/athena/Threads.cpp +++ b/hal/src/main/native/athena/Threads.cpp @@ -66,11 +66,12 @@ HAL_Bool HAL_SetThreadPriority(NativeThreadHandle handle, HAL_Bool realTime, int policy; pthread_getschedparam(*reinterpret_cast(handle), &policy, &sch); - if (scheduler == SCHED_FIFO || scheduler == SCHED_RR) + if (scheduler == SCHED_FIFO || scheduler == SCHED_RR) { sch.sched_priority = priority; - else + } else { // Only need to set 0 priority for non RT thread sch.sched_priority = 0; + } if (pthread_setschedparam(*reinterpret_cast(handle), scheduler, &sch)) { *status = HAL_THREAD_PRIORITY_ERROR; diff --git a/hal/src/main/native/athena/cpp/SerialHelper.cpp b/hal/src/main/native/athena/cpp/SerialHelper.cpp index 297f357933..012d9a0b5b 100644 --- a/hal/src/main/native/athena/cpp/SerialHelper.cpp +++ b/hal/src/main/native/athena/cpp/SerialHelper.cpp @@ -191,25 +191,30 @@ void SerialHelper::QueryHubPaths(int32_t* status) { // Open the resource, grab its interface name, and close it. ViSession vSession; *status = viOpen(m_resourceHandle, desc, VI_NULL, VI_NULL, &vSession); - if (*status < 0) goto done; + if (*status < 0) + goto done; *status = 0; *status = viGetAttribute(vSession, VI_ATTR_INTF_INST_NAME, &osName); // Ignore an error here, as we want to close the session on an error // Use a separate close variable so we can check ViStatus closeStatus = viClose(vSession); - if (*status < 0) goto done; - if (closeStatus < 0) goto done; + if (*status < 0) + goto done; + if (closeStatus < 0) + goto done; *status = 0; // split until (/dev/ wpi::StringRef devNameRef = wpi::StringRef{osName}.split("(/dev/").second; // String not found, continue - if (devNameRef.equals("")) continue; + if (devNameRef.equals("")) + continue; // Split at ) wpi::StringRef matchString = devNameRef.split(')').first; - if (matchString.equals(devNameRef)) continue; + if (matchString.equals(devNameRef)) + continue; // Search directories to get a list of system accessors // The directories we need are not symbolic, so we can safely @@ -218,11 +223,15 @@ void SerialHelper::QueryHubPaths(int32_t* status) { for (auto p = wpi::sys::fs::recursive_directory_iterator( "/sys/devices/soc0", ec, false); p != wpi::sys::fs::recursive_directory_iterator(); p.increment(ec)) { - if (ec) break; + if (ec) + break; wpi::StringRef path{p->path()}; - if (path.find("amba") == wpi::StringRef::npos) continue; - if (path.find("usb") == wpi::StringRef::npos) continue; - if (path.find(matchString) == wpi::StringRef::npos) continue; + if (path.find("amba") == wpi::StringRef::npos) + continue; + if (path.find("usb") == wpi::StringRef::npos) + continue; + if (path.find(matchString) == wpi::StringRef::npos) + continue; wpi::SmallVector pathSplitVec; // Split path into individual directories @@ -246,11 +255,13 @@ void SerialHelper::QueryHubPaths(int32_t* status) { // Get the index for our device int hubIndex = findtty; - if (findtty == -1) hubIndex = findregex; + if (findtty == -1) + hubIndex = findregex; int devStart = findusb + 1; - if (hubIndex < devStart) continue; + if (hubIndex < devStart) + continue; // Add our devices to our list m_unsortedHubPath.emplace_back( diff --git a/hal/src/main/native/athena/mockdata/AddressableLEDData.cpp b/hal/src/main/native/athena/mockdata/AddressableLEDData.cpp index 53af682969..a1d7011945 100644 --- a/hal/src/main/native/athena/mockdata/AddressableLEDData.cpp +++ b/hal/src/main/native/athena/mockdata/AddressableLEDData.cpp @@ -8,7 +8,9 @@ extern "C" { -int32_t HALSIM_FindAddressableLEDForChannel(int32_t channel) { return 0; } +int32_t HALSIM_FindAddressableLEDForChannel(int32_t channel) { + return 0; +} void HALSIM_ResetAddressableLEDData(int32_t index) {} diff --git a/hal/src/main/native/athena/mockdata/AnalogInData.cpp b/hal/src/main/native/athena/mockdata/AnalogInData.cpp index d0df51e626..30ac79561f 100644 --- a/hal/src/main/native/athena/mockdata/AnalogInData.cpp +++ b/hal/src/main/native/athena/mockdata/AnalogInData.cpp @@ -9,7 +9,9 @@ extern "C" { void HALSIM_ResetAnalogInData(int32_t index) {} -HAL_SimDeviceHandle HALSIM_GetAnalogInSimDevice(int32_t index) { return 0; } +HAL_SimDeviceHandle HALSIM_GetAnalogInSimDevice(int32_t index) { + return 0; +} #define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \ HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, AnalogIn##CAPINAME, RETURN) diff --git a/hal/src/main/native/athena/mockdata/AnalogTriggerData.cpp b/hal/src/main/native/athena/mockdata/AnalogTriggerData.cpp index 8bf8abaa7e..af8d7cc53f 100644 --- a/hal/src/main/native/athena/mockdata/AnalogTriggerData.cpp +++ b/hal/src/main/native/athena/mockdata/AnalogTriggerData.cpp @@ -8,7 +8,9 @@ extern "C" { -int32_t HALSIM_FindAnalogTriggerForChannel(int32_t channel) { return 0; } +int32_t HALSIM_FindAnalogTriggerForChannel(int32_t channel) { + return 0; +} void HALSIM_ResetAnalogTriggerData(int32_t index) {} diff --git a/hal/src/main/native/athena/mockdata/DIOData.cpp b/hal/src/main/native/athena/mockdata/DIOData.cpp index 81759f2c18..392c31b6d4 100644 --- a/hal/src/main/native/athena/mockdata/DIOData.cpp +++ b/hal/src/main/native/athena/mockdata/DIOData.cpp @@ -9,7 +9,9 @@ extern "C" { void HALSIM_ResetDIOData(int32_t index) {} -HAL_SimDeviceHandle HALSIM_GetDIOSimDevice(int32_t index) { return 0; } +HAL_SimDeviceHandle HALSIM_GetDIOSimDevice(int32_t index) { + return 0; +} #define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \ HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, DIO##CAPINAME, RETURN) diff --git a/hal/src/main/native/athena/mockdata/DigitalPWMData.cpp b/hal/src/main/native/athena/mockdata/DigitalPWMData.cpp index e51d386a46..c3f5d31e30 100644 --- a/hal/src/main/native/athena/mockdata/DigitalPWMData.cpp +++ b/hal/src/main/native/athena/mockdata/DigitalPWMData.cpp @@ -7,7 +7,9 @@ #include "hal/simulation/SimDataValue.h" extern "C" { -int32_t HALSIM_FindDigitalPWMForChannel(int32_t channel) { return 0; } +int32_t HALSIM_FindDigitalPWMForChannel(int32_t channel) { + return 0; +} void HALSIM_ResetDigitalPWMData(int32_t index) {} diff --git a/hal/src/main/native/athena/mockdata/DutyCycleData.cpp b/hal/src/main/native/athena/mockdata/DutyCycleData.cpp index c288147d49..d63e27e273 100644 --- a/hal/src/main/native/athena/mockdata/DutyCycleData.cpp +++ b/hal/src/main/native/athena/mockdata/DutyCycleData.cpp @@ -7,13 +7,19 @@ #include "hal/simulation/SimDataValue.h" extern "C" { -int32_t HALSIM_FindDutyCycleForChannel(int32_t channel) { return 0; } +int32_t HALSIM_FindDutyCycleForChannel(int32_t channel) { + return 0; +} void HALSIM_ResetDutyCycleData(int32_t index) {} -int32_t HALSIM_GetDutyCycleDigitalChannel(int32_t index) { return 0; } +int32_t HALSIM_GetDutyCycleDigitalChannel(int32_t index) { + return 0; +} -HAL_SimDeviceHandle HALSIM_GetDutyCycleSimDevice(int32_t index) { return 0; } +HAL_SimDeviceHandle HALSIM_GetDutyCycleSimDevice(int32_t index) { + return 0; +} #define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \ HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, DutyCycle##CAPINAME, RETURN) diff --git a/hal/src/main/native/athena/mockdata/EncoderData.cpp b/hal/src/main/native/athena/mockdata/EncoderData.cpp index c411ed718b..4b07b311db 100644 --- a/hal/src/main/native/athena/mockdata/EncoderData.cpp +++ b/hal/src/main/native/athena/mockdata/EncoderData.cpp @@ -7,15 +7,23 @@ #include "hal/simulation/SimDataValue.h" extern "C" { -int32_t HALSIM_FindEncoderForChannel(int32_t channel) { return 0; } +int32_t HALSIM_FindEncoderForChannel(int32_t channel) { + return 0; +} void HALSIM_ResetEncoderData(int32_t index) {} -int32_t HALSIM_GetEncoderDigitalChannelA(int32_t index) { return 0; } +int32_t HALSIM_GetEncoderDigitalChannelA(int32_t index) { + return 0; +} -int32_t HALSIM_GetEncoderDigitalChannelB(int32_t index) { return 0; } +int32_t HALSIM_GetEncoderDigitalChannelB(int32_t index) { + return 0; +} -HAL_SimDeviceHandle HALSIM_GetEncoderSimDevice(int32_t index) { return 0; } +HAL_SimDeviceHandle HALSIM_GetEncoderSimDevice(int32_t index) { + return 0; +} #define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \ HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, Encoder##CAPINAME, RETURN) @@ -32,11 +40,15 @@ DEFINE_CAPI(double, DistancePerPulse, 0) void HALSIM_SetEncoderDistance(int32_t index, double distance) {} -double HALSIM_GetEncoderDistance(int32_t index) { return 0; } +double HALSIM_GetEncoderDistance(int32_t index) { + return 0; +} void HALSIM_SetEncoderRate(int32_t index, double rate) {} -double HALSIM_GetEncoderRate(int32_t index) { return 0; } +double HALSIM_GetEncoderRate(int32_t index) { + return 0; +} void HALSIM_RegisterEncoderAllCallbacks(int32_t index, HAL_NotifyCallback callback, diff --git a/hal/src/main/native/athena/mockdata/MockHooks.cpp b/hal/src/main/native/athena/mockdata/MockHooks.cpp index 79b6ea2f25..0ea05d02e4 100644 --- a/hal/src/main/native/athena/mockdata/MockHooks.cpp +++ b/hal/src/main/native/athena/mockdata/MockHooks.cpp @@ -12,7 +12,9 @@ void HALSIM_WaitForProgramStart(void) {} void HALSIM_SetProgramStarted(void) {} -HAL_Bool HALSIM_GetProgramStarted(void) { return false; } +HAL_Bool HALSIM_GetProgramStarted(void) { + return false; +} void HALSIM_RestartTiming(void) {} @@ -20,7 +22,9 @@ void HALSIM_PauseTiming(void) {} void HALSIM_ResumeTiming(void) {} -HAL_Bool HALSIM_IsTimingPaused(void) { return false; } +HAL_Bool HALSIM_IsTimingPaused(void) { + return false; +} void HALSIM_StepTiming(uint64_t delta) {} diff --git a/hal/src/main/native/athena/mockdata/NotifierData.cpp b/hal/src/main/native/athena/mockdata/NotifierData.cpp index 155b8c0ee6..f75733e0fc 100644 --- a/hal/src/main/native/athena/mockdata/NotifierData.cpp +++ b/hal/src/main/native/athena/mockdata/NotifierData.cpp @@ -6,9 +6,13 @@ extern "C" { -uint64_t HALSIM_GetNextNotifierTimeout(void) { return 0; } +uint64_t HALSIM_GetNextNotifierTimeout(void) { + return 0; +} -int32_t HALSIM_GetNumNotifiers(void) { return 0; } +int32_t HALSIM_GetNumNotifiers(void) { + return 0; +} int32_t HALSIM_GetNotifierInfo(struct HALSIM_NotifierInfo* arr, int32_t size) { return 0; diff --git a/hal/src/main/native/athena/mockdata/PCMData.cpp b/hal/src/main/native/athena/mockdata/PCMData.cpp index 9906e2d0bf..88643da314 100644 --- a/hal/src/main/native/athena/mockdata/PCMData.cpp +++ b/hal/src/main/native/athena/mockdata/PCMData.cpp @@ -21,7 +21,9 @@ DEFINE_CAPI(HAL_Bool, ClosedLoopEnabled, false) DEFINE_CAPI(HAL_Bool, PressureSwitch, false) DEFINE_CAPI(double, CompressorCurrent, 0) -void HALSIM_GetPCMAllSolenoids(int32_t index, uint8_t* values) { *values = 0; } +void HALSIM_GetPCMAllSolenoids(int32_t index, uint8_t* values) { + *values = 0; +} void HALSIM_SetPCMAllSolenoids(int32_t index, uint8_t values) {} diff --git a/hal/src/main/native/athena/mockdata/PDPData.cpp b/hal/src/main/native/athena/mockdata/PDPData.cpp index daf0a0dcf0..9861ad939a 100644 --- a/hal/src/main/native/athena/mockdata/PDPData.cpp +++ b/hal/src/main/native/athena/mockdata/PDPData.cpp @@ -19,7 +19,9 @@ DEFINE_CAPI(double, Voltage, 0) HAL_SIMDATAVALUE_STUB_CAPI_CHANNEL(double, HALSIM, PDPCurrent, 0) void HALSIM_GetPDPAllCurrents(int32_t index, double* currents) { - for (int i = 0; i < hal::kNumPDPChannels; i++) currents[i] = 0; + for (int i = 0; i < hal::kNumPDPChannels; i++) { + currents[i] = 0; + } } void HALSIM_SetPDPAllCurrents(int32_t index, const double* currents) {} diff --git a/hal/src/main/native/athena/mockdata/SimDeviceData.cpp b/hal/src/main/native/athena/mockdata/SimDeviceData.cpp index e5f0efd28e..e3ade62587 100644 --- a/hal/src/main/native/athena/mockdata/SimDeviceData.cpp +++ b/hal/src/main/native/athena/mockdata/SimDeviceData.cpp @@ -10,7 +10,9 @@ extern "C" { void HALSIM_SetSimDeviceEnabled(const char* prefix, HAL_Bool enabled) {} -HAL_Bool HALSIM_IsSimDeviceEnabled(const char* name) { return false; } +HAL_Bool HALSIM_IsSimDeviceEnabled(const char* name) { + return false; +} int32_t HALSIM_RegisterSimDeviceCreatedCallback( const char* prefix, void* param, HALSIM_SimDeviceCallback callback, @@ -28,9 +30,13 @@ int32_t HALSIM_RegisterSimDeviceFreedCallback(const char* prefix, void* param, void HALSIM_CancelSimDeviceFreedCallback(int32_t uid) {} -HAL_SimDeviceHandle HALSIM_GetSimDeviceHandle(const char* name) { return 0; } +HAL_SimDeviceHandle HALSIM_GetSimDeviceHandle(const char* name) { + return 0; +} -const char* HALSIM_GetSimDeviceName(HAL_SimDeviceHandle handle) { return ""; } +const char* HALSIM_GetSimDeviceName(HAL_SimDeviceHandle handle) { + return ""; +} HAL_SimDeviceHandle HALSIM_GetSimValueDeviceHandle(HAL_SimValueHandle handle) { return 0; diff --git a/hal/src/main/native/cpp/Main.cpp b/hal/src/main/native/cpp/Main.cpp index e54c77395e..80bbe6f026 100644 --- a/hal/src/main/native/cpp/Main.cpp +++ b/hal/src/main/native/cpp/Main.cpp @@ -52,10 +52,16 @@ void HAL_SetMain(void* param, void (*mainFunc)(void*), gExitFunc = exitFunc; } -HAL_Bool HAL_HasMain(void) { return gHasMain; } +HAL_Bool HAL_HasMain(void) { + return gHasMain; +} -void HAL_RunMain(void) { gMainFunc(gMainParam); } +void HAL_RunMain(void) { + gMainFunc(gMainParam); +} -void HAL_ExitMain(void) { gExitFunc(gMainParam); } +void HAL_ExitMain(void) { + gExitFunc(gMainParam); +} } // extern "C" diff --git a/hal/src/main/native/cpp/handles/HandlesInternal.cpp b/hal/src/main/native/cpp/handles/HandlesInternal.cpp index 2f487dac77..80dca7107a 100644 --- a/hal/src/main/native/cpp/handles/HandlesInternal.cpp +++ b/hal/src/main/native/cpp/handles/HandlesInternal.cpp @@ -77,9 +77,13 @@ HAL_PortHandle createPortHandleForSPI(uint8_t channel) { } HAL_Handle createHandle(int16_t index, HAL_HandleEnum handleType, int16_t version) { - if (index < 0) return HAL_kInvalidHandle; + if (index < 0) { + return HAL_kInvalidHandle; + } uint8_t hType = static_cast(handleType); - if (hType == 0 || hType > 127) return HAL_kInvalidHandle; + if (hType == 0 || hType > 127) { + return HAL_kInvalidHandle; + } // set last 8 bits, then shift to first 8 bits HAL_Handle handle = hType; handle = handle << 8; diff --git a/hal/src/main/native/cpp/jni/CANAPIJNI.cpp b/hal/src/main/native/cpp/jni/CANAPIJNI.cpp index bf9d33526b..71804afa0c 100644 --- a/hal/src/main/native/cpp/jni/CANAPIJNI.cpp +++ b/hal/src/main/native/cpp/jni/CANAPIJNI.cpp @@ -194,11 +194,15 @@ Java_edu_wpi_first_hal_CANAPIJNI_readCANPacketNew if (!CheckStatus(env, status)) { return false; } - if (dataLength > 8) dataLength = 8; + if (dataLength > 8) { + dataLength = 8; + } jbyteArray toSetArray = SetCANDataObject(env, data, dataLength, timestamp); auto javaLen = env->GetArrayLength(toSetArray); - if (javaLen < dataLength) dataLength = javaLen; + if (javaLen < dataLength) { + dataLength = javaLen; + } env->SetByteArrayRegion(toSetArray, 0, dataLength, reinterpret_cast(dataTemp)); return true; @@ -226,11 +230,15 @@ Java_edu_wpi_first_hal_CANAPIJNI_readCANPacketLatest if (!CheckStatus(env, status)) { return false; } - if (dataLength > 8) dataLength = 8; + if (dataLength > 8) { + dataLength = 8; + } jbyteArray toSetArray = SetCANDataObject(env, data, dataLength, timestamp); auto javaLen = env->GetArrayLength(toSetArray); - if (javaLen < dataLength) dataLength = javaLen; + if (javaLen < dataLength) { + dataLength = javaLen; + } env->SetByteArrayRegion(toSetArray, 0, dataLength, reinterpret_cast(dataTemp)); return true; @@ -259,11 +267,15 @@ Java_edu_wpi_first_hal_CANAPIJNI_readCANPacketTimeout if (!CheckStatus(env, status)) { return false; } - if (dataLength > 8) dataLength = 8; + if (dataLength > 8) { + dataLength = 8; + } jbyteArray toSetArray = SetCANDataObject(env, data, dataLength, timestamp); auto javaLen = env->GetArrayLength(toSetArray); - if (javaLen < dataLength) dataLength = javaLen; + if (javaLen < dataLength) { + dataLength = javaLen; + } env->SetByteArrayRegion(toSetArray, 0, dataLength, reinterpret_cast(dataTemp)); return true; diff --git a/hal/src/main/native/cpp/jni/CANJNI.cpp b/hal/src/main/native/cpp/jni/CANJNI.cpp index b2521c40dc..b430012753 100644 --- a/hal/src/main/native/cpp/jni/CANJNI.cpp +++ b/hal/src/main/native/cpp/jni/CANJNI.cpp @@ -61,7 +61,9 @@ Java_edu_wpi_first_hal_can_CANJNI_FRCNetCommCANSessionMuxReceiveMessage HAL_CAN_ReceiveMessage(messageIDPtr, messageIDMask, buffer, &dataSize, timeStampPtr, &status); - if (!CheckCANStatus(env, status, *messageIDPtr)) return nullptr; + if (!CheckCANStatus(env, status, *messageIDPtr)) { + return nullptr; + } return MakeJByteArray(env, wpi::StringRef{reinterpret_cast(buffer), static_cast(dataSize)}); @@ -85,7 +87,9 @@ Java_edu_wpi_first_hal_can_CANJNI_GetCANStatus HAL_CAN_GetCANStatus(&percentBusUtilization, &busOffCount, &txFullCount, &receiveErrorCount, &transmitErrorCount, &status); - if (!CheckStatus(env, status)) return; + if (!CheckStatus(env, status)) { + return; + } SetCanStatusObject(env, canStatus, percentBusUtilization, busOffCount, txFullCount, receiveErrorCount, transmitErrorCount); diff --git a/hal/src/main/native/cpp/jni/HALUtil.cpp b/hal/src/main/native/cpp/jni/HALUtil.cpp index 09f95535fb..3b6796a057 100644 --- a/hal/src/main/native/cpp/jni/HALUtil.cpp +++ b/hal/src/main/native/cpp/jni/HALUtil.cpp @@ -104,7 +104,9 @@ void ThrowHalHandleException(JNIEnv* env, int32_t status) { } void ReportError(JNIEnv* env, int32_t status, bool doThrow) { - if (status == 0) return; + if (status == 0) { + return; + } if (status == HAL_HANDLE_ERROR) { ThrowHalHandleException(env, status); } @@ -123,7 +125,9 @@ void ReportError(JNIEnv* env, int32_t status, bool doThrow) { void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange, int32_t requestedValue) { - if (status == 0) return; + if (status == 0) { + return; + } if (status == NO_AVAILABLE_RESOURCES || status == RESOURCE_IS_ALLOCATED || status == RESOURCE_OUT_OF_RANGE) { ThrowAllocationException(env, minRange, maxRange, requestedValue, status); @@ -139,7 +143,9 @@ void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange, } void ReportCANError(JNIEnv* env, int32_t status, int message_id) { - if (status >= 0) return; + if (status >= 0) { + return; + } switch (status) { case kRioStatusSuccess: // Everything is ok... don't throw. @@ -147,9 +153,10 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) { case HAL_ERR_CANSessionMux_InvalidBuffer: case kRIOStatusBufferInvalidSize: { static jmethodID invalidBufConstruct = nullptr; - if (!invalidBufConstruct) + if (!invalidBufConstruct) { invalidBufConstruct = env->GetMethodID(canInvalidBufferExCls, "", "()V"); + } jobject exception = env->NewObject(canInvalidBufferExCls, invalidBufConstruct); env->Throw(static_cast(exception)); @@ -158,9 +165,10 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) { case HAL_ERR_CANSessionMux_MessageNotFound: case kRIOStatusOperationTimedOut: { static jmethodID messageNotFoundConstruct = nullptr; - if (!messageNotFoundConstruct) + if (!messageNotFoundConstruct) { messageNotFoundConstruct = env->GetMethodID(canMessageNotFoundExCls, "", "()V"); + } jobject exception = env->NewObject(canMessageNotFoundExCls, messageNotFoundConstruct); env->Throw(static_cast(exception)); @@ -177,9 +185,10 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) { case HAL_ERR_CANSessionMux_NotInitialized: case kRIOStatusResourceNotInitialized: { static jmethodID notInitConstruct = nullptr; - if (!notInitConstruct) + if (!notInitConstruct) { notInitConstruct = env->GetMethodID(canNotInitializedExCls, "", "()V"); + } jobject exception = env->NewObject(canNotInitializedExCls, notInitConstruct); env->Throw(static_cast(exception)); @@ -202,14 +211,16 @@ void ThrowIllegalArgumentException(JNIEnv* env, wpi::StringRef msg) { void ThrowBoundaryException(JNIEnv* env, double value, double lower, double upper) { static jmethodID getMessage = nullptr; - if (!getMessage) + if (!getMessage) { getMessage = env->GetStaticMethodID(boundaryExCls, "getMessage", "(DDD)Ljava/lang/String;"); + } static jmethodID constructor = nullptr; - if (!constructor) + if (!constructor) { constructor = env->GetMethodID(boundaryExCls, "", "(Ljava/lang/String;)V"); + } jobject msg = env->CallStaticObjectMethod( boundaryExCls, getMessage, static_cast(value), @@ -299,7 +310,9 @@ jobject CreateHALValue(JNIEnv* env, const HAL_Value& value) { value1, value2); } -JavaVM* GetJVM() { return jvm; } +JavaVM* GetJVM() { + return jvm; +} namespace sim { jint SimOnLoad(JavaVM* vm, void* reserved); @@ -319,17 +332,22 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { jvm = vm; JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; + } for (auto& c : classes) { *c.cls = JClass(env, c.name); - if (!*c.cls) return JNI_ERR; + if (!*c.cls) { + return JNI_ERR; + } } for (auto& c : exceptions) { *c.cls = JException(env, c.name); - if (!*c.cls) return JNI_ERR; + if (!*c.cls) { + return JNI_ERR; + } } return sim::SimOnLoad(vm, reserved); @@ -339,8 +357,9 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) { sim::SimOnUnload(vm, reserved); JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return; + } // Delete global references for (auto& c : classes) { diff --git a/hal/src/main/native/cpp/jni/HALUtil.h b/hal/src/main/native/cpp/jni/HALUtil.h index d53d6dd21c..c56c36d5d1 100644 --- a/hal/src/main/native/cpp/jni/HALUtil.h +++ b/hal/src/main/native/cpp/jni/HALUtil.h @@ -21,25 +21,33 @@ void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange, int32_t requestedValue); inline bool CheckStatus(JNIEnv* env, int32_t status, bool doThrow = true) { - if (status != 0) ReportError(env, status, doThrow); + if (status != 0) { + ReportError(env, status, doThrow); + } return status == 0; } inline bool CheckStatusRange(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange, int32_t requestedValue) { - if (status != 0) ThrowError(env, status, minRange, maxRange, requestedValue); + if (status != 0) { + ThrowError(env, status, minRange, maxRange, requestedValue); + } return status == 0; } inline bool CheckStatusForceThrow(JNIEnv* env, int32_t status) { - if (status != 0) ThrowError(env, status, 0, 0, 0); + if (status != 0) { + ThrowError(env, status, 0, 0, 0); + } return status == 0; } void ReportCANError(JNIEnv* env, int32_t status, int32_t message_id); inline bool CheckCANStatus(JNIEnv* env, int32_t status, int32_t message_id) { - if (status != 0) ReportCANError(env, status, message_id); + if (status != 0) { + ReportCANError(env, status, message_id); + } return status == 0; } diff --git a/hal/src/main/native/cpp/jni/InterruptJNI.cpp b/hal/src/main/native/cpp/jni/InterruptJNI.cpp index 87a44491bd..d6c366a2e6 100644 --- a/hal/src/main/native/cpp/jni/InterruptJNI.cpp +++ b/hal/src/main/native/cpp/jni/InterruptJNI.cpp @@ -46,7 +46,9 @@ class InterruptJNI : public wpi::SafeThreadOwner { void Notify(uint32_t mask) { auto thr = GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_notify = true; thr->m_mask = mask; thr->m_cond.notify_one(); @@ -56,10 +58,16 @@ class InterruptJNI : public wpi::SafeThreadOwner { void InterruptJNI::SetFunc(JNIEnv* env, jobject func, jmethodID mid, jobject param) { auto thr = GetThread(); - if (!thr) return; + if (!thr) { + return; + } // free global references - if (thr->m_func) env->DeleteGlobalRef(thr->m_func); - if (thr->m_param) env->DeleteGlobalRef(thr->m_param); + if (thr->m_func) { + env->DeleteGlobalRef(thr->m_func); + } + if (thr->m_param) { + env->DeleteGlobalRef(thr->m_param); + } // create global references thr->m_func = env->NewGlobalRef(func); thr->m_param = param ? env->NewGlobalRef(param) : nullptr; @@ -74,14 +82,20 @@ void InterruptThreadJNI::Main() { args.group = nullptr; jint rs = GetJVM()->AttachCurrentThreadAsDaemon( reinterpret_cast(&env), &args); - if (rs != JNI_OK) return; + if (rs != JNI_OK) { + return; + } std::unique_lock lock(m_mutex); while (m_active) { m_cond.wait(lock, [&] { return !m_active || m_notify; }); - if (!m_active) break; + if (!m_active) { + break; + } m_notify = false; - if (!m_func) continue; + if (!m_func) { + continue; + } jobject func = m_func; jmethodID mid = m_mid; uint32_t mask = m_mask; @@ -96,8 +110,12 @@ void InterruptThreadJNI::Main() { } // free global references - if (m_func) env->DeleteGlobalRef(m_func); - if (m_param) env->DeleteGlobalRef(m_param); + if (m_func) { + env->DeleteGlobalRef(m_func); + } + if (m_param) { + env->DeleteGlobalRef(m_param); + } GetJVM()->DetachCurrentThread(); } diff --git a/hal/src/main/native/cpp/jni/SPIJNI.cpp b/hal/src/main/native/cpp/jni/SPIJNI.cpp index 1cfc5f9ac6..303c0337a6 100644 --- a/hal/src/main/native/cpp/jni/SPIJNI.cpp +++ b/hal/src/main/native/cpp/jni/SPIJNI.cpp @@ -367,7 +367,9 @@ Java_edu_wpi_first_hal_SPIJNI_spiReadAutoReceivedData__I_3IID jint retval = HAL_ReadSPIAutoReceivedData(static_cast(port), recvBuf.data(), numToRead, timeout, &status); - if (!CheckStatus(env, status)) return retval; + if (!CheckStatus(env, status)) { + return retval; + } if (numToRead > 0) { env->SetIntArrayRegion(buffer, 0, numToRead, reinterpret_cast(recvBuf.data())); diff --git a/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp b/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp index 5f26828e62..68f6e24f6f 100644 --- a/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp +++ b/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp @@ -93,11 +93,15 @@ Java_edu_wpi_first_hal_SimDeviceJNI_createSimValueEnum for (size_t i = 0; i < len; ++i) { JLocal elem{ env, static_cast(env->GetObjectArrayElement(options, i))}; - if (!elem) return 0; + if (!elem) { + return 0; + } arr.push_back(JStringRef{env, elem}.str()); } wpi::SmallVector carr; - for (auto&& val : arr) carr.push_back(val.c_str()); + for (auto&& val : arr) { + carr.push_back(val.c_str()); + } return HAL_CreateSimValueEnum(device, JStringRef{env, name}.c_str(), direction, len, carr.data(), initialValue); } @@ -114,18 +118,24 @@ Java_edu_wpi_first_hal_SimDeviceJNI_createSimValueEnumDouble { size_t len = env->GetArrayLength(options); size_t len2 = env->GetArrayLength(optionValues); - if (len != len2) return 0; + if (len != len2) { + return 0; + } std::vector arr; arr.reserve(len); for (size_t i = 0; i < len; ++i) { JLocal elem{ env, static_cast(env->GetObjectArrayElement(options, i))}; - if (!elem) return 0; + if (!elem) { + return 0; + } arr.push_back(JStringRef{env, elem}.str()); } wpi::SmallVector carr; - for (auto&& val : arr) carr.push_back(val.c_str()); + for (auto&& val : arr) { + carr.push_back(val.c_str()); + } return HAL_CreateSimValueEnumDouble( device, JStringRef{env, name}.c_str(), direction, len, carr.data(), JDoubleArrayRef{env, optionValues}.array().data(), initialValue); diff --git a/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp index bb983f4481..7f1b5903cb 100644 --- a/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp @@ -82,7 +82,9 @@ void BufferCallbackStore::performCallback(const char* name, uint8_t* buffer, } } -void BufferCallbackStore::free(JNIEnv* env) { m_call.free(env); } +void BufferCallbackStore::free(JNIEnv* env) { + m_call.free(env); +} SIM_JniHandle sim::AllocateBufferCallback( JNIEnv* env, jint index, jobject callback, @@ -105,7 +107,9 @@ SIM_JniHandle sim::AllocateBufferCallback( uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle handle = static_cast(handleTmp); auto data = callbackHandles->Get(handle); - if (!data) return; + if (!data) { + return; + } data->performCallback(name, buffer, length); }; diff --git a/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp index 86a6de497a..d0f30d41d1 100644 --- a/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp @@ -69,7 +69,9 @@ void CallbackStore::performCallback(const char* name, const HAL_Value* value) { } } -void CallbackStore::free(JNIEnv* env) { m_call.free(env); } +void CallbackStore::free(JNIEnv* env) { + m_call.free(env); +} SIM_JniHandle sim::AllocateCallback(JNIEnv* env, jint index, jobject callback, jboolean initialNotify, @@ -92,7 +94,9 @@ SIM_JniHandle sim::AllocateCallback(JNIEnv* env, jint index, jobject callback, uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle handle = static_cast(handleTmp); auto data = callbackHandles->Get(handle); - if (!data) return; + if (!data) { + return; + } data->performCallback(name, value); }; @@ -132,7 +136,9 @@ SIM_JniHandle sim::AllocateChannelCallback( uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle handle = static_cast(handleTmp); auto data = callbackHandles->Get(handle); - if (!data) return; + if (!data) { + return; + } data->performCallback(name, value); }; @@ -174,7 +180,9 @@ SIM_JniHandle sim::AllocateCallbackNoIndex( uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle handle = static_cast(handleTmp); auto data = callbackHandles->Get(handle); - if (!data) return; + if (!data) { + return; + } data->performCallback(name, value); }; diff --git a/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp index 1dbca7554f..c2fb690018 100644 --- a/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp @@ -74,7 +74,9 @@ void ConstBufferCallbackStore::performCallback(const char* name, } } -void ConstBufferCallbackStore::free(JNIEnv* env) { m_call.free(env); } +void ConstBufferCallbackStore::free(JNIEnv* env) { + m_call.free(env); +} SIM_JniHandle sim::AllocateConstBufferCallback( JNIEnv* env, jint index, jobject callback, @@ -97,7 +99,9 @@ SIM_JniHandle sim::AllocateConstBufferCallback( uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle handle = static_cast(handleTmp); auto data = callbackHandles->Get(handle); - if (!data) return; + if (!data) { + return; + } data->performCallback(name, buffer, length); }; diff --git a/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp b/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp index c848fd9cef..60d5fa3be5 100644 --- a/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp +++ b/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp @@ -233,7 +233,9 @@ static SIM_JniHandle AllocateDeviceCallback( uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle jnihandle = static_cast(handleTmp); auto data = deviceCallbackHandles->Get(jnihandle); - if (!data) return; + if (!data) { + return; + } data->performCallback(name, handle); }; @@ -287,7 +289,9 @@ static SIM_JniHandle AllocateValueCallback( uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle jnihandle = static_cast(handleTmp); auto data = valueCallbackHandles->Get(jnihandle); - if (!data) return; + if (!data) { + return; + } data->performCallback(name, handle, direction, *value); }; @@ -312,27 +316,39 @@ namespace sim { bool InitializeSimDeviceDataJNI(JNIEnv* env) { simDeviceInfoCls = JClass( env, "edu/wpi/first/hal/simulation/SimDeviceDataJNI$SimDeviceInfo"); - if (!simDeviceInfoCls) return false; + if (!simDeviceInfoCls) { + return false; + } simValueInfoCls = JClass(env, "edu/wpi/first/hal/simulation/SimDeviceDataJNI$SimValueInfo"); - if (!simValueInfoCls) return false; + if (!simValueInfoCls) { + return false; + } simDeviceCallbackCls = JClass(env, "edu/wpi/first/hal/simulation/SimDeviceCallback"); - if (!simDeviceCallbackCls) return false; + if (!simDeviceCallbackCls) { + return false; + } simDeviceCallbackCallback = env->GetMethodID(simDeviceCallbackCls, "callback", "(Ljava/lang/String;I)V"); - if (!simDeviceCallbackCallback) return false; + if (!simDeviceCallbackCallback) { + return false; + } simValueCallbackCls = JClass(env, "edu/wpi/first/hal/simulation/SimValueCallback"); - if (!simValueCallbackCls) return false; + if (!simValueCallbackCls) { + return false; + } simValueCallbackCallback = env->GetMethodID( simValueCallbackCls, "callbackNative", "(Ljava/lang/String;IZIJD)V"); - if (!simValueCallbackCallback) return false; + if (!simValueCallbackCallback) { + return false; + } static hal::UnlimitedHandleResource @@ -495,7 +511,9 @@ Java_edu_wpi_first_hal_simulation_SimDeviceDataJNI_enumerateSimDevices size_t numElems = arr.size(); jobjectArray jarr = env->NewObjectArray(arr.size(), simDeviceInfoCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < numElems; ++i) { JLocal elem{env, arr[i].MakeJava(env)}; env->SetObjectArrayElement(jarr, i, elem.obj()); @@ -617,7 +635,9 @@ Java_edu_wpi_first_hal_simulation_SimDeviceDataJNI_enumerateSimValues // convert to java size_t numElems = arr.size(); jobjectArray jarr = env->NewObjectArray(arr.size(), simValueInfoCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < numElems; ++i) { JLocal elem{env, arr[i].MakeJava(env)}; env->SetObjectArrayElement(jarr, i, elem.obj()); @@ -635,11 +655,15 @@ Java_edu_wpi_first_hal_simulation_SimDeviceDataJNI_getSimValueEnumOptions (JNIEnv* env, jclass, jint handle) { static JClass stringCls{env, "java/lang/String"}; - if (!stringCls) return nullptr; + if (!stringCls) { + return nullptr; + } int32_t numElems = 0; const char** elems = HALSIM_GetSimValueEnumOptions(handle, &numElems); jobjectArray jarr = env->NewObjectArray(numElems, stringCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (int32_t i = 0; i < numElems; ++i) { JLocal elem{env, MakeJString(env, elems[i])}; env->SetObjectArrayElement(jarr, i, elem.obj()); diff --git a/hal/src/main/native/cpp/jni/simulation/SimulatorJNI.cpp b/hal/src/main/native/cpp/jni/simulation/SimulatorJNI.cpp index 95badcbe80..6b52e3ae45 100644 --- a/hal/src/main/native/cpp/jni/simulation/SimulatorJNI.cpp +++ b/hal/src/main/native/cpp/jni/simulation/SimulatorJNI.cpp @@ -34,55 +34,75 @@ jint SimOnLoad(JavaVM* vm, void* reserved) { jvm = vm; JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; + } notifyCallbackCls = JClass(env, "edu/wpi/first/hal/simulation/NotifyCallback"); - if (!notifyCallbackCls) return JNI_ERR; + if (!notifyCallbackCls) { + return JNI_ERR; + } notifyCallbackCallback = env->GetMethodID(notifyCallbackCls, "callbackNative", "(Ljava/lang/String;IJD)V"); - if (!notifyCallbackCallback) return JNI_ERR; + if (!notifyCallbackCallback) { + return JNI_ERR; + } bufferCallbackCls = JClass(env, "edu/wpi/first/hal/simulation/BufferCallback"); - if (!bufferCallbackCls) return JNI_ERR; + if (!bufferCallbackCls) { + return JNI_ERR; + } bufferCallbackCallback = env->GetMethodID(bufferCallbackCls, "callback", "(Ljava/lang/String;[BI)V"); - if (!bufferCallbackCallback) return JNI_ERR; + if (!bufferCallbackCallback) { + return JNI_ERR; + } constBufferCallbackCls = JClass(env, "edu/wpi/first/hal/simulation/ConstBufferCallback"); - if (!constBufferCallbackCls) return JNI_ERR; + if (!constBufferCallbackCls) { + return JNI_ERR; + } constBufferCallbackCallback = env->GetMethodID( constBufferCallbackCls, "callback", "(Ljava/lang/String;[BI)V"); - if (!constBufferCallbackCallback) return JNI_ERR; + if (!constBufferCallbackCallback) { + return JNI_ERR; + } spiReadAutoReceiveBufferCallbackCls = JClass( env, "edu/wpi/first/hal/simulation/SpiReadAutoReceiveBufferCallback"); - if (!spiReadAutoReceiveBufferCallbackCls) return JNI_ERR; + if (!spiReadAutoReceiveBufferCallbackCls) { + return JNI_ERR; + } spiReadAutoReceiveBufferCallbackCallback = env->GetMethodID(spiReadAutoReceiveBufferCallbackCls, "callback", "(Ljava/lang/String;[II)I"); - if (!spiReadAutoReceiveBufferCallbackCallback) return JNI_ERR; + if (!spiReadAutoReceiveBufferCallbackCallback) { + return JNI_ERR; + } InitializeStore(); InitializeBufferStore(); InitializeConstBufferStore(); InitializeSpiBufferStore(); - if (!InitializeSimDeviceDataJNI(env)) return JNI_ERR; + if (!InitializeSimDeviceDataJNI(env)) { + return JNI_ERR; + } return JNI_VERSION_1_6; } void SimOnUnload(JavaVM* vm, void* reserved) { JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return; + } notifyCallbackCls.free(env); bufferCallbackCls.free(env); @@ -92,13 +112,21 @@ void SimOnUnload(JavaVM* vm, void* reserved) { jvm = nullptr; } -JavaVM* GetJVM() { return jvm; } +JavaVM* GetJVM() { + return jvm; +} -jmethodID GetNotifyCallback() { return notifyCallbackCallback; } +jmethodID GetNotifyCallback() { + return notifyCallbackCallback; +} -jmethodID GetBufferCallback() { return bufferCallbackCallback; } +jmethodID GetBufferCallback() { + return bufferCallbackCallback; +} -jmethodID GetConstBufferCallback() { return constBufferCallbackCallback; } +jmethodID GetConstBufferCallback() { + return constBufferCallbackCallback; +} jmethodID GetSpiReadAutoReceiveBufferCallback() { return spiReadAutoReceiveBufferCallbackCallback; diff --git a/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp index 7454141ca6..634d869a00 100644 --- a/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp @@ -110,7 +110,9 @@ SIM_JniHandle sim::AllocateSpiBufferCallback( uintptr_t handleTmp = reinterpret_cast(param); SIM_JniHandle handle = static_cast(handleTmp); auto data = callbackHandles->Get(handle); - if (!data) return; + if (!data) { + return; + } *outputCount = data->performCallback(name, buffer, numToRead); }; diff --git a/hal/src/main/native/include/hal/SimDevice.h b/hal/src/main/native/include/hal/SimDevice.h index 9893239e9f..22c0576450 100644 --- a/hal/src/main/native/include/hal/SimDevice.h +++ b/hal/src/main/native/include/hal/SimDevice.h @@ -513,7 +513,9 @@ class SimDevice { SimDevice(const char* name, int index, int channel); ~SimDevice() { - if (m_handle != HAL_kInvalidHandle) HAL_FreeSimDevice(m_handle); + if (m_handle != HAL_kInvalidHandle) { + HAL_FreeSimDevice(m_handle); + } } SimDevice(const SimDevice&) = delete; @@ -639,7 +641,9 @@ class SimDevice { std::initializer_list options, std::initializer_list optionValues, int32_t initialValue) { - if (options.size() != optionValues.size()) return {}; + if (options.size() != optionValues.size()) { + return {}; + } return HAL_CreateSimValueEnumDouble( m_handle, name, direction, options.size(), const_cast(options.begin()), optionValues.begin(), @@ -666,7 +670,9 @@ class SimDevice { wpi::ArrayRef options, wpi::ArrayRef optionValues, int32_t initialValue) { - if (options.size() != optionValues.size()) return {}; + if (options.size() != optionValues.size()) { + return {}; + } return HAL_CreateSimValueEnumDouble( m_handle, name, direction, options.size(), const_cast(options.data()), optionValues.data(), diff --git a/hal/src/main/native/include/hal/cpp/UnsafeDIO.h b/hal/src/main/native/include/hal/cpp/UnsafeDIO.h index 07387c9229..de7e12da60 100644 --- a/hal/src/main/native/include/hal/cpp/UnsafeDIO.h +++ b/hal/src/main/native/include/hal/cpp/UnsafeDIO.h @@ -73,7 +73,9 @@ void UnsafeManipulateDIO(HAL_DigitalHandle handle, int32_t* status, wpi::mutex& dioMutex = detail::UnsafeGetDIOMutex(); tDIO* dSys = detail::UnsafeGetDigialSystem(); auto mask = detail::ComputeDigitalMask(handle, status); - if (status != 0) return; + if (status != 0) { + return; + } std::scoped_lock lock(dioMutex); tDIO::tOutputEnable enableOE = dSys->readOutputEnable(status); diff --git a/hal/src/main/native/include/hal/handles/DigitalHandleResource.h b/hal/src/main/native/include/hal/handles/DigitalHandleResource.h index 39095420fe..85a14a7d62 100644 --- a/hal/src/main/native/include/hal/handles/DigitalHandleResource.h +++ b/hal/src/main/native/include/hal/handles/DigitalHandleResource.h @@ -88,7 +88,9 @@ void DigitalHandleResource::Free( THandle handle, HAL_HandleEnum enumValue) { // get handle index, and fail early if index out of range or wrong handle int16_t index = GetIndex(handle, enumValue); - if (index < 0 || index >= size) return; + if (index < 0 || index >= size) { + return; + } // lock and deallocated handle std::scoped_lock lock(m_handleMutexes[index]); m_structures[index].reset(); diff --git a/hal/src/main/native/include/hal/handles/HandlesInternal.h b/hal/src/main/native/include/hal/handles/HandlesInternal.h index 58233cd53f..7c15d034d7 100644 --- a/hal/src/main/native/include/hal/handles/HandlesInternal.h +++ b/hal/src/main/native/include/hal/handles/HandlesInternal.h @@ -128,9 +128,13 @@ static inline bool isHandleCorrectVersion(HAL_Handle handle, int16_t version) { static inline int16_t getHandleTypedIndex(HAL_Handle handle, HAL_HandleEnum enumType, int16_t version) { - if (!isHandleType(handle, enumType)) return InvalidHandleIndex; + if (!isHandleType(handle, enumType)) { + return InvalidHandleIndex; + } #if !defined(__FRC_ROBORIO__) - if (!isHandleCorrectVersion(handle, version)) return InvalidHandleIndex; + if (!isHandleCorrectVersion(handle, version)) { + return InvalidHandleIndex; + } #endif return getHandleIndex(handle); } @@ -152,7 +156,9 @@ static inline int16_t getHandleTypedIndex(HAL_Handle handle, * @return the port channel */ static inline int16_t getPortHandleChannel(HAL_PortHandle handle) { - if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex; + if (!isHandleType(handle, HAL_HandleEnum::Port)) { + return InvalidHandleIndex; + } return static_cast(handle & 0xff); } @@ -164,7 +170,9 @@ static inline int16_t getPortHandleChannel(HAL_PortHandle handle) { * @return the port module */ static inline int16_t getPortHandleModule(HAL_PortHandle handle) { - if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex; + if (!isHandleType(handle, HAL_HandleEnum::Port)) { + return InvalidHandleIndex; + } return static_cast((handle >> 8) & 0xff); } @@ -176,7 +184,9 @@ static inline int16_t getPortHandleModule(HAL_PortHandle handle) { * @return the port SPI channel */ static inline int16_t getPortHandleSPIEnable(HAL_PortHandle handle) { - if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex; + if (!isHandleType(handle, HAL_HandleEnum::Port)) { + return InvalidHandleIndex; + } return static_cast((handle >> 16) & 0xff); } diff --git a/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h b/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h index bc0abb75d0..3292753d0c 100644 --- a/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h @@ -98,7 +98,9 @@ void IndexedClassedHandleResource::Free( THandle handle) { // get handle index, and fail early if index out of range or wrong handle int16_t index = GetIndex(handle); - if (index < 0 || index >= size) return; + if (index < 0 || index >= size) { + return; + } // lock and deallocated handle std::scoped_lock lock(m_handleMutexes[index]); m_structures[index].reset(); diff --git a/hal/src/main/native/include/hal/handles/IndexedHandleResource.h b/hal/src/main/native/include/hal/handles/IndexedHandleResource.h index 24119b71ea..2f158e1913 100644 --- a/hal/src/main/native/include/hal/handles/IndexedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/IndexedHandleResource.h @@ -92,7 +92,9 @@ void IndexedHandleResource::Free( THandle handle) { // get handle index, and fail early if index out of range or wrong handle int16_t index = GetIndex(handle); - if (index < 0 || index >= size) return; + if (index < 0 || index >= size) { + return; + } // lock and deallocated handle std::scoped_lock lock(m_handleMutexes[index]); m_structures[index].reset(); diff --git a/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h b/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h index 52b30104d1..2650708652 100644 --- a/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h @@ -93,7 +93,9 @@ void LimitedClassedHandleResource::Free( THandle handle) { // get handle index, and fail early if index out of range or wrong handle int16_t index = GetIndex(handle); - if (index < 0 || index >= size) return; + if (index < 0 || index >= size) { + return; + } // lock and deallocated handle std::scoped_lock allocateLock(m_allocateMutex); std::scoped_lock handleLock(m_handleMutexes[index]); diff --git a/hal/src/main/native/include/hal/handles/LimitedHandleResource.h b/hal/src/main/native/include/hal/handles/LimitedHandleResource.h index 440bb4387c..6f762933ae 100644 --- a/hal/src/main/native/include/hal/handles/LimitedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/LimitedHandleResource.h @@ -88,7 +88,9 @@ void LimitedHandleResource::Free( THandle handle) { // get handle index, and fail early if index out of range or wrong handle int16_t index = GetIndex(handle); - if (index < 0 || index >= size) return; + if (index < 0 || index >= size) { + return; + } // lock and deallocated handle std::scoped_lock allocateLock(m_allocateMutex); std::scoped_lock handleLock(m_handleMutexes[index]); diff --git a/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h b/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h index f17f9f9eec..09510ac27b 100644 --- a/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h @@ -71,7 +71,9 @@ THandle UnlimitedHandleResource::Allocate( return static_cast(createHandle(i, enumValue, m_version)); } } - if (i >= INT16_MAX) return HAL_kInvalidHandle; + if (i >= INT16_MAX) { + return HAL_kInvalidHandle; + } m_structures.push_back(structure); return static_cast( @@ -83,8 +85,9 @@ std::shared_ptr UnlimitedHandleResource::Get(THandle handle) { int16_t index = GetIndex(handle); std::scoped_lock lock(m_handleMutex); - if (index < 0 || index >= static_cast(m_structures.size())) + if (index < 0 || index >= static_cast(m_structures.size())) { return nullptr; + } return m_structures[index]; } @@ -93,8 +96,9 @@ std::shared_ptr UnlimitedHandleResource::Free(THandle handle) { int16_t index = GetIndex(handle); std::scoped_lock lock(m_handleMutex); - if (index < 0 || index >= static_cast(m_structures.size())) + if (index < 0 || index >= static_cast(m_structures.size())) { return nullptr; + } return std::move(m_structures[index]); } diff --git a/hal/src/main/native/include/hal/simulation/SimCallbackRegistry.h b/hal/src/main/native/include/hal/simulation/SimCallbackRegistry.h index b19db8ca09..3d786e0dc8 100644 --- a/hal/src/main/native/include/hal/simulation/SimCallbackRegistry.h +++ b/hal/src/main/native/include/hal/simulation/SimCallbackRegistry.h @@ -27,7 +27,9 @@ class SimCallbackRegistryBase { public: void Cancel(int32_t uid) { std::scoped_lock lock(m_mutex); - if (m_callbacks && uid > 0) m_callbacks->erase(uid - 1); + if (m_callbacks && uid > 0) { + m_callbacks->erase(uid - 1); + } } void Reset() { @@ -40,13 +42,19 @@ class SimCallbackRegistryBase { protected: int32_t DoRegister(RawFunctor callback, void* param) { // Must return -1 on a null callback for error handling - if (callback == nullptr) return -1; - if (!m_callbacks) m_callbacks = std::make_unique(); + if (callback == nullptr) { + return -1; + } + if (!m_callbacks) { + m_callbacks = std::make_unique(); + } return m_callbacks->emplace_back(param, callback) + 1; } LLVM_ATTRIBUTE_ALWAYS_INLINE void DoReset() { - if (m_callbacks) m_callbacks->clear(); + if (m_callbacks) { + m_callbacks->clear(); + } } mutable wpi::recursive_spinlock m_mutex; @@ -78,9 +86,10 @@ class SimCallbackRegistry : public impl::SimCallbackRegistryBase { #endif if (m_callbacks) { const char* name = GetName(); - for (auto&& cb : *m_callbacks) + for (auto&& cb : *m_callbacks) { reinterpret_cast(cb.callback)(name, cb.param, std::forward(u)...); + } } } diff --git a/hal/src/main/native/include/hal/simulation/SimDataValue.h b/hal/src/main/native/include/hal/simulation/SimDataValue.h index d928721601..fe2998a9b0 100644 --- a/hal/src/main/native/include/hal/simulation/SimDataValue.h +++ b/hal/src/main/native/include/hal/simulation/SimDataValue.h @@ -43,7 +43,9 @@ class SimDataValueBase : protected SimCallbackRegistryBase { HAL_Bool initialNotify, const char* name) { std::unique_lock lock(m_mutex); int32_t newUid = DoRegister(reinterpret_cast(callback), param); - if (newUid == -1) return -1; + if (newUid == -1) { + return -1; + } if (initialNotify) { // We know that the callback is not null because of earlier null check HAL_Value value = MakeValue(m_value); @@ -59,9 +61,10 @@ class SimDataValueBase : protected SimCallbackRegistryBase { m_value = value; if (m_callbacks) { HAL_Value halValue = MakeValue(value); - for (auto&& cb : *m_callbacks) + for (auto&& cb : *m_callbacks) { reinterpret_cast(cb.callback)(name, cb.param, &halValue); + } } } } diff --git a/hal/src/main/native/sim/Accelerometer.cpp b/hal/src/main/native/sim/Accelerometer.cpp index 2eb3b0bed5..9fc4efd3ba 100644 --- a/hal/src/main/native/sim/Accelerometer.cpp +++ b/hal/src/main/native/sim/Accelerometer.cpp @@ -22,7 +22,13 @@ void HAL_SetAccelerometerActive(HAL_Bool active) { void HAL_SetAccelerometerRange(HAL_AccelerometerRange range) { SimAccelerometerData[0].range = range; } -double HAL_GetAccelerometerX(void) { return SimAccelerometerData[0].x; } -double HAL_GetAccelerometerY(void) { return SimAccelerometerData[0].y; } -double HAL_GetAccelerometerZ(void) { return SimAccelerometerData[0].z; } +double HAL_GetAccelerometerX(void) { + return SimAccelerometerData[0].x; +} +double HAL_GetAccelerometerY(void) { + return SimAccelerometerData[0].y; +} +double HAL_GetAccelerometerZ(void) { + return SimAccelerometerData[0].z; +} } // extern "C" diff --git a/hal/src/main/native/sim/AddressableLED.cpp b/hal/src/main/native/sim/AddressableLED.cpp index f14c170c24..9e60a9b77f 100644 --- a/hal/src/main/native/sim/AddressableLED.cpp +++ b/hal/src/main/native/sim/AddressableLED.cpp @@ -83,7 +83,9 @@ HAL_AddressableLEDHandle HAL_InitializeAddressableLED( void HAL_FreeAddressableLED(HAL_AddressableLEDHandle handle) { auto led = ledHandles->Get(handle); ledHandles->Free(handle); - if (!led) return; + if (!led) { + return; + } SimAddressableLEDData[led->index].running = false; SimAddressableLEDData[led->index].initialized = false; } diff --git a/hal/src/main/native/sim/AnalogAccumulator.cpp b/hal/src/main/native/sim/AnalogAccumulator.cpp index dbcf75386c..53ec1c7eca 100644 --- a/hal/src/main/native/sim/AnalogAccumulator.cpp +++ b/hal/src/main/native/sim/AnalogAccumulator.cpp @@ -24,7 +24,9 @@ HAL_Bool HAL_IsAccumulatorChannel(HAL_AnalogInputHandle analogPortHandle, return false; } for (int32_t i = 0; i < kNumAccumulators; i++) { - if (port->channel == kAccumulatorChannels[i]) return true; + if (port->channel == kAccumulatorChannels[i]) { + return true; + } } return false; } diff --git a/hal/src/main/native/sim/AnalogGyro.cpp b/hal/src/main/native/sim/AnalogGyro.cpp index 9f625d51ba..cfc7ce9240 100644 --- a/hal/src/main/native/sim/AnalogGyro.cpp +++ b/hal/src/main/native/sim/AnalogGyro.cpp @@ -50,8 +50,9 @@ HAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analogHandle, auto handle = analogGyroHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } // Initialize port structure auto gyro = analogGyroHandles->Get(handle); @@ -75,7 +76,9 @@ void HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) { void HAL_FreeAnalogGyro(HAL_GyroHandle handle) { auto gyro = analogGyroHandles->Get(handle); analogGyroHandles->Free(handle); - if (gyro == nullptr) return; + if (gyro == nullptr) { + return; + } SimAnalogGyroData[gyro->index].initialized = false; } diff --git a/hal/src/main/native/sim/AnalogInput.cpp b/hal/src/main/native/sim/AnalogInput.cpp index f20fbcf3d7..8244aa4e59 100644 --- a/hal/src/main/native/sim/AnalogInput.cpp +++ b/hal/src/main/native/sim/AnalogInput.cpp @@ -31,8 +31,9 @@ HAL_AnalogInputHandle HAL_InitializeAnalogInputPort(HAL_PortHandle portHandle, HAL_AnalogInputHandle handle = analogInputHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } // Initialize port structure auto analog_port = analogInputHandles->Get(handle); @@ -58,12 +59,16 @@ void HAL_FreeAnalogInputPort(HAL_AnalogInputHandle analogPortHandle) { auto port = analogInputHandles->Get(analogPortHandle); // no status, so no need to check for a proper free. analogInputHandles->Free(analogPortHandle); - if (port == nullptr) return; + if (port == nullptr) { + return; + } SimAnalogInData[port->channel].initialized = false; SimAnalogInData[port->channel].accumulatorInitialized = false; } -HAL_Bool HAL_CheckAnalogModule(int32_t module) { return module == 1; } +HAL_Bool HAL_CheckAnalogModule(int32_t module) { + return module == 1; +} HAL_Bool HAL_CheckAnalogInputChannel(int32_t channel) { return channel < kNumAnalogInputs && channel >= 0; @@ -72,14 +77,18 @@ HAL_Bool HAL_CheckAnalogInputChannel(int32_t channel) { void HAL_SetAnalogInputSimDevice(HAL_AnalogInputHandle handle, HAL_SimDeviceHandle device) { auto port = analogInputHandles->Get(handle); - if (port == nullptr) return; + if (port == nullptr) { + return; + } SimAnalogInData[port->channel].simDevice = device; } void HAL_SetAnalogSampleRate(double samplesPerSecond, int32_t* status) { // No op } -double HAL_GetAnalogSampleRate(int32_t* status) { return kDefaultSampleRate; } +double HAL_GetAnalogSampleRate(int32_t* status) { + return kDefaultSampleRate; +} void HAL_SetAnalogAverageBits(HAL_AnalogInputHandle analogPortHandle, int32_t bits, int32_t* status) { auto port = analogInputHandles->Get(analogPortHandle); diff --git a/hal/src/main/native/sim/AnalogOutput.cpp b/hal/src/main/native/sim/AnalogOutput.cpp index 09af65bdb7..96e411ac9f 100644 --- a/hal/src/main/native/sim/AnalogOutput.cpp +++ b/hal/src/main/native/sim/AnalogOutput.cpp @@ -47,8 +47,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle, HAL_AnalogOutputHandle handle = analogOutputHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = analogOutputHandles->Get(handle); if (port == nullptr) { // would only error on thread issue @@ -66,7 +67,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle, void HAL_FreeAnalogOutputPort(HAL_AnalogOutputHandle analogOutputHandle) { // no status, so no need to check for a proper free. auto port = analogOutputHandles->Get(analogOutputHandle); - if (port == nullptr) return; + if (port == nullptr) { + return; + } analogOutputHandles->Free(analogOutputHandle); SimAnalogOutData[port->channel].initialized = false; } diff --git a/hal/src/main/native/sim/AnalogTrigger.cpp b/hal/src/main/native/sim/AnalogTrigger.cpp index 8a886808df..8729f5fb0e 100644 --- a/hal/src/main/native/sim/AnalogTrigger.cpp +++ b/hal/src/main/native/sim/AnalogTrigger.cpp @@ -99,7 +99,9 @@ void HAL_CleanAnalogTrigger(HAL_AnalogTriggerHandle analogTriggerHandle, int32_t* status) { auto trigger = analogTriggerHandles->Get(analogTriggerHandle); analogTriggerHandles->Free(analogTriggerHandle); - if (trigger == nullptr) return; + if (trigger == nullptr) { + return; + } SimAnalogTriggerData[trigger->index].initialized = false; // caller owns the analog input handle. } @@ -128,10 +130,14 @@ void HAL_SetAnalogTriggerLimitsRaw(HAL_AnalogTriggerHandle analogTriggerHandle, double trigLower = GetAnalogValueToVoltage(trigger->analogHandle, lower, status); - if (status != 0) return; + if (status != 0) { + return; + } double trigUpper = GetAnalogValueToVoltage(trigger->analogHandle, upper, status); - if (status != 0) return; + if (status != 0) { + return; + } SimAnalogTriggerData[trigger->index].triggerUpperBound = trigUpper; SimAnalogTriggerData[trigger->index].triggerLowerBound = trigLower; diff --git a/hal/src/main/native/sim/DIO.cpp b/hal/src/main/native/sim/DIO.cpp index 405ce0ffaf..7d9eeb5369 100644 --- a/hal/src/main/native/sim/DIO.cpp +++ b/hal/src/main/native/sim/DIO.cpp @@ -35,7 +35,9 @@ extern "C" { HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle, HAL_Bool input, int32_t* status) { hal::init::CheckInit(); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex) { @@ -46,8 +48,9 @@ HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle, auto handle = digitalChannelHandles->Allocate(channel, HAL_HandleEnum::DIO, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO); if (port == nullptr) { // would only occur on thread issue. @@ -72,13 +75,17 @@ void HAL_FreeDIOPort(HAL_DigitalHandle dioPortHandle) { auto port = digitalChannelHandles->Get(dioPortHandle, HAL_HandleEnum::DIO); // no status, so no need to check for a proper free. digitalChannelHandles->Free(dioPortHandle, HAL_HandleEnum::DIO); - if (port == nullptr) return; + if (port == nullptr) { + return; + } SimDIOData[port->channel].initialized = false; } void HAL_SetDIOSimDevice(HAL_DigitalHandle handle, HAL_SimDeviceHandle device) { auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO); - if (port == nullptr) return; + if (port == nullptr) { + return; + } SimDIOData[port->channel].simDevice = device; } @@ -104,7 +111,9 @@ HAL_DigitalPWMHandle HAL_AllocateDigitalPWM(int32_t* status) { void HAL_FreeDigitalPWM(HAL_DigitalPWMHandle pwmGenerator, int32_t* status) { auto port = digitalPWMHandles->Get(pwmGenerator); digitalPWMHandles->Free(pwmGenerator); - if (port == nullptr) return; + if (port == nullptr) { + return; + } int32_t id = *port; SimDigitalPWMData[id].initialized = false; } @@ -129,8 +138,12 @@ void HAL_SetDigitalPWMDutyCycle(HAL_DigitalPWMHandle pwmGenerator, return; } int32_t id = *port; - if (dutyCycle > 1.0) dutyCycle = 1.0; - if (dutyCycle < 0.0) dutyCycle = 0.0; + if (dutyCycle > 1.0) { + dutyCycle = 1.0; + } + if (dutyCycle < 0.0) { + dutyCycle = 0.0; + } SimDigitalPWMData[id].dutyCycle = dutyCycle; } @@ -153,7 +166,9 @@ void HAL_SetDIO(HAL_DigitalHandle dioPortHandle, HAL_Bool value, return; } if (value != 0 && value != 1) { - if (value != 0) value = 1; + if (value != 0) { + value = 1; + } } SimDIOData[port->channel].value = value; } @@ -176,8 +191,12 @@ HAL_Bool HAL_GetDIO(HAL_DigitalHandle dioPortHandle, int32_t* status) { return false; } HAL_Bool value = SimDIOData[port->channel].value; - if (value > 1) value = 1; - if (value < 0) value = 0; + if (value > 1) { + value = 1; + } + if (value < 0) { + value = 0; + } return value; } @@ -188,8 +207,12 @@ HAL_Bool HAL_GetDIODirection(HAL_DigitalHandle dioPortHandle, int32_t* status) { return false; } HAL_Bool value = SimDIOData[port->channel].isInput; - if (value > 1) value = 1; - if (value < 0) value = 0; + if (value > 1) { + value = 1; + } + if (value < 0) { + value = 0; + } return value; } diff --git a/hal/src/main/native/sim/DMA.cpp b/hal/src/main/native/sim/DMA.cpp index 84a456b99d..b749e9611a 100644 --- a/hal/src/main/native/sim/DMA.cpp +++ b/hal/src/main/native/sim/DMA.cpp @@ -5,7 +5,9 @@ #include "hal/DMA.h" extern "C" { -HAL_DMAHandle HAL_InitializeDMA(int32_t* status) { return HAL_kInvalidHandle; } +HAL_DMAHandle HAL_InitializeDMA(int32_t* status) { + return HAL_kInvalidHandle; +} void HAL_FreeDMA(HAL_DMAHandle handle) {} void HAL_SetDMAPause(HAL_DMAHandle handle, HAL_Bool pause, int32_t* status) {} @@ -47,7 +49,9 @@ void HAL_SetDMAExternalTrigger(HAL_DMAHandle handle, void HAL_StartDMA(HAL_DMAHandle handle, int32_t queueDepth, int32_t* status) {} void HAL_StopDMA(HAL_DMAHandle handle, int32_t* status) {} -void* HAL_GetDMADirectPointer(HAL_DMAHandle handle) { return nullptr; } +void* HAL_GetDMADirectPointer(HAL_DMAHandle handle) { + return nullptr; +} enum HAL_DMAReadStatus HAL_ReadDMADirect(void* dmaPointer, HAL_DMASample* dmaSample, diff --git a/hal/src/main/native/sim/DigitalInternal.cpp b/hal/src/main/native/sim/DigitalInternal.cpp index c5656c05c0..b7c1d2f2ae 100644 --- a/hal/src/main/native/sim/DigitalInternal.cpp +++ b/hal/src/main/native/sim/DigitalInternal.cpp @@ -52,7 +52,9 @@ bool remapDigitalSource(HAL_Handle digitalSourceHandle, } } -int32_t remapMXPChannel(int32_t channel) { return channel - 10; } +int32_t remapMXPChannel(int32_t channel) { + return channel - 10; +} int32_t remapMXPPWMChannel(int32_t channel) { if (channel < 14) { diff --git a/hal/src/main/native/sim/DriverStation.cpp b/hal/src/main/native/sim/DriverStation.cpp index 1d73741936..ffd943c3a8 100644 --- a/hal/src/main/native/sim/DriverStation.cpp +++ b/hal/src/main/native/sim/DriverStation.cpp @@ -56,9 +56,10 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, const char* details, const char* location, const char* callStack, HAL_Bool printMsg) { auto errorHandler = sendErrorHandler.load(); - if (errorHandler) + if (errorHandler) { return errorHandler(isError, errorCode, isLVCode, details, location, callStack, printMsg); + } // Avoid flooding console by keeping track of previous 5 error // messages and only printing again if they're longer than 1 second old. static constexpr int KEEP_MSGS = 5; @@ -76,7 +77,9 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, auto curTime = fpga_clock::now(); int i; for (i = 0; i < KEEP_MSGS; ++i) { - if (prevMsg[i] == details) break; + if (prevMsg[i] == details) { + break; + } } int retval = 0; if (i == KEEP_MSGS || (curTime - prevMsgTime[i]) >= std::chrono::seconds(1)) { @@ -177,9 +180,13 @@ char* HAL_GetJoystickName(int32_t joystickNum) { return name; } -void HAL_FreeJoystickName(char* name) { std::free(name); } +void HAL_FreeJoystickName(char* name) { + std::free(name); +} -int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) { return 0; } +int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) { + return 0; +} int32_t HAL_SetJoystickOutputs(int32_t joystickNum, int64_t outputs, int32_t leftRumble, int32_t rightRumble) { @@ -197,7 +204,9 @@ int32_t HAL_GetMatchInfo(HAL_MatchInfo* info) { return 0; } -void HAL_ObserveUserProgramStarting(void) { HALSIM_SetProgramStarted(); } +void HAL_ObserveUserProgramStarting(void) { + HALSIM_SetProgramStarted(); +} void HAL_ObserveUserProgramDisabled(void) { // TODO @@ -228,12 +237,16 @@ HAL_Bool HAL_IsNewControlData(void) { std::scoped_lock lock(newDSDataAvailableMutex); int& lastCount = GetThreadLocalLastCount(); int currentCount = newDSDataAvailableCounter; - if (lastCount == currentCount) return false; + if (lastCount == currentCount) { + return false; + } lastCount = currentCount; return true; } -void HAL_WaitForDSData(void) { HAL_WaitForDSDataTimeout(0); } +void HAL_WaitForDSData(void) { + HAL_WaitForDSDataTimeout(0); +} HAL_Bool HAL_WaitForDSDataTimeout(double timeout) { std::unique_lock lock(newDSDataAvailableMutex); @@ -270,7 +283,9 @@ constexpr int32_t refNumber = 42; static int32_t newDataOccur(uint32_t refNum) { // Since we could get other values, require our specific handle // to signal our threads - if (refNum != refNumber) return 0; + if (refNum != refNumber) { + return 0; + } SimDriverStationData->CallNewDataCallbacks(); std::scoped_lock lock(newDSDataAvailableMutex); // Nofify all threads @@ -284,11 +299,15 @@ void HAL_InitializeDriverStation(void) { static std::atomic_bool initialized{false}; static wpi::mutex initializeMutex; // Initial check, as if it's true initialization has finished - if (initialized) return; + if (initialized) { + return; + } std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting - if (initialized) return; + if (initialized) { + return; + } SimDriverStationData->ResetData(); @@ -300,6 +319,8 @@ void HAL_InitializeDriverStation(void) { initialized = true; } -void HAL_ReleaseDSMutex(void) { newDataOccur(refNumber); } +void HAL_ReleaseDSMutex(void) { + newDataOccur(refNumber); +} } // extern "C" diff --git a/hal/src/main/native/sim/DutyCycle.cpp b/hal/src/main/native/sim/DutyCycle.cpp index 1ea39dbf23..68077758e7 100644 --- a/hal/src/main/native/sim/DutyCycle.cpp +++ b/hal/src/main/native/sim/DutyCycle.cpp @@ -62,14 +62,18 @@ HAL_DutyCycleHandle HAL_InitializeDutyCycle(HAL_Handle digitalSourceHandle, void HAL_FreeDutyCycle(HAL_DutyCycleHandle dutyCycleHandle) { auto dutyCycle = dutyCycleHandles->Get(dutyCycleHandle); dutyCycleHandles->Free(dutyCycleHandle); - if (dutyCycle == nullptr) return; + if (dutyCycle == nullptr) { + return; + } SimDutyCycleData[dutyCycle->index].initialized = false; } void HAL_SetDutyCycleSimDevice(HAL_EncoderHandle handle, HAL_SimDeviceHandle device) { auto dutyCycle = dutyCycleHandles->Get(handle); - if (dutyCycle == nullptr) return; + if (dutyCycle == nullptr) { + return; + } SimDutyCycleData[dutyCycle->index].simDevice = device; } diff --git a/hal/src/main/native/sim/Encoder.cpp b/hal/src/main/native/sim/Encoder.cpp index 894301099b..c59e7019c9 100644 --- a/hal/src/main/native/sim/Encoder.cpp +++ b/hal/src/main/native/sim/Encoder.cpp @@ -93,7 +93,9 @@ HAL_EncoderHandle HAL_InitializeEncoder( void HAL_FreeEncoder(HAL_EncoderHandle encoderHandle, int32_t* status) { auto encoder = encoderHandles->Get(encoderHandle); encoderHandles->Free(encoderHandle); - if (encoder == nullptr) return; + if (encoder == nullptr) { + return; + } if (isHandleType(encoder->nativeHandle, HAL_HandleEnum::FPGAEncoder)) { fpgaEncoderHandles->Free(encoder->nativeHandle); } else if (isHandleType(encoder->nativeHandle, HAL_HandleEnum::Counter)) { @@ -105,7 +107,9 @@ void HAL_FreeEncoder(HAL_EncoderHandle encoderHandle, int32_t* status) { void HAL_SetEncoderSimDevice(HAL_EncoderHandle handle, HAL_SimDeviceHandle device) { auto encoder = encoderHandles->Get(handle); - if (encoder == nullptr) return; + if (encoder == nullptr) { + return; + } SimEncoderData[encoder->index].simDevice = device; } diff --git a/hal/src/main/native/sim/Extensions.cpp b/hal/src/main/native/sim/Extensions.cpp index f100ea1cff..4131ddcd9a 100644 --- a/hal/src/main/native/sim/Extensions.cpp +++ b/hal/src/main/native/sim/Extensions.cpp @@ -85,7 +85,9 @@ int HAL_LoadOneExtension(const char* library) { auto init = reinterpret_cast( DLSYM(handle, "HALSIM_InitExtension")); - if (init) rc = (*init)(); + if (init) { + rc = (*init)(); + } if (rc != 0) { wpi::outs() << "HAL Extensions: Failed to load extension\n"; @@ -114,7 +116,9 @@ int HAL_LoadExtensions(void) { for (auto& libref : libraries) { wpi::SmallString<128> library(libref); rc = HAL_LoadOneExtension(library.c_str()); - if (rc < 0) break; + if (rc < 0) { + break; + } } return rc; } @@ -122,8 +126,9 @@ int HAL_LoadExtensions(void) { void HAL_RegisterExtension(const char* name, void* data) { std::scoped_lock lock(gExtensionRegistryMutex); gExtensionRegistry.emplace_back(name, data); - for (auto&& listener : gExtensionListeners) + for (auto&& listener : gExtensionListeners) { listener.second(listener.first, name, data); + } } void HAL_RegisterExtensionListener(void* param, @@ -131,8 +136,9 @@ void HAL_RegisterExtensionListener(void* param, void* data)) { std::scoped_lock lock(gExtensionRegistryMutex); gExtensionListeners.emplace_back(param, func); - for (auto&& extension : gExtensionRegistry) + for (auto&& extension : gExtensionRegistry) { func(param, extension.first, extension.second); + } } void HAL_SetShowExtensionsNotFoundMessages(HAL_Bool showMessage) { diff --git a/hal/src/main/native/sim/HAL.cpp b/hal/src/main/native/sim/HAL.cpp index 3dd058f3a5..5629993ef3 100644 --- a/hal/src/main/native/sim/HAL.cpp +++ b/hal/src/main/native/sim/HAL.cpp @@ -43,8 +43,9 @@ class SimPeriodicCallbackRegistry : public impl::SimCallbackRegistryBase { std::scoped_lock lock(m_mutex); #endif if (m_callbacks) { - for (auto&& cb : *m_callbacks) + for (auto&& cb : *m_callbacks) { reinterpret_cast(cb.callback)(cb.param); + } } } }; @@ -122,14 +123,20 @@ extern "C" { HAL_PortHandle HAL_GetPort(int32_t channel) { // Dont allow a number that wouldn't fit in a uint8_t - if (channel < 0 || channel >= 255) return HAL_kInvalidHandle; + if (channel < 0 || channel >= 255) { + return HAL_kInvalidHandle; + } return createPortHandle(channel, 1); } HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel) { // Dont allow a number that wouldn't fit in a uint8_t - if (channel < 0 || channel >= 255) return HAL_kInvalidHandle; - if (module < 0 || module >= 255) return HAL_kInvalidHandle; + if (channel < 0 || channel >= 255) { + return HAL_kInvalidHandle; + } + if (module < 0 || module >= 255) { + return HAL_kInvalidHandle; + } return createPortHandle(channel, module); } @@ -250,9 +257,13 @@ const char* HAL_GetErrorMessage(int32_t code) { } } -HAL_RuntimeType HAL_GetRuntimeType(void) { return runtimeType; } +HAL_RuntimeType HAL_GetRuntimeType(void) { + return runtimeType; +} -void HALSIM_SetRuntimeType(HAL_RuntimeType type) { runtimeType = type; } +void HALSIM_SetRuntimeType(HAL_RuntimeType type) { + runtimeType = type; +} int32_t HAL_GetFPGAVersion(int32_t* status) { return 2018; // Automatically script this at some point @@ -262,13 +273,17 @@ int64_t HAL_GetFPGARevision(int32_t* status) { return 0; // TODO: Find a better number to return; } -uint64_t HAL_GetFPGATime(int32_t* status) { return hal::GetFPGATime(); } +uint64_t HAL_GetFPGATime(int32_t* status) { + return hal::GetFPGATime(); +} uint64_t HAL_ExpandFPGATime(uint32_t unexpanded_lower, int32_t* status) { // Capture the current FPGA time. This will give us the upper half of the // clock. uint64_t fpga_time = HAL_GetFPGATime(status); - if (*status != 0) return 0; + if (*status != 0) { + return 0; + } // Now, we need to detect the case where the lower bits rolled over after we // sampled. In that case, the upper bits will be 1 bigger than they should @@ -302,11 +317,15 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { static std::atomic_bool initialized{false}; static wpi::mutex initializeMutex; // Initial check, as if it's true initialization has finished - if (initialized) return true; + if (initialized) { + return true; + } std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting - if (initialized) return true; + if (initialized) { + return true; + } hal::init::InitializeHAL(); @@ -334,7 +353,9 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { #endif // _WIN32 wpi::outs().SetUnbuffered(); - if (HAL_LoadExtensions() < 0) return false; + if (HAL_LoadExtensions() < 0) { + return false; + } return true; // Add initialization if we need to at a later point } @@ -355,9 +376,13 @@ void HAL_OnShutdown(void* param, void (*func)(void*)) { gOnShutdown.emplace_back(param, func); } -void HAL_SimPeriodicBefore(void) { gSimPeriodicBefore(); } +void HAL_SimPeriodicBefore(void) { + gSimPeriodicBefore(); +} -void HAL_SimPeriodicAfter(void) { gSimPeriodicAfter(); } +void HAL_SimPeriodicAfter(void) { + gSimPeriodicAfter(); +} int32_t HALSIM_RegisterSimPeriodicBeforeCallback( HALSIM_SimPeriodicCallback callback, void* param) { diff --git a/hal/src/main/native/sim/HALInitializer.cpp b/hal/src/main/native/sim/HALInitializer.cpp index 654adf5cda..1905c9b1d6 100644 --- a/hal/src/main/native/sim/HALInitializer.cpp +++ b/hal/src/main/native/sim/HALInitializer.cpp @@ -9,6 +9,8 @@ namespace hal { namespace init { std::atomic_bool HAL_IsInitialized{false}; -void RunInitialize() { HAL_Initialize(500, 0); } +void RunInitialize() { + HAL_Initialize(500, 0); +} } // namespace init } // namespace hal diff --git a/hal/src/main/native/sim/HALInitializer.h b/hal/src/main/native/sim/HALInitializer.h index 236948e6fa..cace24006c 100644 --- a/hal/src/main/native/sim/HALInitializer.h +++ b/hal/src/main/native/sim/HALInitializer.h @@ -11,7 +11,9 @@ namespace init { extern std::atomic_bool HAL_IsInitialized; extern void RunInitialize(); static inline void CheckInit() { - if (HAL_IsInitialized.load(std::memory_order_relaxed)) return; + if (HAL_IsInitialized.load(std::memory_order_relaxed)) { + return; + } RunInitialize(); } diff --git a/hal/src/main/native/sim/I2C.cpp b/hal/src/main/native/sim/I2C.cpp index 5d77a79ef9..87bda51e11 100644 --- a/hal/src/main/native/sim/I2C.cpp +++ b/hal/src/main/native/sim/I2C.cpp @@ -37,5 +37,7 @@ int32_t HAL_ReadI2C(HAL_I2CPort port, int32_t deviceAddress, uint8_t* buffer, SimI2CData[port].Read(deviceAddress, buffer, count); return 0; } -void HAL_CloseI2C(HAL_I2CPort port) { SimI2CData[port].initialized = false; } +void HAL_CloseI2C(HAL_I2CPort port) { + SimI2CData[port].initialized = false; +} } // extern "C" diff --git a/hal/src/main/native/sim/Interrupts.cpp b/hal/src/main/native/sim/Interrupts.cpp index ebe0c22118..34deca47c4 100644 --- a/hal/src/main/native/sim/Interrupts.cpp +++ b/hal/src/main/native/sim/Interrupts.cpp @@ -125,18 +125,30 @@ static void ProcessInterruptDigitalSynchronous(const char* name, void* param, SynchronousWaitDataHandle handle = static_cast(handleTmp); auto interruptData = synchronousInterruptHandles->Get(handle); - if (interruptData == nullptr) return; + if (interruptData == nullptr) { + return; + } auto interrupt = interruptHandles->Get(interruptData->interruptHandle); - if (interrupt == nullptr) return; + if (interrupt == nullptr) { + return; + } // Have a valid interrupt - if (value->type != HAL_Type::HAL_BOOLEAN) return; + if (value->type != HAL_Type::HAL_BOOLEAN) { + return; + } bool retVal = value->data.v_boolean; // If no change in interrupt, return; - if (retVal == interrupt->previousState) return; + if (retVal == interrupt->previousState) { + return; + } // If its a falling change, and we dont fire on falling return - if (interrupt->previousState && !interrupt->fireOnDown) return; + if (interrupt->previousState && !interrupt->fireOnDown) { + return; + } // If its a rising change, and we dont fire on rising return. - if (!interrupt->previousState && !interrupt->fireOnUp) return; + if (!interrupt->previousState && !interrupt->fireOnUp) { + return; + } interruptData->waitPredicate = true; @@ -158,11 +170,17 @@ static void ProcessInterruptAnalogSynchronous(const char* name, void* param, SynchronousWaitDataHandle handle = static_cast(handleTmp); auto interruptData = synchronousInterruptHandles->Get(handle); - if (interruptData == nullptr) return; + if (interruptData == nullptr) { + return; + } auto interrupt = interruptHandles->Get(interruptData->interruptHandle); - if (interrupt == nullptr) return; + if (interrupt == nullptr) { + return; + } // Have a valid interrupt - if (value->type != HAL_Type::HAL_DOUBLE) return; + if (value->type != HAL_Type::HAL_DOUBLE) { + return; + } int32_t status = 0; bool retVal = GetAnalogTriggerValue(interrupt->portHandle, interrupt->trigType, &status); @@ -173,11 +191,17 @@ static void ProcessInterruptAnalogSynchronous(const char* name, void* param, interruptData->waitCond.notify_all(); } // If no change in interrupt, return; - if (retVal == interrupt->previousState) return; + if (retVal == interrupt->previousState) { + return; + } // If its a falling change, and we dont fire on falling return - if (interrupt->previousState && !interrupt->fireOnDown) return; + if (interrupt->previousState && !interrupt->fireOnDown) { + return; + } // If its a rising change, and we dont fire on rising return. - if (!interrupt->previousState && !interrupt->fireOnUp) return; + if (!interrupt->previousState && !interrupt->fireOnUp) { + return; + } interruptData->waitPredicate = true; @@ -204,7 +228,9 @@ static int64_t WaitForInterruptDigital(HAL_InterruptHandle handle, int32_t digitalIndex = GetDigitalInputChannel(interrupt->portHandle, &status); - if (status != 0) return WaitResult::Timeout; + if (status != 0) { + return WaitResult::Timeout; + } interrupt->previousState = SimDIOData[digitalIndex].value; @@ -235,7 +261,9 @@ static int64_t WaitForInterruptDigital(HAL_InterruptHandle handle, (void)synchronousInterruptHandles->Free(dataHandle); // Check for what to return - if (timedOut) return WaitResult::Timeout; + if (timedOut) { + return WaitResult::Timeout; + } // True => false, Falling if (interrupt->previousState) { // Set our return value and our timestamps @@ -265,12 +293,16 @@ static int64_t WaitForInterruptAnalog(HAL_InterruptHandle handle, interrupt->previousState = GetAnalogTriggerValue( interrupt->portHandle, interrupt->trigType, &status); - if (status != 0) return WaitResult::Timeout; + if (status != 0) { + return WaitResult::Timeout; + } int32_t analogIndex = GetAnalogTriggerInputIndex(interrupt->portHandle, &status); - if (status != 0) return WaitResult::Timeout; + if (status != 0) { + return WaitResult::Timeout; + } int32_t uid = SimAnalogInData[analogIndex].voltage.RegisterCallback( &ProcessInterruptAnalogSynchronous, @@ -299,7 +331,9 @@ static int64_t WaitForInterruptAnalog(HAL_InterruptHandle handle, (void)synchronousInterruptHandles->Free(dataHandle); // Check for what to return - if (timedOut) return WaitResult::Timeout; + if (timedOut) { + return WaitResult::Timeout; + } // True => false, Falling if (interrupt->previousState) { // Set our return value and our timestamps @@ -342,28 +376,40 @@ static void ProcessInterruptDigitalAsynchronous(const char* name, void* param, uintptr_t handleTmp = reinterpret_cast(param); HAL_InterruptHandle handle = static_cast(handleTmp); auto interrupt = interruptHandles->Get(handle); - if (interrupt == nullptr) return; + if (interrupt == nullptr) { + return; + } // Have a valid interrupt - if (value->type != HAL_Type::HAL_BOOLEAN) return; + if (value->type != HAL_Type::HAL_BOOLEAN) { + return; + } bool retVal = value->data.v_boolean; // If no change in interrupt, return; - if (retVal == interrupt->previousState) return; + if (retVal == interrupt->previousState) { + return; + } int32_t mask = 0; if (interrupt->previousState) { interrupt->previousState = retVal; interrupt->fallingTimestamp = hal::GetFPGATime(); mask = 1 << (8 + interrupt->index); - if (!interrupt->fireOnDown) return; + if (!interrupt->fireOnDown) { + return; + } } else { interrupt->previousState = retVal; interrupt->risingTimestamp = hal::GetFPGATime(); mask = 1 << (interrupt->index); - if (!interrupt->fireOnUp) return; + if (!interrupt->fireOnUp) { + return; + } } // run callback auto callback = interrupt->callbackFunction; - if (callback == nullptr) return; + if (callback == nullptr) { + return; + } callback(mask, interrupt->callbackParam); } @@ -374,31 +420,45 @@ static void ProcessInterruptAnalogAsynchronous(const char* name, void* param, uintptr_t handleTmp = reinterpret_cast(param); HAL_InterruptHandle handle = static_cast(handleTmp); auto interrupt = interruptHandles->Get(handle); - if (interrupt == nullptr) return; + if (interrupt == nullptr) { + return; + } // Have a valid interrupt - if (value->type != HAL_Type::HAL_DOUBLE) return; + if (value->type != HAL_Type::HAL_DOUBLE) { + return; + } int32_t status = 0; bool retVal = GetAnalogTriggerValue(interrupt->portHandle, interrupt->trigType, &status); - if (status != 0) return; + if (status != 0) { + return; + } // If no change in interrupt, return; - if (retVal == interrupt->previousState) return; + if (retVal == interrupt->previousState) { + return; + } int mask = 0; if (interrupt->previousState) { interrupt->previousState = retVal; interrupt->fallingTimestamp = hal::GetFPGATime(); - if (!interrupt->fireOnDown) return; + if (!interrupt->fireOnDown) { + return; + } mask = 1 << (8 + interrupt->index); } else { interrupt->previousState = retVal; interrupt->risingTimestamp = hal::GetFPGATime(); - if (!interrupt->fireOnUp) return; + if (!interrupt->fireOnUp) { + return; + } mask = 1 << (interrupt->index); } // run callback auto callback = interrupt->callbackFunction; - if (callback == nullptr) return; + if (callback == nullptr) { + return; + } callback(mask, interrupt->callbackParam); } @@ -406,7 +466,9 @@ static void EnableInterruptsDigital(HAL_InterruptHandle handle, Interrupt* interrupt) { int32_t status = 0; int32_t digitalIndex = GetDigitalInputChannel(interrupt->portHandle, &status); - if (status != 0) return; + if (status != 0) { + return; + } interrupt->previousState = SimDIOData[digitalIndex].value; @@ -421,12 +483,16 @@ static void EnableInterruptsAnalog(HAL_InterruptHandle handle, int32_t status = 0; int32_t analogIndex = GetAnalogTriggerInputIndex(interrupt->portHandle, &status); - if (status != 0) return; + if (status != 0) { + return; + } status = 0; interrupt->previousState = GetAnalogTriggerValue( interrupt->portHandle, interrupt->trigType, &status); - if (status != 0) return; + if (status != 0) { + return; + } int32_t uid = SimAnalogInData[analogIndex].voltage.RegisterCallback( &ProcessInterruptAnalogAsynchronous, @@ -469,20 +535,26 @@ void HAL_DisableInterrupts(HAL_InterruptHandle interruptHandle, } // No need to disable if we are already disabled - if (interrupt->callbackId < 0) return; + if (interrupt->callbackId < 0) { + return; + } if (interrupt->isAnalog) { // Do analog int32_t status = 0; int32_t analogIndex = GetAnalogTriggerInputIndex(interrupt->portHandle, &status); - if (status != 0) return; + if (status != 0) { + return; + } SimAnalogInData[analogIndex].voltage.CancelCallback(interrupt->callbackId); } else { int32_t status = 0; int32_t digitalIndex = GetDigitalInputChannel(interrupt->portHandle, &status); - if (status != 0) return; + if (status != 0) { + return; + } SimDIOData[digitalIndex].value.CancelCallback(interrupt->callbackId); } interrupt->callbackId = -1; diff --git a/hal/src/main/native/sim/MockHooks.cpp b/hal/src/main/native/sim/MockHooks.cpp index 570aa9fb0f..24a7588493 100644 --- a/hal/src/main/native/sim/MockHooks.cpp +++ b/hal/src/main/native/sim/MockHooks.cpp @@ -22,7 +22,9 @@ static std::atomic programStepTime{0}; namespace hal { namespace init { -void InitializeMockHooks() { wpi::SetNowImpl(GetFPGATime); } +void InitializeMockHooks() { + wpi::SetNowImpl(GetFPGATime); +} } // namespace init } // namespace hal @@ -30,11 +32,15 @@ namespace hal { void RestartTiming() { programStartTime = wpi::NowDefault(); programStepTime = 0; - if (programPauseTime != 0) programPauseTime = programStartTime.load(); + if (programPauseTime != 0) { + programPauseTime = programStartTime.load(); + } } void PauseTiming() { - if (programPauseTime == 0) programPauseTime = wpi::NowDefault(); + if (programPauseTime == 0) { + programPauseTime = wpi::NowDefault(); + } } void ResumeTiming() { @@ -44,20 +50,32 @@ void ResumeTiming() { } } -bool IsTimingPaused() { return programPauseTime != 0; } +bool IsTimingPaused() { + return programPauseTime != 0; +} -void StepTiming(uint64_t delta) { programStepTime += delta; } +void StepTiming(uint64_t delta) { + programStepTime += delta; +} uint64_t GetFPGATime() { uint64_t curTime = programPauseTime; - if (curTime == 0) curTime = wpi::NowDefault(); + if (curTime == 0) { + curTime = wpi::NowDefault(); + } return curTime + programStepTime - programStartTime; } -double GetFPGATimestamp() { return GetFPGATime() * 1.0e-6; } +double GetFPGATimestamp() { + return GetFPGATime() * 1.0e-6; +} -void SetProgramStarted() { programStarted = true; } -bool GetProgramStarted() { return programStarted; } +void SetProgramStarted() { + programStarted = true; +} +bool GetProgramStarted() { + return programStarted; +} } // namespace hal using namespace hal; @@ -72,11 +90,17 @@ void HALSIM_WaitForProgramStart(void) { } } -void HALSIM_SetProgramStarted(void) { SetProgramStarted(); } +void HALSIM_SetProgramStarted(void) { + SetProgramStarted(); +} -HAL_Bool HALSIM_GetProgramStarted(void) { return GetProgramStarted(); } +HAL_Bool HALSIM_GetProgramStarted(void) { + return GetProgramStarted(); +} -void HALSIM_RestartTiming(void) { RestartTiming(); } +void HALSIM_RestartTiming(void) { + RestartTiming(); +} void HALSIM_PauseTiming(void) { PauseTiming(); @@ -88,7 +112,9 @@ void HALSIM_ResumeTiming(void) { ResumeNotifiers(); } -HAL_Bool HALSIM_IsTimingPaused(void) { return IsTimingPaused(); } +HAL_Bool HALSIM_IsTimingPaused(void) { + return IsTimingPaused(); +} void HALSIM_StepTiming(uint64_t delta) { WaitNotifiers(); diff --git a/hal/src/main/native/sim/Notifier.cpp b/hal/src/main/native/sim/Notifier.cpp index 9ccfe73f28..3459b6cdce 100644 --- a/hal/src/main/native/sim/Notifier.cpp +++ b/hal/src/main/native/sim/Notifier.cpp @@ -68,7 +68,9 @@ void InitializeNotifier() { } } // namespace init -void PauseNotifiers() { notifiersPaused = true; } +void PauseNotifiers() { + notifiersPaused = true; +} void ResumeNotifiers() { notifiersPaused = false; @@ -107,7 +109,9 @@ void WaitNotifiers() { // No longer need to wait for it, put at end so it can be erased std::swap(it, waiters[--end]); } - if (count == 0) break; + if (count == 0) { + break; + } waiters.resize(count); notifiersWaiterCond.wait_for(ulock, std::chrono::duration(1)); } @@ -148,7 +152,9 @@ void WakeupWaitNotifiers() { // No longer need to wait for it, put at end so it can be erased it.swap(waiters[--end]); } - if (count == 0) break; + if (count == 0) { + break; + } waiters.resize(count); notifiersWaiterCond.wait_for(ulock, std::chrono::duration(1)); } @@ -171,14 +177,18 @@ HAL_NotifierHandle HAL_InitializeNotifier(int32_t* status) { void HAL_SetNotifierName(HAL_NotifierHandle notifierHandle, const char* name, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return; + if (!notifier) { + return; + } std::scoped_lock lock(notifier->mutex); notifier->name = name; } void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return; + if (!notifier) { + return; + } { std::scoped_lock lock(notifier->mutex); @@ -190,7 +200,9 @@ void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Free(notifierHandle); - if (!notifier) return; + if (!notifier) { + return; + } // Just in case HAL_StopNotifier() wasn't called... { @@ -204,7 +216,9 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle, uint64_t triggerTime, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return; + if (!notifier) { + return; + } { std::scoped_lock lock(notifier->mutex); @@ -219,7 +233,9 @@ void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle, void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return; + if (!notifier) { + return; + } { std::scoped_lock lock(notifier->mutex); @@ -230,7 +246,9 @@ void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle, uint64_t HAL_WaitForNotifierAlarm(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); - if (!notifier) return 0; + if (!notifier) { + return 0; + } std::unique_lock ulock(notifiersWaiterMutex); std::unique_lock lock(notifier->mutex); @@ -265,8 +283,9 @@ uint64_t HALSIM_GetNextNotifierTimeout(void) { notifierHandles->ForEach([&](HAL_NotifierHandle, Notifier* notifier) { std::scoped_lock lock(notifier->mutex); if (notifier->active && notifier->waitTimeValid && - timeout > notifier->waitTime) + timeout > notifier->waitTime) { timeout = notifier->waitTime; + } }); return timeout; } @@ -275,7 +294,9 @@ int32_t HALSIM_GetNumNotifiers(void) { int32_t count = 0; notifierHandles->ForEach([&](HAL_NotifierHandle, Notifier* notifier) { std::scoped_lock lock(notifier->mutex); - if (notifier->active) ++count; + if (notifier->active) { + ++count; + } }); return count; } @@ -284,7 +305,9 @@ int32_t HALSIM_GetNotifierInfo(struct HALSIM_NotifierInfo* arr, int32_t size) { int32_t num = 0; notifierHandles->ForEach([&](HAL_NotifierHandle handle, Notifier* notifier) { std::scoped_lock lock(notifier->mutex); - if (!notifier->active) return; + if (!notifier->active) { + return; + } if (num < size) { arr[num].handle = handle; if (notifier->name.empty()) { diff --git a/hal/src/main/native/sim/PDP.cpp b/hal/src/main/native/sim/PDP.cpp index 50b2a3dd00..35fde90874 100644 --- a/hal/src/main/native/sim/PDP.cpp +++ b/hal/src/main/native/sim/PDP.cpp @@ -51,7 +51,9 @@ HAL_Bool HAL_CheckPDPChannel(int32_t channel) { return channel < kNumPDPChannels && channel >= 0; } -void HAL_CleanPDP(HAL_PDPHandle handle) { HAL_CleanCAN(handle); } +void HAL_CleanPDP(HAL_PDPHandle handle) { + HAL_CleanCAN(handle); +} double HAL_GetPDPTemperature(HAL_PDPHandle handle, int32_t* status) { auto module = hal::can::GetCANModuleFromHandle(handle, status); diff --git a/hal/src/main/native/sim/PWM.cpp b/hal/src/main/native/sim/PWM.cpp index d90b5de563..bc14657b08 100644 --- a/hal/src/main/native/sim/PWM.cpp +++ b/hal/src/main/native/sim/PWM.cpp @@ -24,7 +24,9 @@ extern "C" { HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle, int32_t* status) { hal::init::CheckInit(); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex) { @@ -43,8 +45,9 @@ HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle, auto handle = digitalChannelHandles->Allocate(channel, HAL_HandleEnum::PWM, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::PWM); if (port == nullptr) { // would only occur on thread issue. @@ -89,7 +92,9 @@ void HAL_SetPWMConfig(HAL_DigitalHandle pwmPortHandle, double max, // calculate the loop time in milliseconds double loopTime = HAL_GetPWMLoopTiming(status) / (kSystemClockTicksPerMicrosecond * 1e3); - if (*status != 0) return; + if (*status != 0) { + return; + } int32_t maxPwm = static_cast((max - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1); @@ -249,8 +254,12 @@ double HAL_GetPWMSpeed(HAL_DigitalHandle pwmPortHandle, int32_t* status) { } double speed = SimPWMData[port->channel].speed; - if (speed > 1) speed = 1; - if (speed < -1) speed = -1; + if (speed > 1) { + speed = 1; + } + if (speed < -1) { + speed = -1; + } return speed; } @@ -266,8 +275,12 @@ double HAL_GetPWMPosition(HAL_DigitalHandle pwmPortHandle, int32_t* status) { } double position = SimPWMData[port->channel].position; - if (position > 1) position = 1; - if (position < 0) position = 0; + if (position > 1) { + position = 1; + } + if (position < 0) { + position = 0; + } return position; } @@ -293,7 +306,11 @@ void HAL_SetPWMPeriodScale(HAL_DigitalHandle pwmPortHandle, int32_t squelchMask, SimPWMData[port->channel].periodScale = squelchMask; } -int32_t HAL_GetPWMLoopTiming(int32_t* status) { return kExpectedLoopTiming; } +int32_t HAL_GetPWMLoopTiming(int32_t* status) { + return kExpectedLoopTiming; +} -uint64_t HAL_GetPWMCycleStartTime(int32_t* status) { return 0; } +uint64_t HAL_GetPWMCycleStartTime(int32_t* status) { + return 0; +} } // extern "C" diff --git a/hal/src/main/native/sim/Ports.cpp b/hal/src/main/native/sim/Ports.cpp index 642931e4a2..9de99e3a08 100644 --- a/hal/src/main/native/sim/Ports.cpp +++ b/hal/src/main/native/sim/Ports.cpp @@ -15,24 +15,64 @@ void InitializePorts() {} } // namespace hal extern "C" { -int32_t HAL_GetNumAccumulators(void) { return kNumAccumulators; } -int32_t HAL_GetNumAnalogTriggers(void) { return kNumAnalogTriggers; } -int32_t HAL_GetNumAnalogInputs(void) { return kNumAnalogInputs; } -int32_t HAL_GetNumAnalogOutputs(void) { return kNumAnalogOutputs; } -int32_t HAL_GetNumCounters(void) { return kNumCounters; } -int32_t HAL_GetNumDigitalHeaders(void) { return kNumDigitalHeaders; } -int32_t HAL_GetNumPWMHeaders(void) { return kNumPWMHeaders; } -int32_t HAL_GetNumDigitalChannels(void) { return kNumDigitalChannels; } -int32_t HAL_GetNumPWMChannels(void) { return kNumPWMChannels; } -int32_t HAL_GetNumDigitalPWMOutputs(void) { return kNumDigitalPWMOutputs; } -int32_t HAL_GetNumEncoders(void) { return kNumEncoders; } -int32_t HAL_GetNumInterrupts(void) { return kNumInterrupts; } -int32_t HAL_GetNumRelayChannels(void) { return kNumRelayChannels; } -int32_t HAL_GetNumRelayHeaders(void) { return kNumRelayHeaders; } -int32_t HAL_GetNumPCMModules(void) { return kNumPCMModules; } -int32_t HAL_GetNumSolenoidChannels(void) { return kNumSolenoidChannels; } -int32_t HAL_GetNumPDPModules(void) { return kNumPDPModules; } -int32_t HAL_GetNumPDPChannels(void) { return kNumPDPChannels; } -int32_t HAL_GetNumDutyCycles(void) { return kNumDutyCycles; } -int32_t HAL_GetNumAddressableLEDs(void) { return kNumAddressableLEDs; } +int32_t HAL_GetNumAccumulators(void) { + return kNumAccumulators; +} +int32_t HAL_GetNumAnalogTriggers(void) { + return kNumAnalogTriggers; +} +int32_t HAL_GetNumAnalogInputs(void) { + return kNumAnalogInputs; +} +int32_t HAL_GetNumAnalogOutputs(void) { + return kNumAnalogOutputs; +} +int32_t HAL_GetNumCounters(void) { + return kNumCounters; +} +int32_t HAL_GetNumDigitalHeaders(void) { + return kNumDigitalHeaders; +} +int32_t HAL_GetNumPWMHeaders(void) { + return kNumPWMHeaders; +} +int32_t HAL_GetNumDigitalChannels(void) { + return kNumDigitalChannels; +} +int32_t HAL_GetNumPWMChannels(void) { + return kNumPWMChannels; +} +int32_t HAL_GetNumDigitalPWMOutputs(void) { + return kNumDigitalPWMOutputs; +} +int32_t HAL_GetNumEncoders(void) { + return kNumEncoders; +} +int32_t HAL_GetNumInterrupts(void) { + return kNumInterrupts; +} +int32_t HAL_GetNumRelayChannels(void) { + return kNumRelayChannels; +} +int32_t HAL_GetNumRelayHeaders(void) { + return kNumRelayHeaders; +} +int32_t HAL_GetNumPCMModules(void) { + return kNumPCMModules; +} +int32_t HAL_GetNumSolenoidChannels(void) { + return kNumSolenoidChannels; +} +int32_t HAL_GetNumPDPModules(void) { + return kNumPDPModules; +} +int32_t HAL_GetNumPDPChannels(void) { + return kNumPDPChannels; +} +int32_t HAL_GetNumDutyCycles(void) { + return kNumDutyCycles; +} +int32_t HAL_GetNumAddressableLEDs(void) { + return kNumAddressableLEDs; +} } // extern "C" diff --git a/hal/src/main/native/sim/Power.cpp b/hal/src/main/native/sim/Power.cpp index 5f5a579388..bc779329e2 100644 --- a/hal/src/main/native/sim/Power.cpp +++ b/hal/src/main/native/sim/Power.cpp @@ -16,8 +16,12 @@ void InitializePower() {} // TODO: Fix the naming in here extern "C" { -double HAL_GetVinVoltage(int32_t* status) { return SimRoboRioData->vInVoltage; } -double HAL_GetVinCurrent(int32_t* status) { return SimRoboRioData->vInCurrent; } +double HAL_GetVinVoltage(int32_t* status) { + return SimRoboRioData->vInVoltage; +} +double HAL_GetVinCurrent(int32_t* status) { + return SimRoboRioData->vInCurrent; +} double HAL_GetUserVoltage6V(int32_t* status) { return SimRoboRioData->userVoltage6V; } diff --git a/hal/src/main/native/sim/Relay.cpp b/hal/src/main/native/sim/Relay.cpp index 089dbd321b..a5f41f6b5c 100644 --- a/hal/src/main/native/sim/Relay.cpp +++ b/hal/src/main/native/sim/Relay.cpp @@ -36,7 +36,9 @@ extern "C" { HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd, int32_t* status) { hal::init::CheckInit(); - if (*status != 0) return HAL_kInvalidHandle; + if (*status != 0) { + return HAL_kInvalidHandle; + } int16_t channel = getPortHandleChannel(portHandle); if (channel == InvalidHandleIndex) { @@ -44,12 +46,15 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd, return HAL_kInvalidHandle; } - if (!fwd) channel += kNumRelayHeaders; // add 4 to reverse channels + if (!fwd) { + channel += kNumRelayHeaders; // add 4 to reverse channels + } auto handle = relayHandles->Allocate(channel, status); - if (*status != 0) + if (*status != 0) { return HAL_kInvalidHandle; // failed to allocate. Pass error back. + } auto port = relayHandles->Get(handle); if (port == nullptr) { // would only occur on thread issue. @@ -77,11 +82,14 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd, void HAL_FreeRelayPort(HAL_RelayHandle relayPortHandle) { auto port = relayHandles->Get(relayPortHandle); relayHandles->Free(relayPortHandle); - if (port == nullptr) return; - if (port->fwd) + if (port == nullptr) { + return; + } + if (port->fwd) { SimRelayData[port->channel].initializedForward = false; - else + } else { SimRelayData[port->channel].initializedReverse = false; + } } HAL_Bool HAL_CheckRelayChannel(int32_t channel) { @@ -98,10 +106,11 @@ void HAL_SetRelay(HAL_RelayHandle relayPortHandle, HAL_Bool on, *status = HAL_HANDLE_ERROR; return; } - if (port->fwd) + if (port->fwd) { SimRelayData[port->channel].forward = on; - else + } else { SimRelayData[port->channel].reverse = on; + } } HAL_Bool HAL_GetRelay(HAL_RelayHandle relayPortHandle, int32_t* status) { @@ -110,9 +119,10 @@ HAL_Bool HAL_GetRelay(HAL_RelayHandle relayPortHandle, int32_t* status) { *status = HAL_HANDLE_ERROR; return false; } - if (port->fwd) + if (port->fwd) { return SimRelayData[port->channel].forward; - else + } else { return SimRelayData[port->channel].reverse; + } } } // extern "C" diff --git a/hal/src/main/native/sim/SPI.cpp b/hal/src/main/native/sim/SPI.cpp index 4b552dbbb5..e3c479d9da 100644 --- a/hal/src/main/native/sim/SPI.cpp +++ b/hal/src/main/native/sim/SPI.cpp @@ -32,13 +32,17 @@ int32_t HAL_WriteSPI(HAL_SPIPort port, const uint8_t* dataToSend, int32_t HAL_ReadSPI(HAL_SPIPort port, uint8_t* buffer, int32_t count) { return SimSPIData[port].Read(buffer, count); } -void HAL_CloseSPI(HAL_SPIPort port) { SimSPIData[port].initialized = false; } +void HAL_CloseSPI(HAL_SPIPort port) { + SimSPIData[port].initialized = false; +} void HAL_SetSPISpeed(HAL_SPIPort port, int32_t speed) {} void HAL_SetSPIOpts(HAL_SPIPort port, HAL_Bool msbFirst, HAL_Bool sampleOnTrailing, HAL_Bool clkIdleHigh) {} void HAL_SetSPIChipSelectActiveHigh(HAL_SPIPort port, int32_t* status) {} void HAL_SetSPIChipSelectActiveLow(HAL_SPIPort port, int32_t* status) {} -int32_t HAL_GetSPIHandle(HAL_SPIPort port) { return 0; } +int32_t HAL_GetSPIHandle(HAL_SPIPort port) { + return 0; +} void HAL_SetSPIHandle(HAL_SPIPort port, int32_t handle) {} void HAL_InitSPIAuto(HAL_SPIPort port, int32_t bufferSize, int32_t* status) {} diff --git a/hal/src/main/native/sim/SerialPort.cpp b/hal/src/main/native/sim/SerialPort.cpp index d77bd35f34..6ef12089ad 100644 --- a/hal/src/main/native/sim/SerialPort.cpp +++ b/hal/src/main/native/sim/SerialPort.cpp @@ -26,7 +26,9 @@ HAL_SerialPortHandle HAL_InitializeSerialPortDirect(HAL_SerialPort port, return HAL_kInvalidHandle; } -int HAL_GetSerialFD(HAL_SerialPortHandle handle, int32_t* status) { return -1; } +int HAL_GetSerialFD(HAL_SerialPortHandle handle, int32_t* status) { + return -1; +} void HAL_SetSerialBaudRate(HAL_SerialPortHandle handle, int32_t baud, int32_t* status) {} diff --git a/hal/src/main/native/sim/Solenoid.cpp b/hal/src/main/native/sim/Solenoid.cpp index 5ce59197a8..14d6330477 100644 --- a/hal/src/main/native/sim/Solenoid.cpp +++ b/hal/src/main/native/sim/Solenoid.cpp @@ -78,7 +78,9 @@ HAL_SolenoidHandle HAL_InitializeSolenoidPort(HAL_PortHandle portHandle, } void HAL_FreeSolenoidPort(HAL_SolenoidHandle solenoidPortHandle) { auto port = solenoidHandles->Get(solenoidPortHandle); - if (port == nullptr) return; + if (port == nullptr) { + return; + } solenoidHandles->Free(solenoidPortHandle); HALSIM_SetPCMSolenoidInitialized(port->module, port->channel, false); int count = 0; diff --git a/hal/src/main/native/sim/mockdata/AddressableLEDData.cpp b/hal/src/main/native/sim/mockdata/AddressableLEDData.cpp index 8f033f750c..eb929e91d9 100644 --- a/hal/src/main/native/sim/mockdata/AddressableLEDData.cpp +++ b/hal/src/main/native/sim/mockdata/AddressableLEDData.cpp @@ -41,7 +41,9 @@ void AddressableLEDData::SetData(const HAL_AddressableLEDData* d, int32_t len) { int32_t AddressableLEDData::GetData(HAL_AddressableLEDData* d) { std::scoped_lock lock(m_dataMutex); int32_t len = length; - if (d) std::memcpy(d, m_data, len * sizeof(d[0])); + if (d) { + std::memcpy(d, m_data, len * sizeof(d[0])); + } return len; } @@ -50,8 +52,9 @@ extern "C" { int32_t HALSIM_FindAddressableLEDForChannel(int32_t channel) { for (int i = 0; i < kNumAddressableLEDs; ++i) { if (SimAddressableLEDData[i].initialized && - SimAddressableLEDData[i].outputPort == channel) + SimAddressableLEDData[i].outputPort == channel) { return i; + } } return -1; } diff --git a/hal/src/main/native/sim/mockdata/AnalogTriggerData.cpp b/hal/src/main/native/sim/mockdata/AnalogTriggerData.cpp index 64556c0afb..4653bac0b4 100644 --- a/hal/src/main/native/sim/mockdata/AnalogTriggerData.cpp +++ b/hal/src/main/native/sim/mockdata/AnalogTriggerData.cpp @@ -29,8 +29,9 @@ extern "C" { int32_t HALSIM_FindAnalogTriggerForChannel(int32_t channel) { for (int i = 0; i < kNumAnalogTriggers; ++i) { if (SimAnalogTriggerData[i].initialized && - SimAnalogTriggerData[i].inputPort == channel) + SimAnalogTriggerData[i].inputPort == channel) { return i; + } } return -1; } diff --git a/hal/src/main/native/sim/mockdata/CanDataInternal.cpp b/hal/src/main/native/sim/mockdata/CanDataInternal.cpp index 1f654ac3b0..e76e795969 100644 --- a/hal/src/main/native/sim/mockdata/CanDataInternal.cpp +++ b/hal/src/main/native/sim/mockdata/CanDataInternal.cpp @@ -28,7 +28,9 @@ void CanData::ResetData() { extern "C" { -void HALSIM_ResetCanData(void) { SimCanData->ResetData(); } +void HALSIM_ResetCanData(void) { + SimCanData->ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMCALLBACKREGISTRY_DEFINE_CAPI_NOINDEX(TYPE, HALSIM, Can##CAPINAME, \ diff --git a/hal/src/main/native/sim/mockdata/DIOData.cpp b/hal/src/main/native/sim/mockdata/DIOData.cpp index 3511e87321..51634e9c7b 100644 --- a/hal/src/main/native/sim/mockdata/DIOData.cpp +++ b/hal/src/main/native/sim/mockdata/DIOData.cpp @@ -27,7 +27,9 @@ void DIOData::ResetData() { } extern "C" { -void HALSIM_ResetDIOData(int32_t index) { SimDIOData[index].ResetData(); } +void HALSIM_ResetDIOData(int32_t index) { + SimDIOData[index].ResetData(); +} HAL_SimDeviceHandle HALSIM_GetDIOSimDevice(int32_t index) { return SimDIOData[index].simDevice; diff --git a/hal/src/main/native/sim/mockdata/DigitalPWMData.cpp b/hal/src/main/native/sim/mockdata/DigitalPWMData.cpp index 101b72e467..78ad2dd251 100644 --- a/hal/src/main/native/sim/mockdata/DigitalPWMData.cpp +++ b/hal/src/main/native/sim/mockdata/DigitalPWMData.cpp @@ -26,8 +26,10 @@ void DigitalPWMData::ResetData() { extern "C" { int32_t HALSIM_FindDigitalPWMForChannel(int32_t channel) { for (int i = 0; i < kNumDigitalPWMOutputs; ++i) { - if (SimDigitalPWMData[i].initialized && SimDigitalPWMData[i].pin == channel) + if (SimDigitalPWMData[i].initialized && + SimDigitalPWMData[i].pin == channel) { return i; + } } return -1; } diff --git a/hal/src/main/native/sim/mockdata/DriverStationData.cpp b/hal/src/main/native/sim/mockdata/DriverStationData.cpp index ee52227407..4c382e68cd 100644 --- a/hal/src/main/native/sim/mockdata/DriverStationData.cpp +++ b/hal/src/main/native/sim/mockdata/DriverStationData.cpp @@ -20,7 +20,9 @@ void InitializeDriverStationData() { DriverStationData* hal::SimDriverStationData; -DriverStationData::DriverStationData() { ResetData(); } +DriverStationData::DriverStationData() { + ResetData(); +} void DriverStationData::ResetData() { enabled.Reset(false); @@ -60,7 +62,8 @@ void DriverStationData::ResetData() { int32_t DriverStationData::RegisterJoystick##name##Callback( \ int32_t joystickNum, HAL_Joystick##name##Callback callback, void* param, \ HAL_Bool initialNotify) { \ - if (joystickNum < 0 || joystickNum >= kNumJoysticks) return 0; \ + if (joystickNum < 0 || joystickNum >= kNumJoysticks) \ + return 0; \ std::scoped_lock lock(m_joystickDataMutex); \ int32_t uid = m_joystick##name##Callbacks.Register(callback, param); \ if (initialNotify) { \ @@ -79,14 +82,16 @@ void DriverStationData::ResetData() { \ void DriverStationData::GetJoystick##name(int32_t joystickNum, \ HAL_Joystick##name* d) { \ - if (joystickNum < 0 || joystickNum >= kNumJoysticks) return; \ + if (joystickNum < 0 || joystickNum >= kNumJoysticks) \ + return; \ std::scoped_lock lock(m_joystickDataMutex); \ *d = m_joystickData[joystickNum].data##data2; \ } \ \ void DriverStationData::SetJoystick##name(int32_t joystickNum, \ const HAL_Joystick##name* d) { \ - if (joystickNum < 0 || joystickNum >= kNumJoysticks) return; \ + if (joystickNum < 0 || joystickNum >= kNumJoysticks) \ + return; \ std::scoped_lock lock(m_joystickDataMutex); \ m_joystickData[joystickNum].data##data2 = *d; \ m_joystick##name##Callbacks(joystickNum, d); \ @@ -100,14 +105,18 @@ DEFINE_CPPAPI_CALLBACKS(Descriptor, descriptor, ) void DriverStationData::GetJoystickDescriptor( int32_t joystickNum, HAL_JoystickDescriptor* descriptor) { - if (joystickNum < 0 || joystickNum >= kNumJoysticks) return; + if (joystickNum < 0 || joystickNum >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); *descriptor = m_joystickData[joystickNum].descriptor; } void DriverStationData::SetJoystickDescriptor( int32_t joystickNum, const HAL_JoystickDescriptor* descriptor) { - if (joystickNum < 0 || joystickNum >= kNumJoysticks) return; + if (joystickNum < 0 || joystickNum >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[joystickNum].descriptor = *descriptor; // Always ensure name is null terminated @@ -118,8 +127,9 @@ void DriverStationData::SetJoystickDescriptor( int32_t DriverStationData::RegisterJoystickOutputsCallback( int32_t joystickNum, HAL_JoystickOutputsCallback callback, void* param, HAL_Bool initialNotify) { - if (joystickNum < 0 || joystickNum >= DriverStationData::kNumJoysticks) + if (joystickNum < 0 || joystickNum >= DriverStationData::kNumJoysticks) { return 0; + } std::scoped_lock lock(m_joystickDataMutex); int32_t uid = m_joystickOutputsCallbacks.Register(callback, param); if (initialNotify) { @@ -138,7 +148,9 @@ void DriverStationData::GetJoystickOutputs(int32_t joystickNum, int64_t* outputs, int32_t* leftRumble, int32_t* rightRumble) { - if (joystickNum < 0 || joystickNum >= kNumJoysticks) return; + if (joystickNum < 0 || joystickNum >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); *leftRumble = m_joystickData[joystickNum].outputs.leftRumble; *outputs = m_joystickData[joystickNum].outputs.outputs; @@ -148,7 +160,9 @@ void DriverStationData::GetJoystickOutputs(int32_t joystickNum, void DriverStationData::SetJoystickOutputs(int32_t joystickNum, int64_t outputs, int32_t leftRumble, int32_t rightRumble) { - if (joystickNum < 0 || joystickNum >= kNumJoysticks) return; + if (joystickNum < 0 || joystickNum >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[joystickNum].outputs.leftRumble = leftRumble; m_joystickData[joystickNum].outputs.outputs = outputs; @@ -204,23 +218,32 @@ void DriverStationData::CallNewDataCallbacks() { m_newDataCallbacks(&empty); } -void DriverStationData::NotifyNewData() { HAL_ReleaseDSMutex(); } +void DriverStationData::NotifyNewData() { + HAL_ReleaseDSMutex(); +} void DriverStationData::SetJoystickButton(int32_t stick, int32_t button, HAL_Bool state) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); - if (state) + if (state) { m_joystickData[stick].buttons.buttons |= 1 << (button - 1); - else + } else { m_joystickData[stick].buttons.buttons &= ~(1 << (button - 1)); + } m_joystickButtonsCallbacks(stick, &m_joystickData[stick].buttons); } void DriverStationData::SetJoystickAxis(int32_t stick, int32_t axis, double value) { - if (stick < 0 || stick >= kNumJoysticks) return; - if (axis < 0 || axis >= HAL_kMaxJoystickAxes) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } + if (axis < 0 || axis >= HAL_kMaxJoystickAxes) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].axes.axes[axis] = value; m_joystickAxesCallbacks(stick, &m_joystickData[stick].axes); @@ -228,22 +251,30 @@ void DriverStationData::SetJoystickAxis(int32_t stick, int32_t axis, void DriverStationData::SetJoystickPOV(int32_t stick, int32_t pov, int32_t value) { - if (stick < 0 || stick >= kNumJoysticks) return; - if (pov < 0 || pov >= HAL_kMaxJoystickPOVs) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } + if (pov < 0 || pov >= HAL_kMaxJoystickPOVs) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].povs.povs[pov] = value; m_joystickPOVsCallbacks(stick, &m_joystickData[stick].povs); } void DriverStationData::SetJoystickButtons(int32_t stick, uint32_t buttons) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].buttons.buttons = buttons; m_joystickButtonsCallbacks(stick, &m_joystickData[stick].buttons); } void DriverStationData::SetJoystickAxisCount(int32_t stick, int32_t count) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].axes.count = count; m_joystickData[stick].descriptor.axisCount = count; @@ -252,7 +283,9 @@ void DriverStationData::SetJoystickAxisCount(int32_t stick, int32_t count) { } void DriverStationData::SetJoystickPOVCount(int32_t stick, int32_t count) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].povs.count = count; m_joystickData[stick].descriptor.povCount = count; @@ -261,7 +294,9 @@ void DriverStationData::SetJoystickPOVCount(int32_t stick, int32_t count) { } void DriverStationData::SetJoystickButtonCount(int32_t stick, int32_t count) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].buttons.count = count; m_joystickData[stick].descriptor.buttonCount = count; @@ -285,21 +320,27 @@ void DriverStationData::GetJoystickCounts(int32_t stick, int32_t* axisCount, } void DriverStationData::SetJoystickIsXbox(int32_t stick, HAL_Bool isXbox) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].descriptor.isXbox = isXbox; m_joystickDescriptorCallbacks(stick, &m_joystickData[stick].descriptor); } void DriverStationData::SetJoystickType(int32_t stick, int32_t type) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].descriptor.type = type; m_joystickDescriptorCallbacks(stick, &m_joystickData[stick].descriptor); } void DriverStationData::SetJoystickName(int32_t stick, const char* name) { - if (stick < 0 || stick >= kNumJoysticks) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } std::scoped_lock lock(m_joystickDataMutex); std::strncpy(m_joystickData[stick].descriptor.name, name, sizeof(m_joystickData[stick].descriptor.name) - 1); @@ -309,8 +350,12 @@ void DriverStationData::SetJoystickName(int32_t stick, const char* name) { void DriverStationData::SetJoystickAxisType(int32_t stick, int32_t axis, int32_t type) { - if (stick < 0 || stick >= kNumJoysticks) return; - if (axis < 0 || axis >= HAL_kMaxJoystickAxes) return; + if (stick < 0 || stick >= kNumJoysticks) { + return; + } + if (axis < 0 || axis >= HAL_kMaxJoystickAxes) { + return; + } std::scoped_lock lock(m_joystickDataMutex); m_joystickData[stick].descriptor.axisTypes[axis] = type; m_joystickDescriptorCallbacks(stick, &m_joystickData[stick].descriptor); @@ -351,7 +396,9 @@ void DriverStationData::SetReplayNumber(int32_t replayNumber) { } extern "C" { -void HALSIM_ResetDriverStationData(void) { SimDriverStationData->ResetData(); } +void HALSIM_ResetDriverStationData(void) { + SimDriverStationData->ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI_NOINDEX(TYPE, HALSIM, DriverStation##CAPINAME, \ diff --git a/hal/src/main/native/sim/mockdata/DutyCycleData.cpp b/hal/src/main/native/sim/mockdata/DutyCycleData.cpp index affff89dde..21df1401a6 100644 --- a/hal/src/main/native/sim/mockdata/DutyCycleData.cpp +++ b/hal/src/main/native/sim/mockdata/DutyCycleData.cpp @@ -30,8 +30,9 @@ extern "C" { int32_t HALSIM_FindDutyCycleForChannel(int32_t channel) { for (int i = 0; i < kNumDutyCycles; ++i) { if (SimDutyCycleData[i].initialized && - SimDutyCycleData[i].digitalChannel == channel) + SimDutyCycleData[i].digitalChannel == channel) { return i; + } } return -1; } diff --git a/hal/src/main/native/sim/mockdata/EncoderData.cpp b/hal/src/main/native/sim/mockdata/EncoderData.cpp index 5b382b7592..483afd6adb 100644 --- a/hal/src/main/native/sim/mockdata/EncoderData.cpp +++ b/hal/src/main/native/sim/mockdata/EncoderData.cpp @@ -35,10 +35,13 @@ void EncoderData::ResetData() { extern "C" { int32_t HALSIM_FindEncoderForChannel(int32_t channel) { for (int i = 0; i < kNumEncoders; ++i) { - if (!SimEncoderData[i].initialized) continue; + if (!SimEncoderData[i].initialized) { + continue; + } if (SimEncoderData[i].digitalChannelA == channel || - SimEncoderData[i].digitalChannelB == channel) + SimEncoderData[i].digitalChannelB == channel) { return i; + } } return -1; } diff --git a/hal/src/main/native/sim/mockdata/I2CData.cpp b/hal/src/main/native/sim/mockdata/I2CData.cpp index b88a2891d1..b2b2689f2a 100644 --- a/hal/src/main/native/sim/mockdata/I2CData.cpp +++ b/hal/src/main/native/sim/mockdata/I2CData.cpp @@ -34,7 +34,9 @@ void I2CData::Read(int32_t deviceAddress, uint8_t* buffer, int32_t count) { } extern "C" { -void HALSIM_ResetI2CData(int32_t index) { SimI2CData[index].ResetData(); } +void HALSIM_ResetI2CData(int32_t index) { + SimI2CData[index].ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, I2C##CAPINAME, SimI2CData, \ diff --git a/hal/src/main/native/sim/mockdata/PCMData.cpp b/hal/src/main/native/sim/mockdata/PCMData.cpp index a7ae543b2c..1dac48fa86 100644 --- a/hal/src/main/native/sim/mockdata/PCMData.cpp +++ b/hal/src/main/native/sim/mockdata/PCMData.cpp @@ -31,7 +31,9 @@ void PCMData::ResetData() { } extern "C" { -void HALSIM_ResetPCMData(int32_t index) { SimPCMData[index].ResetData(); } +void HALSIM_ResetPCMData(int32_t index) { + SimPCMData[index].ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, PCM##CAPINAME, SimPCMData, \ diff --git a/hal/src/main/native/sim/mockdata/PDPData.cpp b/hal/src/main/native/sim/mockdata/PDPData.cpp index 2dfd634bfc..acfa39062e 100644 --- a/hal/src/main/native/sim/mockdata/PDPData.cpp +++ b/hal/src/main/native/sim/mockdata/PDPData.cpp @@ -27,7 +27,9 @@ void PDPData::ResetData() { } extern "C" { -void HALSIM_ResetPDPData(int32_t index) { SimPDPData[index].ResetData(); } +void HALSIM_ResetPDPData(int32_t index) { + SimPDPData[index].ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, PDP##CAPINAME, SimPDPData, \ diff --git a/hal/src/main/native/sim/mockdata/PWMData.cpp b/hal/src/main/native/sim/mockdata/PWMData.cpp index 92e010be32..7b130f8383 100644 --- a/hal/src/main/native/sim/mockdata/PWMData.cpp +++ b/hal/src/main/native/sim/mockdata/PWMData.cpp @@ -27,7 +27,9 @@ void PWMData::ResetData() { } extern "C" { -void HALSIM_ResetPWMData(int32_t index) { SimPWMData[index].ResetData(); } +void HALSIM_ResetPWMData(int32_t index) { + SimPWMData[index].ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, PWM##CAPINAME, SimPWMData, \ diff --git a/hal/src/main/native/sim/mockdata/RelayData.cpp b/hal/src/main/native/sim/mockdata/RelayData.cpp index 92161a0a13..dae81ba155 100644 --- a/hal/src/main/native/sim/mockdata/RelayData.cpp +++ b/hal/src/main/native/sim/mockdata/RelayData.cpp @@ -25,7 +25,9 @@ void RelayData::ResetData() { } extern "C" { -void HALSIM_ResetRelayData(int32_t index) { SimRelayData[index].ResetData(); } +void HALSIM_ResetRelayData(int32_t index) { + SimRelayData[index].ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, Relay##CAPINAME, SimRelayData, \ diff --git a/hal/src/main/native/sim/mockdata/RoboRioData.cpp b/hal/src/main/native/sim/mockdata/RoboRioData.cpp index 246004684a..217f2c2404 100644 --- a/hal/src/main/native/sim/mockdata/RoboRioData.cpp +++ b/hal/src/main/native/sim/mockdata/RoboRioData.cpp @@ -36,7 +36,9 @@ void RoboRioData::ResetData() { } extern "C" { -void HALSIM_ResetRoboRioData(void) { SimRoboRioData->ResetData(); } +void HALSIM_ResetRoboRioData(void) { + SimRoboRioData->ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI_NOINDEX(TYPE, HALSIM, RoboRio##CAPINAME, \ diff --git a/hal/src/main/native/sim/mockdata/SPIData.cpp b/hal/src/main/native/sim/mockdata/SPIData.cpp index 6d8678b10c..c32ec83e81 100644 --- a/hal/src/main/native/sim/mockdata/SPIData.cpp +++ b/hal/src/main/native/sim/mockdata/SPIData.cpp @@ -49,7 +49,9 @@ int32_t SPIData::ReadAutoReceivedData(uint32_t* buffer, int32_t numToRead, } extern "C" { -void HALSIM_ResetSPIData(int32_t index) { SimSPIData[index].ResetData(); } +void HALSIM_ResetSPIData(int32_t index) { + SimSPIData[index].ResetData(); +} #define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \ HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, SPI##CAPINAME, SimSPIData, \ diff --git a/hal/src/main/native/sim/mockdata/SimDeviceData.cpp b/hal/src/main/native/sim/mockdata/SimDeviceData.cpp index 41ebbd81a3..f1bab9f82b 100644 --- a/hal/src/main/native/sim/mockdata/SimDeviceData.cpp +++ b/hal/src/main/native/sim/mockdata/SimDeviceData.cpp @@ -22,26 +22,34 @@ void InitializeSimDeviceData() { SimDeviceData* hal::SimSimDeviceData; SimDeviceData::Device* SimDeviceData::LookupDevice(HAL_SimDeviceHandle handle) { - if (handle <= 0) return nullptr; - --handle; - if (static_cast(handle) >= m_devices.size() || !m_devices[handle]) + if (handle <= 0) { return nullptr; + } + --handle; + if (static_cast(handle) >= m_devices.size() || !m_devices[handle]) { + return nullptr; + } return m_devices[handle].get(); } SimDeviceData::Value* SimDeviceData::LookupValue(HAL_SimValueHandle handle) { - if (handle <= 0) return nullptr; + if (handle <= 0) { + return nullptr; + } // look up device Device* deviceImpl = LookupDevice(handle >> 16); - if (!deviceImpl) return nullptr; + if (!deviceImpl) { + return nullptr; + } // look up value handle &= 0xffff; --handle; if (static_cast(handle) >= deviceImpl->values.size() || - !deviceImpl->values[handle]) + !deviceImpl->values[handle]) { return nullptr; + } return deviceImpl->values[handle].get(); } @@ -65,7 +73,9 @@ void SimDeviceData::SetDeviceEnabled(const char* prefix, bool enabled) { bool SimDeviceData::IsDeviceEnabled(const char* name) { std::scoped_lock lock(m_mutex); for (const auto& elem : m_prefixEnabled) { - if (wpi::StringRef{name}.startswith(elem.first)) return elem.second; + if (wpi::StringRef{name}.startswith(elem.first)) { + return elem.second; + } } return true; } @@ -76,17 +86,23 @@ HAL_SimDeviceHandle SimDeviceData::CreateDevice(const char* name) { // don't create if disabled for (const auto& elem : m_prefixEnabled) { if (wpi::StringRef{name}.startswith(elem.first)) { - if (elem.second) break; // enabled - return 0; // disabled + if (elem.second) { + break; // enabled + } + return 0; // disabled } } // check for duplicates and don't overwrite them - if (m_deviceMap.count(name) > 0) return 0; + if (m_deviceMap.count(name) > 0) { + return 0; + } // don't allow more than 4096 devices (limit driven by 12-bit allocation in // value changed callback uid) - if (m_devices.size() >= 4095) return 0; + if (m_devices.size() >= 4095) { + return 0; + } // create and save auto deviceImpl = std::make_shared(name); @@ -105,9 +121,13 @@ void SimDeviceData::FreeDevice(HAL_SimDeviceHandle handle) { --handle; // see if it exists - if (handle < 0 || static_cast(handle) >= m_devices.size()) return; + if (handle < 0 || static_cast(handle) >= m_devices.size()) { + return; + } auto deviceImpl = std::move(m_devices[handle]); - if (!deviceImpl) return; + if (!deviceImpl) { + return; + } // remove from map m_deviceMap.erase(deviceImpl->name); @@ -127,15 +147,21 @@ HAL_SimValueHandle SimDeviceData::CreateValue( // look up device Device* deviceImpl = LookupDevice(device); - if (!deviceImpl) return 0; + if (!deviceImpl) { + return 0; + } // check for duplicates and don't overwrite them auto it = deviceImpl->valueMap.find(name); - if (it != deviceImpl->valueMap.end()) return 0; + if (it != deviceImpl->valueMap.end()) { + return 0; + } // don't allow more than 4096 values per device (limit driven by 12-bit // allocation in value changed callback uid) - if (deviceImpl->values.size() >= 4095) return 0; + if (deviceImpl->values.size() >= 4095) { + return 0; + } // create and save; encode device into handle auto valueImplPtr = std::make_unique(name, direction, initialValue); @@ -185,7 +211,9 @@ void SimDeviceData::SetValue(HAL_SimValueHandle handle, const HAL_Value& value) { std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); - if (!valueImpl) return; + if (!valueImpl) { + return; + } valueImpl->value = value; @@ -205,8 +233,9 @@ int32_t SimDeviceData::RegisterDeviceCreatedCallback( // initial notifications if (initialNotify) { for (auto&& device : m_devices) { - if (wpi::StringRef{device->name}.startswith(prefix)) + if (wpi::StringRef{device->name}.startswith(prefix)) { callback(device->name.c_str(), param, device->handle); + } } } @@ -214,7 +243,9 @@ int32_t SimDeviceData::RegisterDeviceCreatedCallback( } void SimDeviceData::CancelDeviceCreatedCallback(int32_t uid) { - if (uid <= 0) return; + if (uid <= 0) { + return; + } std::scoped_lock lock(m_mutex); m_deviceCreated.Cancel(uid); } @@ -226,7 +257,9 @@ int32_t SimDeviceData::RegisterDeviceFreedCallback( } void SimDeviceData::CancelDeviceFreedCallback(int32_t uid) { - if (uid <= 0) return; + if (uid <= 0) { + return; + } std::scoped_lock lock(m_mutex); m_deviceFreed.Cancel(uid); } @@ -234,11 +267,14 @@ void SimDeviceData::CancelDeviceFreedCallback(int32_t uid) { HAL_SimDeviceHandle SimDeviceData::GetDeviceHandle(const char* name) { std::scoped_lock lock(m_mutex); auto it = m_deviceMap.find(name); - if (it == m_deviceMap.end()) return 0; - if (auto deviceImpl = it->getValue().lock()) - return deviceImpl->handle; - else + if (it == m_deviceMap.end()) { return 0; + } + if (auto deviceImpl = it->getValue().lock()) { + return deviceImpl->handle; + } else { + return 0; + } } const char* SimDeviceData::GetDeviceName(HAL_SimDeviceHandle handle) { @@ -246,7 +282,9 @@ const char* SimDeviceData::GetDeviceName(HAL_SimDeviceHandle handle) { // look up device Device* deviceImpl = LookupDevice(handle); - if (!deviceImpl) return nullptr; + if (!deviceImpl) { + return nullptr; + } return deviceImpl->name.c_str(); } @@ -255,8 +293,9 @@ void SimDeviceData::EnumerateDevices(const char* prefix, void* param, HALSIM_SimDeviceCallback callback) { std::scoped_lock lock(m_mutex); for (auto&& device : m_devices) { - if (wpi::StringRef{device->name}.startswith(prefix)) + if (wpi::StringRef{device->name}.startswith(prefix)) { callback(device->name.c_str(), param, device->handle); + } } } @@ -265,16 +304,19 @@ int32_t SimDeviceData::RegisterValueCreatedCallback( bool initialNotify) { std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(device); - if (!deviceImpl) return -1; + if (!deviceImpl) { + return -1; + } // register callback int32_t index = deviceImpl->valueCreated.Register(callback, param); // initial notifications if (initialNotify) { - for (auto&& value : deviceImpl->values) + for (auto&& value : deviceImpl->values) { callback(value->name.c_str(), param, value->handle, value->direction, &value->value); + } } // encode device into uid @@ -282,10 +324,14 @@ int32_t SimDeviceData::RegisterValueCreatedCallback( } void SimDeviceData::CancelValueCreatedCallback(int32_t uid) { - if (uid <= 0) return; + if (uid <= 0) { + return; + } std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(uid >> 16); - if (!deviceImpl) return; + if (!deviceImpl) { + return; + } deviceImpl->valueCreated.Cancel(uid & 0xffff); } @@ -294,15 +340,18 @@ int32_t SimDeviceData::RegisterValueChangedCallback( bool initialNotify) { std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); - if (!valueImpl) return -1; + if (!valueImpl) { + return -1; + } // register callback int32_t index = valueImpl->changed.Register(callback, param); // initial notification - if (initialNotify) + if (initialNotify) { callback(valueImpl->name.c_str(), param, valueImpl->handle, valueImpl->direction, &valueImpl->value); + } // encode device and value into uid return (((handle >> 16) & 0xfff) << 19) | ((handle & 0xfff) << 7) | @@ -310,10 +359,14 @@ int32_t SimDeviceData::RegisterValueChangedCallback( } void SimDeviceData::CancelValueChangedCallback(int32_t uid) { - if (uid <= 0) return; + if (uid <= 0) { + return; + } std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(((uid >> 19) << 16) | ((uid >> 7) & 0xfff)); - if (!valueImpl) return; + if (!valueImpl) { + return; + } valueImpl->changed.Cancel(uid & 0x7f); } @@ -321,12 +374,18 @@ HAL_SimValueHandle SimDeviceData::GetValueHandle(HAL_SimDeviceHandle device, const char* name) { std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(device); - if (!deviceImpl) return 0; + if (!deviceImpl) { + return 0; + } // lookup value auto it = deviceImpl->valueMap.find(name); - if (it == deviceImpl->valueMap.end()) return 0; - if (!it->getValue()) return 0; + if (it == deviceImpl->valueMap.end()) { + return 0; + } + if (!it->getValue()) { + return 0; + } return it->getValue()->handle; } @@ -334,11 +393,14 @@ void SimDeviceData::EnumerateValues(HAL_SimDeviceHandle device, void* param, HALSIM_SimValueCallback callback) { std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(device); - if (!deviceImpl) return; + if (!deviceImpl) { + return; + } - for (auto&& value : deviceImpl->values) + for (auto&& value : deviceImpl->values) { callback(value->name.c_str(), param, value->handle, value->direction, &value->value); + } } const char** SimDeviceData::GetValueEnumOptions(HAL_SimValueHandle handle, @@ -347,7 +409,9 @@ const char** SimDeviceData::GetValueEnumOptions(HAL_SimValueHandle handle, std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); - if (!valueImpl) return nullptr; + if (!valueImpl) { + return nullptr; + } // get list of options (safe to return as they never change) auto& options = valueImpl->cstrEnumOptions; @@ -361,7 +425,9 @@ const double* SimDeviceData::GetValueEnumDoubleValues(HAL_SimValueHandle handle, std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); - if (!valueImpl) return nullptr; + if (!valueImpl) { + return nullptr; + } // get list of option values (safe to return as they never change) auto& optionValues = valueImpl->enumOptionValues; @@ -418,7 +484,9 @@ const char* HALSIM_GetSimDeviceName(HAL_SimDeviceHandle handle) { } HAL_SimDeviceHandle HALSIM_GetSimValueDeviceHandle(HAL_SimValueHandle handle) { - if (handle <= 0) return 0; + if (handle <= 0) { + return 0; + } return handle >> 16; } @@ -471,6 +539,8 @@ const double* HALSIM_GetSimValueEnumDoubleValues(HAL_SimValueHandle handle, return SimSimDeviceData->GetValueEnumDoubleValues(handle, numOptions); } -void HALSIM_ResetSimDeviceData(void) { SimSimDeviceData->ResetData(); } +void HALSIM_ResetSimDeviceData(void) { + SimSimDeviceData->ResetData(); +} } // extern "C" diff --git a/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h b/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h index bd6189e4f7..347e61562b 100644 --- a/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h +++ b/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h @@ -33,17 +33,25 @@ class SimUnnamedCallbackRegistry { public: void Cancel(int32_t uid) { - if (m_callbacks) m_callbacks->erase(uid - 1); + if (m_callbacks) { + m_callbacks->erase(uid - 1); + } } void Reset() { - if (m_callbacks) m_callbacks->clear(); + if (m_callbacks) { + m_callbacks->clear(); + } } int32_t Register(CallbackFunction callback, void* param) { // Must return -1 on a null callback for error handling - if (callback == nullptr) return -1; - if (!m_callbacks) m_callbacks = std::make_unique(); + if (callback == nullptr) { + return -1; + } + if (!m_callbacks) { + m_callbacks = std::make_unique(); + } return m_callbacks->emplace_back(param, reinterpret_cast(callback)) + 1; @@ -84,17 +92,25 @@ class SimPrefixCallbackRegistry { public: void Cancel(int32_t uid) { - if (m_callbacks) m_callbacks->erase(uid - 1); + if (m_callbacks) { + m_callbacks->erase(uid - 1); + } } void Reset() { - if (m_callbacks) m_callbacks->clear(); + if (m_callbacks) { + m_callbacks->clear(); + } } int32_t Register(const char* prefix, void* param, CallbackFunction callback) { // Must return -1 on a null callback for error handling - if (callback == nullptr) return -1; - if (!m_callbacks) m_callbacks = std::make_unique(); + if (callback == nullptr) { + return -1; + } + if (!m_callbacks) { + m_callbacks = std::make_unique(); + } return m_callbacks->emplace_back(prefix, param, callback) + 1; } diff --git a/myRobot/src/main/native/cpp/MyRobot.cpp b/myRobot/src/main/native/cpp/MyRobot.cpp index 3896e9fc9a..f339b95a84 100644 --- a/myRobot/src/main/native/cpp/MyRobot.cpp +++ b/myRobot/src/main/native/cpp/MyRobot.cpp @@ -42,4 +42,6 @@ class MyRobot : public frc::TimedRobot { void RobotPeriodic() override {} }; -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} diff --git a/ntcore/manualTests/native/client.cpp b/ntcore/manualTests/native/client.cpp index 4af9fcdf5e..f9466738e6 100644 --- a/ntcore/manualTests/native/client.cpp +++ b/ntcore/manualTests/native/client.cpp @@ -23,8 +23,9 @@ int main() { auto foo = nt::GetEntry(inst, "/foo"); auto foo_val = nt::GetEntryValue(foo); - if (foo_val && foo_val->IsDouble()) + if (foo_val && foo_val->IsDouble()) { std::printf("Got foo: %g\n", foo_val->GetDouble()); + } auto bar = nt::GetEntry(inst, "/bar"); nt::SetEntryValue(bar, nt::Value::MakeBoolean(false)); diff --git a/ntcore/src/main/native/cpp/CallbackManager.h b/ntcore/src/main/native/cpp/CallbackManager.h index 91bc5af113..9360a92a17 100644 --- a/ntcore/src/main/native/cpp/CallbackManager.h +++ b/ntcore/src/main/native/cpp/CallbackManager.h @@ -57,7 +57,9 @@ class CallbackThread : public wpi::SafeThread { ~CallbackThread() { // Wake up any blocked pollers for (size_t i = 0; i < m_pollers.size(); ++i) { - if (auto poller = m_pollers[i]) poller->Terminate(); + if (auto poller = m_pollers[i]) { + poller->Terminate(); + } } } @@ -87,9 +89,13 @@ class CallbackThread : public wpi::SafeThread { // Must be called with m_mutex held template void SendPoller(unsigned int poller_uid, Args&&... args) { - if (poller_uid > m_pollers.size()) return; + if (poller_uid > m_pollers.size()) { + return; + } auto poller = m_pollers[poller_uid]; - if (!poller) return; + if (!poller) { + return; + } { std::scoped_lock lock(poller->poll_mutex); poller->poll_queue.emplace(std::forward(args)...); @@ -105,11 +111,15 @@ void CallbackThread::Main() { while (m_active) { while (m_queue.empty()) { m_cond.wait(lock); - if (!m_active) return; + if (!m_active) { + return; + } } while (!m_queue.empty()) { - if (!m_active) return; + if (!m_active) { + return; + } auto item = std::move(m_queue.front()); if (item.first != UINT_MAX) { @@ -132,9 +142,12 @@ void CallbackThread::Main() { // Use index because iterator might get invalidated. for (size_t i = 0; i < m_listeners.size(); ++i) { auto& listener = m_listeners[i]; - if (!listener) continue; - if (!static_cast(this)->Matches(listener, item.second)) + if (!listener) { continue; + } + if (!static_cast(this)->Matches(listener, item.second)) { + continue; + } static_cast(this)->SetListener(&item.second, static_cast(i)); if (listener.callback) { @@ -171,7 +184,9 @@ class CallbackManager { void Remove(unsigned int listener_uid) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_listeners.erase(listener_uid); } @@ -184,37 +199,52 @@ class CallbackManager { void RemovePoller(unsigned int poller_uid) { auto thr = m_owner.GetThread(); - if (!thr) return; + if (!thr) { + return; + } // Remove any listeners that are associated with this poller for (size_t i = 0; i < thr->m_listeners.size(); ++i) { - if (thr->m_listeners[i].poller_uid == poller_uid) + if (thr->m_listeners[i].poller_uid == poller_uid) { thr->m_listeners.erase(i); + } } // Wake up any blocked pollers - if (poller_uid >= thr->m_pollers.size()) return; + if (poller_uid >= thr->m_pollers.size()) { + return; + } auto poller = thr->m_pollers[poller_uid]; - if (!poller) return; + if (!poller) { + return; + } poller->Terminate(); return thr->m_pollers.erase(poller_uid); } bool WaitForQueue(double timeout) { auto thr = m_owner.GetThread(); - if (!thr) return true; + if (!thr) { + return true; + } auto& lock = thr.GetLock(); auto timeout_time = std::chrono::steady_clock::now() + std::chrono::duration(timeout); while (!thr->m_queue.empty()) { - if (!thr->m_active) return true; - if (timeout == 0) return false; + if (!thr->m_active) { + return true; + } + if (timeout == 0) { + return false; + } if (timeout < 0) { thr->m_queue_empty.wait(lock); } else { auto cond_timed_out = thr->m_queue_empty.wait_until(lock, timeout_time); - if (cond_timed_out == std::cv_status::timeout) return false; + if (cond_timed_out == std::cv_status::timeout) { + return false; + } } } @@ -232,10 +262,16 @@ class CallbackManager { std::shared_ptr poller; { auto thr = m_owner.GetThread(); - if (!thr) return infos; - if (poller_uid > thr->m_pollers.size()) return infos; + if (!thr) { + return infos; + } + if (poller_uid > thr->m_pollers.size()) { + return infos; + } poller = thr->m_pollers[poller_uid]; - if (!poller) return infos; + if (!poller) { + return infos; + } } std::unique_lock lock(poller->poll_mutex); @@ -243,7 +279,9 @@ class CallbackManager { std::chrono::duration(timeout); *timed_out = false; while (poller->poll_queue.empty()) { - if (poller->terminating) return infos; + if (poller->terminating) { + return infos; + } if (poller->canceling) { // Note: this only works if there's a single thread calling this // function for any particular poller, but that's the intended use. @@ -276,10 +314,16 @@ class CallbackManager { std::shared_ptr poller; { auto thr = m_owner.GetThread(); - if (!thr) return; - if (poller_uid > thr->m_pollers.size()) return; + if (!thr) { + return; + } + if (poller_uid > thr->m_pollers.size()) { + return; + } poller = thr->m_pollers[poller_uid]; - if (!poller) return; + if (!poller) { + return; + } } { @@ -305,7 +349,9 @@ class CallbackManager { template void Send(unsigned int only_listener, Args&&... args) { auto thr = m_owner.GetThread(); - if (!thr || thr->m_listeners.empty()) return; + if (!thr || thr->m_listeners.empty()) { + return; + } thr->m_queue.emplace(std::piecewise_construct, std::make_tuple(only_listener), std::forward_as_tuple(std::forward(args)...)); diff --git a/ntcore/src/main/native/cpp/ConnectionNotifier.cpp b/ntcore/src/main/native/cpp/ConnectionNotifier.cpp index e4a20ab693..60e730349a 100644 --- a/ntcore/src/main/native/cpp/ConnectionNotifier.cpp +++ b/ntcore/src/main/native/cpp/ConnectionNotifier.cpp @@ -8,7 +8,9 @@ using namespace nt; ConnectionNotifier::ConnectionNotifier(int inst) : m_inst(inst) {} -void ConnectionNotifier::Start() { DoStart(m_inst); } +void ConnectionNotifier::Start() { + DoStart(m_inst); +} unsigned int ConnectionNotifier::Add( std::function callback) { diff --git a/ntcore/src/main/native/cpp/Dispatcher.cpp b/ntcore/src/main/native/cpp/Dispatcher.cpp index 86f1b160a9..484a6063ec 100644 --- a/ntcore/src/main/native/cpp/Dispatcher.cpp +++ b/ntcore/src/main/native/cpp/Dispatcher.cpp @@ -38,14 +38,16 @@ void Dispatcher::SetServer(const char* server_name, unsigned int port) { void Dispatcher::SetServer( ArrayRef> servers) { wpi::SmallVector, 16> servers_copy; - for (const auto& server : servers) + for (const auto& server : servers) { servers_copy.emplace_back(std::string{server.first.trim()}, static_cast(server.second)); + } SetConnector([=]() -> std::unique_ptr { wpi::SmallVector, 16> servers_copy2; - for (const auto& server : servers_copy) + for (const auto& server : servers_copy) { servers_copy2.emplace_back(server.first.c_str(), server.second); + } return wpi::TCPConnector::connect_parallel(servers_copy2, m_logger, 1); }); } @@ -100,7 +102,9 @@ void Dispatcher::SetServerOverride(const char* server_name, unsigned int port) { }); } -void Dispatcher::ClearServerOverride() { ClearConnectorOverride(); } +void Dispatcher::ClearServerOverride() { + ClearConnectorOverride(); +} DispatcherBase::DispatcherBase(IStorage& storage, IConnectionNotifier& notifier, wpi::Logger& logger) @@ -109,14 +113,20 @@ DispatcherBase::DispatcherBase(IStorage& storage, IConnectionNotifier& notifier, m_update_rate = 100; } -DispatcherBase::~DispatcherBase() { Stop(); } +DispatcherBase::~DispatcherBase() { + Stop(); +} -unsigned int DispatcherBase::GetNetworkMode() const { return m_networkMode; } +unsigned int DispatcherBase::GetNetworkMode() const { + return m_networkMode; +} void DispatcherBase::StartLocal() { { std::scoped_lock lock(m_user_mutex); - if (m_active) return; + if (m_active) { + return; + } m_active = true; } m_networkMode = NT_NET_MODE_LOCAL; @@ -128,7 +138,9 @@ void DispatcherBase::StartServer( std::unique_ptr acceptor) { { std::scoped_lock lock(m_user_mutex); - if (m_active) return; + if (m_active) { + return; + } m_active = true; } m_networkMode = NT_NET_MODE_SERVER | NT_NET_MODE_STARTING; @@ -160,7 +172,9 @@ void DispatcherBase::StartServer( void DispatcherBase::StartClient() { { std::scoped_lock lock(m_user_mutex); - if (m_active) return; + if (m_active) { + return; + } m_active = true; } m_networkMode = NT_NET_MODE_CLIENT | NT_NET_MODE_STARTING; @@ -184,11 +198,17 @@ void DispatcherBase::Stop() { ClientReconnect(); // wake up server thread by shutting down the socket - if (m_server_acceptor) m_server_acceptor->shutdown(); + if (m_server_acceptor) { + m_server_acceptor->shutdown(); + } // join threads, with timeout - if (m_dispatch_thread.joinable()) m_dispatch_thread.join(); - if (m_clientserver_thread.joinable()) m_clientserver_thread.join(); + if (m_dispatch_thread.joinable()) { + m_dispatch_thread.join(); + } + if (m_clientserver_thread.joinable()) { + m_clientserver_thread.join(); + } std::vector> conns; { @@ -202,10 +222,11 @@ void DispatcherBase::Stop() { void DispatcherBase::SetUpdateRate(double interval) { // don't allow update rates faster than 5 ms or slower than 1 second - if (interval < 0.005) + if (interval < 0.005) { interval = 0.005; - else if (interval > 1.0) + } else if (interval > 1.0) { interval = 1.0; + } m_update_rate = static_cast(interval * 1000); } @@ -219,7 +240,9 @@ void DispatcherBase::Flush() { { std::scoped_lock lock(m_flush_mutex); // don't allow flushes more often than every 5 ms - if ((now - m_last_flush) < 5000) return; + if ((now - m_last_flush) < 5000) { + return; + } m_last_flush = now; m_do_flush = true; } @@ -228,11 +251,15 @@ void DispatcherBase::Flush() { std::vector DispatcherBase::GetConnections() const { std::vector conns; - if (!m_active) return conns; + if (!m_active) { + return conns; + } std::scoped_lock lock(m_user_mutex); for (auto& conn : m_connections) { - if (conn->state() != NetworkConnection::kActive) continue; + if (conn->state() != NetworkConnection::kActive) { + continue; + } conns.emplace_back(conn->info()); } @@ -240,13 +267,19 @@ std::vector DispatcherBase::GetConnections() const { } bool DispatcherBase::IsConnected() const { - if (!m_active) return false; + if (!m_active) { + return false; + } - if (m_networkMode == NT_NET_MODE_LOCAL) return true; + if (m_networkMode == NT_NET_MODE_LOCAL) { + return true; + } std::scoped_lock lock(m_user_mutex); for (auto& conn : m_connections) { - if (conn->state() == NetworkConnection::kActive) return true; + if (conn->state() == NetworkConnection::kActive) { + return true; + } } return false; @@ -260,7 +293,9 @@ unsigned int DispatcherBase::AddListener( // perform immediate notifications if (immediate_notify) { for (auto& conn : m_connections) { - if (conn->state() != NetworkConnection::kActive) continue; + if (conn->state() != NetworkConnection::kActive) { + continue; + } m_notifier.NotifyConnection(true, conn->info(), uid); } } @@ -274,7 +309,9 @@ unsigned int DispatcherBase::AddPolledListener(unsigned int poller_uid, // perform immediate notifications if (immediate_notify) { for (auto& conn : m_connections) { - if (conn->state() != NetworkConnection::kActive) continue; + if (conn->state() != NetworkConnection::kActive) { + continue; + } m_notifier.NotifyConnection(true, conn->info(), uid); } } @@ -307,7 +344,9 @@ void DispatcherBase::DispatchThreadMain() { while (m_active) { // handle loop taking too long auto start = std::chrono::steady_clock::now(); - if (start > timeout_time) timeout_time = start; + if (start > timeout_time) { + timeout_time = start; + } // wait for periodic or when flushed timeout_time += std::chrono::milliseconds(m_update_rate); @@ -316,16 +355,22 @@ void DispatcherBase::DispatchThreadMain() { [&] { return !m_active || m_do_flush; }); m_do_flush = false; flush_lock.unlock(); - if (!m_active) break; // in case we were woken up to terminate + if (!m_active) { + break; // in case we were woken up to terminate + } // perform periodic persistent save if ((m_networkMode & NT_NET_MODE_SERVER) != 0 && !m_persist_filename.empty() && start > next_save_time) { next_save_time += save_delta_time; // handle loop taking too long - if (start > next_save_time) next_save_time = start + save_delta_time; + if (start > next_save_time) { + next_save_time = start + save_delta_time; + } const char* err = m_storage.SavePersistent(m_persist_filename, true); - if (err) WARNING("periodic persistent save: " << err); + if (err) { + WARNING("periodic persistent save: " << err); + } } { @@ -340,13 +385,15 @@ void DispatcherBase::DispatchThreadMain() { for (auto& conn : m_connections) { // post outgoing messages if connection is active // only send keep-alives on client - if (conn->state() == NetworkConnection::kActive) + if (conn->state() == NetworkConnection::kActive) { conn->PostOutgoing((m_networkMode & NT_NET_MODE_CLIENT) != 0); + } // if client, reconnect if connection died if ((m_networkMode & NT_NET_MODE_CLIENT) != 0 && - conn->state() == NetworkConnection::kDead) + conn->state() == NetworkConnection::kDead) { reconnect = true; + } } // reconnect if we disconnected (and a reconnect is not in progress) if (reconnect && !m_do_reconnect) { @@ -362,12 +409,17 @@ void DispatcherBase::QueueOutgoing(std::shared_ptr msg, INetworkConnection* except) { std::scoped_lock user_lock(m_user_mutex); for (auto& conn : m_connections) { - if (conn.get() == except) continue; - if (only && conn.get() != only) continue; + if (conn.get() == except) { + continue; + } + if (only && conn.get() != only) { + continue; + } auto state = conn->state(); if (state != NetworkConnection::kSynchronized && - state != NetworkConnection::kActive) + state != NetworkConnection::kActive) { continue; + } conn->QueueOutgoing(msg); } } @@ -412,7 +464,9 @@ void DispatcherBase::ServerThreadMain() { break; } } - if (!placed) m_connections.emplace_back(conn); + if (!placed) { + m_connections.emplace_back(conn); + } conn->Start(); } } @@ -496,16 +550,22 @@ bool DispatcherBase::ClientHandshake( } if (msg->Is(Message::kProtoUnsup)) { - if (msg->id() == 0x0200) ClientReconnect(0x0200); + if (msg->id() == 0x0200) { + ClientReconnect(0x0200); + } return false; } bool new_server = true; if (conn.proto_rev() >= 0x0300) { // should be server hello; if not, disconnect. - if (!msg->Is(Message::kServerHello)) return false; + if (!msg->Is(Message::kServerHello)) { + return false; + } conn.set_remote_id(msg->str()); - if ((msg->flags() & 1) != 0) new_server = false; + if ((msg->flags() & 1) != 0) { + new_server = false; + } // get the next message msg = get_msg(); } @@ -520,7 +580,9 @@ bool DispatcherBase::ClientHandshake( } DEBUG4("received init str=" << msg->str() << " id=" << msg->id() << " seq_num=" << msg->seq_num_uid()); - if (msg->Is(Message::kServerHelloDone)) break; + if (msg->Is(Message::kServerHelloDone)) { + break; + } // shouldn't receive a keep alive, but handle gracefully if (msg->Is(Message::kKeepAlive)) { msg = get_msg(); @@ -543,10 +605,13 @@ bool DispatcherBase::ClientHandshake( m_storage.ApplyInitialAssignments(conn, incoming, new_server, &outgoing); - if (conn.proto_rev() >= 0x0300) + if (conn.proto_rev() >= 0x0300) { outgoing.emplace_back(Message::ClientHelloDone()); + } - if (!outgoing.empty()) send_msgs(outgoing); + if (!outgoing.empty()) { + send_msgs(outgoing); + } INFO("client: CONNECTED to server " << conn.stream().getPeerIP() << " port " << conn.stream().getPeerPort()); @@ -575,7 +640,9 @@ bool DispatcherBase::ServerHandshake( return false; } - if (proto_rev >= 0x0300) conn.set_remote_id(msg->str()); + if (proto_rev >= 0x0300) { + conn.set_remote_id(msg->str()); + } // Set the proto version to the client requested version DEBUG0("server: client protocol " << proto_rev); @@ -614,7 +681,9 @@ bool DispatcherBase::ServerHandshake( DEBUG0("server: disconnected waiting for initial entries"); return false; } - if (msg->Is(Message::kClientHelloDone)) break; + if (msg->Is(Message::kClientHelloDone)) { + break; + } // shouldn't receive a keep alive, but handle gracefully if (msg->Is(Message::kKeepAlive)) { msg = get_msg(); @@ -631,8 +700,9 @@ bool DispatcherBase::ServerHandshake( // get the next message (blocks) msg = get_msg(); } - for (auto& msg : incoming) + for (auto& msg : incoming) { m_storage.ProcessIncoming(msg, &conn, std::weak_ptr()); + } } INFO("server: client CONNECTED: " << conn.stream().getPeerIP() << " port " @@ -641,7 +711,9 @@ bool DispatcherBase::ServerHandshake( } void DispatcherBase::ClientReconnect(unsigned int proto_rev) { - if ((m_networkMode & NT_NET_MODE_SERVER) != 0) return; + if ((m_networkMode & NT_NET_MODE_SERVER) != 0) { + return; + } { std::scoped_lock lock(m_user_mutex); m_reconnect_proto_rev = proto_rev; diff --git a/ntcore/src/main/native/cpp/DsClient.cpp b/ntcore/src/main/native/cpp/DsClient.cpp index c97670f197..5cdece80c5 100644 --- a/ntcore/src/main/native/cpp/DsClient.cpp +++ b/ntcore/src/main/native/cpp/DsClient.cpp @@ -32,10 +32,11 @@ DsClient::DsClient(Dispatcher& dispatcher, wpi::Logger& logger) void DsClient::Start(unsigned int port) { auto thr = m_owner.GetThread(); - if (!thr) + if (!thr) { m_owner.Start(m_dispatcher, m_logger, port); - else + } else { thr->m_port = port; + } } void DsClient::Stop() { @@ -44,7 +45,9 @@ void DsClient::Stop() { auto thr = m_owner.GetThread(); if (thr) { thr->m_active = false; - if (thr->m_stream) thr->m_stream->close(); + if (thr->m_stream) { + thr->m_stream->close(); + } } } m_owner.Stop(); @@ -64,12 +67,18 @@ void DsClient::Thread::Main() { m_cond.wait_until(lock, timeout_time, [&] { return !m_active; }); port = m_port; } - if (!m_active) goto done; + if (!m_active) { + goto done; + } // Try to connect to DS on the local machine m_stream = wpi::TCPConnector::connect("127.0.0.1", 1742, nolog, 1); - if (!m_active) goto done; - if (!m_stream) continue; + if (!m_active) { + goto done; + } + if (!m_stream) { + continue; + } DEBUG3("connected to DS"); wpi::raw_socket_istream is(*m_stream); @@ -83,8 +92,12 @@ void DsClient::Thread::Main() { // Throw away characters until { do { is.read(ch); - if (is.has_error()) break; - if (!m_active) goto done; + if (is.has_error()) { + break; + } + if (!m_active) { + goto done; + } } while (ch != '{'); json += '{'; @@ -96,8 +109,12 @@ void DsClient::Thread::Main() { // Read characters until } do { is.read(ch); - if (is.has_error()) break; - if (!m_active) goto done; + if (is.has_error()) { + break; + } + if (!m_active) { + goto done; + } json += ch; } while (ch != '}'); @@ -109,16 +126,22 @@ void DsClient::Thread::Main() { // Look for "robotIP":12345, and get 12345 portion size_t pos = json.find("\"robotIP\""); - if (pos == wpi::StringRef::npos) continue; // could not find? + if (pos == wpi::StringRef::npos) { + continue; // could not find? + } pos += 9; pos = json.find(':', pos); - if (pos == wpi::StringRef::npos) continue; // could not find? + if (pos == wpi::StringRef::npos) { + continue; // could not find? + } size_t endpos = json.find_first_not_of("0123456789", pos + 1); DEBUG3("found robotIP=" << json.slice(pos + 1, endpos)); // Parse into number unsigned int ip = 0; - if (json.slice(pos + 1, endpos).getAsInteger(10, ip)) continue; // error + if (json.slice(pos + 1, endpos).getAsInteger(10, ip)) { + continue; // error + } // If zero, clear the server override if (ip == 0) { @@ -128,7 +151,9 @@ void DsClient::Thread::Main() { } // If unchanged, don't reconnect - if (ip == oldip) continue; + if (ip == oldip) { + continue; + } oldip = ip; // Convert number into dotted quad diff --git a/ntcore/src/main/native/cpp/EntryNotifier.cpp b/ntcore/src/main/native/cpp/EntryNotifier.cpp index 41196c410b..81861dfd98 100644 --- a/ntcore/src/main/native/cpp/EntryNotifier.cpp +++ b/ntcore/src/main/native/cpp/EntryNotifier.cpp @@ -13,13 +13,19 @@ EntryNotifier::EntryNotifier(int inst, wpi::Logger& logger) m_local_notifiers = false; } -void EntryNotifier::Start() { DoStart(m_inst); } +void EntryNotifier::Start() { + DoStart(m_inst); +} -bool EntryNotifier::local_notifiers() const { return m_local_notifiers; } +bool EntryNotifier::local_notifiers() const { + return m_local_notifiers; +} bool impl::EntryNotifierThread::Matches(const EntryListenerData& listener, const EntryNotification& data) { - if (!data.value) return false; + if (!data.value) { + return false; + } // Flags must be within requested flag set for this listener. // Because assign messages can result in both a value and flags update, @@ -29,17 +35,24 @@ bool impl::EntryNotifierThread::Matches(const EntryListenerData& listener, unsigned int flags = data.flags & ~(NT_NOTIFY_IMMEDIATE | NT_NOTIFY_LOCAL); unsigned int assign_both = NT_NOTIFY_UPDATE | NT_NOTIFY_FLAGS; if ((flags & assign_both) == assign_both) { - if ((listen_flags & assign_both) == 0) return false; + if ((listen_flags & assign_both) == 0) { + return false; + } listen_flags &= ~assign_both; flags &= ~assign_both; } - if ((flags & ~listen_flags) != 0) return false; + if ((flags & ~listen_flags) != 0) { + return false; + } // must match local id or prefix - if (listener.entry != 0 && data.entry != listener.entry) return false; - if (listener.entry == 0 && - !wpi::StringRef(data.name).startswith(listener.prefix)) + if (listener.entry != 0 && data.entry != listener.entry) { return false; + } + if (listener.entry == 0 && + !wpi::StringRef(data.name).startswith(listener.prefix)) { + return false; + } return true; } @@ -47,28 +60,36 @@ bool impl::EntryNotifierThread::Matches(const EntryListenerData& listener, unsigned int EntryNotifier::Add( std::function callback, StringRef prefix, unsigned int flags) { - if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true; + if ((flags & NT_NOTIFY_LOCAL) != 0) { + m_local_notifiers = true; + } return DoAdd(callback, prefix, flags); } unsigned int EntryNotifier::Add( std::function callback, unsigned int local_id, unsigned int flags) { - if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true; + if ((flags & NT_NOTIFY_LOCAL) != 0) { + m_local_notifiers = true; + } return DoAdd(callback, Handle(m_inst, local_id, Handle::kEntry), flags); } unsigned int EntryNotifier::AddPolled(unsigned int poller_uid, wpi::StringRef prefix, unsigned int flags) { - if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true; + if ((flags & NT_NOTIFY_LOCAL) != 0) { + m_local_notifiers = true; + } return DoAdd(poller_uid, prefix, flags); } unsigned int EntryNotifier::AddPolled(unsigned int poller_uid, unsigned int local_id, unsigned int flags) { - if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true; + if ((flags & NT_NOTIFY_LOCAL) != 0) { + m_local_notifiers = true; + } return DoAdd(poller_uid, Handle(m_inst, local_id, Handle::kEntry), flags); } @@ -78,7 +99,9 @@ void EntryNotifier::NotifyEntry(unsigned int local_id, StringRef name, unsigned int only_listener) { // optimization: don't generate needless local queue entries if we have // no local listeners (as this is a common case on the server side) - if ((flags & NT_NOTIFY_LOCAL) != 0 && !m_local_notifiers) return; + if ((flags & NT_NOTIFY_LOCAL) != 0 && !m_local_notifiers) { + return; + } DEBUG0("notifying '" << name << "' (local=" << local_id << "), flags=" << flags); Send(only_listener, 0, Handle(m_inst, local_id, Handle::kEntry).handle(), diff --git a/ntcore/src/main/native/cpp/InstanceImpl.cpp b/ntcore/src/main/native/cpp/InstanceImpl.cpp index a8f47716f4..c39ba0abe1 100644 --- a/ntcore/src/main/native/cpp/InstanceImpl.cpp +++ b/ntcore/src/main/native/cpp/InstanceImpl.cpp @@ -25,18 +25,26 @@ InstanceImpl::InstanceImpl(int inst) logger.set_min_level(logger_impl.GetMinLevel()); } -InstanceImpl::~InstanceImpl() { logger.SetLogger(nullptr); } +InstanceImpl::~InstanceImpl() { + logger.SetLogger(nullptr); +} -InstanceImpl* InstanceImpl::GetDefault() { return Get(GetDefaultIndex()); } +InstanceImpl* InstanceImpl::GetDefault() { + return Get(GetDefaultIndex()); +} InstanceImpl* InstanceImpl::Get(int inst) { - if (inst < 0) return nullptr; + if (inst < 0) { + return nullptr; + } // fast path, just an atomic read if (static_cast(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { InstanceImpl* ptr = s_fast_instances[inst]; - if (ptr) return ptr; + if (ptr) { + return ptr; + } } // slow path @@ -60,14 +68,18 @@ InstanceImpl* InstanceImpl::Get(int inst) { int InstanceImpl::GetDefaultIndex() { int inst = s_default; - if (inst >= 0) return inst; + if (inst >= 0) { + return inst; + } // slow path std::scoped_lock lock(s_mutex); // double-check inst = s_default; - if (inst >= 0) return inst; + if (inst >= 0) { + return inst; + } // alloc and save inst = AllocImpl(); @@ -94,7 +106,9 @@ int InstanceImpl::AllocImpl() { void InstanceImpl::Destroy(int inst) { std::scoped_lock lock(s_mutex); - if (inst < 0 || static_cast(inst) >= s_instances.size()) return; + if (inst < 0 || static_cast(inst) >= s_instances.size()) { + return; + } if (static_cast(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { diff --git a/ntcore/src/main/native/cpp/LoggerImpl.cpp b/ntcore/src/main/native/cpp/LoggerImpl.cpp index 1a847246ae..067ec05c58 100644 --- a/ntcore/src/main/native/cpp/LoggerImpl.cpp +++ b/ntcore/src/main/native/cpp/LoggerImpl.cpp @@ -22,21 +22,24 @@ static void DefaultLogger(unsigned int level, const char* file, } wpi::StringRef levelmsg; - if (level >= 50) + if (level >= 50) { levelmsg = "CRITICAL: "; - else if (level >= 40) + } else if (level >= 40) { levelmsg = "ERROR: "; - else if (level >= 30) + } else if (level >= 30) { levelmsg = "WARNING: "; - else + } else { return; + } oss << "NT: " << levelmsg << msg << " (" << file << ':' << line << ")\n"; wpi::errs() << oss.str(); } LoggerImpl::LoggerImpl(int inst) : m_inst(inst) {} -void LoggerImpl::Start() { DoStart(m_inst); } +void LoggerImpl::Start() { + DoStart(m_inst); +} unsigned int LoggerImpl::Add( std::function callback, unsigned int min_level, @@ -52,11 +55,15 @@ unsigned int LoggerImpl::AddPolled(unsigned int poller_uid, unsigned int LoggerImpl::GetMinLevel() { auto thr = GetThread(); - if (!thr) return NT_LOG_INFO; + if (!thr) { + return NT_LOG_INFO; + } unsigned int level = NT_LOG_INFO; for (size_t i = 0; i < thr->m_listeners.size(); ++i) { const auto& listener = thr->m_listeners[i]; - if (listener && listener.min_level < level) level = listener.min_level; + if (listener && listener.min_level < level) { + level = listener.min_level; + } } return level; } @@ -67,8 +74,9 @@ void LoggerImpl::Log(unsigned int level, const char* file, unsigned int line, const char* filename = wpi::sys::path::filename(file).data(); { auto thr = GetThread(); - if (!thr || thr->m_listeners.empty()) + if (!thr || thr->m_listeners.empty()) { DefaultLogger(level, filename, line, msg); + } } Send(UINT_MAX, 0, level, filename, line, msg); } diff --git a/ntcore/src/main/native/cpp/Message.cpp b/ntcore/src/main/native/cpp/Message.cpp index 8c6ced56eb..cf42651019 100644 --- a/ntcore/src/main/native/cpp/Message.cpp +++ b/ntcore/src/main/native/cpp/Message.cpp @@ -17,7 +17,9 @@ using namespace nt; std::shared_ptr Message::Read(WireDecoder& decoder, GetEntryTypeFunc get_entry_type) { unsigned int msg_type = 0; - if (!decoder.Read8(&msg_type)) return nullptr; + if (!decoder.Read8(&msg_type)) { + return nullptr; + } auto msg = std::make_shared(static_cast(msg_type), private_init()); switch (msg_type) { @@ -25,17 +27,23 @@ std::shared_ptr Message::Read(WireDecoder& decoder, break; case kClientHello: { unsigned int proto_rev; - if (!decoder.Read16(&proto_rev)) return nullptr; + if (!decoder.Read16(&proto_rev)) { + return nullptr; + } msg->m_id = proto_rev; // This intentionally uses the provided proto_rev instead of // decoder.proto_rev(). if (proto_rev >= 0x0300u) { - if (!decoder.ReadString(&msg->m_str)) return nullptr; + if (!decoder.ReadString(&msg->m_str)) { + return nullptr; + } } break; } case kProtoUnsup: { - if (!decoder.Read16(&msg->m_id)) return nullptr; // proto rev + if (!decoder.Read16(&msg->m_id)) { + return nullptr; // proto rev + } break; } case kServerHelloDone: @@ -45,8 +53,12 @@ std::shared_ptr Message::Read(WireDecoder& decoder, decoder.set_error("received SERVER_HELLO in protocol < 3.0"); return nullptr; } - if (!decoder.Read8(&msg->m_flags)) return nullptr; - if (!decoder.ReadString(&msg->m_str)) return nullptr; + if (!decoder.Read8(&msg->m_flags)) { + return nullptr; + } + if (!decoder.ReadString(&msg->m_str)) { + return nullptr; + } break; case kClientHelloDone: if (decoder.proto_rev() < 0x0300u) { @@ -55,30 +67,50 @@ std::shared_ptr Message::Read(WireDecoder& decoder, } break; case kEntryAssign: { - if (!decoder.ReadString(&msg->m_str)) return nullptr; // name + if (!decoder.ReadString(&msg->m_str)) { + return nullptr; // name + } NT_Type type; - if (!decoder.ReadType(&type)) return nullptr; // entry type - if (!decoder.Read16(&msg->m_id)) return nullptr; // id - if (!decoder.Read16(&msg->m_seq_num_uid)) return nullptr; // seq num + if (!decoder.ReadType(&type)) { + return nullptr; // entry type + } + if (!decoder.Read16(&msg->m_id)) { + return nullptr; // id + } + if (!decoder.Read16(&msg->m_seq_num_uid)) { + return nullptr; // seq num + } if (decoder.proto_rev() >= 0x0300u) { - if (!decoder.Read8(&msg->m_flags)) return nullptr; // flags + if (!decoder.Read8(&msg->m_flags)) { + return nullptr; // flags + } } msg->m_value = decoder.ReadValue(type); - if (!msg->m_value) return nullptr; + if (!msg->m_value) { + return nullptr; + } break; } case kEntryUpdate: { - if (!decoder.Read16(&msg->m_id)) return nullptr; // id - if (!decoder.Read16(&msg->m_seq_num_uid)) return nullptr; // seq num + if (!decoder.Read16(&msg->m_id)) { + return nullptr; // id + } + if (!decoder.Read16(&msg->m_seq_num_uid)) { + return nullptr; // seq num + } NT_Type type; if (decoder.proto_rev() >= 0x0300u) { - if (!decoder.ReadType(&type)) return nullptr; + if (!decoder.ReadType(&type)) { + return nullptr; + } } else { type = get_entry_type(msg->m_id); } WPI_DEBUG4(decoder.logger(), "update message data type: " << type); msg->m_value = decoder.ReadValue(type); - if (!msg->m_value) return nullptr; + if (!msg->m_value) { + return nullptr; + } break; } case kFlagsUpdate: { @@ -86,8 +118,12 @@ std::shared_ptr Message::Read(WireDecoder& decoder, decoder.set_error("received FLAGS_UPDATE in protocol < 3.0"); return nullptr; } - if (!decoder.Read16(&msg->m_id)) return nullptr; - if (!decoder.Read8(&msg->m_flags)) return nullptr; + if (!decoder.Read16(&msg->m_id)) { + return nullptr; + } + if (!decoder.Read8(&msg->m_flags)) { + return nullptr; + } break; } case kEntryDelete: { @@ -95,7 +131,9 @@ std::shared_ptr Message::Read(WireDecoder& decoder, decoder.set_error("received ENTRY_DELETE in protocol < 3.0"); return nullptr; } - if (!decoder.Read16(&msg->m_id)) return nullptr; + if (!decoder.Read16(&msg->m_id)) { + return nullptr; + } break; } case kClearEntries: { @@ -104,7 +142,9 @@ std::shared_ptr Message::Read(WireDecoder& decoder, return nullptr; } uint32_t magic; - if (!decoder.Read32(&magic)) return nullptr; + if (!decoder.Read32(&magic)) { + return nullptr; + } if (magic != kClearAllMagic) { decoder.set_error( "received incorrect CLEAR_ENTRIES magic value, ignoring"); @@ -117,12 +157,20 @@ std::shared_ptr Message::Read(WireDecoder& decoder, decoder.set_error("received EXECUTE_RPC in protocol < 3.0"); return nullptr; } - if (!decoder.Read16(&msg->m_id)) return nullptr; - if (!decoder.Read16(&msg->m_seq_num_uid)) return nullptr; // uid + if (!decoder.Read16(&msg->m_id)) { + return nullptr; + } + if (!decoder.Read16(&msg->m_seq_num_uid)) { + return nullptr; // uid + } uint64_t size; - if (!decoder.ReadUleb128(&size)) return nullptr; + if (!decoder.ReadUleb128(&size)) { + return nullptr; + } const char* params; - if (!decoder.Read(¶ms, size)) return nullptr; + if (!decoder.Read(¶ms, size)) { + return nullptr; + } msg->m_str = wpi::StringRef(params, size); break; } @@ -131,12 +179,20 @@ std::shared_ptr Message::Read(WireDecoder& decoder, decoder.set_error("received RPC_RESPONSE in protocol < 3.0"); return nullptr; } - if (!decoder.Read16(&msg->m_id)) return nullptr; - if (!decoder.Read16(&msg->m_seq_num_uid)) return nullptr; // uid + if (!decoder.Read16(&msg->m_id)) { + return nullptr; + } + if (!decoder.Read16(&msg->m_seq_num_uid)) { + return nullptr; // uid + } uint64_t size; - if (!decoder.ReadUleb128(&size)) return nullptr; + if (!decoder.ReadUleb128(&size)) { + return nullptr; + } const char* results; - if (!decoder.Read(&results, size)) return nullptr; + if (!decoder.Read(&results, size)) { + return nullptr; + } msg->m_str = wpi::StringRef(results, size); break; } @@ -226,7 +282,9 @@ void Message::Write(WireEncoder& encoder) const { case kClientHello: encoder.Write8(kClientHello); encoder.Write16(encoder.proto_rev()); - if (encoder.proto_rev() < 0x0300u) return; + if (encoder.proto_rev() < 0x0300u) { + return; + } encoder.WriteString(m_str); break; case kProtoUnsup: @@ -237,13 +295,17 @@ void Message::Write(WireEncoder& encoder) const { encoder.Write8(kServerHelloDone); break; case kServerHello: - if (encoder.proto_rev() < 0x0300u) return; // new message in version 3.0 + if (encoder.proto_rev() < 0x0300u) { + return; // new message in version 3.0 + } encoder.Write8(kServerHello); encoder.Write8(m_flags); encoder.WriteString(m_str); break; case kClientHelloDone: - if (encoder.proto_rev() < 0x0300u) return; // new message in version 3.0 + if (encoder.proto_rev() < 0x0300u) { + return; // new message in version 3.0 + } encoder.Write8(kClientHelloDone); break; case kEntryAssign: @@ -252,41 +314,55 @@ void Message::Write(WireEncoder& encoder) const { encoder.WriteType(m_value->type()); encoder.Write16(m_id); encoder.Write16(m_seq_num_uid); - if (encoder.proto_rev() >= 0x0300u) encoder.Write8(m_flags); + if (encoder.proto_rev() >= 0x0300u) { + encoder.Write8(m_flags); + } encoder.WriteValue(*m_value); break; case kEntryUpdate: encoder.Write8(kEntryUpdate); encoder.Write16(m_id); encoder.Write16(m_seq_num_uid); - if (encoder.proto_rev() >= 0x0300u) encoder.WriteType(m_value->type()); + if (encoder.proto_rev() >= 0x0300u) { + encoder.WriteType(m_value->type()); + } encoder.WriteValue(*m_value); break; case kFlagsUpdate: - if (encoder.proto_rev() < 0x0300u) return; // new message in version 3.0 + if (encoder.proto_rev() < 0x0300u) { + return; // new message in version 3.0 + } encoder.Write8(kFlagsUpdate); encoder.Write16(m_id); encoder.Write8(m_flags); break; case kEntryDelete: - if (encoder.proto_rev() < 0x0300u) return; // new message in version 3.0 + if (encoder.proto_rev() < 0x0300u) { + return; // new message in version 3.0 + } encoder.Write8(kEntryDelete); encoder.Write16(m_id); break; case kClearEntries: - if (encoder.proto_rev() < 0x0300u) return; // new message in version 3.0 + if (encoder.proto_rev() < 0x0300u) { + return; // new message in version 3.0 + } encoder.Write8(kClearEntries); encoder.Write32(kClearAllMagic); break; case kExecuteRpc: - if (encoder.proto_rev() < 0x0300u) return; // new message in version 3.0 + if (encoder.proto_rev() < 0x0300u) { + return; // new message in version 3.0 + } encoder.Write8(kExecuteRpc); encoder.Write16(m_id); encoder.Write16(m_seq_num_uid); encoder.WriteString(m_str); break; case kRpcResponse: - if (encoder.proto_rev() < 0x0300u) return; // new message in version 3.0 + if (encoder.proto_rev() < 0x0300u) { + return; // new message in version 3.0 + } encoder.Write8(kRpcResponse); encoder.Write16(m_id); encoder.Write16(m_seq_num_uid); diff --git a/ntcore/src/main/native/cpp/NetworkConnection.cpp b/ntcore/src/main/native/cpp/NetworkConnection.cpp index 8b7ad49679..16f9be8118 100644 --- a/ntcore/src/main/native/cpp/NetworkConnection.cpp +++ b/ntcore/src/main/native/cpp/NetworkConnection.cpp @@ -36,14 +36,20 @@ NetworkConnection::NetworkConnection(unsigned int uid, m_stream->setNoDelay(); } -NetworkConnection::~NetworkConnection() { Stop(); } +NetworkConnection::~NetworkConnection() { + Stop(); +} void NetworkConnection::Start() { - if (m_active) return; + if (m_active) { + return; + } m_active = true; set_state(kInit); // clear queue - while (!m_outgoing.empty()) m_outgoing.pop(); + while (!m_outgoing.empty()) { + m_outgoing.pop(); + } // reset shutdown flags { std::scoped_lock lock(m_shutdown_mutex); @@ -60,7 +66,9 @@ void NetworkConnection::Stop() { set_state(kDead); m_active = false; // closing the stream so the read thread terminates - if (m_stream) m_stream->close(); + if (m_stream) { + m_stream->close(); + } // send an empty outgoing message set so the write thread terminates m_outgoing.push(Outgoing()); // wait for threads to terminate, with timeout @@ -69,23 +77,27 @@ void NetworkConnection::Stop() { auto timeout_time = std::chrono::steady_clock::now() + std::chrono::milliseconds(200); if (m_write_shutdown_cv.wait_until(lock, timeout_time, - [&] { return m_write_shutdown; })) + [&] { return m_write_shutdown; })) { m_write_thread.join(); - else + } else { m_write_thread.detach(); // timed out, detach it + } } if (m_read_thread.joinable()) { std::unique_lock lock(m_shutdown_mutex); auto timeout_time = std::chrono::steady_clock::now() + std::chrono::milliseconds(200); if (m_read_shutdown_cv.wait_until(lock, timeout_time, - [&] { return m_read_shutdown; })) + [&] { return m_read_shutdown; })) { m_read_thread.join(); - else + } else { m_read_thread.detach(); // timed out, detach it + } } // clear queue - while (!m_outgoing.empty()) m_outgoing.pop(); + while (!m_outgoing.empty()) { + m_outgoing.pop(); + } } ConnectionInfo NetworkConnection::info() const { @@ -94,7 +106,9 @@ ConnectionInfo NetworkConnection::info() const { m_last_update, m_proto_rev}; } -unsigned int NetworkConnection::proto_rev() const { return m_proto_rev; } +unsigned int NetworkConnection::proto_rev() const { + return m_proto_rev; +} void NetworkConnection::set_proto_rev(unsigned int proto_rev) { m_proto_rev = proto_rev; @@ -108,12 +122,16 @@ NetworkConnection::State NetworkConnection::state() const { void NetworkConnection::set_state(State state) { std::scoped_lock lock(m_state_mutex); // Don't update state any more once we've died - if (m_state == kDead) return; + if (m_state == kDead) { + return; + } // One-shot notify state changes - if (m_state != kActive && state == kActive) + if (m_state != kActive && state == kActive) { m_notifier.NotifyConnection(true, info()); - if (m_state != kDead && state == kDead) + } + if (m_state != kDead && state == kDead) { m_notifier.NotifyConnection(false, info()); + } m_state = state; } @@ -137,8 +155,9 @@ void NetworkConnection::ReadThreadMain() { [&] { decoder.set_proto_rev(m_proto_rev); auto msg = Message::Read(decoder, m_get_entry_type); - if (!msg && decoder.error()) + if (!msg && decoder.error()) { DEBUG0("error reading in handshake: " << decoder.error()); + } return msg; }, [&](wpi::ArrayRef> msgs) { @@ -151,14 +170,20 @@ void NetworkConnection::ReadThreadMain() { set_state(kActive); while (m_active) { - if (!m_stream) break; + if (!m_stream) { + break; + } decoder.set_proto_rev(m_proto_rev); decoder.Reset(); auto msg = Message::Read(decoder, m_get_entry_type); if (!msg) { - if (decoder.error()) INFO("read error: " << decoder.error()); + if (decoder.error()) { + INFO("read error: " << decoder.error()); + } // terminate connection on bad message - if (m_stream) m_stream->close(); + if (m_stream) { + m_stream->close(); + } break; } DEBUG3("received type=" << msg->type() << " with str=" << msg->str() @@ -187,7 +212,9 @@ void NetworkConnection::WriteThreadMain() { while (m_active) { auto msgs = m_outgoing.pop(); DEBUG4("write thread woke up"); - if (msgs.empty()) continue; + if (msgs.empty()) { + continue; + } encoder.set_proto_rev(m_proto_rev); encoder.Reset(); DEBUG3("sending " << msgs.size() << " messages"); @@ -200,15 +227,23 @@ void NetworkConnection::WriteThreadMain() { } } wpi::NetworkStream::Error err; - if (!m_stream) break; - if (encoder.size() == 0) continue; - if (m_stream->send(encoder.data(), encoder.size(), &err) == 0) break; + if (!m_stream) { + break; + } + if (encoder.size() == 0) { + continue; + } + if (m_stream->send(encoder.data(), encoder.size(), &err) == 0) { + break; + } DEBUG4("sent " << encoder.size() << " bytes"); } DEBUG2("write thread died (" << this << ")"); set_state(kDead); m_active = false; - if (m_stream) m_stream->close(); // also kill read thread + if (m_stream) { + m_stream->close(); // also kill read thread + } // use condition variable to signal thread shutdown { @@ -246,7 +281,9 @@ void NetworkConnection::QueueOutgoing(std::shared_ptr msg) { // new, but remember it size_t pos = m_pending_outgoing.size(); m_pending_outgoing.push_back(msg); - if (id >= m_pending_update.size()) m_pending_update.resize(id + 1); + if (id >= m_pending_update.size()) { + m_pending_update.resize(id + 1); + } m_pending_update[id].first = pos + 1; } break; @@ -289,7 +326,9 @@ void NetworkConnection::QueueOutgoing(std::shared_ptr msg) { // new, but remember it size_t pos = m_pending_outgoing.size(); m_pending_outgoing.push_back(msg); - if (id >= m_pending_update.size()) m_pending_update.resize(id + 1); + if (id >= m_pending_update.size()) { + m_pending_update.resize(id + 1); + } m_pending_update[id].second = pos + 1; } break; @@ -297,12 +336,15 @@ void NetworkConnection::QueueOutgoing(std::shared_ptr msg) { case Message::kClearEntries: { // knock out all previous assigns/updates! for (auto& i : m_pending_outgoing) { - if (!i) continue; + if (!i) { + continue; + } auto t = i->type(); if (t == Message::kEntryAssign || t == Message::kEntryUpdate || t == Message::kFlagsUpdate || t == Message::kEntryDelete || - t == Message::kClearEntries) + t == Message::kClearEntries) { i.reset(); + } } m_pending_update.resize(0); m_pending_outgoing.push_back(msg); @@ -318,9 +360,13 @@ void NetworkConnection::PostOutgoing(bool keep_alive) { std::scoped_lock lock(m_pending_mutex); auto now = std::chrono::steady_clock::now(); if (m_pending_outgoing.empty()) { - if (!keep_alive) return; + if (!keep_alive) { + return; + } // send keep-alives once a second (if no other messages have been sent) - if ((now - m_last_post) < std::chrono::seconds(1)) return; + if ((now - m_last_post) < std::chrono::seconds(1)) { + return; + } m_outgoing.emplace(Outgoing{Message::KeepAlive()}); } else { m_outgoing.emplace(std::move(m_pending_outgoing)); diff --git a/ntcore/src/main/native/cpp/RpcServer.cpp b/ntcore/src/main/native/cpp/RpcServer.cpp index c2fd4b6a22..d413cd8438 100644 --- a/ntcore/src/main/native/cpp/RpcServer.cpp +++ b/ntcore/src/main/native/cpp/RpcServer.cpp @@ -9,7 +9,9 @@ using namespace nt; RpcServer::RpcServer(int inst, wpi::Logger& logger) : m_inst(inst), m_logger(logger) {} -void RpcServer::Start() { DoStart(m_inst, m_logger); } +void RpcServer::Start() { + DoStart(m_inst, m_logger); +} unsigned int RpcServer::Add( std::function callback) { @@ -20,7 +22,9 @@ unsigned int RpcServer::AddPolled(unsigned int poller_uid) { return DoAdd(poller_uid); } -void RpcServer::RemoveRpc(unsigned int rpc_uid) { Remove(rpc_uid); } +void RpcServer::RemoveRpc(unsigned int rpc_uid) { + Remove(rpc_uid); +} void RpcServer::ProcessRpc(unsigned int local_id, unsigned int call_uid, StringRef name, StringRef params, diff --git a/ntcore/src/main/native/cpp/SequenceNumber.cpp b/ntcore/src/main/native/cpp/SequenceNumber.cpp index 776a1f0792..e25e636a4a 100644 --- a/ntcore/src/main/native/cpp/SequenceNumber.cpp +++ b/ntcore/src/main/native/cpp/SequenceNumber.cpp @@ -7,21 +7,23 @@ namespace nt { bool operator<(const SequenceNumber& lhs, const SequenceNumber& rhs) { - if (lhs.m_value < rhs.m_value) + if (lhs.m_value < rhs.m_value) { return (rhs.m_value - lhs.m_value) < (1u << 15); - else if (lhs.m_value > rhs.m_value) + } else if (lhs.m_value > rhs.m_value) { return (lhs.m_value - rhs.m_value) > (1u << 15); - else + } else { return false; + } } bool operator>(const SequenceNumber& lhs, const SequenceNumber& rhs) { - if (lhs.m_value < rhs.m_value) + if (lhs.m_value < rhs.m_value) { return (rhs.m_value - lhs.m_value) > (1u << 15); - else if (lhs.m_value > rhs.m_value) + } else if (lhs.m_value > rhs.m_value) { return (lhs.m_value - rhs.m_value) < (1u << 15); - else + } else { return false; + } } } // namespace nt diff --git a/ntcore/src/main/native/cpp/SequenceNumber.h b/ntcore/src/main/native/cpp/SequenceNumber.h index 337477ca68..72960f4ef5 100644 --- a/ntcore/src/main/native/cpp/SequenceNumber.h +++ b/ntcore/src/main/native/cpp/SequenceNumber.h @@ -16,7 +16,9 @@ class SequenceNumber { SequenceNumber& operator++() { ++m_value; - if (m_value > 0xffff) m_value = 0; + if (m_value > 0xffff) { + m_value = 0; + } return *this; } SequenceNumber operator++(int) { diff --git a/ntcore/src/main/native/cpp/Storage.cpp b/ntcore/src/main/native/cpp/Storage.cpp index 13a11eaffd..63929fc175 100644 --- a/ntcore/src/main/native/cpp/Storage.cpp +++ b/ntcore/src/main/native/cpp/Storage.cpp @@ -32,13 +32,19 @@ void Storage::SetDispatcher(IDispatcher* dispatcher, bool server) { m_server = server; } -void Storage::ClearDispatcher() { m_dispatcher = nullptr; } +void Storage::ClearDispatcher() { + m_dispatcher = nullptr; +} NT_Type Storage::GetMessageEntryType(unsigned int id) const { std::scoped_lock lock(m_mutex); - if (id >= m_idmap.size()) return NT_UNASSIGNED; + if (id >= m_idmap.size()) { + return NT_UNASSIGNED; + } Entry* entry = m_idmap[id]; - if (!entry || !entry->value) return NT_UNASSIGNED; + if (!entry || !entry->value) { + return NT_UNASSIGNED; + } return entry->value->type(); } @@ -96,7 +102,9 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr msg, if (id == 0xffff) { entry = GetOrNew(name); // see if it was already assigned; ignore if so. - if (entry->id != 0xffff) return; + if (entry->id != 0xffff) { + return; + } entry->flags = msg->flags(); entry->seq_num = seq_num; @@ -118,7 +126,9 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr msg, DEBUG0("client: received entry assignment request?"); return; } - if (id >= m_idmap.size()) m_idmap.resize(id + 1); + if (id >= m_idmap.size()) { + m_idmap.resize(id + 1); + } entry = m_idmap[id]; if (!entry) { // create local @@ -178,15 +188,19 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr msg, // don't update flags if this is a server response to a client id request if (!may_need_update && conn->proto_rev() >= 0x0300) { // update persistent dirty flag if persistent flag changed - if ((entry->flags & NT_PERSISTENT) != (msg->flags() & NT_PERSISTENT)) + if ((entry->flags & NT_PERSISTENT) != (msg->flags() & NT_PERSISTENT)) { m_persistent_dirty = true; - if (entry->flags != msg->flags()) notify_flags |= NT_NOTIFY_FLAGS; + } + if (entry->flags != msg->flags()) { + notify_flags |= NT_NOTIFY_FLAGS; + } entry->flags = msg->flags(); } // update persistent dirty flag if the value changed and it's persistent - if (entry->IsPersistent() && *entry->value != *msg->value()) + if (entry->IsPersistent() && *entry->value != *msg->value()) { m_persistent_dirty = true; + } // update local entry->value = msg->value(); @@ -221,14 +235,18 @@ void Storage::ProcessIncomingEntryUpdate(std::shared_ptr msg, // ignore if sequence number not higher than local SequenceNumber seq_num(msg->seq_num_uid()); - if (seq_num <= entry->seq_num) return; + if (seq_num <= entry->seq_num) { + return; + } // update local entry->value = msg->value(); entry->seq_num = seq_num; // update persistent dirty flag if it's a persistent value - if (entry->IsPersistent()) m_persistent_dirty = true; + if (entry->IsPersistent()) { + m_persistent_dirty = true; + } // notify m_notifier.NotifyEntry(entry->local_id, entry->name, entry->value, @@ -310,7 +328,9 @@ void Storage::ProcessIncomingExecuteRpc( std::shared_ptr msg, INetworkConnection* /*conn*/, std::weak_ptr conn_weak) { std::unique_lock lock(m_mutex); - if (!m_server) return; // only process on server + if (!m_server) { + return; // only process on server + } unsigned int id = msg->id(); if (id >= m_idmap.size() || !m_idmap[id]) { // ignore call to non-existent RPC @@ -341,7 +361,9 @@ void Storage::ProcessIncomingExecuteRpc( entry->local_id, call_uid, entry->name, msg->str(), conn_info, [=](StringRef result) { auto c = conn_weak.lock(); - if (c) c->QueueOutgoing(Message::RpcResponse(id, call_uid, result)); + if (c) { + c->QueueOutgoing(Message::RpcResponse(id, call_uid, result)); + } }, entry->rpc_uid); } @@ -349,7 +371,9 @@ void Storage::ProcessIncomingExecuteRpc( void Storage::ProcessIncomingRpcResponse(std::shared_ptr msg, INetworkConnection* /*conn*/) { std::unique_lock lock(m_mutex); - if (m_server) return; // only process on client + if (m_server) { + return; // only process on client + } unsigned int id = msg->id(); if (id >= m_idmap.size() || !m_idmap[id]) { // ignore response to non-existent RPC @@ -375,7 +399,9 @@ void Storage::GetInitialAssignments( conn.set_state(INetworkConnection::kSynchronized); for (auto& i : m_entries) { Entry* entry = i.getValue(); - if (!entry->value) continue; + if (!entry->value) { + continue; + } msgs->emplace_back(Message::EntryAssign(i.getKey(), entry->id, entry->seq_num.value(), entry->value, entry->flags)); @@ -386,14 +412,18 @@ void Storage::ApplyInitialAssignments( INetworkConnection& conn, wpi::ArrayRef> msgs, bool /*new_server*/, std::vector>* out_msgs) { std::unique_lock lock(m_mutex); - if (m_server) return; // should not do this on server + if (m_server) { + return; // should not do this on server + } conn.set_state(INetworkConnection::kSynchronized); std::vector> update_msgs; // clear existing id's - for (auto& i : m_entries) i.getValue()->id = 0xffff; + for (auto& i : m_entries) { + i.getValue()->id = 0xffff; + } // clear existing idmap m_idmap.resize(0); @@ -437,7 +467,9 @@ void Storage::ApplyInitialAssignments( unsigned int notify_flags = NT_NOTIFY_UPDATE; // don't update flags from a <3.0 remote (not part of message) if (conn.proto_rev() >= 0x0300) { - if (entry->flags != msg->flags()) notify_flags |= NT_NOTIFY_FLAGS; + if (entry->flags != msg->flags()) { + notify_flags |= NT_NOTIFY_FLAGS; + } entry->flags = msg->flags(); } // notify @@ -447,14 +479,18 @@ void Storage::ApplyInitialAssignments( } // save to idmap - if (id >= m_idmap.size()) m_idmap.resize(id + 1); + if (id >= m_idmap.size()) { + m_idmap.resize(id + 1); + } m_idmap[id] = entry; } // delete or generate assign messages for unassigned local entries DeleteAllEntriesImpl(false, [&](Entry* entry) -> bool { // was assigned by the server, don't delete - if (entry->id != 0xffff) return false; + if (entry->id != 0xffff) { + return false; + } // if we have written the value locally, we send an assign message to the // server instead of deleting if (entry->local_write) { @@ -468,32 +504,43 @@ void Storage::ApplyInitialAssignments( }); auto dispatcher = m_dispatcher; lock.unlock(); - for (auto& msg : update_msgs) + for (auto& msg : update_msgs) { dispatcher->QueueOutgoing(msg, nullptr, nullptr); + } } std::shared_ptr Storage::GetEntryValue(StringRef name) const { std::scoped_lock lock(m_mutex); auto i = m_entries.find(name); - if (i == m_entries.end()) return nullptr; + if (i == m_entries.end()) { + return nullptr; + } return i->getValue()->value; } std::shared_ptr Storage::GetEntryValue(unsigned int local_id) const { std::scoped_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return nullptr; + if (local_id >= m_localmap.size()) { + return nullptr; + } return m_localmap[local_id]->value; } bool Storage::SetDefaultEntryValue(StringRef name, std::shared_ptr value) { - if (name.empty()) return false; - if (!value) return false; + if (name.empty()) { + return false; + } + if (!value) { + return false; + } std::unique_lock lock(m_mutex); Entry* entry = GetOrNew(name); // we return early if value already exists; if types match return true - if (entry->value) return entry->value->type() == value->type(); + if (entry->value) { + return entry->value->type() == value->type(); + } SetEntryValueImpl(entry, value, lock, true); return true; @@ -501,26 +548,37 @@ bool Storage::SetDefaultEntryValue(StringRef name, bool Storage::SetDefaultEntryValue(unsigned int local_id, std::shared_ptr value) { - if (!value) return false; + if (!value) { + return false; + } std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return false; + if (local_id >= m_localmap.size()) { + return false; + } Entry* entry = m_localmap[local_id].get(); // we return early if value already exists; if types match return true - if (entry->value) return entry->value->type() == value->type(); + if (entry->value) { + return entry->value->type() == value->type(); + } SetEntryValueImpl(entry, value, lock, true); return true; } bool Storage::SetEntryValue(StringRef name, std::shared_ptr value) { - if (name.empty()) return true; - if (!value) return true; + if (name.empty()) { + return true; + } + if (!value) { + return true; + } std::unique_lock lock(m_mutex); Entry* entry = GetOrNew(name); - if (entry->value && entry->value->type() != value->type()) + if (entry->value && entry->value->type() != value->type()) { return false; // error on type mismatch + } SetEntryValueImpl(entry, value, lock, true); return true; @@ -528,13 +586,18 @@ bool Storage::SetEntryValue(StringRef name, std::shared_ptr value) { bool Storage::SetEntryValue(unsigned int local_id, std::shared_ptr value) { - if (!value) return true; + if (!value) { + return true; + } std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return true; + if (local_id >= m_localmap.size()) { + return true; + } Entry* entry = m_localmap[local_id].get(); - if (entry->value && entry->value->type() != value->type()) + if (entry->value && entry->value->type() != value->type()) { return false; // error on type mismatch + } SetEntryValueImpl(entry, value, lock, true); return true; @@ -543,7 +606,9 @@ bool Storage::SetEntryValue(unsigned int local_id, void Storage::SetEntryValueImpl(Entry* entry, std::shared_ptr value, std::unique_lock& lock, bool local) { - if (!value) return; + if (!value) { + return; + } auto old_value = entry->value; entry->value = value; @@ -555,31 +620,41 @@ void Storage::SetEntryValueImpl(Entry* entry, std::shared_ptr value, } // update persistent dirty flag if value changed and it's persistent - if (entry->IsPersistent() && (!old_value || *old_value != *value)) + if (entry->IsPersistent() && (!old_value || *old_value != *value)) { m_persistent_dirty = true; + } // notify - if (!old_value) + if (!old_value) { m_notifier.NotifyEntry(entry->local_id, entry->name, value, NT_NOTIFY_NEW | (local ? NT_NOTIFY_LOCAL : 0)); - else if (*old_value != *value) + } else if (*old_value != *value) { m_notifier.NotifyEntry(entry->local_id, entry->name, value, NT_NOTIFY_UPDATE | (local ? NT_NOTIFY_LOCAL : 0)); + } // remember local changes - if (local) entry->local_write = true; + if (local) { + entry->local_write = true; + } // generate message - if (!m_dispatcher || (!local && !m_server)) return; + if (!m_dispatcher || (!local && !m_server)) { + return; + } auto dispatcher = m_dispatcher; if (!old_value || old_value->type() != value->type()) { - if (local) ++entry->seq_num; + if (local) { + ++entry->seq_num; + } auto msg = Message::EntryAssign( entry->name, entry->id, entry->seq_num.value(), value, entry->flags); lock.unlock(); dispatcher->QueueOutgoing(msg, nullptr, nullptr); } else if (*old_value != *value) { - if (local) ++entry->seq_num; + if (local) { + ++entry->seq_num; + } // don't send an update if we don't have an assigned id yet if (entry->id != 0xffff) { auto msg = Message::EntryUpdate(entry->id, entry->seq_num.value(), value); @@ -590,8 +665,12 @@ void Storage::SetEntryValueImpl(Entry* entry, std::shared_ptr value, } void Storage::SetEntryTypeValue(StringRef name, std::shared_ptr value) { - if (name.empty()) return; - if (!value) return; + if (name.empty()) { + return; + } + if (!value) { + return; + } std::unique_lock lock(m_mutex); Entry* entry = GetOrNew(name); @@ -600,37 +679,52 @@ void Storage::SetEntryTypeValue(StringRef name, std::shared_ptr value) { void Storage::SetEntryTypeValue(unsigned int local_id, std::shared_ptr value) { - if (!value) return; + if (!value) { + return; + } std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return; + if (local_id >= m_localmap.size()) { + return; + } Entry* entry = m_localmap[local_id].get(); - if (!entry) return; + if (!entry) { + return; + } SetEntryValueImpl(entry, value, lock, true); } void Storage::SetEntryFlags(StringRef name, unsigned int flags) { - if (name.empty()) return; + if (name.empty()) { + return; + } std::unique_lock lock(m_mutex); auto i = m_entries.find(name); - if (i == m_entries.end()) return; + if (i == m_entries.end()) { + return; + } SetEntryFlagsImpl(i->getValue(), flags, lock, true); } void Storage::SetEntryFlags(unsigned int id_local, unsigned int flags) { std::unique_lock lock(m_mutex); - if (id_local >= m_localmap.size()) return; + if (id_local >= m_localmap.size()) { + return; + } SetEntryFlagsImpl(m_localmap[id_local].get(), flags, lock, true); } void Storage::SetEntryFlagsImpl(Entry* entry, unsigned int flags, std::unique_lock& lock, bool local) { - if (!entry->value || entry->flags == flags) return; + if (!entry->value || entry->flags == flags) { + return; + } // update persistent dirty flag if persistent flag changed - if ((entry->flags & NT_PERSISTENT) != (flags & NT_PERSISTENT)) + if ((entry->flags & NT_PERSISTENT) != (flags & NT_PERSISTENT)) { m_persistent_dirty = true; + } entry->flags = flags; @@ -639,7 +733,9 @@ void Storage::SetEntryFlagsImpl(Entry* entry, unsigned int flags, NT_NOTIFY_FLAGS | (local ? NT_NOTIFY_LOCAL : 0)); // generate message - if (!local || !m_dispatcher) return; + if (!local || !m_dispatcher) { + return; + } auto dispatcher = m_dispatcher; unsigned int id = entry->id; // don't send an update if we don't have an assigned id yet @@ -653,26 +749,34 @@ void Storage::SetEntryFlagsImpl(Entry* entry, unsigned int flags, unsigned int Storage::GetEntryFlags(StringRef name) const { std::scoped_lock lock(m_mutex); auto i = m_entries.find(name); - if (i == m_entries.end()) return 0; + if (i == m_entries.end()) { + return 0; + } return i->getValue()->flags; } unsigned int Storage::GetEntryFlags(unsigned int local_id) const { std::scoped_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return 0; + if (local_id >= m_localmap.size()) { + return 0; + } return m_localmap[local_id]->flags; } void Storage::DeleteEntry(StringRef name) { std::unique_lock lock(m_mutex); auto i = m_entries.find(name); - if (i == m_entries.end()) return; + if (i == m_entries.end()) { + return; + } DeleteEntryImpl(i->getValue(), lock, true); } void Storage::DeleteEntry(unsigned int local_id) { std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return; + if (local_id >= m_localmap.size()) { + return; + } DeleteEntryImpl(m_localmap[local_id].get(), lock, true); } @@ -681,7 +785,9 @@ void Storage::DeleteEntryImpl(Entry* entry, std::unique_lock& lock, unsigned int id = entry->id; // Erase entry from id mapping. - if (id < m_idmap.size()) m_idmap[id] = nullptr; + if (id < m_idmap.size()) { + m_idmap[id] = nullptr; + } // empty the value and reset id and local_write flag std::shared_ptr old_value; @@ -696,12 +802,16 @@ void Storage::DeleteEntryImpl(Entry* entry, std::unique_lock& lock, } // update persistent dirty flag if it's a persistent value - if (entry->IsPersistent()) m_persistent_dirty = true; + if (entry->IsPersistent()) { + m_persistent_dirty = true; + } // reset flags entry->flags = 0; - if (!old_value) return; // was not previously assigned + if (!old_value) { + return; // was not previously assigned + } // notify m_notifier.NotifyEntry(entry->local_id, entry->name, old_value, @@ -710,7 +820,9 @@ void Storage::DeleteEntryImpl(Entry* entry, std::unique_lock& lock, // if it had a value, generate message // don't send an update if we don't have an assigned id yet if (local && id != 0xffff) { - if (!m_dispatcher) return; + if (!m_dispatcher) { + return; + } auto dispatcher = m_dispatcher; lock.unlock(); dispatcher->QueueOutgoing(Message::EntryDelete(id), nullptr, nullptr); @@ -726,7 +838,9 @@ void Storage::DeleteAllEntriesImpl(bool local, F should_delete) { m_notifier.NotifyEntry(entry->local_id, i.getKey(), entry->value, NT_NOTIFY_DELETE | (local ? NT_NOTIFY_LOCAL : 0)); // remove it from idmap - if (entry->id < m_idmap.size()) m_idmap[entry->id] = nullptr; + if (entry->id < m_idmap.size()) { + m_idmap[entry->id] = nullptr; + } entry->id = 0xffff; entry->local_write = false; entry->value.reset(); @@ -743,12 +857,16 @@ void Storage::DeleteAllEntriesImpl(bool local) { void Storage::DeleteAllEntries() { std::unique_lock lock(m_mutex); - if (m_entries.empty()) return; + if (m_entries.empty()) { + return; + } DeleteAllEntriesImpl(true); // generate message - if (!m_dispatcher) return; + if (!m_dispatcher) { + return; + } auto dispatcher = m_dispatcher; lock.unlock(); dispatcher->QueueOutgoing(Message::ClearEntries(), nullptr, nullptr); @@ -768,8 +886,9 @@ Storage::Entry* Storage::GetOrNew(const Twine& name) { unsigned int Storage::GetEntry(const Twine& name) { if (name.isTriviallyEmpty() || - (name.isSingleStringRef() && name.getSingleStringRef().empty())) + (name.isSingleStringRef() && name.getSingleStringRef().empty())) { return UINT_MAX; + } std::unique_lock lock(m_mutex); return GetOrNew(name)->local_id; } @@ -783,8 +902,12 @@ std::vector Storage::GetEntries(const Twine& prefix, for (auto& i : m_entries) { Entry* entry = i.getValue(); auto value = entry->value.get(); - if (!value || !i.getKey().startswith(prefixStr)) continue; - if (types != 0 && (types & value->type()) == 0) continue; + if (!value || !i.getKey().startswith(prefixStr)) { + continue; + } + if (types != 0 && (types & value->type()) == 0) { + continue; + } ids.push_back(entry->local_id); } return ids; @@ -798,9 +921,13 @@ EntryInfo Storage::GetEntryInfo(int inst, unsigned int local_id) const { info.last_change = 0; std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return info; + if (local_id >= m_localmap.size()) { + return info; + } Entry* entry = m_localmap[local_id].get(); - if (!entry->value) return info; + if (!entry->value) { + return info; + } info.entry = Handle(inst, local_id, Handle::kEntry); info.name = entry->name; @@ -812,23 +939,33 @@ EntryInfo Storage::GetEntryInfo(int inst, unsigned int local_id) const { std::string Storage::GetEntryName(unsigned int local_id) const { std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return std::string{}; + if (local_id >= m_localmap.size()) { + return {}; + } return m_localmap[local_id]->name; } NT_Type Storage::GetEntryType(unsigned int local_id) const { std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return NT_UNASSIGNED; + if (local_id >= m_localmap.size()) { + return NT_UNASSIGNED; + } Entry* entry = m_localmap[local_id].get(); - if (!entry->value) return NT_UNASSIGNED; + if (!entry->value) { + return NT_UNASSIGNED; + } return entry->value->type(); } uint64_t Storage::GetEntryLastChange(unsigned int local_id) const { std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return 0; + if (local_id >= m_localmap.size()) { + return 0; + } Entry* entry = m_localmap[local_id].get(); - if (!entry->value) return 0; + if (!entry->value) { + return 0; + } return entry->value->last_change(); } @@ -841,8 +978,12 @@ std::vector Storage::GetEntryInfo(int inst, const Twine& prefix, for (auto& i : m_entries) { Entry* entry = i.getValue(); auto value = entry->value.get(); - if (!value || !i.getKey().startswith(prefixStr)) continue; - if (types != 0 && (types & value->type()) == 0) continue; + if (!value || !i.getKey().startswith(prefixStr)) { + continue; + } + if (types != 0 && (types & value->type()) == 0) { + continue; + } EntryInfo info; info.entry = Handle(inst, entry->local_id, Handle::kEntry); info.name = i.getKey(); @@ -866,7 +1007,9 @@ unsigned int Storage::AddListener( if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0) { for (auto& i : m_entries) { Entry* entry = i.getValue(); - if (!entry->value || !i.getKey().startswith(prefixStr)) continue; + if (!entry->value || !i.getKey().startswith(prefixStr)) { + continue; + } m_notifier.NotifyEntry(entry->local_id, i.getKey(), entry->value, NT_NOTIFY_IMMEDIATE | NT_NOTIFY_NEW, uid); } @@ -902,9 +1045,13 @@ unsigned int Storage::AddPolledListener(unsigned int poller, // perform immediate notifications if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0) { for (auto& i : m_entries) { - if (!i.getKey().startswith(prefixStr)) continue; + if (!i.getKey().startswith(prefixStr)) { + continue; + } Entry* entry = i.getValue(); - if (!entry->value) continue; + if (!entry->value) { + continue; + } m_notifier.NotifyEntry(entry->local_id, i.getKey(), entry->value, NT_NOTIFY_IMMEDIATE | NT_NOTIFY_NEW, uid); } @@ -938,13 +1085,17 @@ bool Storage::GetPersistentEntries( { std::scoped_lock lock(m_mutex); // for periodic, don't re-save unless something has changed - if (periodic && !m_persistent_dirty) return false; + if (periodic && !m_persistent_dirty) { + return false; + } m_persistent_dirty = false; entries->reserve(m_entries.size()); for (auto& i : m_entries) { Entry* entry = i.getValue(); // only write persistent-flagged values - if (!entry->value || !entry->IsPersistent()) continue; + if (!entry->value || !entry->IsPersistent()) { + continue; + } entries->emplace_back(i.getKey(), entry->value); } } @@ -971,7 +1122,9 @@ bool Storage::GetEntries( for (auto& i : m_entries) { Entry* entry = i.getValue(); // only write values with given prefix - if (!entry->value || !i.getKey().startswith(prefixStr)) continue; + if (!entry->value || !i.getKey().startswith(prefixStr)) { + continue; + } entries->emplace_back(i.getKey(), entry->value); } } @@ -988,7 +1141,9 @@ bool Storage::GetEntries( void Storage::CreateRpc(unsigned int local_id, StringRef def, unsigned int rpc_uid) { std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return; + if (local_id >= m_localmap.size()) { + return; + } Entry* entry = m_localmap[local_id].get(); auto old_value = entry->value; @@ -998,7 +1153,9 @@ void Storage::CreateRpc(unsigned int local_id, StringRef def, // set up the RPC info entry->rpc_uid = rpc_uid; - if (old_value && *old_value == *value) return; + if (old_value && *old_value == *value) { + return; + } // assign an id if it doesn't have one if (entry->id == 0xffff) { @@ -1008,7 +1165,9 @@ void Storage::CreateRpc(unsigned int local_id, StringRef def, } // generate message - if (!m_dispatcher) return; + if (!m_dispatcher) { + return; + } auto dispatcher = m_dispatcher; if (!old_value || old_value->type() != value->type()) { ++entry->seq_num; @@ -1026,13 +1185,19 @@ void Storage::CreateRpc(unsigned int local_id, StringRef def, unsigned int Storage::CallRpc(unsigned int local_id, StringRef params) { std::unique_lock lock(m_mutex); - if (local_id >= m_localmap.size()) return 0; + if (local_id >= m_localmap.size()) { + return 0; + } Entry* entry = m_localmap[local_id].get(); - if (!entry->value || !entry->value->IsRpc()) return 0; + if (!entry->value || !entry->value->IsRpc()) { + return 0; + } ++entry->rpc_call_uid; - if (entry->rpc_call_uid > 0xffff) entry->rpc_call_uid = 0; + if (entry->rpc_call_uid > 0xffff) { + entry->rpc_call_uid = 0; + } unsigned int call_uid = entry->rpc_call_uid; auto msg = Message::ExecuteRpc(entry->id, call_uid, params); @@ -1081,7 +1246,9 @@ bool Storage::GetRpcResult(unsigned int local_id, unsigned int call_uid, RpcIdPair call_pair{local_id, call_uid}; // only allow one blocking call per rpc call uid - if (!m_rpc_blocking_calls.insert(call_pair).second) return false; + if (!m_rpc_blocking_calls.insert(call_pair).second) { + return false; + } auto timeout_time = std::chrono::steady_clock::now() + std::chrono::duration(timeout); diff --git a/ntcore/src/main/native/cpp/Storage_load.cpp b/ntcore/src/main/native/cpp/Storage_load.cpp index b5ffa6a190..f73840e731 100644 --- a/ntcore/src/main/native/cpp/Storage_load.cpp +++ b/ntcore/src/main/native/cpp/Storage_load.cpp @@ -43,7 +43,9 @@ class LoadPersistentImpl { std::shared_ptr ReadStringArrayValue(); void Warn(const char* msg) { - if (m_warn) m_warn(m_line_num, msg); + if (m_warn) { + m_warn(m_line_num, msg); + } } wpi::raw_istream& m_is; @@ -71,8 +73,9 @@ class LoadPersistentImpl { static std::pair ReadStringToken( wpi::StringRef source) { // Match opening quote - if (source.empty() || source.front() != '"') + if (source.empty() || source.front() != '"') { return std::make_pair(wpi::StringRef(), source); + } // Scan for ending double quote, checking for escaped as we go. size_t size = source.size(); @@ -87,12 +90,13 @@ static std::pair ReadStringToken( } static int fromxdigit(char ch) { - if (ch >= 'a' && ch <= 'f') + if (ch >= 'a' && ch <= 'f') { return (ch - 'a' + 10); - else if (ch >= 'A' && ch <= 'F') + } else if (ch >= 'A' && ch <= 'F') { return (ch - 'A' + 10); - else + } else { return ch - '0'; + } } static wpi::StringRef UnescapeString(wpi::StringRef source, @@ -134,7 +138,9 @@ static wpi::StringRef UnescapeString(wpi::StringRef source, } bool LoadPersistentImpl::Load(StringRef prefix, std::vector* entries) { - if (!ReadHeader()) return false; // header + if (!ReadHeader()) { + return false; // header + } while (ReadLine()) { // type @@ -147,7 +153,9 @@ bool LoadPersistentImpl::Load(StringRef prefix, std::vector* entries) { // name wpi::SmallString<128> buf; wpi::StringRef name = ReadName(buf); - if (name.empty() || !name.startswith(prefix)) continue; + if (name.empty() || !name.startswith(prefix)) { + continue; + } // = m_line = m_line.ltrim(" \t"); @@ -161,7 +169,9 @@ bool LoadPersistentImpl::Load(StringRef prefix, std::vector* entries) { auto value = ReadValue(type); // move to entries - if (value) entries->emplace_back(name, std::move(value)); + if (value) { + entries->emplace_back(name, std::move(value)); + } } return true; } @@ -171,8 +181,9 @@ bool LoadPersistentImpl::ReadLine() { while (!m_is.has_error()) { ++m_line_num; m_line = m_is.getline(m_line_buf, INT_MAX).trim(); - if (!m_line.empty() && m_line.front() != ';' && m_line.front() != '#') + if (!m_line.empty() && m_line.front() != ';' && m_line.front() != '#') { return true; + } } return false; } @@ -200,12 +211,13 @@ NT_Type LoadPersistentImpl::ReadType() { } else if (tok == "array") { wpi::StringRef array_tok; std::tie(array_tok, m_line) = m_line.split(' '); - if (array_tok == "boolean") + if (array_tok == "boolean") { return NT_BOOLEAN_ARRAY; - else if (array_tok == "double") + } else if (array_tok == "double") { return NT_DOUBLE_ARRAY; - else if (array_tok == "string") + } else if (array_tok == "string") { return NT_STRING_ARRAY; + } } return NT_UNASSIGNED; } @@ -247,8 +259,12 @@ std::shared_ptr LoadPersistentImpl::ReadValue(NT_Type type) { std::shared_ptr LoadPersistentImpl::ReadBooleanValue() { // only true or false is accepted - if (m_line == "true") return Value::MakeBoolean(true); - if (m_line == "false") return Value::MakeBoolean(false); + if (m_line == "true") { + return Value::MakeBoolean(true); + } + if (m_line == "false") { + return Value::MakeBoolean(false); + } Warn("unrecognized boolean value, not 'true' or 'false'"); return nullptr; } @@ -342,7 +358,9 @@ std::shared_ptr LoadPersistentImpl::ReadStringArrayValue() { m_buf_string_array.push_back(UnescapeString(tok, buf)); m_line = m_line.ltrim(" \t"); - if (m_line.empty()) break; + if (m_line.empty()) { + break; + } if (m_line.front() != ',') { Warn("expected comma between strings"); return nullptr; @@ -363,7 +381,9 @@ bool Storage::LoadEntries( std::vector entries; // load file - if (!LoadPersistentImpl(is, warn).Load(prefixStr, &entries)) return false; + if (!LoadPersistentImpl(is, warn).Load(prefixStr, &entries)) { + return false; + } // copy values into storage as quickly as possible so lock isn't held std::vector> msgs; @@ -373,7 +393,9 @@ bool Storage::LoadEntries( auto old_value = entry->value; entry->value = i.second; bool was_persist = entry->IsPersistent(); - if (!was_persist && persistent) entry->flags |= NT_PERSISTENT; + if (!was_persist && persistent) { + entry->flags |= NT_PERSISTENT; + } // if we're the server, assign an id if it doesn't have one if (m_server && entry->id == 0xffff) { @@ -389,7 +411,9 @@ bool Storage::LoadEntries( NT_NOTIFY_NEW | NT_NOTIFY_LOCAL); } else if (*old_value != *i.second) { unsigned int notify_flags = NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL; - if (!was_persist && persistent) notify_flags |= NT_NOTIFY_FLAGS; + if (!was_persist && persistent) { + notify_flags |= NT_NOTIFY_FLAGS; + } m_notifier.NotifyEntry(entry->local_id, i.first, i.second, notify_flags); } else if (!was_persist && persistent) { @@ -398,7 +422,9 @@ bool Storage::LoadEntries( } } - if (!m_dispatcher) continue; // shortcut + if (!m_dispatcher) { + continue; // shortcut + } ++entry->seq_num; // put on update queue @@ -407,19 +433,22 @@ bool Storage::LoadEntries( i.first, entry->id, entry->seq_num.value(), i.second, entry->flags)); } else if (entry->id != 0xffff) { // don't send an update if we don't have an assigned id yet - if (*old_value != *i.second) + if (*old_value != *i.second) { msgs.emplace_back( Message::EntryUpdate(entry->id, entry->seq_num.value(), i.second)); - if (!was_persist) + } + if (!was_persist) { msgs.emplace_back(Message::FlagsUpdate(entry->id, entry->flags)); + } } } if (m_dispatcher) { auto dispatcher = m_dispatcher; lock.unlock(); - for (auto& msg : msgs) + for (auto& msg : msgs) { dispatcher->QueueOutgoing(std::move(msg), nullptr, nullptr); + } } return true; @@ -430,8 +459,12 @@ const char* Storage::LoadPersistent( std::function warn) { std::error_code ec; wpi::raw_fd_istream is(filename, ec); - if (ec.value() != 0) return "could not open file"; - if (!LoadEntries(is, "", true, warn)) return "error reading file"; + if (ec.value() != 0) { + return "could not open file"; + } + if (!LoadEntries(is, "", true, warn)) { + return "error reading file"; + } return nullptr; } @@ -440,7 +473,11 @@ const char* Storage::LoadEntries( std::function warn) { std::error_code ec; wpi::raw_fd_istream is(filename, ec); - if (ec.value() != 0) return "could not open file"; - if (!LoadEntries(is, prefix, false, warn)) return "error reading file"; + if (ec.value() != 0) { + return "could not open file"; + } + if (!LoadEntries(is, prefix, false, warn)) { + return "error reading file"; + } return nullptr; } diff --git a/ntcore/src/main/native/cpp/Storage_save.cpp b/ntcore/src/main/native/cpp/Storage_save.cpp index 90656c069e..113cd4a5ba 100644 --- a/ntcore/src/main/native/cpp/Storage_save.cpp +++ b/ntcore/src/main/native/cpp/Storage_save.cpp @@ -83,17 +83,21 @@ void SavePersistentImpl::WriteHeader() { void SavePersistentImpl::WriteEntries(wpi::ArrayRef entries) { for (auto& i : entries) { - if (!i.second) continue; + if (!i.second) { + continue; + } WriteEntry(i.first, *i.second); } } void SavePersistentImpl::WriteEntry(wpi::StringRef name, const Value& value) { - if (!WriteType(value.type())) return; // type - WriteString(name); // name - m_os << '='; // '=' - WriteValue(value); // value - m_os << '\n'; // eol + if (!WriteType(value.type())) { + return; // type + } + WriteString(name); // name + m_os << '='; // '=' + WriteValue(value); // value + m_os << '\n'; // eol } bool SavePersistentImpl::WriteType(NT_Type type) { @@ -143,7 +147,9 @@ void SavePersistentImpl::WriteValue(const Value& value) { case NT_BOOLEAN_ARRAY: { bool first = true; for (auto elem : value.GetBooleanArray()) { - if (!first) m_os << ','; + if (!first) { + m_os << ','; + } first = false; m_os << (elem ? "true" : "false"); } @@ -152,7 +158,9 @@ void SavePersistentImpl::WriteValue(const Value& value) { case NT_DOUBLE_ARRAY: { bool first = true; for (auto elem : value.GetDoubleArray()) { - if (!first) m_os << ','; + if (!first) { + m_os << ','; + } first = false; m_os << wpi::format("%g", elem); } @@ -161,7 +169,9 @@ void SavePersistentImpl::WriteValue(const Value& value) { case NT_STRING_ARRAY: { bool first = true; for (auto& elem : value.GetStringArray()) { - if (!first) m_os << ','; + if (!first) { + m_os << ','; + } first = false; WriteString(elem); } @@ -174,7 +184,9 @@ void SavePersistentImpl::WriteValue(const Value& value) { void Storage::SavePersistent(wpi::raw_ostream& os, bool periodic) const { std::vector entries; - if (!GetPersistentEntries(periodic, &entries)) return; + if (!GetPersistentEntries(periodic, &entries)) { + return; + } SavePersistentImpl(os).Save(entries); } @@ -189,7 +201,9 @@ const char* Storage::SavePersistent(const Twine& filename, // Get entries before creating file std::vector entries; - if (!GetPersistentEntries(periodic, &entries)) return nullptr; + if (!GetPersistentEntries(periodic, &entries)) { + return nullptr; + } const char* err = nullptr; @@ -220,13 +234,17 @@ const char* Storage::SavePersistent(const Twine& filename, done: // try again if there was an error - if (err && periodic) m_persistent_dirty = true; + if (err && periodic) { + m_persistent_dirty = true; + } return err; } void Storage::SaveEntries(wpi::raw_ostream& os, const Twine& prefix) const { std::vector entries; - if (!GetEntries(prefix, &entries)) return; + if (!GetEntries(prefix, &entries)) { + return; + } SavePersistentImpl(os).Save(entries); } @@ -241,7 +259,9 @@ const char* Storage::SaveEntries(const Twine& filename, // Get entries before creating file std::vector entries; - if (!GetEntries(prefix, &entries)) return nullptr; + if (!GetEntries(prefix, &entries)) { + return nullptr; + } // start by writing to temporary file std::error_code ec; diff --git a/ntcore/src/main/native/cpp/Value.cpp b/ntcore/src/main/native/cpp/Value.cpp index 335a075804..ff7fcb7c0b 100644 --- a/ntcore/src/main/native/cpp/Value.cpp +++ b/ntcore/src/main/native/cpp/Value.cpp @@ -19,25 +19,28 @@ Value::Value() { Value::Value(NT_Type type, uint64_t time, const private_init&) { m_val.type = type; - if (time == 0) + if (time == 0) { m_val.last_change = wpi::Now(); - else + } else { m_val.last_change = time; - if (m_val.type == NT_BOOLEAN_ARRAY) + } + if (m_val.type == NT_BOOLEAN_ARRAY) { m_val.data.arr_boolean.arr = nullptr; - else if (m_val.type == NT_DOUBLE_ARRAY) + } else if (m_val.type == NT_DOUBLE_ARRAY) { m_val.data.arr_double.arr = nullptr; - else if (m_val.type == NT_STRING_ARRAY) + } else if (m_val.type == NT_STRING_ARRAY) { m_val.data.arr_string.arr = nullptr; + } } Value::~Value() { - if (m_val.type == NT_BOOLEAN_ARRAY) + if (m_val.type == NT_BOOLEAN_ARRAY) { delete[] m_val.data.arr_boolean.arr; - else if (m_val.type == NT_DOUBLE_ARRAY) + } else if (m_val.type == NT_DOUBLE_ARRAY) { delete[] m_val.data.arr_double.arr; - else if (m_val.type == NT_STRING_ARRAY) + } else if (m_val.type == NT_STRING_ARRAY) { delete[] m_val.data.arr_string.arr; + } } std::shared_ptr Value::MakeBooleanArray(wpi::ArrayRef value, @@ -137,8 +140,9 @@ void nt::ConvertToC(const Value& in, NT_Value* out) { auto v = in.GetStringArray(); out->data.arr_string.arr = static_cast( wpi::safe_malloc(v.size() * sizeof(NT_String))); - for (size_t i = 0; i < v.size(); ++i) + for (size_t i = 0; i < v.size(); ++i) { ConvertToC(v[i], &out->data.arr_string.arr[i]); + } out->data.arr_string.size = v.size(); break; } @@ -179,8 +183,9 @@ std::shared_ptr nt::ConvertFromC(const NT_Value& value) { case NT_STRING_ARRAY: { std::vector v; v.reserve(value.data.arr_string.size); - for (size_t i = 0; i < value.data.arr_string.size; ++i) + for (size_t i = 0; i < value.data.arr_string.size; ++i) { v.push_back(ConvertFromC(value.data.arr_string.arr[i])); + } return Value::MakeStringArray(std::move(v)); } default: @@ -190,7 +195,9 @@ std::shared_ptr nt::ConvertFromC(const NT_Value& value) { } bool nt::operator==(const Value& lhs, const Value& rhs) { - if (lhs.type() != rhs.type()) return false; + if (lhs.type() != rhs.type()) { + return false; + } switch (lhs.type()) { case NT_UNASSIGNED: return true; // XXX: is this better being false instead? @@ -203,15 +210,17 @@ bool nt::operator==(const Value& lhs, const Value& rhs) { case NT_RPC: return lhs.m_string == rhs.m_string; case NT_BOOLEAN_ARRAY: - if (lhs.m_val.data.arr_boolean.size != rhs.m_val.data.arr_boolean.size) + if (lhs.m_val.data.arr_boolean.size != rhs.m_val.data.arr_boolean.size) { return false; + } return std::memcmp(lhs.m_val.data.arr_boolean.arr, rhs.m_val.data.arr_boolean.arr, lhs.m_val.data.arr_boolean.size * sizeof(lhs.m_val.data.arr_boolean.arr[0])) == 0; case NT_DOUBLE_ARRAY: - if (lhs.m_val.data.arr_double.size != rhs.m_val.data.arr_double.size) + if (lhs.m_val.data.arr_double.size != rhs.m_val.data.arr_double.size) { return false; + } return std::memcmp(lhs.m_val.data.arr_double.arr, rhs.m_val.data.arr_double.arr, lhs.m_val.data.arr_double.size * diff --git a/ntcore/src/main/native/cpp/WireDecoder.cpp b/ntcore/src/main/native/cpp/WireDecoder.cpp index 53afa58895..e0bd01daf5 100644 --- a/ntcore/src/main/native/cpp/WireDecoder.cpp +++ b/ntcore/src/main/native/cpp/WireDecoder.cpp @@ -55,27 +55,37 @@ WireDecoder::WireDecoder(wpi::raw_istream& is, unsigned int proto_rev, m_error = nullptr; } -WireDecoder::~WireDecoder() { std::free(m_buf); } +WireDecoder::~WireDecoder() { + std::free(m_buf); +} bool WireDecoder::ReadDouble(double* val) { const char* buf; - if (!Read(&buf, 8)) return false; + if (!Read(&buf, 8)) { + return false; + } *val = ::ReadDouble(buf); return true; } void WireDecoder::Realloc(size_t len) { // Double current buffer size until we have enough space. - if (m_allocated >= len) return; + if (m_allocated >= len) { + return; + } size_t newlen = m_allocated * 2; - while (newlen < len) newlen *= 2; + while (newlen < len) { + newlen *= 2; + } m_buf = static_cast(wpi::safe_realloc(m_buf, newlen)); m_allocated = newlen; } bool WireDecoder::ReadType(NT_Type* type) { unsigned int itype; - if (!Read8(&itype)) return false; + if (!Read8(&itype)) { + return false; + } // Convert from byte value to enum switch (itype) { case 0x00: @@ -114,17 +124,23 @@ std::shared_ptr WireDecoder::ReadValue(NT_Type type) { switch (type) { case NT_BOOLEAN: { unsigned int v; - if (!Read8(&v)) return nullptr; + if (!Read8(&v)) { + return nullptr; + } return Value::MakeBoolean(v != 0); } case NT_DOUBLE: { double v; - if (!ReadDouble(&v)) return nullptr; + if (!ReadDouble(&v)) { + return nullptr; + } return Value::MakeDouble(v); } case NT_STRING: { std::string v; - if (!ReadString(&v)) return nullptr; + if (!ReadString(&v)) { + return nullptr; + } return Value::MakeString(std::move(v)); } case NT_RAW: { @@ -133,7 +149,9 @@ std::shared_ptr WireDecoder::ReadValue(NT_Type type) { return nullptr; } std::string v; - if (!ReadString(&v)) return nullptr; + if (!ReadString(&v)) { + return nullptr; + } return Value::MakeRaw(std::move(v)); } case NT_RPC: { @@ -142,42 +160,60 @@ std::shared_ptr WireDecoder::ReadValue(NT_Type type) { return nullptr; } std::string v; - if (!ReadString(&v)) return nullptr; + if (!ReadString(&v)) { + return nullptr; + } return Value::MakeRpc(std::move(v)); } case NT_BOOLEAN_ARRAY: { // size unsigned int size; - if (!Read8(&size)) return nullptr; + if (!Read8(&size)) { + return nullptr; + } // array values const char* buf; - if (!Read(&buf, size)) return nullptr; + if (!Read(&buf, size)) { + return nullptr; + } std::vector v(size); - for (unsigned int i = 0; i < size; ++i) v[i] = buf[i] ? 1 : 0; + for (unsigned int i = 0; i < size; ++i) { + v[i] = buf[i] ? 1 : 0; + } return Value::MakeBooleanArray(std::move(v)); } case NT_DOUBLE_ARRAY: { // size unsigned int size; - if (!Read8(&size)) return nullptr; + if (!Read8(&size)) { + return nullptr; + } // array values const char* buf; - if (!Read(&buf, size * 8)) return nullptr; + if (!Read(&buf, size * 8)) { + return nullptr; + } std::vector v(size); - for (unsigned int i = 0; i < size; ++i) v[i] = ::ReadDouble(buf); + for (unsigned int i = 0; i < size; ++i) { + v[i] = ::ReadDouble(buf); + } return Value::MakeDoubleArray(std::move(v)); } case NT_STRING_ARRAY: { // size unsigned int size; - if (!Read8(&size)) return nullptr; + if (!Read8(&size)) { + return nullptr; + } // array values std::vector v(size); for (unsigned int i = 0; i < size; ++i) { - if (!ReadString(&v[i])) return nullptr; + if (!ReadString(&v[i])) { + return nullptr; + } } return Value::MakeStringArray(std::move(v)); } @@ -191,15 +227,21 @@ bool WireDecoder::ReadString(std::string* str) { size_t len; if (m_proto_rev < 0x0300u) { unsigned int v; - if (!Read16(&v)) return false; + if (!Read16(&v)) { + return false; + } len = v; } else { uint64_t v; - if (!ReadUleb128(&v)) return false; + if (!ReadUleb128(&v)) { + return false; + } len = v; } const char* buf; - if (!Read(&buf, len)) return false; + if (!Read(&buf, len)) { + return false; + } *str = wpi::StringRef(buf, len); return true; } diff --git a/ntcore/src/main/native/cpp/WireDecoder.h b/ntcore/src/main/native/cpp/WireDecoder.h index 35948be790..972be57b1f 100644 --- a/ntcore/src/main/native/cpp/WireDecoder.h +++ b/ntcore/src/main/native/cpp/WireDecoder.h @@ -56,7 +56,9 @@ class WireDecoder { * Caution: the buffer is only temporarily valid. */ bool Read(const char** buf, size_t len) { - if (len > m_allocated) Realloc(len); + if (len > m_allocated) { + Realloc(len); + } *buf = m_buf; m_is.read(m_buf, len); #if 0 @@ -78,7 +80,9 @@ class WireDecoder { /* Reads a single byte. */ bool Read8(unsigned int* val) { const char* buf; - if (!Read(&buf, 1)) return false; + if (!Read(&buf, 1)) { + return false; + } *val = (*reinterpret_cast(buf)) & 0xff; return true; } @@ -86,7 +90,9 @@ class WireDecoder { /* Reads a 16-bit word. */ bool Read16(unsigned int* val) { const char* buf; - if (!Read(&buf, 2)) return false; + if (!Read(&buf, 2)) { + return false; + } unsigned int v = (*reinterpret_cast(buf)) & 0xff; ++buf; v <<= 8; @@ -98,7 +104,9 @@ class WireDecoder { /* Reads a 32-bit word. */ bool Read32(uint32_t* val) { const char* buf; - if (!Read(&buf, 4)) return false; + if (!Read(&buf, 4)) { + return false; + } unsigned int v = (*reinterpret_cast(buf)) & 0xff; ++buf; v <<= 8; diff --git a/ntcore/src/main/native/cpp/WireEncoder.cpp b/ntcore/src/main/native/cpp/WireEncoder.cpp index faf61c90e9..ca6bd332d0 100644 --- a/ntcore/src/main/native/cpp/WireEncoder.cpp +++ b/ntcore/src/main/native/cpp/WireEncoder.cpp @@ -30,7 +30,9 @@ void WireEncoder::WriteDouble(double val) { static_cast((v >> 8) & 0xff), static_cast(v & 0xff)}); } -void WireEncoder::WriteUleb128(uint32_t val) { wpi::WriteUleb128(m_data, val); } +void WireEncoder::WriteUleb128(uint32_t val) { + wpi::WriteUleb128(m_data, val); +} void WireEncoder::WriteType(NT_Type type) { char ch; @@ -84,29 +86,41 @@ size_t WireEncoder::GetValueSize(const Value& value) const { case NT_STRING: return GetStringSize(value.GetString()); case NT_RAW: - if (m_proto_rev < 0x0300u) return 0; + if (m_proto_rev < 0x0300u) { + return 0; + } return GetStringSize(value.GetRaw()); case NT_RPC: - if (m_proto_rev < 0x0300u) return 0; + if (m_proto_rev < 0x0300u) { + return 0; + } return GetStringSize(value.GetRpc()); case NT_BOOLEAN_ARRAY: { // 1-byte size, 1 byte per element size_t size = value.GetBooleanArray().size(); - if (size > 0xff) size = 0xff; // size is only 1 byte, truncate + if (size > 0xff) { + size = 0xff; // size is only 1 byte, truncate + } return 1 + size; } case NT_DOUBLE_ARRAY: { // 1-byte size, 8 bytes per element size_t size = value.GetDoubleArray().size(); - if (size > 0xff) size = 0xff; // size is only 1 byte, truncate + if (size > 0xff) { + size = 0xff; // size is only 1 byte, truncate + } return 1 + size * 8; } case NT_STRING_ARRAY: { auto v = value.GetStringArray(); size_t size = v.size(); - if (size > 0xff) size = 0xff; // size is only 1 byte, truncate - size_t len = 1; // 1-byte size - for (size_t i = 0; i < size; ++i) len += GetStringSize(v[i]); + if (size > 0xff) { + size = 0xff; // size is only 1 byte, truncate + } + size_t len = 1; // 1-byte size + for (size_t i = 0; i < size; ++i) { + len += GetStringSize(v[i]); + } return len; } default: @@ -142,28 +156,40 @@ void WireEncoder::WriteValue(const Value& value) { case NT_BOOLEAN_ARRAY: { auto v = value.GetBooleanArray(); size_t size = v.size(); - if (size > 0xff) size = 0xff; // size is only 1 byte, truncate + if (size > 0xff) { + size = 0xff; // size is only 1 byte, truncate + } Write8(size); - for (size_t i = 0; i < size; ++i) Write8(v[i] ? 1 : 0); + for (size_t i = 0; i < size; ++i) { + Write8(v[i] ? 1 : 0); + } break; } case NT_DOUBLE_ARRAY: { auto v = value.GetDoubleArray(); size_t size = v.size(); - if (size > 0xff) size = 0xff; // size is only 1 byte, truncate + if (size > 0xff) { + size = 0xff; // size is only 1 byte, truncate + } Write8(size); - for (size_t i = 0; i < size; ++i) WriteDouble(v[i]); + for (size_t i = 0; i < size; ++i) { + WriteDouble(v[i]); + } break; } case NT_STRING_ARRAY: { auto v = value.GetStringArray(); size_t size = v.size(); - if (size > 0xff) size = 0xff; // size is only 1 byte, truncate + if (size > 0xff) { + size = 0xff; // size is only 1 byte, truncate + } Write8(size); - for (size_t i = 0; i < size; ++i) WriteString(v[i]); + for (size_t i = 0; i < size; ++i) { + WriteString(v[i]); + } break; } default: @@ -175,7 +201,9 @@ void WireEncoder::WriteValue(const Value& value) { size_t WireEncoder::GetStringSize(wpi::StringRef str) const { if (m_proto_rev < 0x0300u) { size_t len = str.size(); - if (len > 0xffff) len = 0xffff; // Limited to 64K length; truncate + if (len > 0xffff) { + len = 0xffff; // Limited to 64K length; truncate + } return 2 + len; } return wpi::SizeUleb128(str.size()) + str.size(); @@ -185,7 +213,9 @@ void WireEncoder::WriteString(wpi::StringRef str) { // length size_t len = str.size(); if (m_proto_rev < 0x0300u) { - if (len > 0xffff) len = 0xffff; // Limited to 64K length; truncate + if (len > 0xffff) { + len = 0xffff; // Limited to 64K length; truncate + } Write16(len); } else { WriteUleb128(len); diff --git a/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp b/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp index 8ca1a68828..03bb8c000b 100644 --- a/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp +++ b/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp @@ -64,18 +64,23 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { jvm = vm; JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; + } // Cache references to classes for (auto& c : classes) { *c.cls = JClass(env, c.name); - if (!*c.cls) return JNI_ERR; + if (!*c.cls) { + return JNI_ERR; + } } for (auto& c : exceptions) { *c.cls = JException(env, c.name); - if (!*c.cls) return JNI_ERR; + if (!*c.cls) { + return JNI_ERR; + } } return JNI_VERSION_1_6; @@ -83,8 +88,9 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) { JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return; + } // Delete global references for (auto& c : classes) { c.cls->free(env); @@ -104,40 +110,52 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) { inline std::shared_ptr FromJavaRaw(JNIEnv* env, jbyteArray jarr, jlong time) { CriticalJByteArrayRef ref{env, jarr}; - if (!ref) return nullptr; + if (!ref) { + return nullptr; + } return nt::Value::MakeRaw(ref, time); } inline std::shared_ptr FromJavaRawBB(JNIEnv* env, jobject jbb, int len, jlong time) { JByteArrayRef ref{env, jbb, len}; - if (!ref) return nullptr; + if (!ref) { + return nullptr; + } return nt::Value::MakeRaw(ref.str(), time); } inline std::shared_ptr FromJavaRpc(JNIEnv* env, jbyteArray jarr, jlong time) { CriticalJByteArrayRef ref{env, jarr}; - if (!ref) return nullptr; + if (!ref) { + return nullptr; + } return nt::Value::MakeRpc(ref.str(), time); } std::shared_ptr FromJavaBooleanArray(JNIEnv* env, jbooleanArray jarr, jlong time) { CriticalJBooleanArrayRef ref{env, jarr}; - if (!ref) return nullptr; + if (!ref) { + return nullptr; + } wpi::ArrayRef elements{ref}; size_t len = elements.size(); std::vector arr; arr.reserve(len); - for (size_t i = 0; i < len; ++i) arr.push_back(elements[i]); + for (size_t i = 0; i < len; ++i) { + arr.push_back(elements[i]); + } return nt::Value::MakeBooleanArray(arr, time); } std::shared_ptr FromJavaDoubleArray(JNIEnv* env, jdoubleArray jarr, jlong time) { CriticalJDoubleArrayRef ref{env, jarr}; - if (!ref) return nullptr; + if (!ref) { + return nullptr; + } return nt::Value::MakeDoubleArray(ref, time); } @@ -149,7 +167,9 @@ std::shared_ptr FromJavaStringArray(JNIEnv* env, jobjectArray jarr, for (size_t i = 0; i < len; ++i) { JLocal elem{ env, static_cast(env->GetObjectArrayElement(jarr, i))}; - if (!elem) return nullptr; + if (!elem) { + return nullptr; + } arr.push_back(JStringRef{env, elem}.str()); } return nt::Value::MakeStringArray(std::move(arr), time); @@ -162,10 +182,12 @@ std::shared_ptr FromJavaStringArray(JNIEnv* env, jobjectArray jarr, static jobject MakeJObject(JNIEnv* env, const nt::Value& value) { static jmethodID booleanConstructor = nullptr; static jmethodID doubleConstructor = nullptr; - if (!booleanConstructor) + if (!booleanConstructor) { booleanConstructor = env->GetMethodID(booleanCls, "", "(Z)V"); - if (!doubleConstructor) + } + if (!doubleConstructor) { doubleConstructor = env->GetMethodID(doubleCls, "", "(D)V"); + } switch (value.type()) { case NT_BOOLEAN: @@ -194,9 +216,10 @@ static jobject MakeJObject(JNIEnv* env, const nt::Value& value) { static jobject MakeJValue(JNIEnv* env, const nt::Value* value) { static jmethodID constructor = env->GetMethodID(valueCls, "", "(ILjava/lang/Object;J)V"); - if (!value) + if (!value) { return env->NewObject(valueCls, constructor, (jint)NT_UNASSIGNED, nullptr, (jlong)0); + } return env->NewObject(valueCls, constructor, (jint)value->type(), MakeJObject(env, *value), (jlong)value->time()); } @@ -281,7 +304,9 @@ static jobjectArray MakeJObject(JNIEnv* env, jobject inst, wpi::ArrayRef arr) { jobjectArray jarr = env->NewObjectArray(arr.size(), connectionNotificationCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal elem{env, MakeJObject(env, inst, arr[i])}; env->SetObjectArrayElement(jarr, i, elem.obj()); @@ -293,7 +318,9 @@ static jobjectArray MakeJObject(JNIEnv* env, jobject inst, wpi::ArrayRef arr) { jobjectArray jarr = env->NewObjectArray(arr.size(), entryNotificationCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal elem{env, MakeJObject(env, inst, arr[i])}; env->SetObjectArrayElement(jarr, i, elem.obj()); @@ -304,7 +331,9 @@ static jobjectArray MakeJObject(JNIEnv* env, jobject inst, static jobjectArray MakeJObject(JNIEnv* env, jobject inst, wpi::ArrayRef arr) { jobjectArray jarr = env->NewObjectArray(arr.size(), logMessageCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal elem{env, MakeJObject(env, inst, arr[i])}; env->SetObjectArrayElement(jarr, i, elem.obj()); @@ -315,7 +344,9 @@ static jobjectArray MakeJObject(JNIEnv* env, jobject inst, static jobjectArray MakeJObject(JNIEnv* env, jobject inst, wpi::ArrayRef arr) { jobjectArray jarr = env->NewObjectArray(arr.size(), rpcAnswerCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal elem{env, MakeJObject(env, inst, arr[i])}; env->SetObjectArrayElement(jarr, i, elem.obj()); @@ -513,7 +544,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setRaw__IJ_3BZ return false; } auto v = FromJavaRaw(env, value, time); - if (!v) return false; + if (!v) { + return false; + } if (force) { nt::SetEntryTypeValue(entry, v); return JNI_TRUE; @@ -536,7 +569,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setRaw__IJLjava_nio_ByteBuffer return false; } auto v = FromJavaRawBB(env, value, len, time); - if (!v) return false; + if (!v) { + return false; + } if (force) { nt::SetEntryTypeValue(entry, v); return JNI_TRUE; @@ -559,7 +594,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setBooleanArray return false; } auto v = FromJavaBooleanArray(env, value, time); - if (!v) return false; + if (!v) { + return false; + } if (force) { nt::SetEntryTypeValue(entry, v); return JNI_TRUE; @@ -582,7 +619,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setDoubleArray return false; } auto v = FromJavaDoubleArray(env, value, time); - if (!v) return false; + if (!v) { + return false; + } if (force) { nt::SetEntryTypeValue(entry, v); return JNI_TRUE; @@ -605,7 +644,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setStringArray return false; } auto v = FromJavaStringArray(env, value, time); - if (!v) return false; + if (!v) { + return false; + } if (force) { nt::SetEntryTypeValue(entry, v); return JNI_TRUE; @@ -636,7 +677,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getBoolean (JNIEnv*, jclass, jint entry, jboolean defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsBoolean()) return defaultValue; + if (!val || !val->IsBoolean()) { + return defaultValue; + } return val->GetBoolean(); } @@ -650,7 +693,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getDouble (JNIEnv*, jclass, jint entry, jdouble defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsDouble()) return defaultValue; + if (!val || !val->IsDouble()) { + return defaultValue; + } return val->GetDouble(); } @@ -664,7 +709,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getString (JNIEnv* env, jclass, jint entry, jstring defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsString()) return defaultValue; + if (!val || !val->IsString()) { + return defaultValue; + } return MakeJString(env, val->GetString()); } @@ -678,7 +725,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getRaw (JNIEnv* env, jclass, jint entry, jbyteArray defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsRaw()) return defaultValue; + if (!val || !val->IsRaw()) { + return defaultValue; + } return MakeJByteArray(env, val->GetRaw()); } @@ -692,7 +741,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getBooleanArray (JNIEnv* env, jclass, jint entry, jbooleanArray defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsBooleanArray()) return defaultValue; + if (!val || !val->IsBooleanArray()) { + return defaultValue; + } return MakeJBooleanArray(env, val->GetBooleanArray()); } @@ -706,7 +757,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getDoubleArray (JNIEnv* env, jclass, jint entry, jdoubleArray defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsDoubleArray()) return defaultValue; + if (!val || !val->IsDoubleArray()) { + return defaultValue; + } return MakeJDoubleArray(env, val->GetDoubleArray()); } @@ -720,7 +773,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getStringArray (JNIEnv* env, jclass, jint entry, jobjectArray defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsStringArray()) return defaultValue; + if (!val || !val->IsStringArray()) { + return defaultValue; + } return MakeJStringArray(env, val->GetStringArray()); } @@ -911,7 +966,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getEntryInfo } auto arr = nt::GetEntryInfo(inst, JStringRef{env, prefix}.str(), types); jobjectArray jarr = env->NewObjectArray(arr.size(), entryInfoCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal jelem{env, MakeJObject(env, instObject, arr[i])}; env->SetObjectArrayElement(jarr, i, jelem); @@ -1291,7 +1348,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getRpcResult__II (JNIEnv* env, jclass, jint entry, jint call) { std::string result; - if (!nt::GetRpcResult(entry, call, &result)) return nullptr; + if (!nt::GetRpcResult(entry, call, &result)) { + return nullptr; + } return MakeJByteArray(env, result); } @@ -1306,8 +1365,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getRpcResult__IID { std::string result; bool timed_out = false; - if (!nt::GetRpcResult(entry, call, &result, timeout, &timed_out)) + if (!nt::GetRpcResult(entry, call, &result, timeout, &timed_out)) { return nullptr; + } return MakeJByteArray(env, result); } @@ -1333,7 +1393,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getRpc (JNIEnv* env, jclass, jint entry, jbyteArray defaultValue) { auto val = nt::GetEntryValue(entry); - if (!val || !val->IsRpc()) return defaultValue; + if (!val || !val->IsRpc()) { + return defaultValue; + } return MakeJByteArray(env, val->GetRpc()); } @@ -1475,7 +1537,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_startClient__I_3Ljava_lang_Str return; } jint* portInts = env->GetIntArrayElements(ports, nullptr); - if (!portInts) return; + if (!portInts) { + return; + } std::vector names; std::vector> servers; @@ -1560,7 +1624,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setServer__I_3Ljava_lang_Strin return; } jint* portInts = env->GetIntArrayElements(ports, nullptr); - if (!portInts) return; + if (!portInts) { + return; + } std::vector names; std::vector> servers; @@ -1653,7 +1719,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getConnections auto arr = nt::GetConnections(inst); jobjectArray jarr = env->NewObjectArray(arr.size(), connectionInfoCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal jelem{env, MakeJObject(env, arr[i])}; env->SetObjectArrayElement(jarr, i, jelem); @@ -1687,7 +1755,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_savePersistent return; } const char* err = nt::SavePersistent(inst, JStringRef{env, filename}.str()); - if (err) persistentEx.Throw(env, err); + if (err) { + persistentEx.Throw(env, err); + } } /* @@ -1737,7 +1807,9 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_saveEntries } const char* err = nt::SaveEntries(inst, JStringRef{env, filename}.str(), JStringRef{env, prefix}.str()); - if (err) persistentEx.Throw(env, err); + if (err) { + persistentEx.Throw(env, err); + } } /* diff --git a/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp b/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp index 794468b5d5..f4a9bd52ac 100644 --- a/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp +++ b/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp @@ -31,7 +31,9 @@ unsigned int NetworkTable::s_port = NT_DEFAULT_PORT; StringRef NetworkTable::BasenameKey(StringRef key) { size_t slash = key.rfind(PATH_SEPARATOR_CHAR); - if (slash == StringRef::npos) return key; + if (slash == StringRef::npos) { + return key; + } return key.substr(slash + 1); } @@ -45,7 +47,9 @@ StringRef NetworkTable::NormalizeKey(const Twine& key, wpi::SmallVectorImpl& buf, bool withLeadingSlash) { buf.clear(); - if (withLeadingSlash) buf.push_back(PATH_SEPARATOR_CHAR); + if (withLeadingSlash) { + buf.push_back(PATH_SEPARATOR_CHAR); + } // for each path element, add it with a slash following wpi::SmallString<128> keyBuf; StringRef keyStr = key.toStringRef(keyBuf); @@ -56,7 +60,9 @@ StringRef NetworkTable::NormalizeKey(const Twine& key, buf.push_back(PATH_SEPARATOR_CHAR); } // remove trailing slash if the input key didn't have one - if (!keyStr.empty() && keyStr.back() != PATH_SEPARATOR_CHAR) buf.pop_back(); + if (!keyStr.empty() && keyStr.back() != PATH_SEPARATOR_CHAR) { + buf.pop_back(); + } return StringRef(buf.data(), buf.size()); } @@ -85,11 +91,15 @@ std::vector NetworkTable::GetHierarchy(const Twine& key) { } void NetworkTable::Initialize() { - if (s_running) Shutdown(); + if (s_running) { + Shutdown(); + } auto inst = NetworkTableInstance::GetDefault(); if (s_client) { inst.StartClient(); - if (s_enable_ds) inst.StartDSClient(s_port); + if (s_enable_ds) { + inst.StartDSClient(s_port); + } } else { inst.StartServer(s_persistent_filename, "", s_port); } @@ -97,7 +107,9 @@ void NetworkTable::Initialize() { } void NetworkTable::Shutdown() { - if (!s_running) return; + if (!s_running) { + return; + } auto inst = NetworkTableInstance::GetDefault(); if (s_client) { inst.StopDSClient(); @@ -108,14 +120,20 @@ void NetworkTable::Shutdown() { s_running = false; } -void NetworkTable::SetClientMode() { s_client = true; } +void NetworkTable::SetClientMode() { + s_client = true; +} -void NetworkTable::SetServerMode() { s_client = false; } +void NetworkTable::SetServerMode() { + s_client = false; +} void NetworkTable::SetTeam(int team) { auto inst = NetworkTableInstance::GetDefault(); inst.SetServerTeam(team, s_port); - if (s_enable_ds) inst.StartDSClient(s_port); + if (s_enable_ds) { + inst.StartDSClient(s_port); + } } void NetworkTable::SetIPAddress(StringRef address) { @@ -124,35 +142,42 @@ void NetworkTable::SetIPAddress(StringRef address) { inst.SetServer(addr_copy.c_str(), s_port); // Stop the DS client if we're explicitly connecting to localhost - if (address == "localhost" || address == "127.0.0.1") + if (address == "localhost" || address == "127.0.0.1") { inst.StopDSClient(); - else if (s_enable_ds) + } else if (s_enable_ds) { inst.StartDSClient(s_port); + } } void NetworkTable::SetIPAddress(ArrayRef addresses) { auto inst = NetworkTableInstance::GetDefault(); wpi::SmallVector servers; - for (const auto& ip_address : addresses) servers.emplace_back(ip_address); + for (const auto& ip_address : addresses) { + servers.emplace_back(ip_address); + } inst.SetServer(servers, s_port); // Stop the DS client if we're explicitly connecting to localhost if (!addresses.empty() && - (addresses[0] == "localhost" || addresses[0] == "127.0.0.1")) + (addresses[0] == "localhost" || addresses[0] == "127.0.0.1")) { inst.StopDSClient(); - else if (s_enable_ds) + } else if (s_enable_ds) { inst.StartDSClient(s_port); + } } -void NetworkTable::SetPort(unsigned int port) { s_port = port; } +void NetworkTable::SetPort(unsigned int port) { + s_port = port; +} void NetworkTable::SetDSClientEnabled(bool enabled) { auto inst = NetworkTableInstance::GetDefault(); s_enable_ds = enabled; - if (s_enable_ds) + if (s_enable_ds) { inst.StartDSClient(s_port); - else + } else { inst.StopDSClient(); + } } void NetworkTable::SetPersistentFilename(StringRef filename) { @@ -167,7 +192,9 @@ void NetworkTable::GlobalDeleteAll() { NetworkTableInstance::GetDefault().DeleteAllEntries(); } -void NetworkTable::Flush() { NetworkTableInstance::GetDefault().Flush(); } +void NetworkTable::Flush() { + NetworkTableInstance::GetDefault().Flush(); +} void NetworkTable::SetUpdateRate(double interval) { NetworkTableInstance::GetDefault().SetUpdateRate(interval); @@ -184,7 +211,9 @@ const char* NetworkTable::LoadPersistent( } std::shared_ptr NetworkTable::GetTable(StringRef key) { - if (!s_running) Initialize(); + if (!s_running) { + Initialize(); + } return NetworkTableInstance::GetDefault().GetTable(key); } @@ -192,8 +221,12 @@ NetworkTable::NetworkTable(NT_Inst inst, const Twine& path, const private_init&) : m_inst(inst), m_path(path.str()) {} NetworkTable::~NetworkTable() { - for (auto& i : m_listeners) RemoveEntryListener(i.second); - for (auto i : m_lambdaListeners) RemoveEntryListener(i); + for (auto& i : m_listeners) { + RemoveEntryListener(i.second); + } + for (auto i : m_lambdaListeners) { + RemoveEntryListener(i); + } } NetworkTableInstance NetworkTable::GetInstance() const { @@ -218,7 +251,9 @@ NT_EntryListener NetworkTable::AddEntryListener(TableEntryListener listener, m_inst, m_path + Twine(PATH_SEPARATOR_CHAR), [=](const EntryNotification& event) { StringRef relative_key = event.name.substr(prefix_len); - if (relative_key.find(PATH_SEPARATOR_CHAR) != StringRef::npos) return; + if (relative_key.find(PATH_SEPARATOR_CHAR) != StringRef::npos) { + return; + } listener(const_cast(this), relative_key, NetworkTableEntry{event.entry}, event.value, event.flags); }, @@ -250,7 +285,9 @@ void NetworkTable::AddTableListener(ITableListener* listener) { void NetworkTable::AddTableListener(ITableListener* listener, bool immediateNotify) { unsigned int flags = NT_NOTIFY_NEW | NT_NOTIFY_UPDATE; - if (immediateNotify) flags |= NT_NOTIFY_IMMEDIATE; + if (immediateNotify) { + flags |= NT_NOTIFY_IMMEDIATE; + } AddTableListenerEx(listener, flags); } @@ -264,7 +301,9 @@ void NetworkTable::AddTableListenerEx(ITableListener* listener, m_inst, path, [=](const EntryNotification& event) { StringRef relative_key = event.name.substr(prefix_len); - if (relative_key.find(PATH_SEPARATOR_CHAR) != StringRef::npos) return; + if (relative_key.find(PATH_SEPARATOR_CHAR) != StringRef::npos) { + return; + } listener->ValueChangedEx(this, relative_key, event.value, event.flags); }, flags); @@ -274,7 +313,9 @@ void NetworkTable::AddTableListenerEx(ITableListener* listener, void NetworkTable::AddTableListener(StringRef key, ITableListener* listener, bool immediateNotify) { unsigned int flags = NT_NOTIFY_NEW | NT_NOTIFY_UPDATE; - if (immediateNotify) flags |= NT_NOTIFY_IMMEDIATE; + if (immediateNotify) { + flags |= NT_NOTIFY_IMMEDIATE; + } AddTableListenerEx(key, listener, flags); } @@ -306,16 +347,21 @@ NT_EntryListener NetworkTable::AddSubTableListener(TableListener listener, auto notified_tables = std::make_shared>(); unsigned int flags = NT_NOTIFY_NEW | NT_NOTIFY_IMMEDIATE; - if (localNotify) flags |= NT_NOTIFY_LOCAL; + if (localNotify) { + flags |= NT_NOTIFY_LOCAL; + } NT_EntryListener id = nt::AddEntryListener( m_inst, m_path + Twine(PATH_SEPARATOR_CHAR), [=](const EntryNotification& event) { StringRef relative_key = event.name.substr(prefix_len); auto end_sub_table = relative_key.find(PATH_SEPARATOR_CHAR); - if (end_sub_table == StringRef::npos) return; - StringRef sub_table_key = relative_key.substr(0, end_sub_table); - if (notified_tables->find(sub_table_key) == notified_tables->end()) + if (end_sub_table == StringRef::npos) { return; + } + StringRef sub_table_key = relative_key.substr(0, end_sub_table); + if (notified_tables->find(sub_table_key) == notified_tables->end()) { + return; + } notified_tables->insert(std::make_pair(sub_table_key, '\0')); listener(this, sub_table_key, this->GetSubTable(sub_table_key)); }, @@ -341,16 +387,21 @@ void NetworkTable::AddSubTableListener(ITableListener* listener, auto notified_tables = std::make_shared>(); unsigned int flags = NT_NOTIFY_NEW | NT_NOTIFY_IMMEDIATE; - if (localNotify) flags |= NT_NOTIFY_LOCAL; + if (localNotify) { + flags |= NT_NOTIFY_LOCAL; + } NT_EntryListener id = nt::AddEntryListener( m_inst, m_path + Twine(PATH_SEPARATOR_CHAR), [=](const EntryNotification& event) { StringRef relative_key = event.name.substr(prefix_len); auto end_sub_table = relative_key.find(PATH_SEPARATOR_CHAR); - if (end_sub_table == StringRef::npos) return; - StringRef sub_table_key = relative_key.substr(0, end_sub_table); - if (notified_tables->find(sub_table_key) == notified_tables->end()) + if (end_sub_table == StringRef::npos) { return; + } + StringRef sub_table_key = relative_key.substr(0, end_sub_table); + if (notified_tables->find(sub_table_key) == notified_tables->end()) { + return; + } notified_tables->insert(std::make_pair(sub_table_key, '\0')); listener->ValueChangedEx(this, sub_table_key, nullptr, event.flags); }, @@ -364,8 +415,9 @@ void NetworkTable::RemoveTableListener(ITableListener* listener) { std::remove_if(m_listeners.begin(), m_listeners.end(), [=](const Listener& x) { return x.first == listener; }); - for (auto i = matches_begin; i != m_listeners.end(); ++i) + for (auto i = matches_begin; i != m_listeners.end(); ++i) { RemoveEntryListener(i->second); + } m_listeners.erase(matches_begin, m_listeners.end()); } @@ -377,8 +429,9 @@ std::shared_ptr NetworkTable::GetSubTable( bool NetworkTable::ContainsKey(const Twine& key) const { if (key.isTriviallyEmpty() || - (key.isSingleStringRef() && key.getSingleStringRef().empty())) + (key.isSingleStringRef() && key.getSingleStringRef().empty())) { return false; + } return GetEntry(key).Exists(); } @@ -397,7 +450,9 @@ std::vector NetworkTable::GetKeys(int types) const { std::scoped_lock lock(m_mutex); for (auto& info : infos) { auto relative_key = StringRef(info.name).substr(prefix_len); - if (relative_key.find(PATH_SEPARATOR_CHAR) != StringRef::npos) continue; + if (relative_key.find(PATH_SEPARATOR_CHAR) != StringRef::npos) { + continue; + } keys.push_back(relative_key); m_entries[relative_key] = info.entry; } @@ -411,7 +466,9 @@ std::vector NetworkTable::GetSubTables() const { GetEntryInfo(m_inst, m_path + Twine(PATH_SEPARATOR_CHAR), 0)) { auto relative_key = StringRef(entry.name).substr(prefix_len); size_t end_subtable = relative_key.find(PATH_SEPARATOR_CHAR); - if (end_subtable == StringRef::npos) continue; + if (end_subtable == StringRef::npos) { + continue; + } keys.push_back(relative_key.substr(0, end_subtable)); } return keys; @@ -441,7 +498,9 @@ unsigned int NetworkTable::GetFlags(StringRef key) const { return GetEntry(key).GetFlags(); } -void NetworkTable::Delete(const Twine& key) { GetEntry(key).Delete(); } +void NetworkTable::Delete(const Twine& key) { + GetEntry(key).Delete(); +} bool NetworkTable::PutNumber(StringRef key, double value) { return GetEntry(key).SetDouble(value); @@ -547,7 +606,9 @@ std::shared_ptr NetworkTable::GetValue(const Twine& key) const { return GetEntry(key).GetValue(); } -StringRef NetworkTable::GetPath() const { return m_path; } +StringRef NetworkTable::GetPath() const { + return m_path; +} const char* NetworkTable::SaveEntries(const Twine& filename) const { return nt::SaveEntries(m_inst, filename, m_path + Twine(PATH_SEPARATOR_CHAR)); diff --git a/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp b/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp index ddcc23d6a4..6697602eea 100644 --- a/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp +++ b/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp @@ -12,7 +12,9 @@ std::shared_ptr NetworkTableInstance::GetTable( const Twine& key) const { StringRef simple; bool isSimple = key.isSingleStringRef(); - if (isSimple) simple = key.getSingleStringRef(); + if (isSimple) { + simple = key.getSingleStringRef(); + } if (isSimple && (simple.empty() || simple == "/")) { return std::make_shared(m_handle, "", NetworkTable::private_init{}); @@ -29,16 +31,18 @@ std::shared_ptr NetworkTableInstance::GetTable( void NetworkTableInstance::StartClient(ArrayRef servers, unsigned int port) { wpi::SmallVector, 8> server_ports; - for (const auto& server : servers) + for (const auto& server : servers) { server_ports.emplace_back(std::make_pair(server, port)); + } StartClient(server_ports); } void NetworkTableInstance::SetServer(ArrayRef servers, unsigned int port) { wpi::SmallVector, 8> server_ports; - for (const auto& server : servers) + for (const auto& server : servers) { server_ports.emplace_back(std::make_pair(server, port)); + } SetServer(server_ports); } diff --git a/ntcore/src/main/native/cpp/ntcore_c.cpp b/ntcore/src/main/native/cpp/ntcore_c.cpp index 3ffa8799fa..03f609035a 100644 --- a/ntcore/src/main/native/cpp/ntcore_c.cpp +++ b/ntcore/src/main/native/cpp/ntcore_c.cpp @@ -56,14 +56,16 @@ static void ConvertToC(const RpcDefinition& in, NT_RpcDefinition* out) { out->num_params = in.params.size(); out->params = static_cast( wpi::safe_malloc(in.params.size() * sizeof(NT_RpcParamDef))); - for (size_t i = 0; i < in.params.size(); ++i) + for (size_t i = 0; i < in.params.size(); ++i) { ConvertToC(in.params[i], &out->params[i]); + } out->num_results = in.results.size(); out->results = static_cast( wpi::safe_malloc(in.results.size() * sizeof(NT_RpcResultDef))); - for (size_t i = 0; i < in.results.size(); ++i) + for (size_t i = 0; i < in.results.size(); ++i) { ConvertToC(in.results[i], &out->results[i]); + } } static void ConvertToC(const RpcAnswer& in, NT_RpcAnswer* out) { @@ -99,11 +101,17 @@ static void ConvertToC(const LogMessage& in, NT_LogMessage* out) { template static O* ConvertToC(const std::vector& in, size_t* out_len) { - if (!out_len) return nullptr; + if (!out_len) { + return nullptr; + } *out_len = in.size(); - if (in.empty()) return nullptr; + if (in.empty()) { + return nullptr; + } O* out = static_cast(wpi::safe_malloc(sizeof(O) * in.size())); - for (size_t i = 0; i < in.size(); ++i) ConvertToC(in[i], &out[i]); + for (size_t i = 0; i < in.size(); ++i) { + ConvertToC(in[i], &out[i]); + } return out; } @@ -112,7 +120,9 @@ static void DisposeConnectionInfo(NT_ConnectionInfo* info) { std::free(info->remote_ip.str); } -static void DisposeEntryInfo(NT_EntryInfo* info) { std::free(info->name.str); } +static void DisposeEntryInfo(NT_EntryInfo* info) { + std::free(info->name.str); +} static void DisposeEntryNotification(NT_EntryNotification* info) { std::free(info->name.str); @@ -143,12 +153,14 @@ static RpcDefinition ConvertFromC(const NT_RpcDefinition& in) { out.name = ConvertFromC(in.name); out.params.reserve(in.num_params); - for (size_t i = 0; i < in.num_params; ++i) + for (size_t i = 0; i < in.num_params; ++i) { out.params.push_back(ConvertFromC(in.params[i])); + } out.results.reserve(in.num_results); - for (size_t i = 0; i < in.num_results; ++i) + for (size_t i = 0; i < in.num_results; ++i) { out.results.push_back(ConvertFromC(in.results[i])); + } return out; } @@ -159,11 +171,17 @@ extern "C" { * Instance Functions */ -NT_Inst NT_GetDefaultInstance(void) { return nt::GetDefaultInstance(); } +NT_Inst NT_GetDefaultInstance(void) { + return nt::GetDefaultInstance(); +} -NT_Inst NT_CreateInstance(void) { return nt::CreateInstance(); } +NT_Inst NT_CreateInstance(void) { + return nt::CreateInstance(); +} -void NT_DestroyInstance(NT_Inst inst) { return nt::DestroyInstance(inst); } +void NT_DestroyInstance(NT_Inst inst) { + return nt::DestroyInstance(inst); +} NT_Inst NT_GetInstanceFromHandle(NT_Handle handle) { return nt::GetInstanceFromHandle(handle); @@ -181,7 +199,9 @@ NT_Entry* NT_GetEntries(NT_Inst inst, const char* prefix, size_t prefix_len, unsigned int types, size_t* count) { auto info_v = nt::GetEntries(inst, StringRef(prefix, prefix_len), types); *count = info_v.size(); - if (info_v.size() == 0) return nullptr; + if (info_v.size() == 0) { + return nullptr; + } // create array and copy into it NT_Entry* info = static_cast( @@ -197,7 +217,9 @@ char* NT_GetEntryName(NT_Entry entry, size_t* name_len) { return v_name.str; } -enum NT_Type NT_GetEntryType(NT_Entry entry) { return nt::GetEntryType(entry); } +enum NT_Type NT_GetEntryType(NT_Entry entry) { + return nt::GetEntryType(entry); +} uint64_t NT_GetEntryLastChange(NT_Entry entry) { return nt::GetEntryLastChange(entry); @@ -206,7 +228,9 @@ uint64_t NT_GetEntryLastChange(NT_Entry entry) { void NT_GetEntryValue(NT_Entry entry, struct NT_Value* value) { NT_InitValue(value); auto v = nt::GetEntryValue(entry); - if (!v) return; + if (!v) { + return; + } ConvertToC(*v, value); } @@ -231,9 +255,13 @@ unsigned int NT_GetEntryFlags(NT_Entry entry) { return nt::GetEntryFlags(entry); } -void NT_DeleteEntry(NT_Entry entry) { nt::DeleteEntry(entry); } +void NT_DeleteEntry(NT_Entry entry) { + nt::DeleteEntry(entry); +} -void NT_DeleteAllEntries(NT_Inst inst) { nt::DeleteAllEntries(inst); } +void NT_DeleteAllEntries(NT_Inst inst) { + nt::DeleteAllEntries(inst); +} struct NT_EntryInfo* NT_GetEntryInfo(NT_Inst inst, const char* prefix, size_t prefix_len, unsigned int types, @@ -244,7 +272,9 @@ struct NT_EntryInfo* NT_GetEntryInfo(NT_Inst inst, const char* prefix, NT_Bool NT_GetEntryInfoHandle(NT_Entry entry, struct NT_EntryInfo* info) { auto info_v = nt::GetEntryInfo(entry); - if (info_v.name.empty()) return false; + if (info_v.name.empty()) { + return false; + } ConvertToC(info_v, info); return true; } @@ -425,7 +455,9 @@ NT_RpcAnswer* NT_PollRpcTimeout(NT_RpcCallPoller poller, size_t* len, return ConvertToC(arr_cpp, len); } -void NT_CancelPollRpc(NT_RpcCallPoller poller) { nt::CancelPollRpc(poller); } +void NT_CancelPollRpc(NT_RpcCallPoller poller) { + nt::CancelPollRpc(poller); +} NT_Bool NT_WaitForRpcCallQueue(NT_Inst inst, double timeout) { return nt::WaitForRpcCallQueue(inst, timeout); @@ -442,7 +474,9 @@ NT_RpcCall NT_CallRpc(NT_Entry entry, const char* params, size_t params_len) { char* NT_GetRpcResult(NT_Entry entry, NT_RpcCall call, size_t* result_len) { std::string result; - if (!nt::GetRpcResult(entry, call, &result)) return nullptr; + if (!nt::GetRpcResult(entry, call, &result)) { + return nullptr; + } // convert result *result_len = result.size(); @@ -486,7 +520,9 @@ char* NT_PackRpcDefinition(const NT_RpcDefinition* def, size_t* packed_len) { NT_Bool NT_UnpackRpcDefinition(const char* packed, size_t packed_len, NT_RpcDefinition* def) { nt::RpcDefinition def_v; - if (!nt::UnpackRpcDefinition(StringRef(packed, packed_len), &def_v)) return 0; + if (!nt::UnpackRpcDefinition(StringRef(packed, packed_len), &def_v)) { + return 0; + } // convert result ConvertToC(def_v, def); @@ -498,8 +534,9 @@ char* NT_PackRpcValues(const NT_Value** values, size_t values_len, // create input vector std::vector> values_v; values_v.reserve(values_len); - for (size_t i = 0; i < values_len; ++i) + for (size_t i = 0; i < values_len; ++i) { values_v.push_back(ConvertFromC(*values[i])); + } // make the call auto packed = nt::PackRpcValues(values_v); @@ -515,7 +552,9 @@ NT_Value** NT_UnpackRpcValues(const char* packed, size_t packed_len, const NT_Type* types, size_t types_len) { auto values_v = nt::UnpackRpcValues(StringRef(packed, packed_len), ArrayRef(types, types_len)); - if (values_v.size() == 0) return nullptr; + if (values_v.size() == 0) { + return nullptr; + } // create array and copy into it NT_Value** values = static_cast( @@ -539,18 +578,26 @@ unsigned int NT_GetNetworkMode(NT_Inst inst) { return nt::GetNetworkMode(inst); } -void NT_StartLocal(NT_Inst inst) { nt::StartLocal(inst); } +void NT_StartLocal(NT_Inst inst) { + nt::StartLocal(inst); +} -void NT_StopLocal(NT_Inst inst) { nt::StopLocal(inst); } +void NT_StopLocal(NT_Inst inst) { + nt::StopLocal(inst); +} void NT_StartServer(NT_Inst inst, const char* persist_filename, const char* listen_address, unsigned int port) { nt::StartServer(inst, persist_filename, listen_address, port); } -void NT_StopServer(NT_Inst inst) { nt::StopServer(inst); } +void NT_StopServer(NT_Inst inst) { + nt::StopServer(inst); +} -void NT_StartClientNone(NT_Inst inst) { nt::StartClient(inst); } +void NT_StartClientNone(NT_Inst inst) { + nt::StartClient(inst); +} void NT_StartClient(NT_Inst inst, const char* server_name, unsigned int port) { nt::StartClient(inst, server_name, port); @@ -560,8 +607,9 @@ void NT_StartClientMulti(NT_Inst inst, size_t count, const char** server_names, const unsigned int* ports) { std::vector> servers; servers.reserve(count); - for (size_t i = 0; i < count; ++i) + for (size_t i = 0; i < count; ++i) { servers.emplace_back(std::make_pair(server_names[i], ports[i])); + } nt::StartClient(inst, servers); } @@ -569,7 +617,9 @@ void NT_StartClientTeam(NT_Inst inst, unsigned int team, unsigned int port) { nt::StartClientTeam(inst, team, port); } -void NT_StopClient(NT_Inst inst) { nt::StopClient(inst); } +void NT_StopClient(NT_Inst inst) { + nt::StopClient(inst); +} void NT_SetServer(NT_Inst inst, const char* server_name, unsigned int port) { nt::SetServer(inst, server_name, port); @@ -579,8 +629,9 @@ void NT_SetServerMulti(NT_Inst inst, size_t count, const char** server_names, const unsigned int* ports) { std::vector> servers; servers.reserve(count); - for (size_t i = 0; i < count; ++i) + for (size_t i = 0; i < count; ++i) { servers.emplace_back(std::make_pair(server_names[i], ports[i])); + } nt::SetServer(inst, servers); } @@ -592,15 +643,21 @@ void NT_StartDSClient(NT_Inst inst, unsigned int port) { nt::StartDSClient(inst, port); } -void NT_StopDSClient(NT_Inst inst) { nt::StopDSClient(inst); } +void NT_StopDSClient(NT_Inst inst) { + nt::StopDSClient(inst); +} void NT_SetUpdateRate(NT_Inst inst, double interval) { nt::SetUpdateRate(inst, interval); } -void NT_Flush(NT_Inst inst) { nt::Flush(inst); } +void NT_Flush(NT_Inst inst) { + nt::Flush(inst); +} -NT_Bool NT_IsConnected(NT_Inst inst) { return nt::IsConnected(inst); } +NT_Bool NT_IsConnected(NT_Inst inst) { + return nt::IsConnected(inst); +} struct NT_ConnectionInfo* NT_GetConnections(NT_Inst inst, size_t* count) { auto conn_v = nt::GetConnections(inst); @@ -635,7 +692,9 @@ const char* NT_LoadEntries(NT_Inst inst, const char* filename, * Utility Functions */ -uint64_t NT_Now(void) { return wpi::Now(); } +uint64_t NT_Now(void) { + return wpi::Now(); +} NT_Logger NT_AddLogger(NT_Inst inst, void* data, NT_LogFunc func, unsigned int min_level, unsigned int max_level) { @@ -680,7 +739,9 @@ void NT_CancelPollLogger(NT_LoggerPoller poller) { nt::CancelPollLogger(poller); } -void NT_RemoveLogger(NT_Logger logger) { nt::RemoveLogger(logger); } +void NT_RemoveLogger(NT_Logger logger) { + nt::RemoveLogger(logger); +} NT_Bool NT_WaitForLoggerQueue(NT_Inst inst, double timeout) { return nt::WaitForLoggerQueue(inst, timeout); @@ -704,8 +765,9 @@ void NT_DisposeValue(NT_Value* value) { std::free(value->data.arr_double.arr); break; case NT_STRING_ARRAY: { - for (size_t i = 0; i < value->data.arr_string.size; i++) + for (size_t i = 0; i < value->data.arr_string.size; i++) { std::free(value->data.arr_string.arr[i].str); + } std::free(value->data.arr_string.arr); break; } @@ -732,22 +794,32 @@ void NT_InitString(NT_String* str) { str->len = 0; } -void NT_DisposeEntryArray(NT_Entry* arr, size_t /*count*/) { std::free(arr); } +void NT_DisposeEntryArray(NT_Entry* arr, size_t /*count*/) { + std::free(arr); +} void NT_DisposeConnectionInfoArray(NT_ConnectionInfo* arr, size_t count) { - for (size_t i = 0; i < count; i++) DisposeConnectionInfo(&arr[i]); + for (size_t i = 0; i < count; i++) { + DisposeConnectionInfo(&arr[i]); + } std::free(arr); } void NT_DisposeEntryInfoArray(NT_EntryInfo* arr, size_t count) { - for (size_t i = 0; i < count; i++) DisposeEntryInfo(&arr[i]); + for (size_t i = 0; i < count; i++) { + DisposeEntryInfo(&arr[i]); + } std::free(arr); } -void NT_DisposeEntryInfo(NT_EntryInfo* info) { DisposeEntryInfo(info); } +void NT_DisposeEntryInfo(NT_EntryInfo* info) { + DisposeEntryInfo(info); +} void NT_DisposeEntryNotificationArray(NT_EntryNotification* arr, size_t count) { - for (size_t i = 0; i < count; i++) DisposeEntryNotification(&arr[i]); + for (size_t i = 0; i < count; i++) { + DisposeEntryNotification(&arr[i]); + } std::free(arr); } @@ -757,7 +829,9 @@ void NT_DisposeEntryNotification(NT_EntryNotification* info) { void NT_DisposeConnectionNotificationArray(NT_ConnectionNotification* arr, size_t count) { - for (size_t i = 0; i < count; i++) DisposeConnectionNotification(&arr[i]); + for (size_t i = 0; i < count; i++) { + DisposeConnectionNotification(&arr[i]); + } std::free(arr); } @@ -766,11 +840,15 @@ void NT_DisposeConnectionNotification(NT_ConnectionNotification* info) { } void NT_DisposeLogMessageArray(NT_LogMessage* arr, size_t count) { - for (size_t i = 0; i < count; i++) NT_DisposeLogMessage(&arr[i]); + for (size_t i = 0; i < count; i++) { + NT_DisposeLogMessage(&arr[i]); + } std::free(arr); } -void NT_DisposeLogMessage(NT_LogMessage* info) { std::free(info->message); } +void NT_DisposeLogMessage(NT_LogMessage* info) { + std::free(info->message); +} void NT_DisposeRpcDefinition(NT_RpcDefinition* def) { NT_DisposeString(&def->name); @@ -783,15 +861,18 @@ void NT_DisposeRpcDefinition(NT_RpcDefinition* def) { def->params = nullptr; def->num_params = 0; - for (size_t i = 0; i < def->num_results; ++i) + for (size_t i = 0; i < def->num_results; ++i) { NT_DisposeString(&def->results[i].name); + } std::free(def->results); def->results = nullptr; def->num_results = 0; } void NT_DisposeRpcAnswerArray(NT_RpcAnswer* arr, size_t count) { - for (size_t i = 0; i < count; i++) NT_DisposeRpcAnswer(&arr[i]); + for (size_t i = 0; i < count; i++) { + NT_DisposeRpcAnswer(&arr[i]); + } std::free(arr); } @@ -831,11 +912,19 @@ struct NT_String* NT_AllocateStringArray(size_t size) { return retVal; } -void NT_FreeCharArray(char* v_char) { std::free(v_char); } -void NT_FreeDoubleArray(double* v_double) { std::free(v_double); } -void NT_FreeBooleanArray(int* v_boolean) { std::free(v_boolean); } +void NT_FreeCharArray(char* v_char) { + std::free(v_char); +} +void NT_FreeDoubleArray(double* v_double) { + std::free(v_double); +} +void NT_FreeBooleanArray(int* v_boolean) { + std::free(v_boolean); +} void NT_FreeStringArray(struct NT_String* v_string, size_t arr_size) { - for (size_t i = 0; i < arr_size; i++) std::free(v_string[i].str); + for (size_t i = 0; i < arr_size; i++) { + std::free(v_string[i].str); + } std::free(v_string); } @@ -912,7 +1001,9 @@ NT_Bool NT_SetEntryStringArray(NT_Entry entry, uint64_t time, NT_Bool force) { std::vector v; v.reserve(size); - for (size_t i = 0; i < size; ++i) v.push_back(ConvertFromC(arr[i])); + for (size_t i = 0; i < size; ++i) { + v.push_back(ConvertFromC(arr[i])); + } if (force != 0) { nt::SetEntryTypeValue(entry, Value::MakeStringArray(std::move(v), time)); @@ -923,13 +1014,17 @@ NT_Bool NT_SetEntryStringArray(NT_Entry entry, uint64_t time, } enum NT_Type NT_GetValueType(const struct NT_Value* value) { - if (!value) return NT_Type::NT_UNASSIGNED; + if (!value) { + return NT_Type::NT_UNASSIGNED; + } return value->type; } NT_Bool NT_GetValueBoolean(const struct NT_Value* value, uint64_t* last_change, NT_Bool* v_boolean) { - if (!value || value->type != NT_Type::NT_BOOLEAN) return 0; + if (!value || value->type != NT_Type::NT_BOOLEAN) { + return 0; + } *v_boolean = value->data.v_boolean; *last_change = value->last_change; return 1; @@ -937,7 +1032,9 @@ NT_Bool NT_GetValueBoolean(const struct NT_Value* value, uint64_t* last_change, NT_Bool NT_GetValueDouble(const struct NT_Value* value, uint64_t* last_change, double* v_double) { - if (!value || value->type != NT_Type::NT_DOUBLE) return 0; + if (!value || value->type != NT_Type::NT_DOUBLE) { + return 0; + } *last_change = value->last_change; *v_double = value->data.v_double; return 1; @@ -945,7 +1042,9 @@ NT_Bool NT_GetValueDouble(const struct NT_Value* value, uint64_t* last_change, char* NT_GetValueString(const struct NT_Value* value, uint64_t* last_change, size_t* str_len) { - if (!value || value->type != NT_Type::NT_STRING) return nullptr; + if (!value || value->type != NT_Type::NT_STRING) { + return nullptr; + } *last_change = value->last_change; *str_len = value->data.v_string.len; char* str = @@ -956,7 +1055,9 @@ char* NT_GetValueString(const struct NT_Value* value, uint64_t* last_change, char* NT_GetValueRaw(const struct NT_Value* value, uint64_t* last_change, size_t* raw_len) { - if (!value || value->type != NT_Type::NT_RAW) return nullptr; + if (!value || value->type != NT_Type::NT_RAW) { + return nullptr; + } *last_change = value->last_change; *raw_len = value->data.v_string.len; char* raw = @@ -967,7 +1068,9 @@ char* NT_GetValueRaw(const struct NT_Value* value, uint64_t* last_change, NT_Bool* NT_GetValueBooleanArray(const struct NT_Value* value, uint64_t* last_change, size_t* arr_size) { - if (!value || value->type != NT_Type::NT_BOOLEAN_ARRAY) return nullptr; + if (!value || value->type != NT_Type::NT_BOOLEAN_ARRAY) { + return nullptr; + } *last_change = value->last_change; *arr_size = value->data.arr_boolean.size; NT_Bool* arr = static_cast( @@ -979,7 +1082,9 @@ NT_Bool* NT_GetValueBooleanArray(const struct NT_Value* value, double* NT_GetValueDoubleArray(const struct NT_Value* value, uint64_t* last_change, size_t* arr_size) { - if (!value || value->type != NT_Type::NT_DOUBLE_ARRAY) return nullptr; + if (!value || value->type != NT_Type::NT_DOUBLE_ARRAY) { + return nullptr; + } *last_change = value->last_change; *arr_size = value->data.arr_double.size; double* arr = static_cast( @@ -991,7 +1096,9 @@ double* NT_GetValueDoubleArray(const struct NT_Value* value, NT_String* NT_GetValueStringArray(const struct NT_Value* value, uint64_t* last_change, size_t* arr_size) { - if (!value || value->type != NT_Type::NT_STRING_ARRAY) return nullptr; + if (!value || value->type != NT_Type::NT_STRING_ARRAY) { + return nullptr; + } *last_change = value->last_change; *arr_size = value->data.arr_string.size; NT_String* arr = static_cast( @@ -1051,8 +1158,9 @@ NT_Bool NT_SetDefaultEntryStringArray(NT_Entry entry, uint64_t time, size_t default_size) { std::vector vec; vec.reserve(default_size); - for (size_t i = 0; i < default_size; ++i) + for (size_t i = 0; i < default_size; ++i) { vec.push_back(ConvertFromC(default_value[i])); + } return nt::SetDefaultEntryValue(entry, Value::MakeStringArray(std::move(vec), time)); @@ -1061,7 +1169,9 @@ NT_Bool NT_SetDefaultEntryStringArray(NT_Entry entry, uint64_t time, NT_Bool NT_GetEntryBoolean(NT_Entry entry, uint64_t* last_change, NT_Bool* v_boolean) { auto v = nt::GetEntryValue(entry); - if (!v || !v->IsBoolean()) return 0; + if (!v || !v->IsBoolean()) { + return 0; + } *v_boolean = v->GetBoolean(); *last_change = v->last_change(); return 1; @@ -1070,7 +1180,9 @@ NT_Bool NT_GetEntryBoolean(NT_Entry entry, uint64_t* last_change, NT_Bool NT_GetEntryDouble(NT_Entry entry, uint64_t* last_change, double* v_double) { auto v = nt::GetEntryValue(entry); - if (!v || !v->IsDouble()) return 0; + if (!v || !v->IsDouble()) { + return 0; + } *last_change = v->last_change(); *v_double = v->GetDouble(); return 1; @@ -1079,7 +1191,9 @@ NT_Bool NT_GetEntryDouble(NT_Entry entry, uint64_t* last_change, char* NT_GetEntryString(NT_Entry entry, uint64_t* last_change, size_t* str_len) { auto v = nt::GetEntryValue(entry); - if (!v || !v->IsString()) return nullptr; + if (!v || !v->IsString()) { + return nullptr; + } *last_change = v->last_change(); struct NT_String v_string; nt::ConvertToC(v->GetString(), &v_string); @@ -1089,7 +1203,9 @@ char* NT_GetEntryString(NT_Entry entry, uint64_t* last_change, char* NT_GetEntryRaw(NT_Entry entry, uint64_t* last_change, size_t* raw_len) { auto v = nt::GetEntryValue(entry); - if (!v || !v->IsRaw()) return nullptr; + if (!v || !v->IsRaw()) { + return nullptr; + } *last_change = v->last_change(); struct NT_String v_raw; nt::ConvertToC(v->GetRaw(), &v_raw); @@ -1100,7 +1216,9 @@ char* NT_GetEntryRaw(NT_Entry entry, uint64_t* last_change, size_t* raw_len) { NT_Bool* NT_GetEntryBooleanArray(NT_Entry entry, uint64_t* last_change, size_t* arr_size) { auto v = nt::GetEntryValue(entry); - if (!v || !v->IsBooleanArray()) return nullptr; + if (!v || !v->IsBooleanArray()) { + return nullptr; + } *last_change = v->last_change(); auto vArr = v->GetBooleanArray(); NT_Bool* arr = @@ -1113,7 +1231,9 @@ NT_Bool* NT_GetEntryBooleanArray(NT_Entry entry, uint64_t* last_change, double* NT_GetEntryDoubleArray(NT_Entry entry, uint64_t* last_change, size_t* arr_size) { auto v = nt::GetEntryValue(entry); - if (!v || !v->IsDoubleArray()) return nullptr; + if (!v || !v->IsDoubleArray()) { + return nullptr; + } *last_change = v->last_change(); auto vArr = v->GetDoubleArray(); double* arr = @@ -1126,7 +1246,9 @@ double* NT_GetEntryDoubleArray(NT_Entry entry, uint64_t* last_change, NT_String* NT_GetEntryStringArray(NT_Entry entry, uint64_t* last_change, size_t* arr_size) { auto v = nt::GetEntryValue(entry); - if (!v || !v->IsStringArray()) return nullptr; + if (!v || !v->IsStringArray()) { + return nullptr; + } *last_change = v->last_change(); auto vArr = v->GetStringArray(); NT_String* arr = static_cast( diff --git a/ntcore/src/main/native/cpp/ntcore_cpp.cpp b/ntcore/src/main/native/cpp/ntcore_cpp.cpp index 352ecacee9..db190837fb 100644 --- a/ntcore/src/main/native/cpp/ntcore_cpp.cpp +++ b/ntcore/src/main/native/cpp/ntcore_cpp.cpp @@ -33,15 +33,18 @@ NT_Inst CreateInstance() { void DestroyInstance(NT_Inst inst) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); - if (i < 0) return; + if (i < 0) { + return; + } InstanceImpl::Destroy(i); } NT_Inst GetInstanceFromHandle(NT_Handle handle) { Handle h{handle}; auto type = h.GetType(); - if (type >= Handle::kConnectionListener && type <= Handle::kRpcCallPoller) + if (type >= Handle::kConnectionListener && type <= Handle::kRpcCallPoller) { return Handle(h.GetInst(), 0, Handle::kInstance); + } return 0; } @@ -53,10 +56,14 @@ NT_Inst GetInstanceFromHandle(NT_Handle handle) { NT_Entry GetEntry(NT_Inst inst, const Twine& name) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return 0; + if (!ii) { + return 0; + } unsigned int id = ii->storage.GetEntry(name); - if (id == UINT_MAX) return 0; + if (id == UINT_MAX) { + return 0; + } return Handle(i, id, Handle::kEntry); } @@ -64,11 +71,15 @@ std::vector GetEntries(NT_Inst inst, const Twine& prefix, unsigned int types) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return std::vector{}; + if (!ii) { + return {}; + } auto arr = ii->storage.GetEntries(prefix, types); // convert indices to handles - for (auto& val : arr) val = Handle(i, val, Handle::kEntry); + for (auto& val : arr) { + val = Handle(i, val, Handle::kEntry); + } return arr; } @@ -76,7 +87,9 @@ std::string GetEntryName(NT_Entry entry) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::string{}; + if (id < 0 || !ii) { + return {}; + } return ii->storage.GetEntryName(id); } @@ -85,7 +98,9 @@ NT_Type GetEntryType(NT_Entry entry) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return NT_UNASSIGNED; + if (id < 0 || !ii) { + return NT_UNASSIGNED; + } return ii->storage.GetEntryType(id); } @@ -94,7 +109,9 @@ uint64_t GetEntryLastChange(NT_Entry entry) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } return ii->storage.GetEntryLastChange(id); } @@ -107,7 +124,9 @@ std::shared_ptr GetEntryValue(NT_Entry entry) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return nullptr; + if (id < 0 || !ii) { + return nullptr; + } return ii->storage.GetEntryValue(id); } @@ -120,7 +139,9 @@ bool SetDefaultEntryValue(NT_Entry entry, std::shared_ptr value) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return false; + if (id < 0 || !ii) { + return false; + } return ii->storage.SetDefaultEntryValue(id, value); } @@ -133,7 +154,9 @@ bool SetEntryValue(NT_Entry entry, std::shared_ptr value) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return false; + if (id < 0 || !ii) { + return false; + } return ii->storage.SetEntryValue(id, value); } @@ -146,7 +169,9 @@ void SetEntryTypeValue(NT_Entry entry, std::shared_ptr value) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->storage.SetEntryTypeValue(id, value); } @@ -159,7 +184,9 @@ void SetEntryFlags(NT_Entry entry, unsigned int flags) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->storage.SetEntryFlags(id, flags); } @@ -172,7 +199,9 @@ unsigned int GetEntryFlags(NT_Entry entry) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } return ii->storage.GetEntryFlags(id); } @@ -185,7 +214,9 @@ void DeleteEntry(NT_Entry entry) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->storage.DeleteEntry(id); } @@ -197,7 +228,9 @@ void DeleteAllEntries() { void DeleteAllEntries(NT_Inst inst) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (i < 0 || !ii) return; + if (i < 0 || !ii) { + return; + } ii->storage.DeleteAllEntries(); } @@ -210,7 +243,9 @@ std::vector GetEntryInfo(NT_Inst inst, const Twine& prefix, unsigned int types) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return std::vector{}; + if (!ii) { + return {}; + } return ii->storage.GetEntryInfo(i, prefix, types); } @@ -253,7 +288,9 @@ NT_EntryListener AddEntryListener( unsigned int flags) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (i < 0 || !ii) return 0; + if (i < 0 || !ii) { + return 0; + } unsigned int uid = ii->storage.AddListener(prefix, callback, flags); return Handle(i, uid, Handle::kEntryListener); @@ -267,7 +304,9 @@ NT_EntryListener AddEntryListener( int id = handle.GetTypedIndex(Handle::kEntry); int i = handle.GetInst(); auto ii = InstanceImpl::Get(i); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } unsigned int uid = ii->storage.AddListener(id, callback, flags); return Handle(i, uid, Handle::kEntryListener); @@ -276,7 +315,9 @@ NT_EntryListener AddEntryListener( NT_EntryListenerPoller CreateEntryListenerPoller(NT_Inst inst) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return 0; + if (!ii) { + return 0; + } return Handle(i, ii->entry_notifier.CreatePoller(), Handle::kEntryListenerPoller); @@ -286,7 +327,9 @@ void DestroyEntryListenerPoller(NT_EntryListenerPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kEntryListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->entry_notifier.RemovePoller(id); } @@ -298,7 +341,9 @@ NT_EntryListener AddPolledEntryListener(NT_EntryListenerPoller poller, int id = handle.GetTypedIndex(Handle::kEntryListenerPoller); int i = handle.GetInst(); auto ii = InstanceImpl::Get(i); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } unsigned int uid = ii->storage.AddPolledListener(id, prefix, flags); return Handle(i, uid, Handle::kEntryListener); @@ -310,12 +355,18 @@ NT_EntryListener AddPolledEntryListener(NT_EntryListenerPoller poller, int id = handle.GetTypedIndex(Handle::kEntry); int i = handle.GetInst(); auto ii = InstanceImpl::Get(i); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } Handle phandle{poller}; int p_id = phandle.GetTypedIndex(Handle::kEntryListenerPoller); - if (p_id < 0) return 0; - if (handle.GetInst() != phandle.GetInst()) return 0; + if (p_id < 0) { + return 0; + } + if (handle.GetInst() != phandle.GetInst()) { + return 0; + } unsigned int uid = ii->storage.AddPolledListener(p_id, id, flags); return Handle(i, uid, Handle::kEntryListener); @@ -326,7 +377,9 @@ std::vector PollEntryListener( Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kEntryListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->entry_notifier.Poll(static_cast(id)); } @@ -338,7 +391,9 @@ std::vector PollEntryListener(NT_EntryListenerPoller poller, Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kEntryListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->entry_notifier.Poll(static_cast(id), timeout, timed_out); @@ -348,7 +403,9 @@ void CancelPollEntryListener(NT_EntryListenerPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kEntryListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->entry_notifier.CancelPoll(id); } @@ -357,7 +414,9 @@ void RemoveEntryListener(NT_EntryListener entry_listener) { Handle handle{entry_listener}; int uid = handle.GetTypedIndex(Handle::kEntryListener); auto ii = InstanceImpl::Get(handle.GetInst()); - if (uid < 0 || !ii) return; + if (uid < 0 || !ii) { + return; + } ii->entry_notifier.Remove(uid); } @@ -365,7 +424,9 @@ void RemoveEntryListener(NT_EntryListener entry_listener) { bool WaitForEntryListenerQueue(NT_Inst inst, double timeout) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return true; + if (!ii) { + return true; + } return ii->entry_notifier.WaitForQueue(timeout); } @@ -385,7 +446,9 @@ NT_ConnectionListener AddConnectionListener( bool immediate_notify) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return 0; + if (!ii) { + return 0; + } unsigned int uid = ii->dispatcher.AddListener(callback, immediate_notify); return Handle(i, uid, Handle::kConnectionListener); @@ -394,7 +457,9 @@ NT_ConnectionListener AddConnectionListener( NT_ConnectionListenerPoller CreateConnectionListenerPoller(NT_Inst inst) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return 0; + if (!ii) { + return 0; + } return Handle(i, ii->connection_notifier.CreatePoller(), Handle::kConnectionListenerPoller); @@ -404,7 +469,9 @@ void DestroyConnectionListenerPoller(NT_ConnectionListenerPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kConnectionListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->connection_notifier.RemovePoller(id); } @@ -415,7 +482,9 @@ NT_ConnectionListener AddPolledConnectionListener( int id = handle.GetTypedIndex(Handle::kConnectionListenerPoller); int i = handle.GetInst(); auto ii = InstanceImpl::Get(i); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } unsigned int uid = ii->dispatcher.AddPolledListener(id, immediate_notify); return Handle(i, uid, Handle::kConnectionListener); @@ -426,7 +495,9 @@ std::vector PollConnectionListener( Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kConnectionListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->connection_notifier.Poll(static_cast(id)); } @@ -437,7 +508,9 @@ std::vector PollConnectionListener( Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kConnectionListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->connection_notifier.Poll(static_cast(id), timeout, timed_out); @@ -447,7 +520,9 @@ void CancelPollConnectionListener(NT_ConnectionListenerPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kConnectionListenerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->connection_notifier.CancelPoll(id); } @@ -456,7 +531,9 @@ void RemoveConnectionListener(NT_ConnectionListener conn_listener) { Handle handle{conn_listener}; int uid = handle.GetTypedIndex(Handle::kConnectionListener); auto ii = InstanceImpl::Get(handle.GetInst()); - if (uid < 0 || !ii) return; + if (uid < 0 || !ii) { + return; + } ii->connection_notifier.Remove(uid); } @@ -464,7 +541,9 @@ void RemoveConnectionListener(NT_ConnectionListener conn_listener) { bool WaitForConnectionListenerQueue(NT_Inst inst, double timeout) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return true; + if (!ii) { + return true; + } return ii->connection_notifier.WaitForQueue(timeout); } @@ -477,11 +556,17 @@ void CreateRpc(NT_Entry entry, StringRef def, Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } // only server can create RPCs - if ((ii->dispatcher.GetNetworkMode() & NT_NET_MODE_SERVER) == 0) return; - if (def.empty() || !callback) return; + if ((ii->dispatcher.GetNetworkMode() & NT_NET_MODE_SERVER) == 0) { + return; + } + if (def.empty() || !callback) { + return; + } ii->storage.CreateRpc(id, def, ii->rpc_server.Add(callback)); } @@ -489,7 +574,9 @@ void CreateRpc(NT_Entry entry, StringRef def, NT_RpcCallPoller CreateRpcCallPoller(NT_Inst inst) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return 0; + if (!ii) { + return 0; + } return Handle(i, ii->rpc_server.CreatePoller(), Handle::kRpcCallPoller); } @@ -498,7 +585,9 @@ void DestroyRpcCallPoller(NT_RpcCallPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kRpcCallPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->rpc_server.RemovePoller(id); } @@ -507,16 +596,26 @@ void CreatePolledRpc(NT_Entry entry, StringRef def, NT_RpcCallPoller poller) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } Handle phandle{poller}; int p_id = phandle.GetTypedIndex(Handle::kRpcCallPoller); - if (p_id < 0) return; - if (handle.GetInst() != phandle.GetInst()) return; + if (p_id < 0) { + return; + } + if (handle.GetInst() != phandle.GetInst()) { + return; + } // only server can create RPCs - if ((ii->dispatcher.GetNetworkMode() & NT_NET_MODE_SERVER) == 0) return; - if (def.empty()) return; + if ((ii->dispatcher.GetNetworkMode() & NT_NET_MODE_SERVER) == 0) { + return; + } + if (def.empty()) { + return; + } ii->storage.CreateRpc(id, def, ii->rpc_server.AddPolled(p_id)); } @@ -525,7 +624,9 @@ std::vector PollRpc(NT_RpcCallPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kRpcCallPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->rpc_server.Poll(static_cast(id)); } @@ -536,7 +637,9 @@ std::vector PollRpc(NT_RpcCallPoller poller, double timeout, Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kRpcCallPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->rpc_server.Poll(static_cast(id), timeout, timed_out); } @@ -545,7 +648,9 @@ void CancelPollRpc(NT_RpcCallPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kRpcCallPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->rpc_server.CancelPoll(id); } @@ -553,7 +658,9 @@ void CancelPollRpc(NT_RpcCallPoller poller) { bool WaitForRpcCallQueue(NT_Inst inst, double timeout) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return true; + if (!ii) { + return true; + } return ii->rpc_server.WaitForQueue(timeout); } @@ -561,12 +668,18 @@ bool PostRpcResponse(NT_Entry entry, NT_RpcCall call, StringRef result) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return false; + if (id < 0 || !ii) { + return false; + } Handle chandle{call}; int call_uid = chandle.GetTypedIndex(Handle::kRpcCall); - if (call_uid < 0) return false; - if (handle.GetInst() != chandle.GetInst()) return false; + if (call_uid < 0) { + return false; + } + if (handle.GetInst() != chandle.GetInst()) { + return false; + } return ii->rpc_server.PostRpcResponse(id, call_uid, result); } @@ -576,10 +689,14 @@ NT_RpcCall CallRpc(NT_Entry entry, StringRef params) { int id = handle.GetTypedIndex(Handle::kEntry); int i = handle.GetInst(); auto ii = InstanceImpl::Get(i); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } unsigned int call_uid = ii->storage.CallRpc(id, params); - if (call_uid == 0) return 0; + if (call_uid == 0) { + return 0; + } return Handle(i, call_uid, Handle::kRpcCall); } @@ -587,12 +704,18 @@ bool GetRpcResult(NT_Entry entry, NT_RpcCall call, std::string* result) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return false; + if (id < 0 || !ii) { + return false; + } Handle chandle{call}; int call_uid = chandle.GetTypedIndex(Handle::kRpcCall); - if (call_uid < 0) return false; - if (handle.GetInst() != chandle.GetInst()) return false; + if (call_uid < 0) { + return false; + } + if (handle.GetInst() != chandle.GetInst()) { + return false; + } return ii->storage.GetRpcResult(id, call_uid, result); } @@ -603,12 +726,18 @@ bool GetRpcResult(NT_Entry entry, NT_RpcCall call, std::string* result, Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return false; + if (id < 0 || !ii) { + return false; + } Handle chandle{call}; int call_uid = chandle.GetTypedIndex(Handle::kRpcCall); - if (call_uid < 0) return false; - if (handle.GetInst() != chandle.GetInst()) return false; + if (call_uid < 0) { + return false; + } + if (handle.GetInst() != chandle.GetInst()) { + return false; + } return ii->storage.GetRpcResult(id, call_uid, result, timeout, timed_out); } @@ -617,12 +746,18 @@ void CancelRpcResult(NT_Entry entry, NT_RpcCall call) { Handle handle{entry}; int id = handle.GetTypedIndex(Handle::kEntry); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } Handle chandle{call}; int call_uid = chandle.GetTypedIndex(Handle::kRpcCall); - if (call_uid < 0) return; - if (handle.GetInst() != chandle.GetInst()) return; + if (call_uid < 0) { + return; + } + if (handle.GetInst() != chandle.GetInst()) { + return; + } ii->storage.CancelRpcResult(id, call_uid); } @@ -634,7 +769,9 @@ std::string PackRpcDefinition(const RpcDefinition& def) { // parameters unsigned int params_size = def.params.size(); - if (params_size > 0xff) params_size = 0xff; + if (params_size > 0xff) { + params_size = 0xff; + } enc.Write8(params_size); for (size_t i = 0; i < params_size; ++i) { enc.WriteType(def.params[i].def_value->type()); @@ -644,7 +781,9 @@ std::string PackRpcDefinition(const RpcDefinition& def) { // results unsigned int results_size = def.results.size(); - if (results_size > 0xff) results_size = 0xff; + if (results_size > 0xff) { + results_size = 0xff; + } enc.Write8(results_size); for (size_t i = 0; i < results_size; ++i) { enc.WriteType(def.results[i].type); @@ -658,33 +797,51 @@ bool UnpackRpcDefinition(StringRef packed, RpcDefinition* def) { wpi::raw_mem_istream is(packed.data(), packed.size()); wpi::Logger logger; WireDecoder dec(is, 0x0300, logger); - if (!dec.Read8(&def->version)) return false; - if (!dec.ReadString(&def->name)) return false; + if (!dec.Read8(&def->version)) { + return false; + } + if (!dec.ReadString(&def->name)) { + return false; + } // parameters unsigned int params_size; - if (!dec.Read8(¶ms_size)) return false; + if (!dec.Read8(¶ms_size)) { + return false; + } def->params.resize(0); def->params.reserve(params_size); for (size_t i = 0; i < params_size; ++i) { RpcParamDef pdef; NT_Type type; - if (!dec.ReadType(&type)) return false; - if (!dec.ReadString(&pdef.name)) return false; + if (!dec.ReadType(&type)) { + return false; + } + if (!dec.ReadString(&pdef.name)) { + return false; + } pdef.def_value = dec.ReadValue(type); - if (!pdef.def_value) return false; + if (!pdef.def_value) { + return false; + } def->params.emplace_back(std::move(pdef)); } // results unsigned int results_size; - if (!dec.Read8(&results_size)) return false; + if (!dec.Read8(&results_size)) { + return false; + } def->results.resize(0); def->results.reserve(results_size); for (size_t i = 0; i < results_size; ++i) { RpcResultDef rdef; - if (!dec.ReadType(&rdef.type)) return false; - if (!dec.ReadString(&rdef.name)) return false; + if (!dec.ReadType(&rdef.type)) { + return false; + } + if (!dec.ReadString(&rdef.name)) { + return false; + } def->results.emplace_back(std::move(rdef)); } @@ -693,7 +850,9 @@ bool UnpackRpcDefinition(StringRef packed, RpcDefinition* def) { std::string PackRpcValues(ArrayRef> values) { WireEncoder enc(0x0300); - for (auto& value : values) enc.WriteValue(*value); + for (auto& value : values) { + enc.WriteValue(*value); + } return enc.ToStringRef(); } @@ -705,13 +864,17 @@ std::vector> UnpackRpcValues(StringRef packed, std::vector> vec; for (auto type : types) { auto item = dec.ReadValue(type); - if (!item) return std::vector>(); + if (!item) { + return std::vector>(); + } vec.emplace_back(std::move(item)); } return vec; } -uint64_t Now() { return wpi::Now(); } +uint64_t Now() { + return wpi::Now(); +} /* * Client/Server Functions @@ -723,7 +886,9 @@ void SetNetworkIdentity(StringRef name) { void SetNetworkIdentity(NT_Inst inst, const Twine& name) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetIdentity(name); } @@ -734,21 +899,27 @@ unsigned int GetNetworkMode() { unsigned int GetNetworkMode(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return 0; + if (!ii) { + return 0; + } return ii->dispatcher.GetNetworkMode(); } void StartLocal(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.StartLocal(); } void StopLocal(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.Stop(); } @@ -762,25 +933,35 @@ void StartServer(StringRef persist_filename, const char* listen_address, void StartServer(NT_Inst inst, const Twine& persist_filename, const char* listen_address, unsigned int port) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.StartServer(persist_filename, listen_address, port); } -void StopServer() { InstanceImpl::GetDefault()->dispatcher.Stop(); } +void StopServer() { + InstanceImpl::GetDefault()->dispatcher.Stop(); +} void StopServer(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.Stop(); } -void StartClient() { InstanceImpl::GetDefault()->dispatcher.StartClient(); } +void StartClient() { + InstanceImpl::GetDefault()->dispatcher.StartClient(); +} void StartClient(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.StartClient(); } @@ -793,7 +974,9 @@ void StartClient(const char* server_name, unsigned int port) { void StartClient(NT_Inst inst, const char* server_name, unsigned int port) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetServer(server_name, port); ii->dispatcher.StartClient(); @@ -808,7 +991,9 @@ void StartClient(ArrayRef> servers) { void StartClient(NT_Inst inst, ArrayRef> servers) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetServer(servers); ii->dispatcher.StartClient(); @@ -816,17 +1001,23 @@ void StartClient(NT_Inst inst, void StartClientTeam(NT_Inst inst, unsigned int team, unsigned int port) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetServerTeam(team, port); ii->dispatcher.StartClient(); } -void StopClient() { InstanceImpl::GetDefault()->dispatcher.Stop(); } +void StopClient() { + InstanceImpl::GetDefault()->dispatcher.Stop(); +} void StopClient(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.Stop(); } @@ -837,7 +1028,9 @@ void SetServer(const char* server_name, unsigned int port) { void SetServer(NT_Inst inst, const char* server_name, unsigned int port) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetServer(server_name, port); } @@ -849,14 +1042,18 @@ void SetServer(ArrayRef> servers) { void SetServer(NT_Inst inst, ArrayRef> servers) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetServer(servers); } void SetServerTeam(NT_Inst inst, unsigned int team, unsigned int port) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetServerTeam(team, port); } @@ -867,16 +1064,22 @@ void StartDSClient(unsigned int port) { void StartDSClient(NT_Inst inst, unsigned int port) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->ds_client.Start(port); } -void StopDSClient() { InstanceImpl::GetDefault()->ds_client.Stop(); } +void StopDSClient() { + InstanceImpl::GetDefault()->ds_client.Stop(); +} void StopDSClient(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->ds_client.Stop(); } @@ -887,16 +1090,22 @@ void SetUpdateRate(double interval) { void SetUpdateRate(NT_Inst inst, double interval) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.SetUpdateRate(interval); } -void Flush() { InstanceImpl::GetDefault()->dispatcher.Flush(); } +void Flush() { + InstanceImpl::GetDefault()->dispatcher.Flush(); +} void Flush(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return; + if (!ii) { + return; + } ii->dispatcher.Flush(); } @@ -907,14 +1116,18 @@ std::vector GetConnections() { std::vector GetConnections(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return std::vector{}; + if (!ii) { + return {}; + } return ii->dispatcher.GetConnections(); } bool IsConnected(NT_Inst inst) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return false; + if (!ii) { + return false; + } return ii->dispatcher.IsConnected(); } @@ -929,7 +1142,9 @@ const char* SavePersistent(StringRef filename) { const char* SavePersistent(NT_Inst inst, const Twine& filename) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return "invalid instance handle"; + if (!ii) { + return "invalid instance handle"; + } return ii->storage.SavePersistent(filename, false); } @@ -944,7 +1159,9 @@ const char* LoadPersistent( NT_Inst inst, const Twine& filename, std::function warn) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return "invalid instance handle"; + if (!ii) { + return "invalid instance handle"; + } return ii->storage.LoadPersistent(filename, warn); } @@ -952,7 +1169,9 @@ const char* LoadPersistent( const char* SaveEntries(NT_Inst inst, const Twine& filename, const Twine& prefix) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return "invalid instance handle"; + if (!ii) { + return "invalid instance handle"; + } return ii->storage.SaveEntries(filename, prefix); } @@ -961,7 +1180,9 @@ const char* LoadEntries( NT_Inst inst, const Twine& filename, const Twine& prefix, std::function warn) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); - if (!ii) return "invalid instance handle"; + if (!ii) { + return "invalid instance handle"; + } return ii->storage.LoadEntries(filename, prefix, warn); } @@ -971,7 +1192,9 @@ void SetLogger(LogFunc func, unsigned int min_level) { static wpi::mutex mutex; static unsigned int logger = 0; std::scoped_lock lock(mutex); - if (logger != 0) ii->logger_impl.Remove(logger); + if (logger != 0) { + ii->logger_impl.Remove(logger); + } logger = ii->logger_impl.Add( [=](const LogMessage& msg) { func(msg.level, msg.filename, msg.line, msg.message.c_str()); @@ -984,9 +1207,13 @@ NT_Logger AddLogger(NT_Inst inst, unsigned int min_level, unsigned int max_level) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return 0; + if (!ii) { + return 0; + } - if (min_level < ii->logger.min_level()) ii->logger.set_min_level(min_level); + if (min_level < ii->logger.min_level()) { + ii->logger.set_min_level(min_level); + } return Handle(i, ii->logger_impl.Add(func, min_level, max_level), Handle::kLogger); @@ -995,7 +1222,9 @@ NT_Logger AddLogger(NT_Inst inst, NT_LoggerPoller CreateLoggerPoller(NT_Inst inst) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return 0; + if (!ii) { + return 0; + } return Handle(i, ii->logger_impl.CreatePoller(), Handle::kLoggerPoller); } @@ -1004,7 +1233,9 @@ void DestroyLoggerPoller(NT_LoggerPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kLoggerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->logger_impl.RemovePoller(id); } @@ -1015,9 +1246,13 @@ NT_Logger AddPolledLogger(NT_LoggerPoller poller, unsigned int min_level, int id = handle.GetTypedIndex(Handle::kLoggerPoller); int i = handle.GetInst(); auto ii = InstanceImpl::Get(i); - if (id < 0 || !ii) return 0; + if (id < 0 || !ii) { + return 0; + } - if (min_level < ii->logger.min_level()) ii->logger.set_min_level(min_level); + if (min_level < ii->logger.min_level()) { + ii->logger.set_min_level(min_level); + } return Handle(i, ii->logger_impl.AddPolled(id, min_level, max_level), Handle::kLogger); @@ -1027,7 +1262,9 @@ std::vector PollLogger(NT_LoggerPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kLoggerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->logger_impl.Poll(static_cast(id)); } @@ -1038,7 +1275,9 @@ std::vector PollLogger(NT_LoggerPoller poller, double timeout, Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kLoggerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return std::vector{}; + if (id < 0 || !ii) { + return {}; + } return ii->logger_impl.Poll(static_cast(id), timeout, timed_out); @@ -1048,7 +1287,9 @@ void CancelPollLogger(NT_LoggerPoller poller) { Handle handle{poller}; int id = handle.GetTypedIndex(Handle::kLoggerPoller); auto ii = InstanceImpl::Get(handle.GetInst()); - if (id < 0 || !ii) return; + if (id < 0 || !ii) { + return; + } ii->logger_impl.CancelPoll(id); } @@ -1057,7 +1298,9 @@ void RemoveLogger(NT_Logger logger) { Handle handle{logger}; int uid = handle.GetTypedIndex(Handle::kLogger); auto ii = InstanceImpl::Get(handle.GetInst()); - if (uid < 0 || !ii) return; + if (uid < 0 || !ii) { + return; + } ii->logger_impl.Remove(uid); ii->logger.set_min_level(ii->logger_impl.GetMinLevel()); @@ -1066,7 +1309,9 @@ void RemoveLogger(NT_Logger logger) { bool WaitForLoggerQueue(NT_Inst inst, double timeout) { int i = Handle{inst}.GetTypedInst(Handle::kInstance); auto ii = InstanceImpl::Get(i); - if (!ii) return true; + if (!ii) { + return true; + } return ii->logger_impl.WaitForQueue(timeout); } diff --git a/ntcore/src/main/native/include/networktables/NetworkTableEntry.inl b/ntcore/src/main/native/include/networktables/NetworkTableEntry.inl index 9d962f529c..89556e0ffd 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableEntry.inl +++ b/ntcore/src/main/native/include/networktables/NetworkTableEntry.inl @@ -16,7 +16,9 @@ inline NetworkTableEntry::NetworkTableEntry() : m_handle{0} {} inline NetworkTableEntry::NetworkTableEntry(NT_Entry handle) : m_handle{handle} {} -inline NT_Entry NetworkTableEntry::GetHandle() const { return m_handle; } +inline NT_Entry NetworkTableEntry::GetHandle() const { + return m_handle; +} inline bool NetworkTableEntry::Exists() const { return GetEntryType(m_handle) != NT_UNASSIGNED; @@ -48,32 +50,37 @@ inline std::shared_ptr NetworkTableEntry::GetValue() const { inline bool NetworkTableEntry::GetBoolean(bool defaultValue) const { auto value = GetEntryValue(m_handle); - if (!value || value->type() != NT_BOOLEAN) return defaultValue; + if (!value || value->type() != NT_BOOLEAN) + return defaultValue; return value->GetBoolean(); } inline double NetworkTableEntry::GetDouble(double defaultValue) const { auto value = GetEntryValue(m_handle); - if (!value || value->type() != NT_DOUBLE) return defaultValue; + if (!value || value->type() != NT_DOUBLE) + return defaultValue; return value->GetDouble(); } inline std::string NetworkTableEntry::GetString(StringRef defaultValue) const { auto value = GetEntryValue(m_handle); - if (!value || value->type() != NT_STRING) return defaultValue; + if (!value || value->type() != NT_STRING) + return defaultValue; return value->GetString(); } inline std::string NetworkTableEntry::GetRaw(StringRef defaultValue) const { auto value = GetEntryValue(m_handle); - if (!value || value->type() != NT_RAW) return defaultValue; + if (!value || value->type() != NT_RAW) + return defaultValue; return value->GetString(); } inline std::vector NetworkTableEntry::GetBooleanArray( ArrayRef defaultValue) const { auto value = GetEntryValue(m_handle); - if (!value || value->type() != NT_BOOLEAN_ARRAY) return defaultValue; + if (!value || value->type() != NT_BOOLEAN_ARRAY) + return defaultValue; return value->GetBooleanArray(); } @@ -86,7 +93,8 @@ inline std::vector NetworkTableEntry::GetBooleanArray( inline std::vector NetworkTableEntry::GetDoubleArray( ArrayRef defaultValue) const { auto value = GetEntryValue(m_handle); - if (!value || value->type() != NT_DOUBLE_ARRAY) return defaultValue; + if (!value || value->type() != NT_DOUBLE_ARRAY) + return defaultValue; return value->GetDoubleArray(); } @@ -99,7 +107,8 @@ inline std::vector NetworkTableEntry::GetDoubleArray( inline std::vector NetworkTableEntry::GetStringArray( ArrayRef defaultValue) const { auto value = GetEntryValue(m_handle); - if (!value || value->type() != NT_STRING_ARRAY) return defaultValue; + if (!value || value->type() != NT_STRING_ARRAY) + return defaultValue; return value->GetStringArray(); } @@ -280,15 +289,21 @@ inline void NetworkTableEntry::ClearFlags(unsigned int flags) { SetEntryFlags(m_handle, GetFlags() & ~flags); } -inline void NetworkTableEntry::SetPersistent() { SetFlags(kPersistent); } +inline void NetworkTableEntry::SetPersistent() { + SetFlags(kPersistent); +} -inline void NetworkTableEntry::ClearPersistent() { ClearFlags(kPersistent); } +inline void NetworkTableEntry::ClearPersistent() { + ClearFlags(kPersistent); +} inline bool NetworkTableEntry::IsPersistent() const { return (GetFlags() & kPersistent) != 0; } -inline void NetworkTableEntry::Delete() { DeleteEntry(m_handle); } +inline void NetworkTableEntry::Delete() { + DeleteEntry(m_handle); +} inline void NetworkTableEntry::CreateRpc( std::function callback) { diff --git a/ntcore/src/main/native/include/networktables/NetworkTableInstance.inl b/ntcore/src/main/native/include/networktables/NetworkTableInstance.inl index fe9d0cd4b5..172061c058 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableInstance.inl +++ b/ntcore/src/main/native/include/networktables/NetworkTableInstance.inl @@ -24,10 +24,13 @@ inline NetworkTableInstance NetworkTableInstance::Create() { } inline void NetworkTableInstance::Destroy(NetworkTableInstance inst) { - if (inst.m_handle != 0) DestroyInstance(inst.m_handle); + if (inst.m_handle != 0) + DestroyInstance(inst.m_handle); } -inline NT_Inst NetworkTableInstance::GetHandle() const { return m_handle; } +inline NT_Inst NetworkTableInstance::GetHandle() const { + return m_handle; +} inline NetworkTableEntry NetworkTableInstance::GetEntry(const Twine& name) { return NetworkTableEntry{::nt::GetEntry(m_handle, name)}; @@ -81,9 +84,13 @@ inline unsigned int NetworkTableInstance::GetNetworkMode() const { return ::nt::GetNetworkMode(m_handle); } -inline void NetworkTableInstance::StartLocal() { ::nt::StartLocal(m_handle); } +inline void NetworkTableInstance::StartLocal() { + ::nt::StartLocal(m_handle); +} -inline void NetworkTableInstance::StopLocal() { ::nt::StopLocal(m_handle); } +inline void NetworkTableInstance::StopLocal() { + ::nt::StopLocal(m_handle); +} inline void NetworkTableInstance::StartServer(const Twine& persist_filename, const char* listen_address, @@ -91,9 +98,13 @@ inline void NetworkTableInstance::StartServer(const Twine& persist_filename, ::nt::StartServer(m_handle, persist_filename, listen_address, port); } -inline void NetworkTableInstance::StopServer() { ::nt::StopServer(m_handle); } +inline void NetworkTableInstance::StopServer() { + ::nt::StopServer(m_handle); +} -inline void NetworkTableInstance::StartClient() { ::nt::StartClient(m_handle); } +inline void NetworkTableInstance::StartClient() { + ::nt::StartClient(m_handle); +} inline void NetworkTableInstance::StartClient(const char* server_name, unsigned int port) { @@ -110,7 +121,9 @@ inline void NetworkTableInstance::StartClientTeam(unsigned int team, ::nt::StartClientTeam(m_handle, team, port); } -inline void NetworkTableInstance::StopClient() { ::nt::StopClient(m_handle); } +inline void NetworkTableInstance::StopClient() { + ::nt::StopClient(m_handle); +} inline void NetworkTableInstance::SetServer(const char* server_name, unsigned int port) { @@ -139,7 +152,9 @@ inline void NetworkTableInstance::SetUpdateRate(double interval) { ::nt::SetUpdateRate(m_handle, interval); } -inline void NetworkTableInstance::Flush() const { ::nt::Flush(m_handle); } +inline void NetworkTableInstance::Flush() const { + ::nt::Flush(m_handle); +} inline std::vector NetworkTableInstance::GetConnections() const { diff --git a/ntcore/src/main/native/include/networktables/RpcCall.inl b/ntcore/src/main/native/include/networktables/RpcCall.inl index e753ddf377..f18b78e0f8 100644 --- a/ntcore/src/main/native/include/networktables/RpcCall.inl +++ b/ntcore/src/main/native/include/networktables/RpcCall.inl @@ -18,7 +18,8 @@ inline RpcCall::RpcCall(RpcCall&& other) noexcept : RpcCall() { inline RpcCall::~RpcCall() { // automatically cancel result if user didn't request it - if (m_call != 0) CancelResult(); + if (m_call != 0) + CancelResult(); } inline bool RpcCall::GetResult(std::string* result) { diff --git a/ntcore/src/test/native/cpp/ConnectionListenerTest.cpp b/ntcore/src/test/native/cpp/ConnectionListenerTest.cpp index f071c1c62d..69c3ab8d0b 100644 --- a/ntcore/src/test/native/cpp/ConnectionListenerTest.cpp +++ b/ntcore/src/test/native/cpp/ConnectionListenerTest.cpp @@ -35,8 +35,9 @@ void ConnectionListenerTest::Connect() { nt::StartClient(client_inst, "127.0.0.1", 10000); // wait for client to report it's started, then wait another 0.1 sec - while ((nt::GetNetworkMode(client_inst) & NT_NET_MODE_STARTING) != 0) + while ((nt::GetNetworkMode(client_inst) & NT_NET_MODE_STARTING) != 0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } diff --git a/ntcore/src/test/native/cpp/EntryListenerTest.cpp b/ntcore/src/test/native/cpp/EntryListenerTest.cpp index b147a00491..96a7b67cc7 100644 --- a/ntcore/src/test/native/cpp/EntryListenerTest.cpp +++ b/ntcore/src/test/native/cpp/EntryListenerTest.cpp @@ -82,7 +82,9 @@ TEST_F(EntryListenerTest, EntryNewLocal) { TEST_F(EntryListenerTest, DISABLED_EntryNewRemote) { Connect(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } std::vector events; auto handle = nt::AddEntryListener( nt::GetEntry(server_inst, "/foo"), @@ -134,7 +136,9 @@ TEST_F(EntryListenerTest, PrefixNewLocal) { TEST_F(EntryListenerTest, DISABLED_PrefixNewRemote) { Connect(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } std::vector events; auto handle = nt::AddEntryListener( server_inst, "/foo", diff --git a/ntcore/src/test/native/cpp/MessageMatcher.cpp b/ntcore/src/test/native/cpp/MessageMatcher.cpp index 3979540960..69c87a00d4 100644 --- a/ntcore/src/test/native/cpp/MessageMatcher.cpp +++ b/ntcore/src/test/native/cpp/MessageMatcher.cpp @@ -10,7 +10,9 @@ bool MessageMatcher::MatchAndExplain( std::shared_ptr msg, ::testing::MatchResultListener* listener) const { bool match = true; - if (!msg) return false; + if (!msg) { + return false; + } if (msg->str() != goodmsg->str()) { *listener << "str mismatch "; match = false; diff --git a/ntcore/src/test/native/cpp/StorageTest.cpp b/ntcore/src/test/native/cpp/StorageTest.cpp index e09fd39aa8..2cc9a9c4c4 100644 --- a/ntcore/src/test/native/cpp/StorageTest.cpp +++ b/ntcore/src/test/native/cpp/StorageTest.cpp @@ -378,10 +378,11 @@ TEST_P(StorageTestPopulated, SetDefaultEntryEmptyName) { EXPECT_FALSE(ret_val); // assert that no entries get added EXPECT_EQ(4u, entries().size()); - if (GetParam()) + if (GetParam()) { EXPECT_EQ(4u, idmap().size()); - else + } else { EXPECT_EQ(0u, idmap().size()); + } } TEST_P(StorageTestPopulated, SetDefaultEntryEmptyValue) { @@ -390,10 +391,11 @@ TEST_P(StorageTestPopulated, SetDefaultEntryEmptyValue) { EXPECT_FALSE(ret_val); // assert that no entries get added EXPECT_EQ(4u, entries().size()); - if (GetParam()) + if (GetParam()) { EXPECT_EQ(4u, idmap().size()); - else + } else { EXPECT_EQ(0u, idmap().size()); + } } TEST_P(StorageTestEmpty, SetEntryFlagsNew) { @@ -446,7 +448,9 @@ TEST_P(StorageTestPopulateOne, GetEntryFlagsExist) { EXPECT_EQ(1u, storage.GetEntryFlags("foo")); } -TEST_P(StorageTestEmpty, DeleteEntryNotExist) { storage.DeleteEntry("foo"); } +TEST_P(StorageTestEmpty, DeleteEntryNotExist) { + storage.DeleteEntry("foo"); +} TEST_P(StorageTestPopulated, DeleteEntryExist) { // client shouldn't send an update as id not assigned yet @@ -551,7 +555,9 @@ TEST_P(StorageTestPersistent, SavePersistentEmpty) { } TEST_P(StorageTestPersistent, SavePersistent) { - for (auto& i : entries()) i.getValue()->flags = NT_PERSISTENT; + for (auto& i : entries()) { + i.getValue()->flags = NT_PERSISTENT; + } wpi::SmallString<256> buf; wpi::raw_svector_ostream oss(buf); storage.SavePersistent(oss, false); diff --git a/ntcore/src/test/native/cpp/TestPrinters.h b/ntcore/src/test/native/cpp/TestPrinters.h index 998fb07330..9c9ae0140a 100644 --- a/ntcore/src/test/native/cpp/TestPrinters.h +++ b/ntcore/src/test/native/cpp/TestPrinters.h @@ -34,7 +34,9 @@ void PrintTo(const Message& msg, std::ostream* os); inline void PrintTo(std::shared_ptr msg, std::ostream* os) { *os << "shared_ptr{"; - if (msg) PrintTo(*msg, os); + if (msg) { + PrintTo(*msg, os); + } *os << '}'; } @@ -42,7 +44,9 @@ void PrintTo(const Value& value, std::ostream* os); inline void PrintTo(std::shared_ptr value, std::ostream* os) { *os << "shared_ptr{"; - if (value) PrintTo(*value, os); + if (value) { + PrintTo(*value, os); + } *os << '}'; } diff --git a/ntcore/src/test/native/cpp/WireDecoderTest.cpp b/ntcore/src/test/native/cpp/WireDecoderTest.cpp index a63053602b..b2c87b458f 100644 --- a/ntcore/src/test/native/cpp/WireDecoderTest.cpp +++ b/ntcore/src/test/native/cpp/WireDecoderTest.cpp @@ -34,7 +34,9 @@ class WireDecoderTest : public ::testing::Test { v_string_array = Value::MakeStringArray(std::move(sa)); sa.clear(); - for (int i = 0; i < 255; ++i) sa.push_back("h"); + for (int i = 0; i < 255; ++i) { + sa.push_back("h"); + } v_string_array_big = Value::MakeStringArray(std::move(sa)); s_normal = std::string("hello"); @@ -364,7 +366,9 @@ TEST_F(WireDecoderTest, ReadStringArrayValue2) { TEST_F(WireDecoderTest, ReadStringArrayBigValue2) { std::string s; s.push_back('\xff'); - for (int i = 0; i < 255; ++i) s.append("\x00\x01h", 3); + for (int i = 0; i < 255; ++i) { + s.append("\x00\x01h", 3); + } wpi::raw_mem_istream is(s.data(), s.size()); wpi::Logger logger; WireDecoder d(is, 0x0200u, logger); @@ -561,7 +565,9 @@ TEST_F(WireDecoderTest, ReadStringArrayValue3) { TEST_F(WireDecoderTest, ReadStringArrayBigValue3) { std::string s; s.push_back('\xff'); - for (int i = 0; i < 255; ++i) s.append("\x01h", 2); + for (int i = 0; i < 255; ++i) { + s.append("\x01h", 2); + } wpi::raw_mem_istream is(s.data(), s.size()); wpi::Logger logger; WireDecoder d(is, 0x0300u, logger); diff --git a/ntcore/src/test/native/cpp/WireEncoderTest.cpp b/ntcore/src/test/native/cpp/WireEncoderTest.cpp index f9b0930f3e..46e362281c 100644 --- a/ntcore/src/test/native/cpp/WireEncoderTest.cpp +++ b/ntcore/src/test/native/cpp/WireEncoderTest.cpp @@ -35,7 +35,9 @@ class WireEncoderTest : public ::testing::Test { v_string_array = Value::MakeStringArray(std::move(sa)); sa.clear(); - for (int i = 0; i < 256; ++i) sa.push_back("h"); + for (int i = 0; i < 256; ++i) { + sa.push_back("h"); + } v_string_array_big = Value::MakeStringArray(std::move(sa)); s_normal = "hello"; @@ -74,7 +76,9 @@ TEST_F(WireEncoderTest, SetProtoRev) { TEST_F(WireEncoderTest, Write8) { size_t off = BUFSIZE - 1; WireEncoder e(0x0300u); - for (size_t i = 0; i < off; ++i) e.Write8(0u); // test across Reserve() + for (size_t i = 0; i < off; ++i) { + e.Write8(0u); // test across Reserve() + } e.Write8(5u); e.Write8(0x101u); // should be truncated e.Write8(0u); @@ -86,7 +90,9 @@ TEST_F(WireEncoderTest, Write8) { TEST_F(WireEncoderTest, Write16) { size_t off = BUFSIZE - 2; WireEncoder e(0x0300u); - for (size_t i = 0; i < off; ++i) e.Write8(0u); // test across Reserve() + for (size_t i = 0; i < off; ++i) { + e.Write8(0u); // test across Reserve() + } e.Write16(5u); e.Write16(0x10001u); // should be truncated e.Write16(0x4567u); @@ -99,7 +105,9 @@ TEST_F(WireEncoderTest, Write16) { TEST_F(WireEncoderTest, Write32) { size_t off = BUFSIZE - 4; WireEncoder e(0x0300u); - for (size_t i = 0; i < off; ++i) e.Write8(0u); // test across Reserve() + for (size_t i = 0; i < off; ++i) { + e.Write8(0u); // test across Reserve() + } e.Write32(5ul); e.Write32(1ul); e.Write32(0xabcdul); @@ -115,7 +123,9 @@ TEST_F(WireEncoderTest, Write32) { TEST_F(WireEncoderTest, WriteDouble) { size_t off = BUFSIZE - 8; WireEncoder e(0x0300u); - for (size_t i = 0; i < off; ++i) e.Write8(0u); // test across Reserve() + for (size_t i = 0; i < off; ++i) { + e.Write8(0u); // test across Reserve() + } e.WriteDouble(0.0); e.WriteDouble(2.3e5); e.WriteDouble(std::numeric_limits::infinity()); @@ -136,7 +146,9 @@ TEST_F(WireEncoderTest, WriteDouble) { TEST_F(WireEncoderTest, WriteUleb128) { size_t off = BUFSIZE - 2; WireEncoder e(0x0300u); - for (size_t i = 0; i < off; ++i) e.Write8(0u); // test across Reserve() + for (size_t i = 0; i < off; ++i) { + e.Write8(0u); // test across Reserve() + } e.WriteUleb128(0ul); e.WriteUleb128(0x7ful); e.WriteUleb128(0x80ul); @@ -148,7 +160,9 @@ TEST_F(WireEncoderTest, WriteUleb128) { TEST_F(WireEncoderTest, WriteType) { size_t off = BUFSIZE - 1; WireEncoder e(0x0300u); - for (size_t i = 0; i < off; ++i) e.Write8(0u); // test across Reserve() + for (size_t i = 0; i < off; ++i) { + e.Write8(0u); // test across Reserve() + } e.WriteType(NT_BOOLEAN); e.WriteType(NT_DOUBLE); e.WriteType(NT_STRING); diff --git a/simulation/frc_gazebo_plugins/src/clockTest/cpp/clockTest.cpp b/simulation/frc_gazebo_plugins/src/clockTest/cpp/clockTest.cpp index c4c637a9a1..7590d304aa 100644 --- a/simulation/frc_gazebo_plugins/src/clockTest/cpp/clockTest.cpp +++ b/simulation/frc_gazebo_plugins/src/clockTest/cpp/clockTest.cpp @@ -18,7 +18,9 @@ static char* library; static char* world_sdf; static double latest_time; -void cb(gazebo::msgs::ConstFloat64Ptr& msg) { latest_time = msg->data(); } +void cb(gazebo::msgs::ConstFloat64Ptr& msg) { + latest_time = msg->data(); +} TEST(ClockTests, test_clock) { gazebo::physics::WorldPtr world; @@ -64,9 +66,13 @@ TEST(ClockTests, test_clock) { int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); - if (argc >= 1) library = argv[1]; + if (argc >= 1) { + library = argv[1]; + } - if (argc >= 2) world_sdf = argv[2]; + if (argc >= 2) { + world_sdf = argv[2]; + } return RUN_ALL_TESTS(); } diff --git a/simulation/frc_gazebo_plugins/src/drive_motor/cpp/drive_motor.cpp b/simulation/frc_gazebo_plugins/src/drive_motor/cpp/drive_motor.cpp index de12bb5861..01679e97bd 100644 --- a/simulation/frc_gazebo_plugins/src/drive_motor/cpp/drive_motor.cpp +++ b/simulation/frc_gazebo_plugins/src/drive_motor/cpp/drive_motor.cpp @@ -87,7 +87,9 @@ void DriveMotor::Load(gazebo::physics::ModelPtr model, sdf::ElementPtr sdf) { static double computeForce(double input, double velocity, double max) { double output = input; - if (max == 0.0) return output; + if (max == 0.0) { + return output; + } if (std::fabs(velocity) >= max) { output = 0; } else { @@ -104,7 +106,8 @@ void DriveMotor::Update(const gazebo::common::UpdateInfo& info) { ignition::math::Vector3d velocity = parent->GetRelativeLinearVel().Ign(); #endif - if (signal == 0) return; + if (signal == 0) + return; double x = computeForce(signal * dx * multiplier, velocity.X(), std::fabs(maxSpeed * dx)); diff --git a/simulation/frc_gazebo_plugins/src/gyro/cpp/gyro.cpp b/simulation/frc_gazebo_plugins/src/gyro/cpp/gyro.cpp index 7c3cdbeb10..b30d9b7ffc 100644 --- a/simulation/frc_gazebo_plugins/src/gyro/cpp/gyro.cpp +++ b/simulation/frc_gazebo_plugins/src/gyro/cpp/gyro.cpp @@ -20,9 +20,12 @@ void Gyro::Load(gazebo::physics::ModelPtr model, sdf::ElementPtr sdf) { } std::string axisString = sdf->Get("axis"); - if (axisString == "roll") axis = Roll; - if (axisString == "pitch") axis = Pitch; - if (axisString == "yaw") axis = Yaw; + if (axisString == "roll") + axis = Roll; + if (axisString == "pitch") + axis = Pitch; + if (axisString == "yaw") + axis = Yaw; if (sdf->HasElement("units")) { radians = sdf->Get("units") != "degrees"; diff --git a/simulation/frc_gazebo_plugins/src/pneumatic_piston/cpp/pneumatic_piston.cpp b/simulation/frc_gazebo_plugins/src/pneumatic_piston/cpp/pneumatic_piston.cpp index 4a2662ce3a..a1f8d8db74 100644 --- a/simulation/frc_gazebo_plugins/src/pneumatic_piston/cpp/pneumatic_piston.cpp +++ b/simulation/frc_gazebo_plugins/src/pneumatic_piston/cpp/pneumatic_piston.cpp @@ -78,7 +78,8 @@ void PneumaticPiston::Update(const gazebo::common::UpdateInfo& info) { the lack of the forward signal suffices. Note that a true simulation would not allow a SingleSolenoid to have reverse force, but we put that in the hands of the model builder.*/ - if (reverse_topic.empty() || reverse_signal) force = reverse_force; + if (reverse_topic.empty() || reverse_signal) + force = reverse_force; } joint->SetForce(0, force); } diff --git a/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp b/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp index 19e5f1981e..0aad44faa4 100644 --- a/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp +++ b/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp @@ -47,7 +47,9 @@ void DSCommPacket::SetAlliance(uint8_t station_code) { } void DSCommPacket::ReadMatchtimeTag(wpi::ArrayRef tagData) { - if (tagData.size() < 6) return; + if (tagData.size() < 6) { + return; + } uint32_t store = tagData[2] << 24; store |= tagData[3] << 16; @@ -137,7 +139,9 @@ void DSCommPacket::DecodeTCP(wpi::ArrayRef packet) { } void DSCommPacket::DecodeUDP(wpi::ArrayRef packet) { - if (packet.size() < 6) return; + if (packet.size() < 6) { + return; + } // Decode fixed header m_hi = packet[0]; m_lo = packet[1]; @@ -146,7 +150,9 @@ void DSCommPacket::DecodeUDP(wpi::ArrayRef packet) { SetAlliance(packet[5]); // Return if packet finished - if (packet.size() == 6) return; + if (packet.size() == 6) { + return; + } // Else, handle tagged data packet = packet.slice(6); @@ -173,7 +179,9 @@ void DSCommPacket::DecodeUDP(wpi::ArrayRef packet) { void DSCommPacket::ReadNewMatchInfoTag(wpi::ArrayRef data) { // Size 2 bytes, tag 1 byte - if (data.size() <= 3) return; + if (data.size() <= 3) { + return; + } int nameLength = std::min(data[3], sizeof(matchInfo.eventName) - 1); @@ -185,7 +193,9 @@ void DSCommPacket::ReadNewMatchInfoTag(wpi::ArrayRef data) { data = data.slice(4 + nameLength); - if (data.size() < 4) return; + if (data.size() < 4) { + return; + } matchInfo.matchType = static_cast( data[0]); // None, Practice, Qualification, Elimination, Test @@ -197,7 +207,9 @@ void DSCommPacket::ReadNewMatchInfoTag(wpi::ArrayRef data) { void DSCommPacket::ReadGameSpecificMessageTag(wpi::ArrayRef data) { // Size 2 bytes, tag 1 byte - if (data.size() <= 3) return; + if (data.size() <= 3) { + return; + } int length = std::min(((data[0] << 8) | data[1]) - 1, sizeof(matchInfo.gameSpecificMessage)); @@ -210,7 +222,9 @@ void DSCommPacket::ReadGameSpecificMessageTag(wpi::ArrayRef data) { HALSIM_SetMatchInfo(&matchInfo); } void DSCommPacket::ReadJoystickDescriptionTag(wpi::ArrayRef data) { - if (data.size() < 3) return; + if (data.size() < 3) { + return; + } data = data.slice(3); int joystickNum = data[0]; DSCommJoystickPacket& packet = m_joystick_packets[joystickNum]; diff --git a/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp b/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp index a304697eb5..bac36b4334 100644 --- a/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp +++ b/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp @@ -57,7 +57,9 @@ static void HandleTcpDataStream(Buffer& buf, size_t size, DataStore& store) { size_t toCopy = (std::min)(2u - store.m_frame.size(), data.size()); store.m_frame.append(data.bytes_begin(), data.bytes_begin() + toCopy); data = data.drop_front(toCopy); - if (store.m_frame.size() < 2u) return; // need more data + if (store.m_frame.size() < 2u) { + return; // need more data + } } store.m_frameSize = (static_cast(store.m_frame[0]) << 8) | static_cast(store.m_frame[1]); diff --git a/simulation/halsim_ds_socket/src/test/native/cpp/DSCommPacketTest.cpp b/simulation/halsim_ds_socket/src/test/native/cpp/DSCommPacketTest.cpp index c7655599f9..18e658c0d7 100644 --- a/simulation/halsim_ds_socket/src/test/native/cpp/DSCommPacketTest.cpp +++ b/simulation/halsim_ds_socket/src/test/native/cpp/DSCommPacketTest.cpp @@ -67,7 +67,8 @@ TEST_F(DSCommPacketTest, MainJoystickTag) { std::array _buttons{{0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1}}; std::array _button_bytes{{0, 0}}; - for (int btn = 0; btn < 8; btn++) _button_bytes[1] |= _buttons[btn] << btn; + for (int btn = 0; btn < 8; btn++) + _button_bytes[1] |= _buttons[btn] << btn; for (int btn = 8; btn < 12; btn++) _button_bytes[0] |= _buttons[btn] << (btn - 8); diff --git a/simulation/halsim_gazebo/src/main/native/cpp/GazeboEncoder.cpp b/simulation/halsim_gazebo/src/main/native/cpp/GazeboEncoder.cpp index 815a41475b..1a95cb48c8 100644 --- a/simulation/halsim_gazebo/src/main/native/cpp/GazeboEncoder.cpp +++ b/simulation/halsim_gazebo/src/main/native/cpp/GazeboEncoder.cpp @@ -30,7 +30,8 @@ static void encoder_reset_callback(const char* name, void* param, static void encoder_reverse_callback(const char* name, void* param, const struct HAL_Value* value) { GazeboEncoder* encoder = static_cast(param); - if (encoder->IsInitialized()) encoder->SetReverse(value->data.v_boolean); + if (encoder->IsInitialized()) + encoder->SetReverse(value->data.v_boolean); } GazeboEncoder::GazeboEncoder(int index, HALSimGazebo* halsim) { @@ -56,7 +57,8 @@ void GazeboEncoder::Control(const char* command) { } gazebo::msgs::String msg; msg.set_data(command); - if (m_pub) m_pub->Publish(msg); + if (m_pub) + m_pub->Publish(msg); } void GazeboEncoder::Listen() { diff --git a/simulation/halsim_gazebo/src/main/native/cpp/GazeboPCM.cpp b/simulation/halsim_gazebo/src/main/native/cpp/GazeboPCM.cpp index ee386065f4..7997d4452b 100644 --- a/simulation/halsim_gazebo/src/main/native/cpp/GazeboPCM.cpp +++ b/simulation/halsim_gazebo/src/main/native/cpp/GazeboPCM.cpp @@ -21,7 +21,8 @@ static void init_callback(const char* name, void* param, static void output_callback(const char* name, void* param, const struct HAL_Value* value) { GazeboPCM* pcm = static_cast(param); - if (pcm->IsInitialized()) pcm->Publish(value->data.v_boolean); + if (pcm->IsInitialized()) + pcm->Publish(value->data.v_boolean); } GazeboPCM::GazeboPCM(int index, int channel, HALSimGazebo* halsim) { @@ -44,7 +45,8 @@ void GazeboPCM::Publish(bool value) { } gazebo::msgs::Bool msg; msg.set_data(value); - if (m_pub) m_pub->Publish(msg); + if (m_pub) + m_pub->Publish(msg); } void GazeboPCM_SetPressureSwitch(int index, bool value) { diff --git a/simulation/halsim_gazebo/src/main/native/cpp/GazeboPWM.cpp b/simulation/halsim_gazebo/src/main/native/cpp/GazeboPWM.cpp index 04c33b17f5..af71e121d2 100644 --- a/simulation/halsim_gazebo/src/main/native/cpp/GazeboPWM.cpp +++ b/simulation/halsim_gazebo/src/main/native/cpp/GazeboPWM.cpp @@ -21,7 +21,8 @@ static void init_callback(const char* name, void* param, static void speed_callback(const char* name, void* param, const struct HAL_Value* value) { GazeboPWM* pwm = static_cast(param); - if (pwm->IsInitialized()) pwm->Publish(value->data.v_double); + if (pwm->IsInitialized()) + pwm->Publish(value->data.v_double); } GazeboPWM::GazeboPWM(int port, HALSimGazebo* halsim) { @@ -39,5 +40,6 @@ void GazeboPWM::Publish(double value) { } gazebo::msgs::Float64 msg; msg.set_data(value); - if (m_pub) m_pub->Publish(msg); + if (m_pub) + m_pub->Publish(msg); } diff --git a/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp b/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp index 94fdb5ba65..37f2005245 100644 --- a/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp @@ -63,7 +63,9 @@ void AddressableLEDsModel::Update() { if (!model) { model = std::make_unique(i); } - if (model) model->Update(); + if (model) { + model->Update(); + } } else { model.reset(); } @@ -72,7 +74,9 @@ void AddressableLEDsModel::Update() { bool AddressableLEDsModel::Exists() { for (auto&& model : m_models) { - if (model && model->Exists()) return true; + if (model && model->Exists()) { + return true; + } } return false; } @@ -80,14 +84,18 @@ bool AddressableLEDsModel::Exists() { void AddressableLEDsModel::ForEachLEDDisplay( wpi::function_ref func) { for (int i = 0; i < static_cast(m_models.size()); ++i) { - if (m_models[i]) func(*m_models[i], i); + if (m_models[i]) { + func(*m_models[i], i); + } } } static bool AddressableLEDsExists() { static const int numLED = HAL_GetNumAddressableLEDs(); for (int i = 0; i < numLED; ++i) { - if (HALSIM_GetAddressableLEDInitialized(i)) return true; + if (HALSIM_GetAddressableLEDInitialized(i)) { + return true; + } } return false; } diff --git a/simulation/halsim_gui/src/main/native/cpp/AnalogInputSimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/AnalogInputSimGui.cpp index b8774b04cd..5a3b2d8108 100644 --- a/simulation/halsim_gui/src/main/native/cpp/AnalogInputSimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/AnalogInputSimGui.cpp @@ -101,7 +101,9 @@ void AnalogInputsSimModel::ForEachAnalogInput( static bool AnalogInputsAnyInitialized() { static const int32_t num = HAL_GetNumAnalogInputs(); for (int32_t i = 0; i < num; ++i) { - if (HALSIM_GetAnalogInInitialized(i)) return true; + if (HALSIM_GetAnalogInInitialized(i)) { + return true; + } } return false; } diff --git a/simulation/halsim_gui/src/main/native/cpp/DIOSimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/DIOSimGui.cpp index 2b8b568a12..22c06dd400 100644 --- a/simulation/halsim_gui/src/main/native/cpp/DIOSimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/DIOSimGui.cpp @@ -201,11 +201,13 @@ void DIOsSimModel::Update() { EncoderSimGui::GetEncodersModel().ForEachEncoder([&](auto& encoder, int i) { int channel = encoder.GetChannelA(); - if (channel >= 0 && channel < numDIO && m_dioModels[channel]) + if (channel >= 0 && channel < numDIO && m_dioModels[channel]) { m_dioModels[channel]->SetEncoder(&encoder); + } channel = encoder.GetChannelB(); - if (channel >= 0 && channel < numDIO && m_dioModels[channel]) + if (channel >= 0 && channel < numDIO && m_dioModels[channel]) { m_dioModels[channel]->SetEncoder(&encoder); + } }); } @@ -222,7 +224,9 @@ void DIOsSimModel::ForEachDIO( static bool DIOAnyInitialized() { static const int32_t num = HAL_GetNumDigitalChannels(); for (int32_t i = 0; i < num; ++i) { - if (HALSIM_GetDIOInitialized(i)) return true; + if (HALSIM_GetDIOInitialized(i)) { + return true; + } } return false; } diff --git a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp index 15436cbdeb..326e81755c 100644 --- a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp @@ -147,7 +147,9 @@ class GlfwKeyboardJoystick : public KeyboardJoystick { explicit GlfwKeyboardJoystick(int index, bool noDefaults = false); const char* GetKeyName(int key) const override { - if (key < 0) return "(None)"; + if (key < 0) { + return "(None)"; + } return glfwGetKeyName(key, 0); } }; @@ -174,7 +176,9 @@ class JoystickModel { explicit JoystickModel(int index); ~JoystickModel() { HALSIM_CancelDriverStationNewDataCallback(m_callback); - for (int i = 0; i < buttonCount; ++i) delete buttons[i]; + for (int i = 0; i < buttonCount; ++i) { + delete buttons[i]; + } } JoystickModel(const JoystickModel&) = delete; JoystickModel& operator=(const JoystickModel&) = delete; @@ -311,7 +315,9 @@ JoystickModel::JoystickModel(int index) : m_index{index} { wpi::Twine{i + 1} + wpi::Twine{']'}); buttons[i]->SetDigital(true); } - for (int i = buttonCount; i < 32; ++i) buttons[i] = nullptr; + for (int i = buttonCount; i < 32; ++i) { + buttons[i] = nullptr; + } HAL_JoystickPOVs halPOVs; HALSIM_GetJoystickPOVs(index, &halPOVs); @@ -332,20 +338,25 @@ void JoystickModel::CallbackFunc(const char*, void* param, const HAL_Value*) { HAL_JoystickAxes halAxes; HALSIM_GetJoystickAxes(self->m_index, &halAxes); for (int i = 0; i < halAxes.count; ++i) { - if (auto axis = self->axes[i].get()) axis->SetValue(halAxes.axes[i]); + if (auto axis = self->axes[i].get()) { + axis->SetValue(halAxes.axes[i]); + } } HAL_JoystickButtons halButtons; HALSIM_GetJoystickButtons(self->m_index, &halButtons); for (int i = 0; i < halButtons.count; ++i) { - if (auto button = self->buttons[i]) + if (auto button = self->buttons[i]) { button->SetValue((halButtons.buttons & (1u << i)) != 0 ? 1 : 0); + } } HAL_JoystickPOVs halPOVs; HALSIM_GetJoystickPOVs(self->m_index, &halPOVs); for (int i = 0; i < halPOVs.count; ++i) { - if (auto pov = self->povs[i].get()) pov->SetValue(halPOVs.povs[i]); + if (auto pov = self->povs[i].get()) { + pov->SetValue(halPOVs.povs[i]); + } } } @@ -353,8 +364,12 @@ void JoystickModel::CallbackFunc(const char*, void* param, const HAL_Value*) { static void* JoystickReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) return nullptr; - if (num < 0 || num >= HAL_kMaxJoysticks) return nullptr; + if (wpi::StringRef{name}.getAsInteger(10, num)) { + return nullptr; + } + if (num < 0 || num >= HAL_kMaxJoysticks) { + return nullptr; + } return &gRobotJoysticks[num]; } @@ -370,7 +385,9 @@ static void JoystickReadLine(ImGuiContext* ctx, ImGuiSettingsHandler* handler, joy->guid = value; } else if (name == "useGamepad") { int num; - if (value.getAsInteger(10, num)) return; + if (value.getAsInteger(10, num)) { + return; + } joy->useGamepad = num; } else { joy->name.ReadIni(name, value); @@ -381,13 +398,19 @@ static void JoystickWriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf) { for (int i = 0; i < HAL_kMaxJoysticks; ++i) { auto& joy = gRobotJoysticks[i]; - if (!joy.name.HasName() && !joy.sys) continue; + if (!joy.name.HasName() && !joy.sys) { + continue; + } out_buf->appendf("[Joystick][%d]\nuseGamepad=%d\n", i, joy.useGamepad ? 1 : 0); - if (joy.name.HasName()) joy.name.WriteIni(out_buf); + if (joy.name.HasName()) { + joy.name.WriteIni(out_buf); + } if (joy.sys) { const char* guid = joy.sys->GetGUID(); - if (guid) out_buf->appendf("guid=%s\n", guid); + if (guid) { + out_buf->appendf("guid=%s\n", guid); + } } out_buf->append("\n"); } @@ -398,9 +421,12 @@ static void* KeyboardJoystickReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) return nullptr; - if (num < 0 || num >= static_cast(gKeyboardJoysticks.size())) + if (wpi::StringRef{name}.getAsInteger(10, num)) { return nullptr; + } + if (num < 0 || num >= static_cast(gKeyboardJoysticks.size())) { + return nullptr; + } auto joy = gKeyboardJoysticks[num].get(); *joy = GlfwKeyboardJoystick(num, true); return joy; @@ -430,7 +456,9 @@ static void KeyboardJoystickWriteAll(ImGuiContext* ctx, static void* DriverStationReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { - if (name == wpi::StringRef{"Main"}) return &gDisableDS; + if (name == wpi::StringRef{"Main"}) { + return &gDisableDS; + } return nullptr; } @@ -443,19 +471,27 @@ static void DriverStationReadLine(ImGuiContext* ctx, value = value.trim(); if (name == "disable") { int num; - if (value.getAsInteger(10, num)) return; + if (value.getAsInteger(10, num)) { + return; + } gDisableDS = num; } else if (name == "zeroDisconnectedJoysticks") { int num; - if (value.getAsInteger(10, num)) return; + if (value.getAsInteger(10, num)) { + return; + } gZeroDisconnectedJoysticks = num; } else if (name == "enableDisableKeys") { int num; - if (value.getAsInteger(10, num)) return; + if (value.getAsInteger(10, num)) { + return; + } gUseEnableDisableHotkeys = num; } else if (name == "estopKey") { int num; - if (value.getAsInteger(10, num)) return; + if (value.getAsInteger(10, num)) { + return; + } gUseEstopHotkey = num; } } @@ -474,7 +510,9 @@ void GlfwSystemJoystick::Update() { bool wasPresent = m_present; m_present = glfwJoystickPresent(m_index); - if (!m_present) return; + if (!m_present) { + return; + } m_axes = glfwGetJoystickAxes(m_index, &m_axisCount); m_buttons = glfwGetJoystickButtons(m_index, &m_buttonCount); m_hats = glfwGetJoystickHats(m_index, &m_hatCount); @@ -494,7 +532,9 @@ void GlfwSystemJoystick::Update() { } } - if (!m_present || wasPresent) return; + if (!m_present || wasPresent) { + return; + } m_name = glfwGetJoystickName(m_index); // try to find matching GUID @@ -533,7 +573,9 @@ static int HatToAngle(unsigned char hat) { } void GlfwSystemJoystick::GetData(HALJoystickData* data, bool mapGamepad) const { - if (!m_present) return; + if (!m_present) { + return; + } // use gamepad mappings if present and enabled const float* sysAxes; @@ -562,8 +604,9 @@ void GlfwSystemJoystick::GetData(HALJoystickData* data, bool mapGamepad) const { data->desc.povCount = (std::min)(m_hatCount, HAL_kMaxJoystickPOVs); data->buttons.count = data->desc.buttonCount; - for (int j = 0; j < data->buttons.count; ++j) + for (int j = 0; j < data->buttons.count; ++j) { data->buttons.buttons |= (sysButtons[j] ? 1u : 0u) << j; + } data->axes.count = data->desc.axisCount; if (m_isGamepad && mapGamepad) { @@ -590,8 +633,9 @@ void GlfwSystemJoystick::GetData(HALJoystickData* data, bool mapGamepad) const { } data->povs.count = data->desc.povCount; - for (int j = 0; j < data->povs.count; ++j) + for (int j = 0; j < data->povs.count; ++j) { data->povs.povs[j] = HatToAngle(m_hats[j]); + } } KeyboardJoystick::KeyboardJoystick(int index) : m_index{index} { @@ -625,9 +669,13 @@ void KeyboardJoystick::EditKey(const char* label, int* key) { char editLabel[32]; std::snprintf(editLabel, sizeof(editLabel), "%s###edit", s_keyEdit == key ? "(press key)" : GetKeyName(*key)); - if (ImGui::SmallButton(editLabel)) s_keyEdit = key; + if (ImGui::SmallButton(editLabel)) { + s_keyEdit = key; + } ImGui::SameLine(); - if (ImGui::SmallButton("Clear")) *key = -1; + if (ImGui::SmallButton("Clear")) { + *key = -1; + } ImGui::PopID(); } @@ -637,7 +685,9 @@ void KeyboardJoystick::SettingsDisplay() { for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); ++i) { if (io.KeysDown[i]) { // remove all other uses - for (auto&& joy : gKeyboardJoysticks) joy->ClearKey(i); + for (auto&& joy : gKeyboardJoysticks) { + joy->ClearKey(i); + } *s_keyEdit = i; s_keyEdit = nullptr; } @@ -651,8 +701,12 @@ void KeyboardJoystick::SettingsDisplay() { ImGui::PushID("Axes"); int axisCount = m_data.axes.count; if (ImGui::InputInt("Count", &axisCount)) { - if (axisCount < 0) axisCount = 0; - if (axisCount > HAL_kMaxJoystickAxes) axisCount = HAL_kMaxJoystickAxes; + if (axisCount < 0) { + axisCount = 0; + } + if (axisCount > HAL_kMaxJoystickAxes) { + axisCount = HAL_kMaxJoystickAxes; + } m_data.axes.count = axisCount; } for (int i = 0; i < axisCount; ++i) { @@ -673,8 +727,12 @@ void KeyboardJoystick::SettingsDisplay() { ImGui::PushID("Buttons"); int buttonCount = m_data.buttons.count; if (ImGui::InputInt("Count", &buttonCount)) { - if (buttonCount < 0) buttonCount = 0; - if (buttonCount > kMaxButtonCount) buttonCount = kMaxButtonCount; + if (buttonCount < 0) { + buttonCount = 0; + } + if (buttonCount > kMaxButtonCount) { + buttonCount = kMaxButtonCount; + } m_data.buttons.count = buttonCount; } for (int i = 0; i < buttonCount; ++i) { @@ -689,8 +747,12 @@ void KeyboardJoystick::SettingsDisplay() { ImGui::PushID("POVs"); int povCount = m_data.povs.count; if (ImGui::InputInt("Count", &povCount)) { - if (povCount < 0) povCount = 0; - if (povCount > HAL_kMaxJoystickPOVs) povCount = HAL_kMaxJoystickPOVs; + if (povCount < 0) { + povCount = 0; + } + if (povCount > HAL_kMaxJoystickPOVs) { + povCount = HAL_kMaxJoystickPOVs; + } m_data.povs.count = povCount; } for (int i = 0; i < povCount; ++i) { @@ -717,8 +779,9 @@ void KeyboardJoystick::Update() { ImGuiIO& io = ImGui::GetIO(); if (m_data.axes.count > 0 || m_data.buttons.count > 0 || - m_data.povs.count > 0) + m_data.povs.count > 0) { m_present = true; + } // axes for (int i = 0; i < m_data.axes.count; ++i) { @@ -727,22 +790,28 @@ void KeyboardJoystick::Update() { // increase/decrease while key held down (to saturation); decay back to 0 if (config.incKey >= 0 && io.KeysDown[config.incKey]) { axisValue += config.keyRate; - if (axisValue > 1.0) axisValue = 1.0; + if (axisValue > 1.0) { + axisValue = 1.0; + } } else if (axisValue > 0) { - if (axisValue < config.decayRate) + if (axisValue < config.decayRate) { axisValue = 0; - else + } else { axisValue -= config.decayRate; + } } if (config.decKey >= 0 && io.KeysDown[config.decKey]) { axisValue -= config.keyRate; - if (axisValue < -1.0) axisValue = -1.0; + if (axisValue < -1.0) { + axisValue = -1.0; + } } else if (axisValue < 0) { - if (axisValue > -config.decayRate) + if (axisValue > -config.decayRate) { axisValue = 0; - else + } else { axisValue += config.decayRate; + } } } @@ -761,22 +830,23 @@ void KeyboardJoystick::Update() { auto& config = m_povConfig[i]; auto& povValue = m_data.povs.povs[i]; povValue = -1; - if (config.key0 >= 0 && io.KeysDown[config.key0]) + if (config.key0 >= 0 && io.KeysDown[config.key0]) { povValue = 0; - else if (config.key45 >= 0 && io.KeysDown[config.key45]) + } else if (config.key45 >= 0 && io.KeysDown[config.key45]) { povValue = 45; - else if (config.key90 >= 0 && io.KeysDown[config.key90]) + } else if (config.key90 >= 0 && io.KeysDown[config.key90]) { povValue = 90; - else if (config.key135 >= 0 && io.KeysDown[config.key135]) + } else if (config.key135 >= 0 && io.KeysDown[config.key135]) { povValue = 135; - else if (config.key180 >= 0 && io.KeysDown[config.key180]) + } else if (config.key180 >= 0 && io.KeysDown[config.key180]) { povValue = 180; - else if (config.key225 >= 0 && io.KeysDown[config.key225]) + } else if (config.key225 >= 0 && io.KeysDown[config.key225]) { povValue = 225; - else if (config.key270 >= 0 && io.KeysDown[config.key270]) + } else if (config.key270 >= 0 && io.KeysDown[config.key270]) { povValue = 270; - else if (config.key315 >= 0 && io.KeysDown[config.key315]) + } else if (config.key315 >= 0 && io.KeysDown[config.key315]) { povValue = 315; + } } // try to find matching GUID @@ -796,21 +866,43 @@ void KeyboardJoystick::Update() { void KeyboardJoystick::ClearKey(int key) { for (auto&& config : m_axisConfig) { - if (config.incKey == key) config.incKey = -1; - if (config.decKey == key) config.decKey = -1; + if (config.incKey == key) { + config.incKey = -1; + } + if (config.decKey == key) { + config.decKey = -1; + } } for (auto&& buttonKey : m_buttonKey) { - if (buttonKey == key) buttonKey = -1; + if (buttonKey == key) { + buttonKey = -1; + } } for (auto&& config : m_povConfig) { - if (config.key0 == key) config.key0 = -1; - if (config.key45 == key) config.key45 = -1; - if (config.key90 == key) config.key90 = -1; - if (config.key135 == key) config.key135 = -1; - if (config.key180 == key) config.key180 = -1; - if (config.key225 == key) config.key225 = -1; - if (config.key270 == key) config.key270 = -1; - if (config.key315 == key) config.key315 = -1; + if (config.key0 == key) { + config.key0 = -1; + } + if (config.key45 == key) { + config.key45 = -1; + } + if (config.key90 == key) { + config.key90 = -1; + } + if (config.key135 == key) { + config.key135 = -1; + } + if (config.key180 == key) { + config.key180 = -1; + } + if (config.key225 == key) { + config.key225 = -1; + } + if (config.key270 == key) { + config.key270 = -1; + } + if (config.key315 == key) { + config.key315 = -1; + } } } @@ -819,21 +911,31 @@ void KeyboardJoystick::ReadIni(wpi::StringRef name, wpi::StringRef value) { name = name.drop_front(4); if (name == "Count") { int v; - if (value.getAsInteger(10, v)) return; + if (value.getAsInteger(10, v)) { + return; + } m_data.axes.count = (std::min)(v, HAL_kMaxJoystickAxes); return; } unsigned int index; - if (name.consumeInteger(10, index)) return; - if (index >= HAL_kMaxJoystickAxes) return; + if (name.consumeInteger(10, index)) { + return; + } + if (index >= HAL_kMaxJoystickAxes) { + return; + } if (name == "incKey") { int v; - if (value.getAsInteger(10, v)) return; + if (value.getAsInteger(10, v)) { + return; + } m_axisConfig[index].incKey = v; } else if (name == "decKey") { int v; - if (value.getAsInteger(10, v)) return; + if (value.getAsInteger(10, v)) { + return; + } m_axisConfig[index].decKey = v; } else if (name == "keyRate") { std::sscanf(value.data(), "%f", &m_axisConfig[index].keyRate); @@ -844,31 +946,47 @@ void KeyboardJoystick::ReadIni(wpi::StringRef name, wpi::StringRef value) { name = name.drop_front(6); if (name == "Count") { int v; - if (value.getAsInteger(10, v)) return; + if (value.getAsInteger(10, v)) { + return; + } m_data.buttons.count = (std::min)(v, kMaxButtonCount); return; } unsigned int index; - if (name.getAsInteger(10, index)) return; - if (index >= kMaxButtonCount) return; + if (name.getAsInteger(10, index)) { + return; + } + if (index >= kMaxButtonCount) { + return; + } int v; - if (value.getAsInteger(10, v)) return; + if (value.getAsInteger(10, v)) { + return; + } m_buttonKey[index] = v; } else if (name.startswith("pov")) { name = name.drop_front(3); if (name == "Count") { int v; - if (value.getAsInteger(10, v)) return; + if (value.getAsInteger(10, v)) { + return; + } m_data.povs.count = (std::min)(v, HAL_kMaxJoystickPOVs); return; } unsigned int index; - if (name.consumeInteger(10, index)) return; - if (index >= HAL_kMaxJoystickPOVs) return; + if (name.consumeInteger(10, index)) { + return; + } + if (index >= HAL_kMaxJoystickPOVs) { + return; + } int v; - if (value.getAsInteger(10, v)) return; + if (value.getAsInteger(10, v)) { + return; + } if (name == "key0") { m_povConfig[index].key0 = v; } else if (name == "key45") { @@ -914,7 +1032,9 @@ void KeyboardJoystick::WriteIni(ImGuiTextBuffer* out_buf) const { GlfwKeyboardJoystick::GlfwKeyboardJoystick(int index, bool noDefaults) : KeyboardJoystick{index} { - if (noDefaults) return; + if (noDefaults) { + return; + } // set up a default keyboard config for 0, 1, and 2 if (index == 0) { m_data.axes.count = 3; @@ -969,11 +1089,15 @@ GlfwKeyboardJoystick::GlfwKeyboardJoystick(int index, bool noDefaults) void RobotJoystick::Update() { Clear(); - if (sys) sys->GetData(&data, useGamepad); + if (sys) { + sys->GetData(&data, useGamepad); + } } void RobotJoystick::SetHAL(int i) { - if (!gZeroDisconnectedJoysticks && (!sys || !sys->IsPresent())) return; + if (!gZeroDisconnectedJoysticks && (!sys || !sys->IsPresent())) { + return; + } // set at HAL level HALSIM_SetJoystickDescriptor(i, &data.desc); HALSIM_SetJoystickAxes(i, &data.axes); @@ -1018,7 +1142,9 @@ static void DriverStationExecute() { } } prevDisableDS = disableDS; - if (disableDS) return; + if (disableDS) { + return; + } double curTime = glfwGetTime(); @@ -1026,12 +1152,18 @@ static void DriverStationExecute() { gNumGlfwJoysticks = 0; for (int i = 0; i <= GLFW_JOYSTICK_LAST; ++i) { gGlfwJoysticks[i]->Update(); - if (gGlfwJoysticks[i]->IsPresent()) gNumGlfwJoysticks = i + 1; + if (gGlfwJoysticks[i]->IsPresent()) { + gNumGlfwJoysticks = i + 1; + } + } + for (auto&& joy : gKeyboardJoysticks) { + joy->Update(); } - for (auto&& joy : gKeyboardJoysticks) joy->Update(); // update robot joysticks - for (auto&& joy : gRobotJoysticks) joy.Update(); + for (auto&& joy : gRobotJoysticks) { + joy.Update(); + } bool isEnabled = HALSIM_GetDriverStationEnabled(); bool isAuto = HALSIM_GetDriverStationAutonomous(); @@ -1044,12 +1176,13 @@ static void DriverStationExecute() { bool disableHotkey = false; if (gUseEnableDisableHotkeys) { ImGuiIO& io = ImGui::GetIO(); - if (io.KeysDown[GLFW_KEY_ENTER] || io.KeysDown[GLFW_KEY_KP_ENTER]) + if (io.KeysDown[GLFW_KEY_ENTER] || io.KeysDown[GLFW_KEY_KP_ENTER]) { disableHotkey = true; - else if (io.KeysDown[GLFW_KEY_LEFT_BRACKET] && - io.KeysDown[GLFW_KEY_RIGHT_BRACKET] && - io.KeysDown[GLFW_KEY_BACKSLASH]) + } else if (io.KeysDown[GLFW_KEY_LEFT_BRACKET] && + io.KeysDown[GLFW_KEY_RIGHT_BRACKET] && + io.KeysDown[GLFW_KEY_BACKSLASH]) { enableHotkey = true; + } } if (gUseEstopHotkey) { ImGuiIO& io = ImGui::GetIO(); @@ -1083,7 +1216,9 @@ static void DriverStationExecute() { } // Update HAL - for (int i = 0; i < HAL_kMaxJoysticks; ++i) gRobotJoysticks[i].SetHAL(i); + for (int i = 0; i < HAL_kMaxJoysticks; ++i) { + gRobotJoysticks[i].SetHAL(i); + } // Send new data every 20 ms (may be slower depending on GUI refresh rate) static double lastNewDataTime = 0.0; @@ -1117,12 +1252,16 @@ void FMSSimModel::Update() { if (m_matchTimeEnabled && !IsDSDisabled()) { int32_t status = 0; double curTime = HAL_GetFPGATime(&status) * 1.0e-6; - if (m_startMatchTime == 0.0) m_startMatchTime = curTime; + if (m_startMatchTime == 0.0) { + m_startMatchTime = curTime; + } if (enabled) { matchTime = curTime - m_startMatchTime; HALSIM_SetDriverStationMatchTime(matchTime); } else { - if (m_prevTime == 0.0) m_prevTime = curTime; + if (m_prevTime == 0.0) { + m_prevTime = curTime; + } m_startMatchTime += (curTime - m_prevTime); } m_prevTime = curTime; @@ -1133,7 +1272,9 @@ void FMSSimModel::Update() { m_matchTime.SetValue(matchTime); } -bool FMSSimModel::IsReadOnly() { return IsDSDisabled(); } +bool FMSSimModel::IsReadOnly() { + return IsDSDisabled(); +} static void DisplaySystemJoystick(SystemJoystick& joy, int i) { char label[64]; @@ -1141,12 +1282,15 @@ static void DisplaySystemJoystick(SystemJoystick& joy, int i) { // highlight if any buttons pressed bool anyButtonPressed = joy.IsAnyButtonPressed(); - if (anyButtonPressed) + if (anyButtonPressed) { ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 255, 0, 255)); + } ImGui::Selectable(label, false, joy.IsPresent() ? ImGuiSelectableFlags_None : ImGuiSelectableFlags_Disabled); - if (anyButtonPressed) ImGui::PopStyleColor(); + if (anyButtonPressed) { + ImGui::PopStyleColor(); + } // drag and drop sources are the low level joysticks if (ImGui::BeginDragDropSource()) { @@ -1160,10 +1304,12 @@ static void DisplaySystemJoystick(SystemJoystick& joy, int i) { static void DisplaySystemJoysticks() { ImGui::Text("(Drag and drop to Joysticks)"); int numShowJoysticks = gNumGlfwJoysticks < 6 ? 6 : gNumGlfwJoysticks; - for (int i = 0; i < numShowJoysticks; ++i) + for (int i = 0; i < numShowJoysticks; ++i) { DisplaySystemJoystick(*gGlfwJoysticks[i], i); - for (size_t i = 0; i < gKeyboardJoysticks.size(); ++i) + } + for (size_t i = 0; i < gKeyboardJoysticks.size(); ++i) { DisplaySystemJoystick(*gKeyboardJoysticks[i], i + GLFW_JOYSTICK_LAST + 1); + } } static void DisplayJoysticks() { @@ -1194,7 +1340,9 @@ static void DisplayJoysticks() { *static_cast(payload->Data); // clear it from the other joysticks for (auto&& joy2 : gRobotJoysticks) { - if (joy2.sys == payload_sys) joy2.sys = nullptr; + if (joy2.sys == payload_sys) { + joy2.sys = nullptr; + } } joy.sys = payload_sys; joy.guid.clear(); @@ -1212,7 +1360,9 @@ static void DisplayJoysticks() { auto& joy = gRobotJoysticks[i]; auto source = gJoystickSources[i].get(); - if (disableDS) joy.GetHAL(i); + if (disableDS) { + joy.GetHAL(i); + } if ((disableDS && joy.data.desc.type != 0) || (joy.sys && joy.sys->IsPresent())) { @@ -1224,8 +1374,9 @@ static void DisplayJoysticks() { } else { ImGui::Text("%d: %s", joy.sys->GetIndex(), joy.sys->GetName()); - if (joy.sys->IsGamepad()) + if (joy.sys->IsGamepad()) { ImGui::Checkbox("Map gamepad", &joy.useGamepad); + } } for (int j = 0; j < joy.data.axes.count; ++j) { @@ -1258,8 +1409,9 @@ static void DisplayJoysticks() { static const ImU32 color = IM_COL32(255, 255, 102, 255); wpi::SmallVector buttons; buttons.resize(joy.data.buttons.count); - for (int j = 0; j < joy.data.buttons.count; ++j) + for (int j = 0; j < joy.data.buttons.count; ++j) { buttons[j] = joy.IsButtonPressed(j) ? 1 : -1; + } DrawLEDSources(buttons.data(), source ? source->buttons : nullptr, buttons.size(), 8, &color); ImGui::PopID(); @@ -1318,10 +1470,12 @@ static void DriverStationInitialize() { void DriverStationGui::GlobalInit() { // set up system joysticks (both GLFW and keyboard) - for (int i = 0; i <= GLFW_JOYSTICK_LAST; ++i) + for (int i = 0; i <= GLFW_JOYSTICK_LAST; ++i) { gGlfwJoysticks.emplace_back(std::make_unique(i)); - for (int i = 0; i < 4; ++i) + } + for (int i = 0; i < 4; ++i) { gKeyboardJoysticks.emplace_back(std::make_unique(i)); + } dsManager.GlobalInit(); @@ -1358,7 +1512,9 @@ void DriverStationGui::GlobalInit() { win->SetVisible(false); win->DisableRenamePopup(); win->SetDefaultPos(10 + 310 * i++, 50); - if (i > 3) i = 0; + if (i > 3) { + i = 0; + } win->SetDefaultSize(300, 560); } } diff --git a/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp index dc7cfd067b..b88e55eb3f 100644 --- a/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp @@ -57,15 +57,19 @@ class EncoderSimModel : public glass::EncoderModel { HALSIM_GetEncoderDigitalChannelB(index)) {} ~EncoderSimModel() { - if (m_distancePerPulseCallback != 0) + if (m_distancePerPulseCallback != 0) { HALSIM_CancelEncoderDistancePerPulseCallback(m_index, m_distancePerPulseCallback); - if (m_countCallback != 0) + } + if (m_countCallback != 0) { HALSIM_CancelEncoderCountCallback(m_index, m_countCallback); - if (m_periodCallback != 0) + } + if (m_periodCallback != 0) { HALSIM_CancelEncoderCountCallback(m_index, m_periodCallback); - if (m_directionCallback != 0) + } + if (m_directionCallback != 0) { HALSIM_CancelEncoderCountCallback(m_index, m_directionCallback); + } } void Update() override {} @@ -75,10 +79,11 @@ class EncoderSimModel : public glass::EncoderModel { int32_t GetIndex() const { return m_index; } const char* GetSimDevice() const override { - if (auto simDevice = HALSIM_GetEncoderSimDevice(m_index)) + if (auto simDevice = HALSIM_GetEncoderSimDevice(m_index)) { return HALSIM_GetSimDeviceName(simDevice); - else + } else { return nullptr; + } } int GetChannelA() const override { return m_channelA; } @@ -127,12 +132,13 @@ class EncoderSimModel : public glass::EncoderModel { self->m_distancePerPulse.SetValue(distPerPulse); self->m_distance.SetValue(self->m_count.GetValue() * distPerPulse); double period = self->m_period.GetValue(); - if (period == 0) + if (period == 0) { self->m_rate.SetValue(std::numeric_limits::infinity()); - else if (period == std::numeric_limits::infinity()) + } else if (period == std::numeric_limits::infinity()) { self->m_rate.SetValue(0); - else + } else { self->m_rate.SetValue(static_cast(distPerPulse / period)); + } } } @@ -152,13 +158,14 @@ class EncoderSimModel : public glass::EncoderModel { auto self = static_cast(param); double period = value->data.v_double; self->m_period.SetValue(period); - if (period == 0) + if (period == 0) { self->m_rate.SetValue(std::numeric_limits::infinity()); - else if (period == std::numeric_limits::infinity()) + } else if (period == std::numeric_limits::infinity()) { self->m_rate.SetValue(0); - else + } else { self->m_rate.SetValue( static_cast(self->m_distancePerPulse.GetValue() / period)); + } } } @@ -230,7 +237,9 @@ void EncodersSimModel::ForEachEncoder( static bool EncodersAnyInitialized() { static const int32_t num = HAL_GetNumEncoders(); for (int32_t i = 0; i < num; ++i) { - if (HALSIM_GetEncoderInitialized(i)) return true; + if (HALSIM_GetEncoderInitialized(i)) { + return true; + } } return false; } diff --git a/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp b/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp index af8ed5cc69..0f2a2f8cfa 100644 --- a/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp @@ -44,21 +44,29 @@ void HALProvider::Update() { // check for visible windows that need displays (typically this is due to // file loading) for (auto&& window : m_windows) { - if (!window->IsVisible() || window->HasView()) continue; + if (!window->IsVisible() || window->HasView()) { + continue; + } auto id = window->GetId(); auto it = FindViewEntry(id); - if (it == m_viewEntries.end() || (*it)->name != id) continue; + if (it == m_viewEntries.end() || (*it)->name != id) { + continue; + } Show(it->get(), window.get()); } } glass::Model* HALProvider::GetModel(wpi::StringRef name) { auto it = FindModelEntry(name); - if (it == m_modelEntries.end() || (*it)->name != name) return nullptr; + if (it == m_modelEntries.end() || (*it)->name != name) { + return nullptr; + } auto entry = it->get(); // get or create model - if (!entry->model) entry->model = entry->createModel(); + if (!entry->model) { + entry->model = entry->createModel(); + } return entry->model.get(); } @@ -70,18 +78,27 @@ void HALProvider::Show(ViewEntry* entry, glass::Window* window) { } // get or create model - if (!entry->modelEntry->model) + if (!entry->modelEntry->model) { entry->modelEntry->model = entry->modelEntry->createModel(); - if (!entry->modelEntry->model) return; + } + if (!entry->modelEntry->model) { + return; + } // the window might exist and we're just not associated to it yet - if (!window) window = GetOrAddWindow(entry->name, true); - if (!window) return; + if (!window) { + window = GetOrAddWindow(entry->name, true); + } + if (!window) { + return; + } entry->window = window; // create view auto view = entry->createView(window, entry->modelEntry->model.get()); - if (!view) return; + if (!view) { + return; + } window->SetView(std::move(view)); entry->window->SetVisible(true); diff --git a/simulation/halsim_gui/src/main/native/cpp/Mechanism2D.cpp b/simulation/halsim_gui/src/main/native/cpp/Mechanism2D.cpp index fe15d853dd..01dd90fa04 100644 --- a/simulation/halsim_gui/src/main/native/cpp/Mechanism2D.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/Mechanism2D.cpp @@ -98,7 +98,9 @@ void WriteIni(ImGuiTextBuffer* out) { static void* Mechanism2DReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { - if (name == wpi::StringRef{"Mechanism2D"}) return &mechanism2DInfo; + if (name == wpi::StringRef{"Mechanism2D"}) { + return &mechanism2DInfo; + } return nullptr; } @@ -109,7 +111,9 @@ static void Mechanism2DReadLine(ImGuiContext* ctx, auto [name, value] = line.split('='); name = name.trim(); value = value.trim(); - if (entry == &mechanism2DInfo) ReadIni(name, value); + if (entry == &mechanism2DInfo) { + ReadIni(name, value); + } } static void Mechanism2DWriteAll(ImGuiContext* ctx, @@ -166,20 +170,28 @@ static void buildDrawList(float startXLocation, float startYLocation, minSize = ImGui::GetWindowHeight() > ImGui::GetWindowWidth() ? ImGui::GetWindowWidth() : ImGui::GetWindowHeight(); - if (devHandle == 0) devHandle = HALSIM_GetSimDeviceHandle("Mechanism2D"); + if (devHandle == 0) { + devHandle = HALSIM_GetSimDeviceHandle("Mechanism2D"); + } // Get the length - if (!lengthHandle) + if (!lengthHandle) { lengthHandle = HALSIM_GetSimValueHandle( devHandle, (bodyConfig.name + "/length").c_str()); - if (lengthHandle) length = lengthHandle.Get(); + } + if (lengthHandle) { + length = lengthHandle.Get(); + } if (length <= 0) { length = bodyConfig.length; } // Get the angle - if (!angleHandle) + if (!angleHandle) { angleHandle = HALSIM_GetSimValueHandle( devHandle, (bodyConfig.name + "/angle").c_str()); - if (angleHandle) angle = angleHandle.Get(); + } + if (angleHandle) { + angle = angleHandle.Get(); + } // Calculate the next angle to go to float angleToGoTo = angle + bodyConfig.angle + previousAngle; // Draw the first line and get the ending coordinates diff --git a/simulation/halsim_gui/src/main/native/cpp/PCMSimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/PCMSimGui.cpp index 9176f13757..75c6f5bf90 100644 --- a/simulation/halsim_gui/src/main/native/cpp/PCMSimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/PCMSimGui.cpp @@ -152,7 +152,9 @@ void PCMSimModel::Update() { void PCMSimModel::ForEachSolenoid( wpi::function_ref func) { - if (m_solenoidInitCount == 0) return; + if (m_solenoidInitCount == 0) { + return; + } int32_t numSolenoids = m_solenoids.size(); for (int32_t i = 0; i < numSolenoids; ++i) { if (auto model = m_solenoids[i].get()) { @@ -191,8 +193,9 @@ static bool PCMsAnyInitialized() { static const int32_t num = HAL_GetNumPCMModules(); for (int32_t i = 0; i < num; ++i) { if (HALSIM_GetPCMCompressorInitialized(i) || - HALSIM_GetPCMAnySolenoidInitialized(i)) + HALSIM_GetPCMAnySolenoidInitialized(i)) { return true; + } } return false; } @@ -207,8 +210,9 @@ void PCMSimGui::Initialize() { bool any = false; static_cast(model)->ForEachPCM( [&](glass::PCMModel& pcm, int) { - if (static_cast(&pcm)->GetNumSolenoids() > 0) + if (static_cast(&pcm)->GetNumSolenoids() > 0) { any = true; + } }); return any; }, diff --git a/simulation/halsim_gui/src/main/native/cpp/PDPSimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/PDPSimGui.cpp index c032e14ed1..d1ce8bce5c 100644 --- a/simulation/halsim_gui/src/main/native/cpp/PDPSimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/PDPSimGui.cpp @@ -30,8 +30,9 @@ class PDPSimModel : public glass::PDPModel { : m_index{index}, m_temp{index}, m_voltage{index} { const int numChannels = HAL_GetNumPDPChannels(); m_currents.reserve(numChannels); - for (int i = 0; i < numChannels; ++i) + for (int i = 0; i < numChannels; ++i) { m_currents.emplace_back(std::make_unique(index, i)); + } } void Update() override {} @@ -104,7 +105,9 @@ void PDPsSimModel::ForEachPDP( static bool PDPsAnyInitialized() { static const int32_t num = HAL_GetNumPDPModules(); for (int32_t i = 0; i < num; ++i) { - if (HALSIM_GetPDPInitialized(i)) return true; + if (HALSIM_GetPDPInitialized(i)) { + return true; + } } return false; } diff --git a/simulation/halsim_gui/src/main/native/cpp/PWMSimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/PWMSimGui.cpp index 9518e6b863..3cb5e1a4ee 100644 --- a/simulation/halsim_gui/src/main/native/cpp/PWMSimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/PWMSimGui.cpp @@ -77,8 +77,9 @@ void PWMsSimModel::Update() { for (int32_t i = 0; i < numLED; ++i) { if (HALSIM_GetAddressableLEDInitialized(i)) { int32_t channel = HALSIM_GetAddressableLEDOutputPort(i); - if (channel >= 0 && channel < numPWM && m_sources[channel]) + if (channel >= 0 && channel < numPWM && m_sources[channel]) { m_sources[channel]->SetAddressableLED(i); + } } } } @@ -96,7 +97,9 @@ void PWMsSimModel::ForEachPWM( static bool PWMsAnyInitialized() { static const int32_t num = HAL_GetNumPWMChannels(); for (int32_t i = 0; i < num; ++i) { - if (HALSIM_GetPWMInitialized(i)) return true; + if (HALSIM_GetPWMInitialized(i)) { + return true; + } } return false; } diff --git a/simulation/halsim_gui/src/main/native/cpp/RelaySimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/RelaySimGui.cpp index 47d83a802c..3815617588 100644 --- a/simulation/halsim_gui/src/main/native/cpp/RelaySimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/RelaySimGui.cpp @@ -96,8 +96,9 @@ static bool RelayAnyInitialized() { static const int32_t num = HAL_GetNumRelayHeaders(); for (int32_t i = 0; i < num; ++i) { if (HALSIM_GetRelayInitializedForward(i) || - HALSIM_GetRelayInitializedReverse(i)) + HALSIM_GetRelayInitializedReverse(i)) { return true; + } } return false; } diff --git a/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp b/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp index c193680bd3..778a7ab9ab 100644 --- a/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp @@ -25,7 +25,9 @@ class SimValueSource : public glass::DataSource { m_callback{HALSIM_RegisterSimValueChangedCallback( handle, this, CallbackFunc, true)} {} ~SimValueSource() { - if (m_callback != 0) HALSIM_CancelSimValueChangedCallback(m_callback); + if (m_callback != 0) { + HALSIM_CancelSimValueChangedCallback(m_callback); + } } private: @@ -136,7 +138,9 @@ static void DisplaySimDevice(const char* name, void* data, HAL_SimDeviceHandle handle) { // only show "Foo" portion of "Accel:Foo" auto [type, id] = wpi::StringRef{name}.split(':'); - if (id.empty()) id = type; + if (id.empty()) { + id = type; + } if (glass::BeginDevice(id.data())) { HALSIM_EnumerateSimValues(handle, data, DisplaySimValue); glass::EndDevice(); diff --git a/simulation/halsim_gui/src/main/native/cpp/TimingGui.cpp b/simulation/halsim_gui/src/main/native/cpp/TimingGui.cpp index c65ec9639d..1928063d8a 100644 --- a/simulation/halsim_gui/src/main/native/cpp/TimingGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/TimingGui.cpp @@ -32,16 +32,21 @@ static void DisplayTiming() { int32_t status = 0; uint64_t curTime = HAL_GetFPGATime(&status); - if (ImGui::Button("Run")) HALSIM_ResumeTiming(); + if (ImGui::Button("Run")) { + HALSIM_ResumeTiming(); + } ImGui::SameLine(); - if (ImGui::Button("Pause")) HALSIM_PauseTiming(); + if (ImGui::Button("Pause")) { + HALSIM_PauseTiming(); + } ImGui::SameLine(); ImGui::PushButtonRepeat(true); if (ImGui::Button("Step")) { HALSIM_PauseTiming(); uint64_t nextTimeout = HALSIM_GetNextNotifierTimeout(); - if (nextTimeout != UINT64_MAX) + if (nextTimeout != UINT64_MAX) { HALSIM_StepTimingAsync(nextTimeout - curTime); + } } ImGui::PopButtonRepeat(); ImGui::PushItemWidth(ImGui::GetFontSize() * 4); @@ -54,11 +59,14 @@ static void DisplayTiming() { notifiers.resize(num); HALSIM_GetNotifierInfo(notifiers.data(), notifiers.size()); } - if (num > 0) ImGui::Separator(); + if (num > 0) { + ImGui::Separator(); + } ImGui::PushItemWidth(ImGui::GetFontSize() * 4); - for (int32_t i = 0; i < num; ++i) + for (int32_t i = 0; i < num; ++i) { ImGui::LabelText(notifiers[i].name, "%.3f", notifiers[i].timeout / 1000000.0); + } ImGui::PopItemWidth(); } diff --git a/simulation/halsim_gui/src/main/native/cpp/main.cpp b/simulation/halsim_gui/src/main/native/cpp/main.cpp index 640595eb49..26fb2554a9 100644 --- a/simulation/halsim_gui/src/main/native/cpp/main.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/main.cpp @@ -99,7 +99,9 @@ __declspec(dllexport) } }); - if (!gui::Initialize("Robot Simulation", 1280, 720)) return 0; + if (!gui::Initialize("Robot Simulation", 1280, 720)) { + return 0; + } HAL_RegisterExtensionListener( nullptr, [](void*, const char* name, void* data) { if (wpi::StringRef{name} == "ds_socket") { diff --git a/simulation/halsim_gui/src/main/native/include/HALDataSource.h b/simulation/halsim_gui/src/main/native/include/HALDataSource.h index e2f9a2caba..c04f3589b3 100644 --- a/simulation/halsim_gui/src/main/native/include/HALDataSource.h +++ b/simulation/halsim_gui/src/main/native/include/HALDataSource.h @@ -17,7 +17,8 @@ } \ \ ~cbname##Source() { \ - if (m_callback != 0) HALSIM_Cancel##cbname##Callback(m_callback); \ + if (m_callback != 0) \ + HALSIM_Cancel##cbname##Callback(m_callback); \ } \ \ private: \ diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp index 340b27c5c6..e9576aeea8 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp @@ -16,7 +16,9 @@ void HALSimWSHalProvider::OnNetworkConnected( RegisterCallbacks(); } -void HALSimWSHalProvider::OnNetworkDisconnected() { CancelCallbacks(); } +void HALSimWSHalProvider::OnNetworkDisconnected() { + CancelCallbacks(); +} void HALSimWSHalProvider::ProcessHalCallback(const wpi::json& payload) { auto ws = m_ws.lock(); diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Analog.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Analog.cpp index bca4e48da2..be19a1dfc7 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Analog.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Analog.cpp @@ -42,7 +42,9 @@ void HALSimWSProviderAnalogIn::Initialize(WSRegisterFunc webRegisterFunc) { webRegisterFunc); } -HALSimWSProviderAnalogIn::~HALSimWSProviderAnalogIn() { DoCancelCallbacks(); } +HALSimWSProviderAnalogIn::~HALSimWSProviderAnalogIn() { + DoCancelCallbacks(); +} void HALSimWSProviderAnalogIn::RegisterCallbacks() { m_initCbKey = REGISTER_AIN(Initialized, "match_time", double, double); } -void HALSimWSProviderDriverStation::CancelCallbacks() { DoCancelCallbacks(); } +void HALSimWSProviderDriverStation::CancelCallbacks() { + DoCancelCallbacks(); +} void HALSimWSProviderDriverStation::DoCancelCallbacks() { HALSIM_CancelDriverStationEnabledCallback(m_enabledCbKey); @@ -118,7 +120,9 @@ void HALSimWSProviderDriverStation::DoCancelCallbacks() { void HALSimWSProviderDriverStation::OnNetValueChanged(const wpi::json& json) { // ignore if DS connected - if (gDSSocketConnected && *gDSSocketConnected) return; + if (gDSSocketConnected && *gDSSocketConnected) { + return; + } wpi::json::const_iterator it; if ((it = json.find(">enabled")) != json.end()) { diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Encoder.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Encoder.cpp index b1b0269d60..73f05dc462 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Encoder.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Encoder.cpp @@ -23,7 +23,9 @@ void HALSimWSProviderEncoder::Initialize(WSRegisterFunc webRegisterFunc) { webRegisterFunc); } -HALSimWSProviderEncoder::~HALSimWSProviderEncoder() { DoCancelCallbacks(); } +HALSimWSProviderEncoder::~HALSimWSProviderEncoder() { + DoCancelCallbacks(); +} void HALSimWSProviderEncoder::RegisterCallbacks() { // Special case for initialization since we will need to send @@ -72,7 +74,9 @@ void HALSimWSProviderEncoder::RegisterCallbacks() { m_samplesCbKey = REGISTER(SamplesToAverage, "axes")) != json.end()) { diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_PWM.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_PWM.cpp index f2c0b1a327..5792ef507e 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_PWM.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_PWM.cpp @@ -22,7 +22,9 @@ void HALSimWSProviderPWM::Initialize(WSRegisterFunc webRegisterFunc) { webRegisterFunc); } -HALSimWSProviderPWM::~HALSimWSProviderPWM() { DoCancelCallbacks(); } +HALSimWSProviderPWM::~HALSimWSProviderPWM() { + DoCancelCallbacks(); +} void HALSimWSProviderPWM::RegisterCallbacks() { m_initCbKey = REGISTER(Initialized, "("RoboRIO", webRegisterFunc); } -HALSimWSProviderRoboRIO::~HALSimWSProviderRoboRIO() { DoCancelCallbacks(); } +HALSimWSProviderRoboRIO::~HALSimWSProviderRoboRIO() { + DoCancelCallbacks(); +} void HALSimWSProviderRoboRIO::RegisterCallbacks() { m_fpgaCbKey = REGISTER(FPGAButton, ">fpga_button", bool, boolean); @@ -44,7 +46,9 @@ void HALSimWSProviderRoboRIO::RegisterCallbacks() { m_3v3FaultsCbKey = REGISTER(UserFaults3V3, ">3v3_faults", int32_t, int); } -void HALSimWSProviderRoboRIO::CancelCallbacks() { DoCancelCallbacks(); } +void HALSimWSProviderRoboRIO::CancelCallbacks() { + DoCancelCallbacks(); +} void HALSimWSProviderRoboRIO::DoCancelCallbacks() { HALSIM_CancelRoboRioFPGAButtonCallback(m_fpgaCbKey); diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp index 051680fb6f..930a78602e 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp @@ -11,7 +11,9 @@ namespace wpilibws { -HALSimWSProviderSimDevice::~HALSimWSProviderSimDevice() { CancelCallbacks(); } +HALSimWSProviderSimDevice::~HALSimWSProviderSimDevice() { + CancelCallbacks(); +} void HALSimWSProviderSimDevice::OnNetworkConnected( std::shared_ptr ws) { @@ -77,16 +79,18 @@ void HALSimWSProviderSimDevice::OnNetValueChanged(const wpi::json& json) { auto optionIt = std::find_if(options.begin(), options.end(), [&](const std::string& v) { return v == str; }); - if (optionIt != options.end()) + if (optionIt != options.end()) { value.data.v_enum = optionIt - options.begin(); + } } else if (it->is_number()) { auto& values = vd->second->optionValues; double num = it.value(); auto valueIt = std::find_if( values.begin(), values.end(), [&](double v) { return std::fabs(v - num) < 1e-4; }); - if (valueIt != values.end()) + if (valueIt != values.end()) { value.data.v_enum = valueIt - values.begin(); + } } value.data.v_enum = it.value(); break; @@ -143,8 +147,9 @@ void HALSimWSProviderSimDevice::OnValueCreated(const char* name, const char** options = HALSIM_GetSimValueEnumOptions(handle, &numOptions); data->options.reserve(numOptions); - for (int32_t i = 0; i < numOptions; ++i) + for (int32_t i = 0; i < numOptions; ++i) { data->options.emplace_back(options[i]); + } const double* values = HALSIM_GetSimValueEnumDoubleValues(handle, &numOptions); @@ -185,10 +190,11 @@ void HALSimWSProviderSimDevice::OnValueChanged(SimDeviceValueData* valueData, break; case HAL_ENUM: { int v = value->data.v_enum; - if (v >= 0 && v < static_cast(valueData->optionValues.size())) + if (v >= 0 && v < static_cast(valueData->optionValues.size())) { ProcessHalCallback({{valueData->key, valueData->optionValues[v]}}); - else if (v >= 0 && v < static_cast(valueData->options.size())) + } else if (v >= 0 && v < static_cast(valueData->options.size())) { ProcessHalCallback({{valueData->key, valueData->options[v]}}); + } break; } case HAL_INT: @@ -212,7 +218,9 @@ void HALSimWSProviderSimDevice::ProcessHalCallback(const wpi::json& payload) { } } -HALSimWSProviderSimDevices::~HALSimWSProviderSimDevices() { CancelCallbacks(); } +HALSimWSProviderSimDevices::~HALSimWSProviderSimDevices() { + CancelCallbacks(); +} void HALSimWSProviderSimDevices::DeviceCreatedCallback( const char* name, HAL_SimDeviceHandle handle) { @@ -265,6 +273,8 @@ void HALSimWSProviderSimDevices::OnNetworkConnected( m_ws = hws; } -void HALSimWSProviderSimDevices::OnNetworkDisconnected() { m_ws = nullptr; } +void HALSimWSProviderSimDevices::OnNetworkDisconnected() { + m_ws = nullptr; +} } // namespace wpilibws diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_dPWM.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_dPWM.cpp index bf0e5e4403..af8a8e4aa3 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_dPWM.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_dPWM.cpp @@ -33,7 +33,9 @@ void HALSimWSProviderDigitalPWM::RegisterCallbacks() { m_pinCbKey = REGISTER(Pin, "connection.connect([this, srv = m_server.get()] { auto tcp = srv->Accept(); - if (!tcp) return; + if (!tcp) { + return; + } tcp->SetNoDelay(true); diff --git a/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp b/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp index 51d13480b5..03469f3360 100644 --- a/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp +++ b/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp @@ -154,6 +154,8 @@ void WebServerClientTest::SendMessage(const wpi::json& msg) { }); } -const wpi::json& WebServerClientTest::GetLastMessage() { return m_json; } +const wpi::json& WebServerClientTest::GetLastMessage() { + return m_json; +} } // namespace wpilibws diff --git a/wpigui/src/main/native/cpp/wpigui.cpp b/wpigui/src/main/native/cpp/wpigui.cpp index d58c8e3a5d..fae573fa09 100644 --- a/wpigui/src/main/native/cpp/wpigui.cpp +++ b/wpigui/src/main/native/cpp/wpigui.cpp @@ -53,7 +53,9 @@ static void WindowPosCallback(GLFWwindow* window, int xpos, int ypos) { static void* IniReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { - if (std::strcmp(name, "GLOBAL") != 0) return nullptr; + if (std::strcmp(name, "GLOBAL") != 0) { + return nullptr; + } return static_cast(gContext); } @@ -61,7 +63,9 @@ static void IniReadLine(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* lineStr) { auto impl = static_cast(entry); const char* value = std::strchr(lineStr, '='); - if (!value) return; + if (!value) { + return; + } ++value; int num = std::atoi(value); if (std::strncmp(lineStr, "width=", 6) == 0) { @@ -85,7 +89,9 @@ static void IniReadLine(ImGuiContext* ctx, ImGuiSettingsHandler* handler, static void IniWriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf) { - if (!gContext) return; + if (!gContext) { + return; + } out_buf->appendf( "[MainWindow][GLOBAL]\nwidth=%d\nheight=%d\nmaximized=%d\n" "xpos=%d\nypos=%d\nuserScale=%d\nstyle=%d\n\n", @@ -118,7 +124,9 @@ bool gui::Initialize(const char* title, int width, int height) { glfwSetErrorCallback(ErrorCallback); glfwInitHint(GLFW_JOYSTICK_HAT_BUTTONS, GLFW_FALSE); PlatformGlfwInitHints(); - if (!glfwInit()) return false; + if (!glfwInit()) { + return false; + } PlatformGlfwWindowHints(); @@ -140,7 +148,9 @@ bool gui::Initialize(const char* title, int width, int height) { io.IniFilename = gContext->iniPath.c_str(); for (auto&& initialize : gContext->initializers) { - if (initialize) initialize(); + if (initialize) { + initialize(); + } } // Load INI file @@ -170,25 +180,32 @@ bool gui::Initialize(const char* title, int width, int height) { } } } - if (gContext->xPos != -1 && gContext->yPos != -1) + if (gContext->xPos != -1 && gContext->yPos != -1) { glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + } // Create window with graphics context gContext->window = glfwCreateWindow(gContext->width, gContext->height, gContext->title.c_str(), nullptr, nullptr); - if (!gContext->window) return false; + if (!gContext->window) { + return false; + } if (!gContext->loadedWidthHeight) { - if (windowScale == 1.0) + if (windowScale == 1.0) { glfwGetWindowContentScale(gContext->window, &windowScale, nullptr); + } // force user scale if window scale is smaller - if (windowScale <= 0.5) + if (windowScale <= 0.5) { gContext->userScale = 0; - else if (windowScale <= 0.75) + } else if (windowScale <= 0.75) { gContext->userScale = 1; + } if (windowScale != 1.0) { - for (auto&& func : gContext->windowScalers) func(windowScale); + for (auto&& func : gContext->windowScalers) { + func(windowScale); + } } } @@ -209,7 +226,9 @@ bool gui::Initialize(const char* title, int width, int height) { if (!gContext->icons.empty()) { glfwSetWindowIcon(gContext->window, gContext->icons.size(), gContext->icons.data()); - for (auto&& icon : gContext->icons) stbi_image_free(icon.pixels); + for (auto&& icon : gContext->icons) { + stbi_image_free(icon.pixels); + } gContext->icons.clear(); } @@ -232,7 +251,9 @@ bool gui::Initialize(const char* title, int width, int height) { } } - if (!PlatformInitRenderer()) return false; + if (!PlatformInitRenderer()) { + return false; + } return true; } @@ -273,12 +294,16 @@ void gui::CommonRenderFrame() { for (size_t i = 0; i < gContext->earlyExecutors.size(); ++i) { auto& execute = gContext->earlyExecutors[i]; - if (execute) execute(); + if (execute) { + execute(); + } } for (size_t i = 0; i < gContext->lateExecutors.size(); ++i) { auto& execute = gContext->lateExecutors[i]; - if (execute) execute(); + if (execute) { + execute(); + } } // Rendering @@ -286,35 +311,48 @@ void gui::CommonRenderFrame() { } void gui::Exit() { - if (!gContext) return; + if (!gContext) { + return; + } gContext->exit = true; } void gui::AddInit(std::function initialize) { - if (initialize) gContext->initializers.emplace_back(std::move(initialize)); + if (initialize) { + gContext->initializers.emplace_back(std::move(initialize)); + } } void gui::AddWindowScaler(std::function windowScaler) { - if (windowScaler) + if (windowScaler) { gContext->windowScalers.emplace_back(std::move(windowScaler)); + } } void gui::AddEarlyExecute(std::function execute) { - if (execute) gContext->earlyExecutors.emplace_back(std::move(execute)); + if (execute) { + gContext->earlyExecutors.emplace_back(std::move(execute)); + } } void gui::AddLateExecute(std::function execute) { - if (execute) gContext->lateExecutors.emplace_back(std::move(execute)); + if (execute) { + gContext->lateExecutors.emplace_back(std::move(execute)); + } } -GLFWwindow* gui::GetSystemWindow() { return gContext->window; } +GLFWwindow* gui::GetSystemWindow() { + return gContext->window; +} bool gui::AddIcon(const unsigned char* data, int len) { // Load from memory GLFWimage image; image.pixels = stbi_load_from_memory(data, len, &image.width, &image.height, nullptr, 4); - if (!data) return false; + if (!data) { + return false; + } gContext->icons.emplace_back(std::move(image)); return true; } @@ -323,7 +361,9 @@ int gui::AddFont( const char* name, std::function makeFont) { - if (makeFont) gContext->makeFonts.emplace_back(name, std::move(makeFont)); + if (makeFont) { + gContext->makeFonts.emplace_back(name, std::move(makeFont)); + } return gContext->makeFonts.size() - 1; } @@ -346,13 +386,16 @@ void gui::SetStyle(Style style) { } } -void gui::SetClearColor(ImVec4 color) { gContext->clearColor = color; } +void gui::SetClearColor(ImVec4 color) { + gContext->clearColor = color; +} void gui::ConfigurePlatformSaveFile(const std::string& name) { gContext->iniPath = name; #if defined(_MSC_VER) const char* env = std::getenv("APPDATA"); - if (env) gContext->iniPath = env + std::string("/" + name); + if (env) + gContext->iniPath = env + std::string("/" + name); #elif defined(__APPLE__) const char* env = std::getenv("HOME"); if (env) @@ -360,10 +403,11 @@ void gui::ConfigurePlatformSaveFile(const std::string& name) { #else const char* xdg = std::getenv("XDG_CONFIG_HOME"); const char* env = std::getenv("HOME"); - if (xdg) + if (xdg) { gContext->iniPath = xdg + std::string("/" + name); - else if (env) + } else if (env) { gContext->iniPath = env + std::string("/.config/" + name); + } #endif } @@ -372,14 +416,17 @@ void gui::EmitViewMenu() { if (ImGui::BeginMenu("Style")) { bool selected; selected = gContext->style == kStyleClassic; - if (ImGui::MenuItem("Classic", nullptr, &selected, true)) + if (ImGui::MenuItem("Classic", nullptr, &selected, true)) { SetStyle(kStyleClassic); + } selected = gContext->style == kStyleDark; - if (ImGui::MenuItem("Dark", nullptr, &selected, true)) + if (ImGui::MenuItem("Dark", nullptr, &selected, true)) { SetStyle(kStyleDark); + } selected = gContext->style == kStyleLight; - if (ImGui::MenuItem("Light", nullptr, &selected, true)) + if (ImGui::MenuItem("Light", nullptr, &selected, true)) { SetStyle(kStyleLight); + } ImGui::EndMenu(); } @@ -391,8 +438,9 @@ void gui::EmitViewMenu() { bool enabled = (gContext->fontScale - gContext->userScale + i) >= 0 && (gContext->fontScale - gContext->userScale + i) < Font::kScaledLevels; - if (ImGui::MenuItem(label, nullptr, &selected, enabled)) + if (ImGui::MenuItem(label, nullptr, &selected, enabled)) { gContext->userScale = i; + } } ImGui::EndMenu(); } @@ -407,12 +455,15 @@ bool gui::UpdateTextureFromImage(ImTextureID* texture, int width, int height, int height2 = 0; unsigned char* imgData = stbi_load_from_memory(data, len, &width2, &height2, nullptr, 4); - if (!data) return false; + if (!data) { + return false; + } - if (width2 == width && height2 == height) + if (width2 == width && height2 == height) { UpdateTexture(texture, kPixelRGBA, width2, height2, imgData); - else + } else { *texture = CreateTexture(kPixelRGBA, width2, height2, imgData); + } stbi_image_free(imgData); @@ -425,11 +476,17 @@ bool gui::CreateTextureFromFile(const char* filename, ImTextureID* out_texture, int width = 0; int height = 0; unsigned char* data = stbi_load(filename, &width, &height, nullptr, 4); - if (!data) return false; + if (!data) { + return false; + } *out_texture = CreateTexture(kPixelRGBA, width, height, data); - if (out_width) *out_width = width; - if (out_height) *out_height = height; + if (out_width) { + *out_width = width; + } + if (out_height) { + *out_height = height; + } stbi_image_free(data); @@ -444,11 +501,17 @@ bool gui::CreateTextureFromImage(const unsigned char* data, int len, int height = 0; unsigned char* imgData = stbi_load_from_memory(data, len, &width, &height, nullptr, 4); - if (!imgData) return false; + if (!imgData) { + return false; + } *out_texture = CreateTexture(kPixelRGBA, width, height, imgData); - if (out_width) *out_width = width; - if (out_height) *out_height = height; + if (out_width) { + *out_width = width; + } + if (out_height) { + *out_height = height; + } stbi_image_free(imgData); @@ -458,7 +521,9 @@ bool gui::CreateTextureFromImage(const unsigned char* data, int len, void gui::MaxFit(ImVec2* min, ImVec2* max, float width, float height) { float destWidth = max->x - min->x; float destHeight = max->y - min->y; - if (width == 0 || height == 0) return; + if (width == 0 || height == 0) { + return; + } if (destWidth * height > destHeight * width) { float outputWidth = width * destHeight / height; min->x += (destWidth - outputWidth) / 2; diff --git a/wpigui/src/main/native/directx11/wpigui_directx11.cpp b/wpigui/src/main/native/directx11/wpigui_directx11.cpp index 2a3fcb0029..26e153a17c 100644 --- a/wpigui/src/main/native/directx11/wpigui_directx11.cpp +++ b/wpigui/src/main/native/directx11/wpigui_directx11.cpp @@ -101,7 +101,9 @@ static void CleanupDeviceD3D() { namespace wpi { -void gui::PlatformCreateContext() { gPlatformContext = new PlatformContext; } +void gui::PlatformCreateContext() { + gPlatformContext = new PlatformContext; +} void gui::PlatformDestroyContext() { CleanupDeviceD3D(); @@ -173,7 +175,9 @@ static inline DXGI_FORMAT DXPixelFormat(PixelFormat format) { ImTextureID gui::CreateTexture(PixelFormat format, int width, int height, const unsigned char* data) { - if (!gPlatformValid) return nullptr; + if (!gPlatformValid) { + return nullptr; + } // Create texture D3D11_TEXTURE2D_DESC desc; @@ -212,7 +216,9 @@ ImTextureID gui::CreateTexture(PixelFormat format, int width, int height, void gui::UpdateTexture(ImTextureID texture, PixelFormat, int width, int height, const unsigned char* data) { - if (!texture) return; + if (!texture) { + return; + } D3D11_BOX box; box.front = 0; @@ -234,8 +240,11 @@ void gui::UpdateTexture(ImTextureID texture, PixelFormat, int width, int height, } void gui::DeleteTexture(ImTextureID texture) { - if (!gPlatformValid) return; - if (texture) static_cast(texture)->Release(); + if (!gPlatformValid) { + return; + } + if (texture) + static_cast(texture)->Release(); } } // namespace wpi diff --git a/wpigui/src/main/native/include/wpigui.h b/wpigui/src/main/native/include/wpigui.h index 853694b12a..2933631bfc 100644 --- a/wpigui/src/main/native/include/wpigui.h +++ b/wpigui/src/main/native/include/wpigui.h @@ -271,7 +271,9 @@ class Texture { Texture& operator=(const Texture&) = delete; Texture& operator=(Texture&& oth) { - if (m_texture) DeleteTexture(m_texture); + if (m_texture) { + DeleteTexture(m_texture); + } m_texture = oth.m_texture; oth.m_texture = 0; m_format = oth.m_format; @@ -281,7 +283,9 @@ class Texture { } ~Texture() { - if (m_texture) DeleteTexture(m_texture); + if (m_texture) { + DeleteTexture(m_texture); + } } /** @@ -351,8 +355,9 @@ class Texture { static Texture CreateFromFile(const char* filename) { Texture texture; if (!CreateTextureFromFile(filename, &texture.m_texture, &texture.m_width, - &texture.m_height)) + &texture.m_height)) { return {}; + } return texture; } @@ -367,8 +372,9 @@ class Texture { static Texture CreateFromImage(const unsigned char* data, int len) { Texture texture; if (!CreateTextureFromImage(data, len, &texture.m_texture, &texture.m_width, - &texture.m_height)) + &texture.m_height)) { return {}; + } return texture; } diff --git a/wpigui/src/main/native/opengl3/wpigui_opengl3.cpp b/wpigui/src/main/native/opengl3/wpigui_opengl3.cpp index 700be88e76..c85ad04b80 100644 --- a/wpigui/src/main/native/opengl3/wpigui_opengl3.cpp +++ b/wpigui/src/main/native/opengl3/wpigui_opengl3.cpp @@ -111,7 +111,9 @@ static inline GLenum GLPixelFormat(PixelFormat format) { ImTextureID gui::CreateTexture(PixelFormat format, int width, int height, const unsigned char* data) { - if (!gPlatformValid) return nullptr; + if (!gPlatformValid) { + return nullptr; + } // Create a OpenGL texture identifier GLuint texture; @@ -133,16 +135,22 @@ ImTextureID gui::CreateTexture(PixelFormat format, int width, int height, void gui::UpdateTexture(ImTextureID texture, PixelFormat format, int width, int height, const unsigned char* data) { GLuint glTexture = static_cast(reinterpret_cast(texture)); - if (glTexture == 0) return; + if (glTexture == 0) { + return; + } glBindTexture(GL_TEXTURE_2D, glTexture); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GLPixelFormat(format), GL_UNSIGNED_BYTE, data); } void gui::DeleteTexture(ImTextureID texture) { - if (!gPlatformValid) return; + if (!gPlatformValid) { + return; + } GLuint glTexture = static_cast(reinterpret_cast(texture)); - if (glTexture != 0) glDeleteTextures(1, &glTexture); + if (glTexture != 0) { + glDeleteTextures(1, &glTexture); + } } } // namespace wpi diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp index a96b93c264..8d2d6d2bd4 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp @@ -17,7 +17,9 @@ using namespace frc2; -Command::~Command() { CommandScheduler::GetInstance().Cancel(this); } +Command::~Command() { + CommandScheduler::GetInstance().Cancel(this); +} Command::Command(const Command& rhs) : ErrorBase(rhs) {} @@ -83,13 +85,17 @@ PerpetualCommand Command::Perpetually() && { return PerpetualCommand(std::move(*this).TransferOwnership()); } -ProxyScheduleCommand Command::AsProxy() { return ProxyScheduleCommand(this); } +ProxyScheduleCommand Command::AsProxy() { + return ProxyScheduleCommand(this); +} void Command::Schedule(bool interruptible) { CommandScheduler::GetInstance().Schedule(interruptible, this); } -void Command::Cancel() { CommandScheduler::GetInstance().Cancel(this); } +void Command::Cancel() { + CommandScheduler::GetInstance().Cancel(this); +} bool Command::IsScheduled() const { return CommandScheduler::GetInstance().IsScheduled(this); @@ -103,11 +109,17 @@ bool Command::HasRequirement(Subsystem* requirement) const { return hasRequirement; } -std::string Command::GetName() const { return GetTypeName(*this); } +std::string Command::GetName() const { + return GetTypeName(*this); +} -bool Command::IsGrouped() const { return m_isGrouped; } +bool Command::IsGrouped() const { + return m_isGrouped; +} -void Command::SetGrouped(bool grouped) { m_isGrouped = grouped; } +void Command::SetGrouped(bool grouped) { + m_isGrouped = grouped; +} namespace frc2 { bool RequirementsDisjoint(Command* first, Command* second) { diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp index a47cd8e39c..f13c53fbe9 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp @@ -99,7 +99,9 @@ void CommandScheduler::AddButton(wpi::unique_function button) { m_impl->buttons.emplace_back(std::move(button)); } -void CommandScheduler::ClearButtons() { m_impl->buttons.clear(); } +void CommandScheduler::ClearButtons() { + m_impl->buttons.clear(); +} void CommandScheduler::Schedule(bool interruptible, Command* command) { if (m_impl->inRunLoop) { @@ -152,7 +154,9 @@ void CommandScheduler::Schedule(bool interruptible, Command* command) { } } -void CommandScheduler::Schedule(Command* command) { Schedule(true, command); } +void CommandScheduler::Schedule(Command* command) { + Schedule(true, command); +} void CommandScheduler::Schedule(bool interruptible, wpi::ArrayRef commands) { @@ -314,7 +318,9 @@ void CommandScheduler::Cancel(Command* command) { } auto find = m_impl->scheduledCommands.find(command); - if (find == m_impl->scheduledCommands.end()) return; + if (find == m_impl->scheduledCommands.end()) { + return; + } command->End(true); for (auto&& action : m_impl->interruptActions) { action(*command); @@ -390,9 +396,13 @@ Command* CommandScheduler::Requiring(const Subsystem* subsystem) const { } } -void CommandScheduler::Disable() { m_impl->disabled = true; } +void CommandScheduler::Disable() { + m_impl->disabled = true; +} -void CommandScheduler::Enable() { m_impl->disabled = false; } +void CommandScheduler::Enable() { + m_impl->disabled = false; +} void CommandScheduler::OnCommandInitialize(Action action) { m_impl->initActions.emplace_back(std::move(action)); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandState.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandState.cpp index d67f2ab90e..979b1e6f62 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandState.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandState.cpp @@ -16,7 +16,9 @@ CommandState::CommandState(bool interruptible) void CommandState::StartTiming() { m_startTime = frc::Timer::GetFPGATimestamp(); } -void CommandState::StartRunning() { m_startTime = -1; } +void CommandState::StartRunning() { + m_startTime = -1; +} double CommandState::TimeSinceInitialized() const { return m_startTime != -1 ? frc::Timer::GetFPGATimestamp() - m_startTime : -1; } diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp index ccc0300d79..30ef410741 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp @@ -36,7 +36,9 @@ void ConditionalCommand::Initialize() { m_selectedCommand->Initialize(); } -void ConditionalCommand::Execute() { m_selectedCommand->Execute(); } +void ConditionalCommand::Execute() { + m_selectedCommand->Execute(); +} void ConditionalCommand::End(bool interrupted) { m_selectedCommand->End(interrupted); @@ -46,4 +48,6 @@ bool ConditionalCommand::IsFinished() { return m_selectedCommand->IsFinished(); } -bool ConditionalCommand::RunsWhenDisabled() const { return m_runsWhenDisabled; } +bool ConditionalCommand::RunsWhenDisabled() const { + return m_runsWhenDisabled; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/FunctionalCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/FunctionalCommand.cpp index 23d69e5a26..ab0a3bbb28 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/FunctionalCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/FunctionalCommand.cpp @@ -29,10 +29,18 @@ FunctionalCommand::FunctionalCommand(std::function onInit, AddRequirements(requirements); } -void FunctionalCommand::Initialize() { m_onInit(); } +void FunctionalCommand::Initialize() { + m_onInit(); +} -void FunctionalCommand::Execute() { m_onExecute(); } +void FunctionalCommand::Execute() { + m_onExecute(); +} -void FunctionalCommand::End(bool interrupted) { m_onEnd(interrupted); } +void FunctionalCommand::End(bool interrupted) { + m_onEnd(interrupted); +} -bool FunctionalCommand::IsFinished() { return m_isFinished(); } +bool FunctionalCommand::IsFinished() { + return m_isFinished(); +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/InstantCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/InstantCommand.cpp index d9ad48fd87..b7a6ae7d86 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/InstantCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/InstantCommand.cpp @@ -20,6 +20,10 @@ InstantCommand::InstantCommand(std::function toRun, InstantCommand::InstantCommand() : m_toRun{[] {}} {} -void InstantCommand::Initialize() { m_toRun(); } +void InstantCommand::Initialize() { + m_toRun(); +} -bool InstantCommand::IsFinished() { return true; } +bool InstantCommand::IsFinished() { + return true; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp index 0432835176..1af0bf8c6b 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp @@ -335,7 +335,9 @@ void MecanumControllerCommand::Execute() { } } -void MecanumControllerCommand::End(bool interrupted) { m_timer.Stop(); } +void MecanumControllerCommand::End(bool interrupted) { + m_timer.Stop(); +} bool MecanumControllerCommand::IsFinished() { return m_timer.HasElapsed(m_trajectory.TotalTime()); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/NotifierCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/NotifierCommand.cpp index 89a2f10860..6928a35094 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/NotifierCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/NotifierCommand.cpp @@ -32,6 +32,10 @@ NotifierCommand::NotifierCommand(const NotifierCommand& other) m_notifier(frc::Notifier(other.m_toRun)), m_period(other.m_period) {} -void NotifierCommand::Initialize() { m_notifier.StartPeriodic(m_period); } +void NotifierCommand::Initialize() { + m_notifier.StartPeriodic(m_period); +} -void NotifierCommand::End(bool interrupted) { m_notifier.Stop(); } +void NotifierCommand::End(bool interrupted) { + m_notifier.Stop(); +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDCommand.cpp index 0029f02eff..10cb99cfd4 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDCommand.cpp @@ -46,12 +46,18 @@ PIDCommand::PIDCommand(PIDController controller, controller, measurementSource, [setpoint] { return setpoint; }, useOutput, requirements) {} -void PIDCommand::Initialize() { m_controller.Reset(); } +void PIDCommand::Initialize() { + m_controller.Reset(); +} void PIDCommand::Execute() { m_useOutput(m_controller.Calculate(m_measurement(), m_setpoint())); } -void PIDCommand::End(bool interrupted) { m_useOutput(0); } +void PIDCommand::End(bool interrupted) { + m_useOutput(0); +} -PIDController& PIDCommand::GetController() { return m_controller; } +PIDController& PIDCommand::GetController() { + return m_controller; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDSubsystem.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDSubsystem.cpp index 4b67827d22..c869776dc7 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDSubsystem.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/PIDSubsystem.cpp @@ -18,9 +18,13 @@ void PIDSubsystem::Periodic() { } } -void PIDSubsystem::SetSetpoint(double setpoint) { m_setpoint = setpoint; } +void PIDSubsystem::SetSetpoint(double setpoint) { + m_setpoint = setpoint; +} -double PIDSubsystem::GetSetpoint() const { return m_setpoint; } +double PIDSubsystem::GetSetpoint() const { + return m_setpoint; +} void PIDSubsystem::Enable() { m_controller.Reset(); @@ -32,6 +36,10 @@ void PIDSubsystem::Disable() { m_enabled = false; } -bool PIDSubsystem::IsEnabled() { return m_enabled; } +bool PIDSubsystem::IsEnabled() { + return m_enabled; +} -PIDController& PIDSubsystem::GetController() { return m_controller; } +PIDController& PIDSubsystem::GetController() { + return m_controller; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp index 57325e84e4..c243ed5429 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp @@ -21,7 +21,9 @@ void ParallelCommandGroup::Initialize() { void ParallelCommandGroup::Execute() { for (auto& commandRunning : m_commands) { - if (!commandRunning.second) continue; + if (!commandRunning.second) { + continue; + } commandRunning.first->Execute(); if (commandRunning.first->IsFinished()) { commandRunning.first->End(false); @@ -43,7 +45,9 @@ void ParallelCommandGroup::End(bool interrupted) { bool ParallelCommandGroup::IsFinished() { for (auto& command : m_commands) { - if (command.second) return false; + if (command.second) { + return false; + } } return true; } @@ -55,7 +59,9 @@ bool ParallelCommandGroup::RunsWhenDisabled() const { void ParallelCommandGroup::AddCommands( std::vector>&& commands) { for (auto&& command : commands) { - if (!RequireUngrouped(*command)) return; + if (!RequireUngrouped(*command)) { + return; + } } if (isRunning) { diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp index 7c22aee973..d544a6b905 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp @@ -23,7 +23,9 @@ void ParallelDeadlineGroup::Initialize() { void ParallelDeadlineGroup::Execute() { for (auto& commandRunning : m_commands) { - if (!commandRunning.second) continue; + if (!commandRunning.second) { + continue; + } commandRunning.first->Execute(); if (commandRunning.first->IsFinished()) { commandRunning.first->End(false); @@ -43,7 +45,9 @@ void ParallelDeadlineGroup::End(bool interrupted) { } } -bool ParallelDeadlineGroup::IsFinished() { return m_finished; } +bool ParallelDeadlineGroup::IsFinished() { + return m_finished; +} bool ParallelDeadlineGroup::RunsWhenDisabled() const { return m_runWhenDisabled; diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp index 7896895430..3bee59845c 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp @@ -35,9 +35,13 @@ void ParallelRaceGroup::End(bool interrupted) { isRunning = false; } -bool ParallelRaceGroup::IsFinished() { return m_finished; } +bool ParallelRaceGroup::IsFinished() { + return m_finished; +} -bool ParallelRaceGroup::RunsWhenDisabled() const { return m_runWhenDisabled; } +bool ParallelRaceGroup::RunsWhenDisabled() const { + return m_runWhenDisabled; +} void ParallelRaceGroup::AddCommands( std::vector>&& commands) { diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/PerpetualCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/PerpetualCommand.cpp index 9c77fa6a0d..d0307d34ca 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/PerpetualCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/PerpetualCommand.cpp @@ -15,8 +15,14 @@ PerpetualCommand::PerpetualCommand(std::unique_ptr&& command) { AddRequirements(m_command->GetRequirements()); } -void PerpetualCommand::Initialize() { m_command->Initialize(); } +void PerpetualCommand::Initialize() { + m_command->Initialize(); +} -void PerpetualCommand::Execute() { m_command->Execute(); } +void PerpetualCommand::Execute() { + m_command->Execute(); +} -void PerpetualCommand::End(bool interrupted) { m_command->End(interrupted); } +void PerpetualCommand::End(bool interrupted) { + m_command->End(interrupted); +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp index 3a0315e43d..a9909ab772 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp @@ -12,4 +12,6 @@ PrintCommand::PrintCommand(const wpi::Twine& message) : CommandHelper{[str = message.str()] { wpi::outs() << str << "\n"; }, {}} { } -bool PrintCommand::RunsWhenDisabled() const { return true; } +bool PrintCommand::RunsWhenDisabled() const { + return true; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyScheduleCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyScheduleCommand.cpp index ace8a155c1..52e34d0f4e 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyScheduleCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyScheduleCommand.cpp @@ -31,4 +31,6 @@ void ProxyScheduleCommand::Execute() { } } -bool ProxyScheduleCommand::IsFinished() { return m_finished; } +bool ProxyScheduleCommand::IsFinished() { + return m_finished; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp index e8688c9546..26c1e06b58 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp @@ -102,10 +102,11 @@ void RamseteCommand::Execute() { auto dt = curTime - m_prevTime; if (m_prevTime < 0_s) { - if (m_usePID) + if (m_usePID) { m_outputVolts(0_V, 0_V); - else + } else { m_outputVel(0_mps, 0_mps); + } m_prevTime = curTime; return; @@ -141,7 +142,9 @@ void RamseteCommand::Execute() { m_prevTime = curTime; } -void RamseteCommand::End(bool interrupted) { m_timer.Stop(); } +void RamseteCommand::End(bool interrupted) { + m_timer.Stop(); +} bool RamseteCommand::IsFinished() { return m_timer.HasElapsed(m_trajectory.TotalTime()); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/RunCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/RunCommand.cpp index b92fabbeb1..1e073c903e 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/RunCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/RunCommand.cpp @@ -18,4 +18,6 @@ RunCommand::RunCommand(std::function toRun, AddRequirements(requirements); } -void RunCommand::Execute() { m_toRun(); } +void RunCommand::Execute() { + m_toRun(); +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ScheduleCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ScheduleCommand.cpp index d710b4df1a..bd580118ac 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ScheduleCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ScheduleCommand.cpp @@ -16,6 +16,10 @@ void ScheduleCommand::Initialize() { } } -bool ScheduleCommand::IsFinished() { return true; } +bool ScheduleCommand::IsFinished() { + return true; +} -bool ScheduleCommand::RunsWhenDisabled() const { return true; } +bool ScheduleCommand::RunsWhenDisabled() const { + return true; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp index 8c8cd6dedc..766d0cefa4 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp @@ -20,7 +20,9 @@ void SequentialCommandGroup::Initialize() { } void SequentialCommandGroup::Execute() { - if (m_commands.empty()) return; + if (m_commands.empty()) { + return; + } auto& currentCommand = m_commands[m_currentCommandIndex]; diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/StartEndCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/StartEndCommand.cpp index 21e5b19a2e..a53ad8a179 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/StartEndCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/StartEndCommand.cpp @@ -26,6 +26,10 @@ StartEndCommand::StartEndCommand(const StartEndCommand& other) m_onEnd = other.m_onEnd; } -void StartEndCommand::Initialize() { m_onInit(); } +void StartEndCommand::Initialize() { + m_onInit(); +} -void StartEndCommand::End(bool interrupted) { m_onEnd(); } +void StartEndCommand::End(bool interrupted) { + m_onEnd(); +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp index 45d149f408..65f3467437 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp @@ -26,7 +26,9 @@ void SubsystemBase::InitSendable(frc::SendableBuilder& builder) { ".default", [this]() -> std::string { auto command = GetDefaultCommand(); - if (command == nullptr) return "none"; + if (command == nullptr) { + return "none"; + } return command->GetName(); }, nullptr); @@ -37,7 +39,9 @@ void SubsystemBase::InitSendable(frc::SendableBuilder& builder) { ".command", [this]() -> std::string { auto command = GetCurrentCommand(); - if (command == nullptr) return "none"; + if (command == nullptr) { + return "none"; + } return command->GetName(); }, nullptr); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitCommand.cpp index f5958d6574..f2eef1cdbc 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitCommand.cpp @@ -16,8 +16,14 @@ void WaitCommand::Initialize() { m_timer.Start(); } -void WaitCommand::End(bool interrupted) { m_timer.Stop(); } +void WaitCommand::End(bool interrupted) { + m_timer.Stop(); +} -bool WaitCommand::IsFinished() { return m_timer.HasElapsed(m_duration); } +bool WaitCommand::IsFinished() { + return m_timer.HasElapsed(m_duration); +} -bool WaitCommand::RunsWhenDisabled() const { return true; } +bool WaitCommand::RunsWhenDisabled() const { + return true; +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitUntilCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitUntilCommand.cpp index 3e8fc39a39..66204fe241 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitUntilCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/WaitUntilCommand.cpp @@ -14,6 +14,10 @@ WaitUntilCommand::WaitUntilCommand(std::function condition) WaitUntilCommand::WaitUntilCommand(units::second_t time) : m_condition{[=] { return Timer::GetMatchTime() - time > 0_s; }} {} -bool WaitUntilCommand::IsFinished() { return m_condition(); } +bool WaitUntilCommand::IsFinished() { + return m_condition(); +} -bool WaitUntilCommand::RunsWhenDisabled() const { return true; } +bool WaitUntilCommand::RunsWhenDisabled() const { + return true; +} diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.cpp b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.cpp index f525258acd..7ebbb70005 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.cpp +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.cpp @@ -13,9 +13,13 @@ CommandTestBase::CommandTestBase() { scheduler.ClearButtons(); } -CommandScheduler CommandTestBase::GetScheduler() { return CommandScheduler(); } +CommandScheduler CommandTestBase::GetScheduler() { + return CommandScheduler(); +} -void CommandTestBase::SetUp() { frc::sim::DriverStationSim::SetEnabled(true); } +void CommandTestBase::SetUp() { + frc::sim::DriverStationSim::SetEnabled(true); +} void CommandTestBase::TearDown() { CommandScheduler::GetInstance().ClearButtons(); diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/ErrorConfirmer.h b/wpilibNewCommands/src/test/native/cpp/frc2/command/ErrorConfirmer.h index 9ce37e5f72..e503ab95a9 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/ErrorConfirmer.h +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/ErrorConfirmer.h @@ -11,7 +11,9 @@ class ErrorConfirmer { public: explicit ErrorConfirmer(const char* msg) : m_msg(msg) { - if (instance != nullptr) return; + if (instance != nullptr) { + return; + } HALSIM_SetSendError(HandleError); EXPECT_CALL(*this, ConfirmError()); instance = this; diff --git a/wpilibOldCommands/src/main/native/cpp/buttons/Button.cpp b/wpilibOldCommands/src/main/native/cpp/buttons/Button.cpp index c86c6bd989..ef2c03d12d 100644 --- a/wpilibOldCommands/src/main/native/cpp/buttons/Button.cpp +++ b/wpilibOldCommands/src/main/native/cpp/buttons/Button.cpp @@ -6,12 +6,22 @@ using namespace frc; -void Button::WhenPressed(Command* command) { WhenActive(command); } +void Button::WhenPressed(Command* command) { + WhenActive(command); +} -void Button::WhileHeld(Command* command) { WhileActive(command); } +void Button::WhileHeld(Command* command) { + WhileActive(command); +} -void Button::WhenReleased(Command* command) { WhenInactive(command); } +void Button::WhenReleased(Command* command) { + WhenInactive(command); +} -void Button::CancelWhenPressed(Command* command) { CancelWhenActive(command); } +void Button::CancelWhenPressed(Command* command) { + CancelWhenActive(command); +} -void Button::ToggleWhenPressed(Command* command) { ToggleWhenActive(command); } +void Button::ToggleWhenPressed(Command* command) { + ToggleWhenActive(command); +} diff --git a/wpilibOldCommands/src/main/native/cpp/buttons/ButtonScheduler.cpp b/wpilibOldCommands/src/main/native/cpp/buttons/ButtonScheduler.cpp index c791ad5260..b210c8df5e 100644 --- a/wpilibOldCommands/src/main/native/cpp/buttons/ButtonScheduler.cpp +++ b/wpilibOldCommands/src/main/native/cpp/buttons/ButtonScheduler.cpp @@ -11,4 +11,6 @@ using namespace frc; ButtonScheduler::ButtonScheduler(bool last, Trigger* button, Command* orders) : m_pressedLast(last), m_button(button), m_command(orders) {} -void ButtonScheduler::Start() { Scheduler::GetInstance()->AddButton(this); } +void ButtonScheduler::Start() { + Scheduler::GetInstance()->AddButton(this); +} diff --git a/wpilibOldCommands/src/main/native/cpp/buttons/InternalButton.cpp b/wpilibOldCommands/src/main/native/cpp/buttons/InternalButton.cpp index 6365504678..5adf83c999 100644 --- a/wpilibOldCommands/src/main/native/cpp/buttons/InternalButton.cpp +++ b/wpilibOldCommands/src/main/native/cpp/buttons/InternalButton.cpp @@ -9,8 +9,14 @@ using namespace frc; InternalButton::InternalButton(bool inverted) : m_pressed(inverted), m_inverted(inverted) {} -void InternalButton::SetInverted(bool inverted) { m_inverted = inverted; } +void InternalButton::SetInverted(bool inverted) { + m_inverted = inverted; +} -void InternalButton::SetPressed(bool pressed) { m_pressed = pressed; } +void InternalButton::SetPressed(bool pressed) { + m_pressed = pressed; +} -bool InternalButton::Get() { return m_pressed ^ m_inverted; } +bool InternalButton::Get() { + return m_pressed ^ m_inverted; +} diff --git a/wpilibOldCommands/src/main/native/cpp/buttons/JoystickButton.cpp b/wpilibOldCommands/src/main/native/cpp/buttons/JoystickButton.cpp index ebe06668bc..459c076359 100644 --- a/wpilibOldCommands/src/main/native/cpp/buttons/JoystickButton.cpp +++ b/wpilibOldCommands/src/main/native/cpp/buttons/JoystickButton.cpp @@ -9,4 +9,6 @@ using namespace frc; JoystickButton::JoystickButton(GenericHID* joystick, int buttonNumber) : m_joystick(joystick), m_buttonNumber(buttonNumber) {} -bool JoystickButton::Get() { return m_joystick->GetRawButton(m_buttonNumber); } +bool JoystickButton::Get() { + return m_joystick->GetRawButton(m_buttonNumber); +} diff --git a/wpilibOldCommands/src/main/native/cpp/buttons/POVButton.cpp b/wpilibOldCommands/src/main/native/cpp/buttons/POVButton.cpp index 6fcf227e60..67b8caeedf 100644 --- a/wpilibOldCommands/src/main/native/cpp/buttons/POVButton.cpp +++ b/wpilibOldCommands/src/main/native/cpp/buttons/POVButton.cpp @@ -9,4 +9,6 @@ using namespace frc; POVButton::POVButton(GenericHID& joystick, int angle, int povNumber) : m_joystick(&joystick), m_angle(angle), m_povNumber(povNumber) {} -bool POVButton::Get() { return m_joystick->GetPOV(m_povNumber) == m_angle; } +bool POVButton::Get() { + return m_joystick->GetPOV(m_povNumber) == m_angle; +} diff --git a/wpilibOldCommands/src/main/native/cpp/buttons/Trigger.cpp b/wpilibOldCommands/src/main/native/cpp/buttons/Trigger.cpp index d22d895c51..40afef8bf8 100644 --- a/wpilibOldCommands/src/main/native/cpp/buttons/Trigger.cpp +++ b/wpilibOldCommands/src/main/native/cpp/buttons/Trigger.cpp @@ -33,7 +33,9 @@ Trigger& Trigger::operator=(Trigger&& rhs) { return *this; } -bool Trigger::Grab() { return Get() || m_sendablePressed; } +bool Trigger::Grab() { + return Get() || m_sendablePressed; +} void Trigger::WhenActive(Command* command) { auto pbs = new PressedButtonScheduler(Grab(), this, command); diff --git a/wpilibOldCommands/src/main/native/cpp/commands/Command.cpp b/wpilibOldCommands/src/main/native/cpp/commands/Command.cpp index ded86ebadc..b1a7554069 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/Command.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/Command.cpp @@ -31,8 +31,9 @@ Command::Command(Subsystem& subsystem) : Command("", -1.0) { Command::Command(const wpi::Twine& name, double timeout) { // We use -1.0 to indicate no timeout. - if (timeout < 0.0 && timeout != -1.0) + if (timeout < 0.0 && timeout != -1.0) { wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0"); + } m_timeout = timeout; @@ -61,37 +62,45 @@ Command::Command(const wpi::Twine& name, double timeout, Subsystem& subsystem) } double Command::TimeSinceInitialized() const { - if (m_startTime < 0.0) + if (m_startTime < 0.0) { return 0.0; - else + } else { return Timer::GetFPGATimestamp() - m_startTime; + } } void Command::Requires(Subsystem* subsystem) { - if (!AssertUnlocked("Can not add new requirement to command")) return; + if (!AssertUnlocked("Can not add new requirement to command")) { + return; + } - if (subsystem != nullptr) + if (subsystem != nullptr) { m_requirements.insert(subsystem); - else + } else { wpi_setWPIErrorWithContext(NullParameter, "subsystem"); + } } void Command::Start() { LockChanges(); - if (m_parent != nullptr) + if (m_parent != nullptr) { wpi_setWPIErrorWithContext( CommandIllegalUse, "Can not start a command that is part of a command group"); + } m_completed = false; Scheduler::GetInstance()->AddCommand(this); } bool Command::Run() { - if (!m_runWhenDisabled && m_parent == nullptr && RobotState::IsDisabled()) + if (!m_runWhenDisabled && m_parent == nullptr && RobotState::IsDisabled()) { Cancel(); + } - if (IsCanceled()) return false; + if (IsCanceled()) { + return false; + } if (!m_initialized) { m_initialized = true; @@ -105,23 +114,34 @@ bool Command::Run() { } void Command::Cancel() { - if (m_parent != nullptr) + if (m_parent != nullptr) { wpi_setWPIErrorWithContext( CommandIllegalUse, "Can not cancel a command that is part of a command group"); + } _Cancel(); } -bool Command::IsRunning() const { return m_running; } +bool Command::IsRunning() const { + return m_running; +} -bool Command::IsInitialized() const { return m_initialized; } +bool Command::IsInitialized() const { + return m_initialized; +} -bool Command::IsCompleted() const { return m_completed; } +bool Command::IsCompleted() const { + return m_completed; +} -bool Command::IsCanceled() const { return m_canceled; } +bool Command::IsCanceled() const { + return m_canceled; +} -bool Command::IsInterruptible() const { return m_interruptible; } +bool Command::IsInterruptible() const { + return m_interruptible; +} void Command::SetInterruptible(bool interruptible) { m_interruptible = interruptible; @@ -135,19 +155,28 @@ const Command::SubsystemSet& Command::GetRequirements() const { return m_requirements; } -CommandGroup* Command::GetGroup() const { return m_parent; } +CommandGroup* Command::GetGroup() const { + return m_parent; +} -void Command::SetRunWhenDisabled(bool run) { m_runWhenDisabled = run; } +void Command::SetRunWhenDisabled(bool run) { + m_runWhenDisabled = run; +} -bool Command::WillRunWhenDisabled() const { return m_runWhenDisabled; } +bool Command::WillRunWhenDisabled() const { + return m_runWhenDisabled; +} -int Command::GetID() const { return m_commandID; } +int Command::GetID() const { + return m_commandID; +} void Command::SetTimeout(double timeout) { - if (timeout < 0.0) + if (timeout < 0.0) { wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0"); - else + } else { m_timeout = timeout; + } } bool Command::IsTimedOut() const { @@ -177,9 +206,13 @@ void Command::SetParent(CommandGroup* parent) { } } -bool Command::IsParented() const { return m_parent != nullptr; } +bool Command::IsParented() const { + return m_parent != nullptr; +} -void Command::ClearRequirements() { m_requirements.clear(); } +void Command::ClearRequirements() { + m_requirements.clear(); +} void Command::Initialize() {} @@ -187,21 +220,33 @@ void Command::Execute() {} void Command::End() {} -void Command::Interrupted() { End(); } +void Command::Interrupted() { + End(); +} -void Command::_Initialize() { m_completed = false; } +void Command::_Initialize() { + m_completed = false; +} -void Command::_Interrupted() { m_completed = true; } +void Command::_Interrupted() { + m_completed = true; +} void Command::_Execute() {} -void Command::_End() { m_completed = true; } - -void Command::_Cancel() { - if (IsRunning()) m_canceled = true; +void Command::_End() { + m_completed = true; } -void Command::LockChanges() { m_locked = true; } +void Command::_Cancel() { + if (IsRunning()) { + m_canceled = true; + } +} + +void Command::LockChanges() { + m_locked = true; +} void Command::Removed() { if (m_initialized) { @@ -225,7 +270,9 @@ void Command::StartRunning() { m_completed = false; } -void Command::StartTiming() { m_startTime = Timer::GetFPGATimestamp(); } +void Command::StartTiming() { + m_startTime = Timer::GetFPGATimestamp(); +} std::string Command::GetName() const { return SendableRegistry::GetInstance().GetName(this); @@ -252,9 +299,13 @@ void Command::InitSendable(SendableBuilder& builder) { "running", [=]() { return IsRunning(); }, [=](bool value) { if (value) { - if (!IsRunning()) Start(); + if (!IsRunning()) { + Start(); + } } else { - if (IsRunning()) Cancel(); + if (IsRunning()) { + Cancel(); + } } }); builder.AddBooleanProperty( diff --git a/wpilibOldCommands/src/main/native/cpp/commands/CommandGroup.cpp b/wpilibOldCommands/src/main/native/cpp/commands/CommandGroup.cpp index 6c6c8b3f9c..ff8ee7c985 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/CommandGroup.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/CommandGroup.cpp @@ -15,7 +15,9 @@ void CommandGroup::AddSequential(Command* command) { wpi_setWPIErrorWithContext(NullParameter, "command"); return; } - if (!AssertUnlocked("Cannot add new command to command group")) return; + if (!AssertUnlocked("Cannot add new command to command group")) { + return; + } m_commands.emplace_back(command, CommandGroupEntry::kSequence_InSequence); @@ -23,7 +25,9 @@ void CommandGroup::AddSequential(Command* command) { // Iterate through command->GetRequirements() and call Requires() on each // required subsystem - for (auto&& requirement : command->GetRequirements()) Requires(requirement); + for (auto&& requirement : command->GetRequirements()) { + Requires(requirement); + } } void CommandGroup::AddSequential(Command* command, double timeout) { @@ -31,7 +35,9 @@ void CommandGroup::AddSequential(Command* command, double timeout) { wpi_setWPIErrorWithContext(NullParameter, "command"); return; } - if (!AssertUnlocked("Cannot add new command to command group")) return; + if (!AssertUnlocked("Cannot add new command to command group")) { + return; + } if (timeout < 0.0) { wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0"); return; @@ -44,7 +50,9 @@ void CommandGroup::AddSequential(Command* command, double timeout) { // Iterate through command->GetRequirements() and call Requires() on each // required subsystem - for (auto&& requirement : command->GetRequirements()) Requires(requirement); + for (auto&& requirement : command->GetRequirements()) { + Requires(requirement); + } } void CommandGroup::AddParallel(Command* command) { @@ -52,7 +60,9 @@ void CommandGroup::AddParallel(Command* command) { wpi_setWPIErrorWithContext(NullParameter, "command"); return; } - if (!AssertUnlocked("Cannot add new command to command group")) return; + if (!AssertUnlocked("Cannot add new command to command group")) { + return; + } m_commands.emplace_back(command, CommandGroupEntry::kSequence_BranchChild); @@ -60,7 +70,9 @@ void CommandGroup::AddParallel(Command* command) { // Iterate through command->GetRequirements() and call Requires() on each // required subsystem - for (auto&& requirement : command->GetRequirements()) Requires(requirement); + for (auto&& requirement : command->GetRequirements()) { + Requires(requirement); + } } void CommandGroup::AddParallel(Command* command, double timeout) { @@ -68,7 +80,9 @@ void CommandGroup::AddParallel(Command* command, double timeout) { wpi_setWPIErrorWithContext(NullParameter, "command"); return; } - if (!AssertUnlocked("Cannot add new command to command group")) return; + if (!AssertUnlocked("Cannot add new command to command group")) { + return; + } if (timeout < 0.0) { wpi_setWPIErrorWithContext(ParameterOutOfRange, "timeout < 0.0"); return; @@ -81,26 +95,36 @@ void CommandGroup::AddParallel(Command* command, double timeout) { // Iterate through command->GetRequirements() and call Requires() on each // required subsystem - for (auto&& requirement : command->GetRequirements()) Requires(requirement); + for (auto&& requirement : command->GetRequirements()) { + Requires(requirement); + } } bool CommandGroup::IsInterruptible() const { - if (!Command::IsInterruptible()) return false; + if (!Command::IsInterruptible()) { + return false; + } if (m_currentCommandIndex != -1 && static_cast(m_currentCommandIndex) < m_commands.size()) { Command* cmd = m_commands[m_currentCommandIndex].m_command; - if (!cmd->IsInterruptible()) return false; + if (!cmd->IsInterruptible()) { + return false; + } } for (const auto& child : m_children) { - if (!child->m_command->IsInterruptible()) return false; + if (!child->m_command->IsInterruptible()) { + return false; + } } return true; } -int CommandGroup::GetSize() const { return m_children.size(); } +int CommandGroup::GetSize() const { + return m_children.size(); +} void CommandGroup::Initialize() {} @@ -115,7 +139,9 @@ void CommandGroup::End() {} void CommandGroup::Interrupted() {} -void CommandGroup::_Initialize() { m_currentCommandIndex = -1; } +void CommandGroup::_Initialize() { + m_currentCommandIndex = -1; +} void CommandGroup::_Execute() { CommandGroupEntry* entry; @@ -132,7 +158,9 @@ void CommandGroup::_Execute() { // If a command is prepared to run if (cmd != nullptr) { // If command timed out, cancel it so it's removed from the Scheduler - if (entry->IsTimedOut()) cmd->_Cancel(); + if (entry->IsTimedOut()) { + cmd->_Cancel(); + } // If command finished or was canceled, remove it from Scheduler if (cmd->Run()) { @@ -219,7 +247,9 @@ void CommandGroup::_End() { m_children.clear(); } -void CommandGroup::_Interrupted() { _End(); } +void CommandGroup::_Interrupted() { + _End(); +} void CommandGroup::CancelConflicts(Command* command) { for (auto childIter = m_children.begin(); childIter != m_children.end();) { @@ -235,6 +265,8 @@ void CommandGroup::CancelConflicts(Command* command) { break; } } - if (!erased) childIter++; + if (!erased) { + childIter++; + } } } diff --git a/wpilibOldCommands/src/main/native/cpp/commands/CommandGroupEntry.cpp b/wpilibOldCommands/src/main/native/cpp/commands/CommandGroupEntry.cpp index cc5667670b..c8a31568de 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/CommandGroupEntry.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/CommandGroupEntry.cpp @@ -13,8 +13,12 @@ CommandGroupEntry::CommandGroupEntry(Command* command, Sequence state, : m_timeout(timeout), m_command(command), m_state(state) {} bool CommandGroupEntry::IsTimedOut() const { - if (m_timeout < 0.0) return false; + if (m_timeout < 0.0) { + return false; + } double time = m_command->TimeSinceInitialized(); - if (time == 0.0) return false; + if (time == 0.0) { + return false; + } return time >= m_timeout; } diff --git a/wpilibOldCommands/src/main/native/cpp/commands/ConditionalCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/ConditionalCommand.cpp index 02a8b82d4e..5b507d7f2f 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/ConditionalCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/ConditionalCommand.cpp @@ -10,12 +10,14 @@ using namespace frc; static void RequireAll(Command& command, Command* onTrue, Command* onFalse) { if (onTrue != nullptr) { - for (auto requirement : onTrue->GetRequirements()) + for (auto requirement : onTrue->GetRequirements()) { command.Requires(requirement); + } } if (onFalse != nullptr) { - for (auto requirement : onFalse->GetRequirements()) + for (auto requirement : onFalse->GetRequirements()) { command.Requires(requirement); + } } } diff --git a/wpilibOldCommands/src/main/native/cpp/commands/InstantCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/InstantCommand.cpp index e07604ef46..f487c87aa7 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/InstantCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/InstantCommand.cpp @@ -39,4 +39,6 @@ void InstantCommand::_Initialize() { } } -bool InstantCommand::IsFinished() { return true; } +bool InstantCommand::IsFinished() { + return true; +} diff --git a/wpilibOldCommands/src/main/native/cpp/commands/PIDCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/PIDCommand.cpp index 5e3e9a511e..25c3ed6ad9 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/PIDCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/PIDCommand.cpp @@ -72,19 +72,29 @@ PIDCommand::PIDCommand(double p, double i, double d, double period, m_controller = std::make_shared(p, i, d, this, this, period); } -void PIDCommand::_Initialize() { m_controller->Enable(); } +void PIDCommand::_Initialize() { + m_controller->Enable(); +} -void PIDCommand::_End() { m_controller->Disable(); } +void PIDCommand::_End() { + m_controller->Disable(); +} -void PIDCommand::_Interrupted() { _End(); } +void PIDCommand::_Interrupted() { + _End(); +} void PIDCommand::SetSetpointRelative(double deltaSetpoint) { SetSetpoint(GetSetpoint() + deltaSetpoint); } -void PIDCommand::PIDWrite(double output) { UsePIDOutput(output); } +void PIDCommand::PIDWrite(double output) { + UsePIDOutput(output); +} -double PIDCommand::PIDGet() { return ReturnPIDInput(); } +double PIDCommand::PIDGet() { + return ReturnPIDInput(); +} std::shared_ptr PIDCommand::GetPIDController() const { return m_controller; @@ -94,9 +104,13 @@ void PIDCommand::SetSetpoint(double setpoint) { m_controller->SetSetpoint(setpoint); } -double PIDCommand::GetSetpoint() const { return m_controller->GetSetpoint(); } +double PIDCommand::GetSetpoint() const { + return m_controller->GetSetpoint(); +} -double PIDCommand::GetPosition() { return ReturnPIDInput(); } +double PIDCommand::GetPosition() { + return ReturnPIDInput(); +} void PIDCommand::InitSendable(SendableBuilder& builder) { m_controller->InitSendable(builder); diff --git a/wpilibOldCommands/src/main/native/cpp/commands/PIDSubsystem.cpp b/wpilibOldCommands/src/main/native/cpp/commands/PIDSubsystem.cpp index b6b9970c4b..02765da897 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/PIDSubsystem.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/PIDSubsystem.cpp @@ -49,13 +49,21 @@ PIDSubsystem::PIDSubsystem(double p, double i, double d, double f, AddChild("PIDController", m_controller); } -void PIDSubsystem::Enable() { m_controller->Enable(); } +void PIDSubsystem::Enable() { + m_controller->Enable(); +} -void PIDSubsystem::Disable() { m_controller->Disable(); } +void PIDSubsystem::Disable() { + m_controller->Disable(); +} -void PIDSubsystem::PIDWrite(double output) { UsePIDOutput(output); } +void PIDSubsystem::PIDWrite(double output) { + UsePIDOutput(output); +} -double PIDSubsystem::PIDGet() { return ReturnPIDInput(); } +double PIDSubsystem::PIDGet() { + return ReturnPIDInput(); +} void PIDSubsystem::SetSetpoint(double setpoint) { m_controller->SetSetpoint(setpoint); @@ -73,11 +81,17 @@ void PIDSubsystem::SetOutputRange(double minimumOutput, double maximumOutput) { m_controller->SetOutputRange(minimumOutput, maximumOutput); } -double PIDSubsystem::GetSetpoint() { return m_controller->GetSetpoint(); } +double PIDSubsystem::GetSetpoint() { + return m_controller->GetSetpoint(); +} -double PIDSubsystem::GetPosition() { return ReturnPIDInput(); } +double PIDSubsystem::GetPosition() { + return ReturnPIDInput(); +} -double PIDSubsystem::GetRate() { return ReturnPIDInput(); } +double PIDSubsystem::GetRate() { + return ReturnPIDInput(); +} void PIDSubsystem::SetAbsoluteTolerance(double absValue) { m_controller->SetAbsoluteTolerance(absValue); @@ -87,7 +101,9 @@ void PIDSubsystem::SetPercentTolerance(double percent) { m_controller->SetPercentTolerance(percent); } -bool PIDSubsystem::OnTarget() const { return m_controller->OnTarget(); } +bool PIDSubsystem::OnTarget() const { + return m_controller->OnTarget(); +} std::shared_ptr PIDSubsystem::GetPIDController() { return m_controller; diff --git a/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp index b06c983c5f..6f2a58b33b 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp @@ -13,4 +13,6 @@ PrintCommand::PrintCommand(const wpi::Twine& message) m_message = message.str(); } -void PrintCommand::Initialize() { wpi::outs() << m_message << '\n'; } +void PrintCommand::Initialize() { + wpi::outs() << m_message << '\n'; +} diff --git a/wpilibOldCommands/src/main/native/cpp/commands/Scheduler.cpp b/wpilibOldCommands/src/main/native/cpp/commands/Scheduler.cpp index 6f117c24cf..73569b803d 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/Scheduler.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/Scheduler.cpp @@ -52,8 +52,9 @@ Scheduler* Scheduler::GetInstance() { void Scheduler::AddCommand(Command* command) { std::scoped_lock lock(m_impl->additionsMutex); if (std::find(m_impl->additions.begin(), m_impl->additions.end(), command) != - m_impl->additions.end()) + m_impl->additions.end()) { return; + } m_impl->additions.push_back(command); } @@ -73,7 +74,9 @@ void Scheduler::RegisterSubsystem(Subsystem* subsystem) { void Scheduler::Run() { // Get button input (going backwards preserves button priority) { - if (!m_impl->enabled) return; + if (!m_impl->enabled) { + return; + } std::scoped_lock lock(m_impl->buttonsMutex); for (auto& button : m_impl->buttons) { @@ -152,7 +155,9 @@ void Scheduler::ResetAll() { m_impl->commands.clear(); } -void Scheduler::SetEnabled(bool enabled) { m_impl->enabled = enabled; } +void Scheduler::SetEnabled(bool enabled) { + m_impl->enabled = enabled; +} void Scheduler::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Scheduler"); @@ -163,7 +168,9 @@ void Scheduler::InitSendable(SendableBuilder& builder) { // Get the list of possible commands to cancel auto new_toCancel = cancelEntry.GetValue(); wpi::ArrayRef toCancel; - if (new_toCancel) toCancel = new_toCancel->GetDoubleArray(); + if (new_toCancel) { + toCancel = new_toCancel->GetDoubleArray(); + } // Cancel commands whose cancel buttons were pressed on the SmartDashboard if (!toCancel.empty()) { @@ -212,7 +219,9 @@ Scheduler::~Scheduler() { } void Scheduler::Impl::Remove(Command* command) { - if (!commands.erase(command)) return; + if (!commands.erase(command)) { + return; + } for (auto&& requirement : command->GetRequirements()) { requirement->SetCurrentCommand(nullptr); @@ -222,7 +231,9 @@ void Scheduler::Impl::Remove(Command* command) { } void Scheduler::Impl::ProcessCommandAddition(Command* command) { - if (command == nullptr) return; + if (command == nullptr) { + return; + } // Only add if not already in auto found = commands.find(command); @@ -231,8 +242,9 @@ void Scheduler::Impl::ProcessCommandAddition(Command* command) { const auto& requirements = command->GetRequirements(); for (const auto requirement : requirements) { if (requirement->GetCurrentCommand() != nullptr && - !requirement->GetCurrentCommand()->IsInterruptible()) + !requirement->GetCurrentCommand()->IsInterruptible()) { return; + } } // Give it the requirements diff --git a/wpilibOldCommands/src/main/native/cpp/commands/StartCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/StartCommand.cpp index 8112864eef..05dc0793ba 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/StartCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/StartCommand.cpp @@ -11,4 +11,6 @@ StartCommand::StartCommand(Command* commandToStart) m_commandToFork = commandToStart; } -void StartCommand::Initialize() { m_commandToFork->Start(); } +void StartCommand::Initialize() { + m_commandToFork->Start(); +} diff --git a/wpilibOldCommands/src/main/native/cpp/commands/Subsystem.cpp b/wpilibOldCommands/src/main/native/cpp/commands/Subsystem.cpp index b2b11a09da..3026af85e4 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/Subsystem.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/Subsystem.cpp @@ -55,7 +55,9 @@ void Subsystem::SetCurrentCommand(Command* command) { m_currentCommandChanged = true; } -Command* Subsystem::GetCurrentCommand() const { return m_currentCommand; } +Command* Subsystem::GetCurrentCommand() const { + return m_currentCommand; +} wpi::StringRef Subsystem::GetCurrentCommandName() const { Command* currentCommand = GetCurrentCommand(); @@ -100,9 +102,13 @@ void Subsystem::AddChild(const wpi::Twine& name, Sendable& child) { registry.AddLW(&child, registry.GetSubsystem(this), name); } -void Subsystem::AddChild(std::shared_ptr child) { AddChild(*child); } +void Subsystem::AddChild(std::shared_ptr child) { + AddChild(*child); +} -void Subsystem::AddChild(Sendable* child) { AddChild(*child); } +void Subsystem::AddChild(Sendable* child) { + AddChild(*child); +} void Subsystem::AddChild(Sendable& child) { auto& registry = SendableRegistry::GetInstance(); @@ -111,7 +117,9 @@ void Subsystem::AddChild(Sendable& child) { } void Subsystem::ConfirmCommand() { - if (m_currentCommandChanged) m_currentCommandChanged = false; + if (m_currentCommandChanged) { + m_currentCommandChanged = false; + } } void Subsystem::InitSendable(SendableBuilder& builder) { diff --git a/wpilibOldCommands/src/main/native/cpp/commands/TimedCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/TimedCommand.cpp index a3016ae0c4..5a91068982 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/TimedCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/TimedCommand.cpp @@ -18,4 +18,6 @@ TimedCommand::TimedCommand(const wpi::Twine& name, double timeout, TimedCommand::TimedCommand(double timeout, Subsystem& subsystem) : Command(timeout, subsystem) {} -bool TimedCommand::IsFinished() { return IsTimedOut(); } +bool TimedCommand::IsFinished() { + return IsTimedOut(); +} diff --git a/wpilibOldCommands/src/main/native/cpp/commands/WaitUntilCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/WaitUntilCommand.cpp index 658b5f52d3..338d128a73 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/WaitUntilCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/WaitUntilCommand.cpp @@ -18,4 +18,6 @@ WaitUntilCommand::WaitUntilCommand(const wpi::Twine& name, double time) m_time = time; } -bool WaitUntilCommand::IsFinished() { return Timer::GetMatchTime() >= m_time; } +bool WaitUntilCommand::IsFinished() { + return Timer::GetMatchTime() >= m_time; +} diff --git a/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp b/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp index 368d344d6f..8d651a6201 100644 --- a/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp +++ b/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp @@ -38,16 +38,28 @@ void ADXL345_I2C::SetRange(Range range) { kDataFormat_FullRes | static_cast(range)); } -double ADXL345_I2C::GetX() { return GetAcceleration(kAxis_X); } +double ADXL345_I2C::GetX() { + return GetAcceleration(kAxis_X); +} -double ADXL345_I2C::GetY() { return GetAcceleration(kAxis_Y); } +double ADXL345_I2C::GetY() { + return GetAcceleration(kAxis_Y); +} -double ADXL345_I2C::GetZ() { return GetAcceleration(kAxis_Z); } +double ADXL345_I2C::GetZ() { + return GetAcceleration(kAxis_Z); +} double ADXL345_I2C::GetAcceleration(ADXL345_I2C::Axes axis) { - if (axis == kAxis_X && m_simX) return m_simX.Get(); - if (axis == kAxis_Y && m_simY) return m_simY.Get(); - if (axis == kAxis_Z && m_simZ) return m_simZ.Get(); + if (axis == kAxis_X && m_simX) { + return m_simX.Get(); + } + if (axis == kAxis_Y && m_simY) { + return m_simY.Get(); + } + if (axis == kAxis_Z && m_simZ) { + return m_simZ.Get(); + } int16_t rawAccel = 0; m_i2c.Read(kDataRegister + static_cast(axis), sizeof(rawAccel), reinterpret_cast(&rawAccel)); diff --git a/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp b/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp index 8394402ecb..be7bf31dd0 100644 --- a/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp +++ b/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp @@ -49,19 +49,33 @@ void ADXL345_SPI::SetRange(Range range) { commands[1] = kDataFormat_FullRes | static_cast(range & 0x03); m_spi.Transaction(commands, commands, 2); - if (m_simRange) m_simRange.Set(range); + if (m_simRange) { + m_simRange.Set(range); + } } -double ADXL345_SPI::GetX() { return GetAcceleration(kAxis_X); } +double ADXL345_SPI::GetX() { + return GetAcceleration(kAxis_X); +} -double ADXL345_SPI::GetY() { return GetAcceleration(kAxis_Y); } +double ADXL345_SPI::GetY() { + return GetAcceleration(kAxis_Y); +} -double ADXL345_SPI::GetZ() { return GetAcceleration(kAxis_Z); } +double ADXL345_SPI::GetZ() { + return GetAcceleration(kAxis_Z); +} double ADXL345_SPI::GetAcceleration(ADXL345_SPI::Axes axis) { - if (axis == kAxis_X && m_simX) return m_simX.Get(); - if (axis == kAxis_Y && m_simY) return m_simY.Get(); - if (axis == kAxis_Z && m_simZ) return m_simZ.Get(); + if (axis == kAxis_X && m_simX) { + return m_simX.Get(); + } + if (axis == kAxis_Y && m_simY) { + return m_simY.Get(); + } + if (axis == kAxis_Z && m_simZ) { + return m_simZ.Get(); + } uint8_t buffer[3]; uint8_t command[3] = {0, 0, 0}; command[0] = (kAddress_Read | kAddress_MultiByte | kDataRegister) + diff --git a/wpilibc/src/main/native/cpp/ADXL362.cpp b/wpilibc/src/main/native/cpp/ADXL362.cpp index 84be4a7d60..884ee9c4c5 100644 --- a/wpilibc/src/main/native/cpp/ADXL362.cpp +++ b/wpilibc/src/main/native/cpp/ADXL362.cpp @@ -76,7 +76,9 @@ ADXL362::ADXL362(SPI::Port port, Range range) } void ADXL362::SetRange(Range range) { - if (m_gsPerLSB == 0.0) return; + if (m_gsPerLSB == 0.0) { + return; + } uint8_t commands[3]; @@ -100,21 +102,37 @@ void ADXL362::SetRange(Range range) { kFilterCtl_ODR_100Hz | static_cast((range & 0x03) << 6); m_spi.Write(commands, 3); - if (m_simRange) m_simRange.Set(range); + if (m_simRange) { + m_simRange.Set(range); + } } -double ADXL362::GetX() { return GetAcceleration(kAxis_X); } +double ADXL362::GetX() { + return GetAcceleration(kAxis_X); +} -double ADXL362::GetY() { return GetAcceleration(kAxis_Y); } +double ADXL362::GetY() { + return GetAcceleration(kAxis_Y); +} -double ADXL362::GetZ() { return GetAcceleration(kAxis_Z); } +double ADXL362::GetZ() { + return GetAcceleration(kAxis_Z); +} double ADXL362::GetAcceleration(ADXL362::Axes axis) { - if (m_gsPerLSB == 0.0) return 0.0; + if (m_gsPerLSB == 0.0) { + return 0.0; + } - if (axis == kAxis_X && m_simX) return m_simX.Get(); - if (axis == kAxis_Y && m_simY) return m_simY.Get(); - if (axis == kAxis_Z && m_simZ) return m_simZ.Get(); + if (axis == kAxis_X && m_simX) { + return m_simX.Get(); + } + if (axis == kAxis_Y && m_simY) { + return m_simY.Get(); + } + if (axis == kAxis_Z && m_simZ) { + return m_simZ.Get(); + } uint8_t buffer[4]; uint8_t command[4] = {0, 0, 0, 0}; diff --git a/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp b/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp index d622664cf1..cfdccbccda 100644 --- a/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp +++ b/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp @@ -79,7 +79,9 @@ static inline int BytesToIntBE(uint8_t* buf) { uint16_t ADXRS450_Gyro::ReadRegister(int reg) { int cmd = 0x80000000 | static_cast(reg) << 17; - if (!CalcParity(cmd)) cmd |= 1u; + if (!CalcParity(cmd)) { + cmd |= 1u; + } // big endian uint8_t buf[4] = {static_cast((cmd >> 24) & 0xff), @@ -89,24 +91,34 @@ uint16_t ADXRS450_Gyro::ReadRegister(int reg) { m_spi.Write(buf, 4); m_spi.Read(false, buf, 4); - if ((buf[0] & 0xe0) == 0) return 0; // error, return 0 + if ((buf[0] & 0xe0) == 0) { + return 0; // error, return 0 + } return static_cast((BytesToIntBE(buf) >> 5) & 0xffff); } double ADXRS450_Gyro::GetAngle() const { - if (m_simAngle) return m_simAngle.Get(); + if (m_simAngle) { + return m_simAngle.Get(); + } return m_spi.GetAccumulatorIntegratedValue() * kDegreePerSecondPerLSB; } double ADXRS450_Gyro::GetRate() const { - if (m_simRate) return m_simRate.Get(); + if (m_simRate) { + return m_simRate.Get(); + } return static_cast(m_spi.GetAccumulatorLastValue()) * kDegreePerSecondPerLSB; } void ADXRS450_Gyro::Reset() { - if (m_simAngle) m_simAngle.Set(0.0); - if (m_simRate) m_simRate.Set(0.0); + if (m_simAngle) { + m_simAngle.Set(0.0); + } + if (m_simRate) { + m_simRate.Set(0.0); + } m_spi.ResetAccumulator(); } @@ -122,4 +134,6 @@ void ADXRS450_Gyro::Calibrate() { m_spi.ResetAccumulator(); } -int ADXRS450_Gyro::GetPort() const { return m_port; } +int ADXRS450_Gyro::GetPort() const { + return m_port; +} diff --git a/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp b/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp index 5ab9658067..fa8654076a 100644 --- a/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp +++ b/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp @@ -44,9 +44,13 @@ void AnalogAccelerometer::SetSensitivity(double sensitivity) { m_voltsPerG = sensitivity; } -void AnalogAccelerometer::SetZero(double zero) { m_zeroGVoltage = zero; } +void AnalogAccelerometer::SetZero(double zero) { + m_zeroGVoltage = zero; +} -double AnalogAccelerometer::PIDGet() { return GetAcceleration(); } +double AnalogAccelerometer::PIDGet() { + return GetAcceleration(); +} void AnalogAccelerometer::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Accelerometer"); diff --git a/wpilibc/src/main/native/cpp/AnalogEncoder.cpp b/wpilibc/src/main/native/cpp/AnalogEncoder.cpp index c912226460..20fb1b57ba 100644 --- a/wpilibc/src/main/native/cpp/AnalogEncoder.cpp +++ b/wpilibc/src/main/native/cpp/AnalogEncoder.cpp @@ -51,7 +51,9 @@ void AnalogEncoder::Init() { } units::turn_t AnalogEncoder::Get() const { - if (m_simPosition) return units::turn_t{m_simPosition.Get()}; + if (m_simPosition) { + return units::turn_t{m_simPosition.Get()}; + } // As the values are not atomic, keep trying until we get 2 reads of the same // value If we don't within 10 attempts, error @@ -73,7 +75,9 @@ units::turn_t AnalogEncoder::Get() const { return m_lastPosition; } -double AnalogEncoder::GetPositionOffset() const { return m_positionOffset; } +double AnalogEncoder::GetPositionOffset() const { + return m_positionOffset; +} void AnalogEncoder::SetDistancePerRotation(double distancePerRotation) { m_distancePerRotation = distancePerRotation; @@ -92,7 +96,9 @@ void AnalogEncoder::Reset() { m_positionOffset = m_analogInput->GetVoltage(); } -int AnalogEncoder::GetChannel() const { return m_analogInput->GetChannel(); } +int AnalogEncoder::GetChannel() const { + return m_analogInput->GetChannel(); +} void AnalogEncoder::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("AbsoluteEncoder"); diff --git a/wpilibc/src/main/native/cpp/AnalogGyro.cpp b/wpilibc/src/main/native/cpp/AnalogGyro.cpp index d04b3dc307..867d1c618f 100644 --- a/wpilibc/src/main/native/cpp/AnalogGyro.cpp +++ b/wpilibc/src/main/native/cpp/AnalogGyro.cpp @@ -62,10 +62,14 @@ AnalogGyro::AnalogGyro(std::shared_ptr channel, int center, } } -AnalogGyro::~AnalogGyro() { HAL_FreeAnalogGyro(m_gyroHandle); } +AnalogGyro::~AnalogGyro() { + HAL_FreeAnalogGyro(m_gyroHandle); +} double AnalogGyro::GetAngle() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double value = HAL_GetAnalogGyroAngle(m_gyroHandle, &status); wpi_setHALError(status); @@ -73,7 +77,9 @@ double AnalogGyro::GetAngle() const { } double AnalogGyro::GetRate() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double value = HAL_GetAnalogGyroRate(m_gyroHandle, &status); wpi_setHALError(status); @@ -81,7 +87,9 @@ double AnalogGyro::GetRate() const { } int AnalogGyro::GetCenter() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int value = HAL_GetAnalogGyroCenter(m_gyroHandle, &status); wpi_setHALError(status); @@ -89,7 +97,9 @@ int AnalogGyro::GetCenter() const { } double AnalogGyro::GetOffset() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double value = HAL_GetAnalogGyroOffset(m_gyroHandle, &status); wpi_setHALError(status); @@ -104,21 +114,27 @@ void AnalogGyro::SetSensitivity(double voltsPerDegreePerSecond) { } void AnalogGyro::SetDeadband(double volts) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogGyroDeadband(m_gyroHandle, volts, &status); wpi_setHALError(status); } void AnalogGyro::Reset() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_ResetAnalogGyro(m_gyroHandle, &status); wpi_setHALError(status); } void AnalogGyro::InitGyro() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } if (m_gyroHandle == HAL_kInvalidHandle) { int32_t status = 0; m_gyroHandle = HAL_InitializeAnalogGyro(m_analog->m_port, &status); @@ -153,7 +169,9 @@ void AnalogGyro::InitGyro() { } void AnalogGyro::Calibrate() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_CalibrateAnalogGyro(m_gyroHandle, &status); wpi_setHALError(status); diff --git a/wpilibc/src/main/native/cpp/AnalogInput.cpp b/wpilibc/src/main/native/cpp/AnalogInput.cpp index ef0aff7b83..b67120dbf2 100644 --- a/wpilibc/src/main/native/cpp/AnalogInput.cpp +++ b/wpilibc/src/main/native/cpp/AnalogInput.cpp @@ -42,10 +42,14 @@ AnalogInput::AnalogInput(int channel) { SendableRegistry::GetInstance().AddLW(this, "AnalogInput", channel); } -AnalogInput::~AnalogInput() { HAL_FreeAnalogInputPort(m_port); } +AnalogInput::~AnalogInput() { + HAL_FreeAnalogInputPort(m_port); +} int AnalogInput::GetValue() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int value = HAL_GetAnalogValue(m_port, &status); wpi_setHALError(status); @@ -53,7 +57,9 @@ int AnalogInput::GetValue() const { } int AnalogInput::GetAverageValue() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int value = HAL_GetAnalogAverageValue(m_port, &status); wpi_setHALError(status); @@ -61,7 +67,9 @@ int AnalogInput::GetAverageValue() const { } double AnalogInput::GetVoltage() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double voltage = HAL_GetAnalogVoltage(m_port, &status); wpi_setHALError(status); @@ -69,7 +77,9 @@ double AnalogInput::GetVoltage() const { } double AnalogInput::GetAverageVoltage() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double voltage = HAL_GetAnalogAverageVoltage(m_port, &status); wpi_setHALError(status); @@ -77,12 +87,16 @@ double AnalogInput::GetAverageVoltage() const { } int AnalogInput::GetChannel() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } return m_channel; } void AnalogInput::SetAverageBits(int bits) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogAverageBits(m_port, bits, &status); wpi_setHALError(status); @@ -96,14 +110,18 @@ int AnalogInput::GetAverageBits() const { } void AnalogInput::SetOversampleBits(int bits) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogOversampleBits(m_port, bits, &status); wpi_setHALError(status); } int AnalogInput::GetOversampleBits() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int oversampleBits = HAL_GetAnalogOversampleBits(m_port, &status); wpi_setHALError(status); @@ -111,7 +129,9 @@ int AnalogInput::GetOversampleBits() const { } int AnalogInput::GetLSBWeight() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int lsbWeight = HAL_GetAnalogLSBWeight(m_port, &status); wpi_setHALError(status); @@ -119,7 +139,9 @@ int AnalogInput::GetLSBWeight() const { } int AnalogInput::GetOffset() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int offset = HAL_GetAnalogOffset(m_port, &status); wpi_setHALError(status); @@ -127,7 +149,9 @@ int AnalogInput::GetOffset() const { } bool AnalogInput::IsAccumulatorChannel() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool isAccum = HAL_IsAccumulatorChannel(m_port, &status); wpi_setHALError(status); @@ -135,7 +159,9 @@ bool AnalogInput::IsAccumulatorChannel() const { } void AnalogInput::InitAccumulator() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } m_accumulatorOffset = 0; int32_t status = 0; HAL_InitAccumulator(m_port, &status); @@ -143,12 +169,16 @@ void AnalogInput::InitAccumulator() { } void AnalogInput::SetAccumulatorInitialValue(int64_t initialValue) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } m_accumulatorOffset = initialValue; } void AnalogInput::ResetAccumulator() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_ResetAccumulator(m_port, &status); wpi_setHALError(status); @@ -164,21 +194,27 @@ void AnalogInput::ResetAccumulator() { } void AnalogInput::SetAccumulatorCenter(int center) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAccumulatorCenter(m_port, center, &status); wpi_setHALError(status); } void AnalogInput::SetAccumulatorDeadband(int deadband) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAccumulatorDeadband(m_port, deadband, &status); wpi_setHALError(status); } int64_t AnalogInput::GetAccumulatorValue() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int64_t value = HAL_GetAccumulatorValue(m_port, &status); wpi_setHALError(status); @@ -186,7 +222,9 @@ int64_t AnalogInput::GetAccumulatorValue() const { } int64_t AnalogInput::GetAccumulatorCount() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int64_t count = HAL_GetAccumulatorCount(m_port, &status); wpi_setHALError(status); @@ -194,7 +232,9 @@ int64_t AnalogInput::GetAccumulatorCount() const { } void AnalogInput::GetAccumulatorOutput(int64_t& value, int64_t& count) const { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_GetAccumulatorOutput(m_port, &value, &count, &status); wpi_setHALError(status); @@ -215,7 +255,9 @@ double AnalogInput::GetSampleRate() { } double AnalogInput::PIDGet() { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } return GetAverageVoltage(); } diff --git a/wpilibc/src/main/native/cpp/AnalogOutput.cpp b/wpilibc/src/main/native/cpp/AnalogOutput.cpp index 440201766e..1c3e2b061a 100644 --- a/wpilibc/src/main/native/cpp/AnalogOutput.cpp +++ b/wpilibc/src/main/native/cpp/AnalogOutput.cpp @@ -44,7 +44,9 @@ AnalogOutput::AnalogOutput(int channel) { SendableRegistry::GetInstance().AddLW(this, "AnalogOutput", m_channel); } -AnalogOutput::~AnalogOutput() { HAL_FreeAnalogOutputPort(m_port); } +AnalogOutput::~AnalogOutput() { + HAL_FreeAnalogOutputPort(m_port); +} void AnalogOutput::SetVoltage(double voltage) { int32_t status = 0; @@ -62,7 +64,9 @@ double AnalogOutput::GetVoltage() const { return voltage; } -int AnalogOutput::GetChannel() const { return m_channel; } +int AnalogOutput::GetChannel() const { + return m_channel; +} void AnalogOutput::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Analog Output"); diff --git a/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp b/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp index 21aa9fb4fd..e16bab4d29 100644 --- a/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp +++ b/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp @@ -38,7 +38,9 @@ double AnalogPotentiometer::Get() const { m_offset; } -double AnalogPotentiometer::PIDGet() { return Get(); } +double AnalogPotentiometer::PIDGet() { + return Get(); +} void AnalogPotentiometer::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Analog Input"); diff --git a/wpilibc/src/main/native/cpp/AnalogTrigger.cpp b/wpilibc/src/main/native/cpp/AnalogTrigger.cpp index 4f8c8eb8ff..6b547b3e1e 100644 --- a/wpilibc/src/main/native/cpp/AnalogTrigger.cpp +++ b/wpilibc/src/main/native/cpp/AnalogTrigger.cpp @@ -83,42 +83,54 @@ AnalogTrigger& AnalogTrigger::operator=(AnalogTrigger&& rhs) { } void AnalogTrigger::SetLimitsVoltage(double lower, double upper) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status); wpi_setHALError(status); } void AnalogTrigger::SetLimitsDutyCycle(double lower, double upper) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogTriggerLimitsDutyCycle(m_trigger, lower, upper, &status); wpi_setHALError(status); } void AnalogTrigger::SetLimitsRaw(int lower, int upper) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status); wpi_setHALError(status); } void AnalogTrigger::SetAveraged(bool useAveragedValue) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogTriggerAveraged(m_trigger, useAveragedValue, &status); wpi_setHALError(status); } void AnalogTrigger::SetFiltered(bool useFilteredValue) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetAnalogTriggerFiltered(m_trigger, useFilteredValue, &status); wpi_setHALError(status); } int AnalogTrigger::GetIndex() const { - if (StatusIsFatal()) return -1; + if (StatusIsFatal()) { + return -1; + } int32_t status = 0; auto ret = HAL_GetAnalogTriggerFPGAIndex(m_trigger, &status); wpi_setHALError(status); @@ -126,7 +138,9 @@ int AnalogTrigger::GetIndex() const { } bool AnalogTrigger::GetInWindow() { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool result = HAL_GetAnalogTriggerInWindow(m_trigger, &status); wpi_setHALError(status); @@ -134,7 +148,9 @@ bool AnalogTrigger::GetInWindow() { } bool AnalogTrigger::GetTriggerState() { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool result = HAL_GetAnalogTriggerTriggerState(m_trigger, &status); wpi_setHALError(status); @@ -143,11 +159,15 @@ bool AnalogTrigger::GetTriggerState() { std::shared_ptr AnalogTrigger::CreateOutput( AnalogTriggerType type) const { - if (StatusIsFatal()) return nullptr; + if (StatusIsFatal()) { + return nullptr; + } return std::shared_ptr( new AnalogTriggerOutput(*this, type), NullDeleter()); } void AnalogTrigger::InitSendable(SendableBuilder& builder) { - if (m_ownsAnalog) m_analogInput->InitSendable(builder); + if (m_ownsAnalog) { + m_analogInput->InitSendable(builder); + } } diff --git a/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp b/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp index f0f0a4b0e3..a9b8fb4b7f 100644 --- a/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp +++ b/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp @@ -28,9 +28,13 @@ AnalogTriggerType AnalogTriggerOutput::GetAnalogTriggerTypeForRouting() const { return m_outputType; } -bool AnalogTriggerOutput::IsAnalogTrigger() const { return true; } +bool AnalogTriggerOutput::IsAnalogTrigger() const { + return true; +} -int AnalogTriggerOutput::GetChannel() const { return m_trigger->GetIndex(); } +int AnalogTriggerOutput::GetChannel() const { + return m_trigger->GetIndex(); +} void AnalogTriggerOutput::InitSendable(SendableBuilder&) {} diff --git a/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp b/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp index 0b1290abfb..1a3d79837d 100644 --- a/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp +++ b/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp @@ -32,11 +32,17 @@ void BuiltInAccelerometer::SetRange(Range range) { HAL_SetAccelerometerActive(true); } -double BuiltInAccelerometer::GetX() { return HAL_GetAccelerometerX(); } +double BuiltInAccelerometer::GetX() { + return HAL_GetAccelerometerX(); +} -double BuiltInAccelerometer::GetY() { return HAL_GetAccelerometerY(); } +double BuiltInAccelerometer::GetY() { + return HAL_GetAccelerometerY(); +} -double BuiltInAccelerometer::GetZ() { return HAL_GetAccelerometerZ(); } +double BuiltInAccelerometer::GetZ() { + return HAL_GetAccelerometerZ(); +} void BuiltInAccelerometer::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("3AxisAccelerometer"); diff --git a/wpilibc/src/main/native/cpp/CAN.cpp b/wpilibc/src/main/native/cpp/CAN.cpp index 6ae9f8a558..ee2003bd7a 100644 --- a/wpilibc/src/main/native/cpp/CAN.cpp +++ b/wpilibc/src/main/native/cpp/CAN.cpp @@ -41,7 +41,9 @@ CAN::CAN(int deviceId, int deviceManufacturer, int deviceType) { } CAN::~CAN() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } if (m_handle != HAL_kInvalidHandle) { HAL_CleanCAN(m_handle); m_handle = HAL_kInvalidHandle; diff --git a/wpilibc/src/main/native/cpp/Compressor.cpp b/wpilibc/src/main/native/cpp/Compressor.cpp index 3536ab7941..88e5eb6415 100644 --- a/wpilibc/src/main/native/cpp/Compressor.cpp +++ b/wpilibc/src/main/native/cpp/Compressor.cpp @@ -29,17 +29,23 @@ Compressor::Compressor(int pcmID) : m_module(pcmID) { } void Compressor::Start() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } SetClosedLoopControl(true); } void Compressor::Stop() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } SetClosedLoopControl(false); } bool Compressor::Enabled() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -53,7 +59,9 @@ bool Compressor::Enabled() const { } bool Compressor::GetPressureSwitchValue() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -67,7 +75,9 @@ bool Compressor::GetPressureSwitchValue() const { } double Compressor::GetCompressorCurrent() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; double value; @@ -81,7 +91,9 @@ double Compressor::GetCompressorCurrent() const { } void Compressor::SetClosedLoopControl(bool on) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCompressorClosedLoopControl(m_compressorHandle, on, &status); @@ -92,7 +104,9 @@ void Compressor::SetClosedLoopControl(bool on) { } bool Compressor::GetClosedLoopControl() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -106,7 +120,9 @@ bool Compressor::GetClosedLoopControl() const { } bool Compressor::GetCompressorCurrentTooHighFault() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -120,7 +136,9 @@ bool Compressor::GetCompressorCurrentTooHighFault() const { } bool Compressor::GetCompressorCurrentTooHighStickyFault() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -135,7 +153,9 @@ bool Compressor::GetCompressorCurrentTooHighStickyFault() const { } bool Compressor::GetCompressorShortedStickyFault() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -149,7 +169,9 @@ bool Compressor::GetCompressorShortedStickyFault() const { } bool Compressor::GetCompressorShortedFault() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -163,7 +185,9 @@ bool Compressor::GetCompressorShortedFault() const { } bool Compressor::GetCompressorNotConnectedStickyFault() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -177,7 +201,9 @@ bool Compressor::GetCompressorNotConnectedStickyFault() const { } bool Compressor::GetCompressorNotConnectedFault() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value; @@ -191,7 +217,9 @@ bool Compressor::GetCompressorNotConnectedFault() const { } void Compressor::ClearAllPCMStickyFaults() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_ClearAllPCMStickyFaults(m_module, &status); @@ -201,17 +229,20 @@ void Compressor::ClearAllPCMStickyFaults() { } } -int Compressor::GetModule() const { return m_module; } +int Compressor::GetModule() const { + return m_module; +} void Compressor::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Compressor"); builder.AddBooleanProperty( "Enabled", [=]() { return Enabled(); }, [=](bool value) { - if (value) + if (value) { Start(); - else + } else { Stop(); + } }); builder.AddBooleanProperty( "Pressure switch", [=]() { return GetPressureSwitchValue(); }, nullptr); diff --git a/wpilibc/src/main/native/cpp/Counter.cpp b/wpilibc/src/main/native/cpp/Counter.cpp index 5af93d776b..c12b43be4b 100644 --- a/wpilibc/src/main/native/cpp/Counter.cpp +++ b/wpilibc/src/main/native/cpp/Counter.cpp @@ -93,7 +93,9 @@ Counter::~Counter() { } void Counter::SetUpSource(int channel) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } SetUpSource(std::make_shared(channel)); SendableRegistry::GetInstance().AddChild(this, m_upSource.get()); } @@ -107,7 +109,9 @@ void Counter::SetUpSource(AnalogTrigger* analogTrigger, void Counter::SetUpSource(std::shared_ptr analogTrigger, AnalogTriggerType triggerType) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } SetUpSource(analogTrigger->CreateOutput(triggerType)); } @@ -117,7 +121,9 @@ void Counter::SetUpSource(DigitalSource* source) { } void Counter::SetUpSource(std::shared_ptr source) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } m_upSource = source; if (m_upSource->StatusIsFatal()) { CloneError(*m_upSource); @@ -137,7 +143,9 @@ void Counter::SetUpSource(DigitalSource& source) { } void Counter::SetUpSourceEdge(bool risingEdge, bool fallingEdge) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } if (m_upSource == nullptr) { wpi_setWPIErrorWithContext( NullParameter, @@ -149,7 +157,9 @@ void Counter::SetUpSourceEdge(bool risingEdge, bool fallingEdge) { } void Counter::ClearUpSource() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } m_upSource.reset(); int32_t status = 0; HAL_ClearCounterUpSource(m_counter, &status); @@ -157,7 +167,9 @@ void Counter::ClearUpSource() { } void Counter::SetDownSource(int channel) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } SetDownSource(std::make_shared(channel)); SendableRegistry::GetInstance().AddChild(this, m_downSource.get()); } @@ -171,7 +183,9 @@ void Counter::SetDownSource(AnalogTrigger* analogTrigger, void Counter::SetDownSource(std::shared_ptr analogTrigger, AnalogTriggerType triggerType) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } SetDownSource(analogTrigger->CreateOutput(triggerType)); } @@ -186,7 +200,9 @@ void Counter::SetDownSource(DigitalSource& source) { } void Counter::SetDownSource(std::shared_ptr source) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } m_downSource = source; if (m_downSource->StatusIsFatal()) { CloneError(*m_downSource); @@ -201,7 +217,9 @@ void Counter::SetDownSource(std::shared_ptr source) { } void Counter::SetDownSourceEdge(bool risingEdge, bool fallingEdge) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } if (m_downSource == nullptr) { wpi_setWPIErrorWithContext( NullParameter, @@ -213,7 +231,9 @@ void Counter::SetDownSourceEdge(bool risingEdge, bool fallingEdge) { } void Counter::ClearDownSource() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } m_downSource.reset(); int32_t status = 0; HAL_ClearCounterDownSource(m_counter, &status); @@ -221,35 +241,45 @@ void Counter::ClearDownSource() { } void Counter::SetUpDownCounterMode() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCounterUpDownMode(m_counter, &status); wpi_setHALError(status); } void Counter::SetExternalDirectionMode() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCounterExternalDirectionMode(m_counter, &status); wpi_setHALError(status); } void Counter::SetSemiPeriodMode(bool highSemiPeriod) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCounterSemiPeriodMode(m_counter, highSemiPeriod, &status); wpi_setHALError(status); } void Counter::SetPulseLengthMode(double threshold) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCounterPulseLengthMode(m_counter, threshold, &status); wpi_setHALError(status); } void Counter::SetReverseDirection(bool reverseDirection) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCounterReverseDirection(m_counter, reverseDirection, &status); wpi_setHALError(status); @@ -273,10 +303,14 @@ int Counter::GetSamplesToAverage() const { return samples; } -int Counter::GetFPGAIndex() const { return m_index; } +int Counter::GetFPGAIndex() const { + return m_index; +} int Counter::Get() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int value = HAL_GetCounter(m_counter, &status); wpi_setHALError(status); @@ -284,14 +318,18 @@ int Counter::Get() const { } void Counter::Reset() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_ResetCounter(m_counter, &status); wpi_setHALError(status); } double Counter::GetPeriod() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double value = HAL_GetCounterPeriod(m_counter, &status); wpi_setHALError(status); @@ -299,21 +337,27 @@ double Counter::GetPeriod() const { } void Counter::SetMaxPeriod(double maxPeriod) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCounterMaxPeriod(m_counter, maxPeriod, &status); wpi_setHALError(status); } void Counter::SetUpdateWhenEmpty(bool enabled) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetCounterUpdateWhenEmpty(m_counter, enabled, &status); wpi_setHALError(status); } bool Counter::GetStopped() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value = HAL_GetCounterStopped(m_counter, &status); wpi_setHALError(status); @@ -321,7 +365,9 @@ bool Counter::GetStopped() const { } bool Counter::GetDirection() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value = HAL_GetCounterDirection(m_counter, &status); wpi_setHALError(status); diff --git a/wpilibc/src/main/native/cpp/DMA.cpp b/wpilibc/src/main/native/cpp/DMA.cpp index 896fdfd131..87164f9a94 100644 --- a/wpilibc/src/main/native/cpp/DMA.cpp +++ b/wpilibc/src/main/native/cpp/DMA.cpp @@ -21,7 +21,9 @@ DMA::DMA() { wpi_setErrorWithContext(status, HAL_GetErrorMessage(status)); } -DMA::~DMA() { HAL_FreeDMA(dmaHandle); } +DMA::~DMA() { + HAL_FreeDMA(dmaHandle); +} void DMA::SetPause(bool pause) { int32_t status = 0; diff --git a/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp b/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp index 41c207995d..0ff4ed93aa 100644 --- a/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp +++ b/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp @@ -103,7 +103,9 @@ void DigitalGlitchFilter::Add(Counter* input) { Add(input->m_downSource.get()); } -void DigitalGlitchFilter::Remove(DigitalSource* input) { DoAdd(input, 0); } +void DigitalGlitchFilter::Remove(DigitalSource* input) { + DoAdd(input, 0); +} void DigitalGlitchFilter::Remove(Encoder* input) { Remove(input->m_aSource.get()); diff --git a/wpilibc/src/main/native/cpp/DigitalInput.cpp b/wpilibc/src/main/native/cpp/DigitalInput.cpp index 4732ccbbee..51a8495462 100644 --- a/wpilibc/src/main/native/cpp/DigitalInput.cpp +++ b/wpilibc/src/main/native/cpp/DigitalInput.cpp @@ -41,31 +41,41 @@ DigitalInput::DigitalInput(int channel) { } DigitalInput::~DigitalInput() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } HAL_FreeDIOPort(m_handle); } bool DigitalInput::Get() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value = HAL_GetDIO(m_handle, &status); wpi_setHALError(status); return value; } -HAL_Handle DigitalInput::GetPortHandleForRouting() const { return m_handle; } +HAL_Handle DigitalInput::GetPortHandleForRouting() const { + return m_handle; +} AnalogTriggerType DigitalInput::GetAnalogTriggerTypeForRouting() const { return (AnalogTriggerType)0; } -bool DigitalInput::IsAnalogTrigger() const { return false; } +bool DigitalInput::IsAnalogTrigger() const { + return false; +} void DigitalInput::SetSimDevice(HAL_SimDeviceHandle device) { HAL_SetDIOSimDevice(m_handle, device); } -int DigitalInput::GetChannel() const { return m_channel; } +int DigitalInput::GetChannel() const { + return m_channel; +} void DigitalInput::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Digital Input"); diff --git a/wpilibc/src/main/native/cpp/DigitalOutput.cpp b/wpilibc/src/main/native/cpp/DigitalOutput.cpp index 0c197eb461..3601c7ecf7 100644 --- a/wpilibc/src/main/native/cpp/DigitalOutput.cpp +++ b/wpilibc/src/main/native/cpp/DigitalOutput.cpp @@ -42,7 +42,9 @@ DigitalOutput::DigitalOutput(int channel) { } DigitalOutput::~DigitalOutput() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } // Disable the PWM in case it was running. DisablePWM(); @@ -50,7 +52,9 @@ DigitalOutput::~DigitalOutput() { } void DigitalOutput::Set(bool value) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetDIO(m_handle, value, &status); @@ -58,7 +62,9 @@ void DigitalOutput::Set(bool value) { } bool DigitalOutput::Get() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool val = HAL_GetDIO(m_handle, &status); @@ -66,18 +72,26 @@ bool DigitalOutput::Get() const { return val; } -HAL_Handle DigitalOutput::GetPortHandleForRouting() const { return m_handle; } +HAL_Handle DigitalOutput::GetPortHandleForRouting() const { + return m_handle; +} AnalogTriggerType DigitalOutput::GetAnalogTriggerTypeForRouting() const { return (AnalogTriggerType)0; } -bool DigitalOutput::IsAnalogTrigger() const { return false; } +bool DigitalOutput::IsAnalogTrigger() const { + return false; +} -int DigitalOutput::GetChannel() const { return m_channel; } +int DigitalOutput::GetChannel() const { + return m_channel; +} void DigitalOutput::Pulse(double length) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_Pulse(m_handle, length, &status); @@ -85,7 +99,9 @@ void DigitalOutput::Pulse(double length) { } bool DigitalOutput::IsPulsing() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value = HAL_IsPulsing(m_handle, &status); @@ -94,7 +110,9 @@ bool DigitalOutput::IsPulsing() const { } void DigitalOutput::SetPWMRate(double rate) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetDigitalPWMRate(rate, &status); @@ -102,26 +120,38 @@ void DigitalOutput::SetPWMRate(double rate) { } void DigitalOutput::EnablePWM(double initialDutyCycle) { - if (m_pwmGenerator != HAL_kInvalidHandle) return; + if (m_pwmGenerator != HAL_kInvalidHandle) { + return; + } int32_t status = 0; - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } m_pwmGenerator = HAL_AllocateDigitalPWM(&status); wpi_setHALError(status); - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } HAL_SetDigitalPWMDutyCycle(m_pwmGenerator, initialDutyCycle, &status); wpi_setHALError(status); - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } HAL_SetDigitalPWMOutputChannel(m_pwmGenerator, m_channel, &status); wpi_setHALError(status); } void DigitalOutput::DisablePWM() { - if (StatusIsFatal()) return; - if (m_pwmGenerator == HAL_kInvalidHandle) return; + if (StatusIsFatal()) { + return; + } + if (m_pwmGenerator == HAL_kInvalidHandle) { + return; + } int32_t status = 0; @@ -137,7 +167,9 @@ void DigitalOutput::DisablePWM() { } void DigitalOutput::UpdateDutyCycle(double dutyCycle) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetDigitalPWMDutyCycle(m_pwmGenerator, dutyCycle, &status); diff --git a/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp b/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp index e3d97f55ed..ec8af951aa 100644 --- a/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp +++ b/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp @@ -85,7 +85,9 @@ DoubleSolenoid::~DoubleSolenoid() { } void DoubleSolenoid::Set(Value value) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } bool forward = false; bool reverse = false; @@ -115,7 +117,9 @@ void DoubleSolenoid::Set(Value value) { } DoubleSolenoid::Value DoubleSolenoid::Get() const { - if (StatusIsFatal()) return kOff; + if (StatusIsFatal()) { + return kOff; + } int fstatus = 0; int rstatus = 0; @@ -172,10 +176,11 @@ void DoubleSolenoid::InitSendable(SendableBuilder& builder) { }, [=](wpi::StringRef value) { Value lvalue = kOff; - if (value == "Forward") + if (value == "Forward") { lvalue = kForward; - else if (value == "Reverse") + } else if (value == "Reverse") { lvalue = kReverse; + } Set(lvalue); }); } diff --git a/wpilibc/src/main/native/cpp/DriverStation.cpp b/wpilibc/src/main/native/cpp/DriverStation.cpp index 308c89c9ad..2cce5f6c53 100644 --- a/wpilibc/src/main/native/cpp/DriverStation.cpp +++ b/wpilibc/src/main/native/cpp/DriverStation.cpp @@ -421,7 +421,9 @@ bool DriverStation::IsNewControlData() const { std::unique_lock lock(m_waitForDataMutex); int& lastCount = GetDSLastCount(); int currentCount = m_waitForDataCounter; - if (lastCount == currentCount) return false; + if (lastCount == currentCount) { + return false; + } lastCount = currentCount; return true; } @@ -498,7 +500,9 @@ int DriverStation::GetLocation() const { } } -void DriverStation::WaitForData() { WaitForData(0); } +void DriverStation::WaitForData() { + WaitForData(0); +} bool DriverStation::WaitForData(double timeout) { auto timeoutTime = @@ -621,16 +625,26 @@ void DriverStation::Run() { HAL_WaitForDSData(); GetData(); - if (IsDisabled()) safetyCounter = 0; + if (IsDisabled()) { + safetyCounter = 0; + } if (++safetyCounter >= 4) { MotorSafety::CheckMotors(); safetyCounter = 0; } - if (m_userInDisabled) HAL_ObserveUserProgramDisabled(); - if (m_userInAutonomous) HAL_ObserveUserProgramAutonomous(); - if (m_userInTeleop) HAL_ObserveUserProgramTeleop(); - if (m_userInTest) HAL_ObserveUserProgramTest(); + if (m_userInDisabled) { + HAL_ObserveUserProgramDisabled(); + } + if (m_userInAutonomous) { + HAL_ObserveUserProgramAutonomous(); + } + if (m_userInTeleop) { + HAL_ObserveUserProgramTeleop(); + } + if (m_userInTest) { + HAL_ObserveUserProgramTest(); + } } } diff --git a/wpilibc/src/main/native/cpp/DutyCycle.cpp b/wpilibc/src/main/native/cpp/DutyCycle.cpp index 73e2062ebe..6ffcd9713d 100644 --- a/wpilibc/src/main/native/cpp/DutyCycle.cpp +++ b/wpilibc/src/main/native/cpp/DutyCycle.cpp @@ -37,7 +37,9 @@ DutyCycle::DutyCycle(std::shared_ptr source) } } -DutyCycle::~DutyCycle() { HAL_FreeDutyCycle(m_handle); } +DutyCycle::~DutyCycle() { + HAL_FreeDutyCycle(m_handle); +} void DutyCycle::InitDutyCycle() { int32_t status = 0; @@ -87,7 +89,9 @@ unsigned int DutyCycle::GetOutputScaleFactor() const { return retVal; } -int DutyCycle::GetSourceChannel() const { return m_source->GetChannel(); } +int DutyCycle::GetSourceChannel() const { + return m_source->GetChannel(); +} void DutyCycle::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Duty Cycle"); diff --git a/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp b/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp index f6c4b20e1b..d3dc95c337 100644 --- a/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp +++ b/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp @@ -76,7 +76,9 @@ void DutyCycleEncoder::Init() { } units::turn_t DutyCycleEncoder::Get() const { - if (m_simPosition) return units::turn_t{m_simPosition.Get()}; + if (m_simPosition) { + return units::turn_t{m_simPosition.Get()}; + } // As the values are not atomic, keep trying until we get 2 reads of the same // value If we don't within 10 attempts, error @@ -116,12 +118,16 @@ int DutyCycleEncoder::GetFrequency() const { } void DutyCycleEncoder::Reset() { - if (m_counter) m_counter->Reset(); + if (m_counter) { + m_counter->Reset(); + } m_positionOffset = m_dutyCycle->GetOutput(); } bool DutyCycleEncoder::IsConnected() const { - if (m_simIsConnected) return m_simIsConnected.Get(); + if (m_simIsConnected) { + return m_simIsConnected.Get(); + } return GetFrequency() > m_frequencyThreshold; } diff --git a/wpilibc/src/main/native/cpp/Encoder.cpp b/wpilibc/src/main/native/cpp/Encoder.cpp index 0af92fc61b..d469917e6b 100644 --- a/wpilibc/src/main/native/cpp/Encoder.cpp +++ b/wpilibc/src/main/native/cpp/Encoder.cpp @@ -31,10 +31,11 @@ Encoder::Encoder(DigitalSource* aSource, DigitalSource* bSource, bool reverseDirection, EncodingType encodingType) : m_aSource(aSource, NullDeleter()), m_bSource(bSource, NullDeleter()) { - if (m_aSource == nullptr || m_bSource == nullptr) + if (m_aSource == nullptr || m_bSource == nullptr) { wpi_setWPIError(NullParameter); - else + } else { InitEncoder(reverseDirection, encodingType); + } } Encoder::Encoder(DigitalSource& aSource, DigitalSource& bSource, @@ -48,10 +49,11 @@ Encoder::Encoder(std::shared_ptr aSource, std::shared_ptr bSource, bool reverseDirection, EncodingType encodingType) : m_aSource(aSource), m_bSource(bSource) { - if (m_aSource == nullptr || m_bSource == nullptr) + if (m_aSource == nullptr || m_bSource == nullptr) { wpi_setWPIError(NullParameter); - else + } else { InitEncoder(reverseDirection, encodingType); + } } Encoder::~Encoder() { @@ -61,7 +63,9 @@ Encoder::~Encoder() { } int Encoder::Get() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int value = HAL_GetEncoder(m_encoder, &status); wpi_setHALError(status); @@ -69,14 +73,18 @@ int Encoder::Get() const { } void Encoder::Reset() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_ResetEncoder(m_encoder, &status); wpi_setHALError(status); } double Encoder::GetPeriod() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double value = HAL_GetEncoderPeriod(m_encoder, &status); wpi_setHALError(status); @@ -84,14 +92,18 @@ double Encoder::GetPeriod() const { } void Encoder::SetMaxPeriod(double maxPeriod) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetEncoderMaxPeriod(m_encoder, maxPeriod, &status); wpi_setHALError(status); } bool Encoder::GetStopped() const { - if (StatusIsFatal()) return true; + if (StatusIsFatal()) { + return true; + } int32_t status = 0; bool value = HAL_GetEncoderStopped(m_encoder, &status); wpi_setHALError(status); @@ -99,7 +111,9 @@ bool Encoder::GetStopped() const { } bool Encoder::GetDirection() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value = HAL_GetEncoderDirection(m_encoder, &status); wpi_setHALError(status); @@ -107,7 +121,9 @@ bool Encoder::GetDirection() const { } int Encoder::GetRaw() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; int value = HAL_GetEncoderRaw(m_encoder, &status); wpi_setHALError(status); @@ -122,7 +138,9 @@ int Encoder::GetEncodingScale() const { } double Encoder::GetDistance() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double value = HAL_GetEncoderDistance(m_encoder, &status); wpi_setHALError(status); @@ -130,7 +148,9 @@ double Encoder::GetDistance() const { } double Encoder::GetRate() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double value = HAL_GetEncoderRate(m_encoder, &status); wpi_setHALError(status); @@ -138,21 +158,27 @@ double Encoder::GetRate() const { } void Encoder::SetMinRate(double minRate) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetEncoderMinRate(m_encoder, minRate, &status); wpi_setHALError(status); } void Encoder::SetDistancePerPulse(double distancePerPulse) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetEncoderDistancePerPulse(m_encoder, distancePerPulse, &status); wpi_setHALError(status); } double Encoder::GetDistancePerPulse() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double distancePerPulse = HAL_GetEncoderDistancePerPulse(m_encoder, &status); wpi_setHALError(status); @@ -160,7 +186,9 @@ double Encoder::GetDistancePerPulse() const { } void Encoder::SetReverseDirection(bool reverseDirection) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetEncoderReverseDirection(m_encoder, reverseDirection, &status); wpi_setHALError(status); @@ -186,7 +214,9 @@ int Encoder::GetSamplesToAverage() const { } double Encoder::PIDGet() { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } switch (GetPIDSourceType()) { case PIDSourceType::kDisplacement: return GetDistance(); @@ -229,10 +259,11 @@ void Encoder::InitSendable(SendableBuilder& builder) { int32_t status = 0; HAL_EncoderEncodingType type = HAL_GetEncoderEncodingType(m_encoder, &status); wpi_setHALError(status); - if (type == HAL_EncoderEncodingType::HAL_Encoder_k4X) + if (type == HAL_EncoderEncodingType::HAL_Encoder_k4X) { builder.SetSmartDashboardType("Quadrature Encoder"); - else + } else { builder.SetSmartDashboardType("Encoder"); + } builder.AddDoubleProperty( "Speed", [=]() { return GetRate(); }, nullptr); @@ -259,7 +290,9 @@ void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) { } double Encoder::DecodingScaleFactor() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double val = HAL_GetEncoderDecodingScaleFactor(m_encoder, &status); wpi_setHALError(status); diff --git a/wpilibc/src/main/native/cpp/Error.cpp b/wpilibc/src/main/native/cpp/Error.cpp index f0cbebe432..383bde3830 100644 --- a/wpilibc/src/main/native/cpp/Error.cpp +++ b/wpilibc/src/main/native/cpp/Error.cpp @@ -39,21 +39,33 @@ bool Error::operator<(const Error& rhs) const { } } -Error::Code Error::GetCode() const { return m_code; } +Error::Code Error::GetCode() const { + return m_code; +} -std::string Error::GetMessage() const { return m_message; } +std::string Error::GetMessage() const { + return m_message; +} -std::string Error::GetFilename() const { return m_filename; } +std::string Error::GetFilename() const { + return m_filename; +} -std::string Error::GetFunction() const { return m_function; } +std::string Error::GetFunction() const { + return m_function; +} -int Error::GetLineNumber() const { return m_lineNumber; } +int Error::GetLineNumber() const { + return m_lineNumber; +} const ErrorBase* Error::GetOriginatingObject() const { return m_originatingObject; } -double Error::GetTimestamp() const { return m_timestamp; } +double Error::GetTimestamp() const { + return m_timestamp; +} void Error::Set(Code code, const wpi::Twine& contextMessage, wpi::StringRef filename, wpi::StringRef function, diff --git a/wpilibc/src/main/native/cpp/ErrorBase.cpp b/wpilibc/src/main/native/cpp/ErrorBase.cpp index 702f5ba25d..e6c3c9c241 100644 --- a/wpilibc/src/main/native/cpp/ErrorBase.cpp +++ b/wpilibc/src/main/native/cpp/ErrorBase.cpp @@ -48,13 +48,21 @@ void GlobalErrors::Insert(Error&& error) { inst.lastError = &(*inst.errors.insert(std::move(error)).first); } -ErrorBase::ErrorBase() { HAL_Initialize(500, 0); } +ErrorBase::ErrorBase() { + HAL_Initialize(500, 0); +} -Error& ErrorBase::GetError() { return m_error; } +Error& ErrorBase::GetError() { + return m_error; +} -const Error& ErrorBase::GetError() const { return m_error; } +const Error& ErrorBase::GetError() const { + return m_error; +} -void ErrorBase::ClearError() const { m_error.Clear(); } +void ErrorBase::ClearError() const { + m_error.Clear(); +} void ErrorBase::SetErrnoError(const wpi::Twine& contextMessage, wpi::StringRef filename, wpi::StringRef function, @@ -139,7 +147,9 @@ void ErrorBase::CloneError(const ErrorBase& rhs) const { m_error = rhs.GetError(); } -bool ErrorBase::StatusIsFatal() const { return m_error.GetCode() < 0; } +bool ErrorBase::StatusIsFatal() const { + return m_error.GetCode() < 0; +} void ErrorBase::SetGlobalError(Error::Code code, const wpi::Twine& contextMessage, @@ -164,7 +174,9 @@ void ErrorBase::SetGlobalWPIError(const wpi::Twine& errorMessage, Error ErrorBase::GetGlobalError() { auto& inst = GlobalErrors::GetInstance(); std::scoped_lock mutex(inst.mutex); - if (!inst.lastError) return Error{}; + if (!inst.lastError) { + return {}; + } return *inst.lastError; } @@ -172,7 +184,9 @@ std::vector ErrorBase::GetGlobalErrors() { auto& inst = GlobalErrors::GetInstance(); std::scoped_lock mutex(inst.mutex); std::vector rv; - for (auto&& error : inst.errors) rv.push_back(error); + for (auto&& error : inst.errors) { + rv.push_back(error); + } return rv; } diff --git a/wpilibc/src/main/native/cpp/GenericHID.cpp b/wpilibc/src/main/native/cpp/GenericHID.cpp index 040a0a95ff..d606b372f8 100644 --- a/wpilibc/src/main/native/cpp/GenericHID.cpp +++ b/wpilibc/src/main/native/cpp/GenericHID.cpp @@ -34,11 +34,17 @@ double GenericHID::GetRawAxis(int axis) const { return m_ds->GetStickAxis(m_port, axis); } -int GenericHID::GetPOV(int pov) const { return m_ds->GetStickPOV(m_port, pov); } +int GenericHID::GetPOV(int pov) const { + return m_ds->GetStickPOV(m_port, pov); +} -int GenericHID::GetAxisCount() const { return m_ds->GetStickAxisCount(m_port); } +int GenericHID::GetAxisCount() const { + return m_ds->GetStickAxisCount(m_port); +} -int GenericHID::GetPOVCount() const { return m_ds->GetStickPOVCount(m_port); } +int GenericHID::GetPOVCount() const { + return m_ds->GetStickPOVCount(m_port); +} int GenericHID::GetButtonCount() const { return m_ds->GetStickButtonCount(m_port); @@ -60,7 +66,9 @@ int GenericHID::GetAxisType(int axis) const { return m_ds->GetJoystickAxisType(m_port, axis); } -int GenericHID::GetPort() const { return m_port; } +int GenericHID::GetPort() const { + return m_port; +} void GenericHID::SetOutput(int outputNumber, bool value) { m_outputs = @@ -75,10 +83,11 @@ void GenericHID::SetOutputs(int value) { } void GenericHID::SetRumble(RumbleType type, double value) { - if (value < 0) + if (value < 0) { value = 0; - else if (value > 1) + } else if (value > 1) { value = 1; + } if (type == kLeftRumble) { m_leftRumble = value * 65535; } else { diff --git a/wpilibc/src/main/native/cpp/I2C.cpp b/wpilibc/src/main/native/cpp/I2C.cpp index 55bc3f5a42..df44730801 100644 --- a/wpilibc/src/main/native/cpp/I2C.cpp +++ b/wpilibc/src/main/native/cpp/I2C.cpp @@ -22,7 +22,9 @@ I2C::I2C(Port port, int deviceAddress) HAL_Report(HALUsageReporting::kResourceType_I2C, deviceAddress); } -I2C::~I2C() { HAL_CloseI2C(m_port); } +I2C::~I2C() { + HAL_CloseI2C(m_port); +} bool I2C::Transaction(uint8_t* dataToSend, int sendSize, uint8_t* dataReceived, int receiveSize) { @@ -33,7 +35,9 @@ bool I2C::Transaction(uint8_t* dataToSend, int sendSize, uint8_t* dataReceived, return status < 0; } -bool I2C::AddressOnly() { return Transaction(nullptr, 0, nullptr, 0); } +bool I2C::AddressOnly() { + return Transaction(nullptr, 0, nullptr, 0); +} bool I2C::Write(int registerAddress, uint8_t data) { uint8_t buffer[2]; @@ -83,10 +87,14 @@ bool I2C::VerifySensor(int registerAddress, int count, i += 4, curRegisterAddress += 4) { int toRead = count - i < 4 ? count - i : 4; // Read the chunk of data. Return false if the sensor does not respond. - if (Read(curRegisterAddress, toRead, deviceData)) return false; + if (Read(curRegisterAddress, toRead, deviceData)) { + return false; + } for (int j = 0; j < toRead; j++) { - if (deviceData[j] != expected[i + j]) return false; + if (deviceData[j] != expected[i + j]) { + return false; + } } } return true; diff --git a/wpilibc/src/main/native/cpp/InterruptableSensorBase.cpp b/wpilibc/src/main/native/cpp/InterruptableSensorBase.cpp index ec98d297b2..1dda99dcc5 100644 --- a/wpilibc/src/main/native/cpp/InterruptableSensorBase.cpp +++ b/wpilibc/src/main/native/cpp/InterruptableSensorBase.cpp @@ -10,7 +10,9 @@ using namespace frc; InterruptableSensorBase::~InterruptableSensorBase() { - if (m_interrupt == HAL_kInvalidHandle) return; + if (m_interrupt == HAL_kInvalidHandle) { + return; + } int32_t status = 0; HAL_CleanInterrupts(m_interrupt, &status); // Ignore status, as an invalid handle just needs to be ignored. @@ -18,11 +20,15 @@ InterruptableSensorBase::~InterruptableSensorBase() { void InterruptableSensorBase::RequestInterrupts( HAL_InterruptHandlerFunction handler, void* param) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } wpi_assert(m_interrupt == HAL_kInvalidHandle); AllocateInterrupts(false); - if (StatusIsFatal()) return; // if allocate failed, out of interrupts + if (StatusIsFatal()) { + return; // if allocate failed, out of interrupts + } int32_t status = 0; HAL_RequestInterrupts( @@ -35,11 +41,15 @@ void InterruptableSensorBase::RequestInterrupts( } void InterruptableSensorBase::RequestInterrupts(InterruptEventHandler handler) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } wpi_assert(m_interrupt == HAL_kInvalidHandle); AllocateInterrupts(false); - if (StatusIsFatal()) return; // if allocate failed, out of interrupts + if (StatusIsFatal()) { + return; // if allocate failed, out of interrupts + } m_interruptHandler = std::make_unique(std::move(handler)); @@ -68,11 +78,15 @@ void InterruptableSensorBase::RequestInterrupts(InterruptEventHandler handler) { } void InterruptableSensorBase::RequestInterrupts() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } wpi_assert(m_interrupt == HAL_kInvalidHandle); AllocateInterrupts(true); - if (StatusIsFatal()) return; // if allocate failed, out of interrupts + if (StatusIsFatal()) { + return; // if allocate failed, out of interrupts + } int32_t status = 0; HAL_RequestInterrupts( @@ -84,7 +98,9 @@ void InterruptableSensorBase::RequestInterrupts() { } void InterruptableSensorBase::CancelInterrupts() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } wpi_assert(m_interrupt != HAL_kInvalidHandle); int32_t status = 0; HAL_CleanInterrupts(m_interrupt, &status); @@ -95,7 +111,9 @@ void InterruptableSensorBase::CancelInterrupts() { InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt( double timeout, bool ignorePrevious) { - if (StatusIsFatal()) return InterruptableSensorBase::kTimeout; + if (StatusIsFatal()) { + return InterruptableSensorBase::kTimeout; + } wpi_assert(m_interrupt != HAL_kInvalidHandle); int32_t status = 0; int result; @@ -113,7 +131,9 @@ InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt( } void InterruptableSensorBase::EnableInterrupts() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } wpi_assert(m_interrupt != HAL_kInvalidHandle); int32_t status = 0; HAL_EnableInterrupts(m_interrupt, &status); @@ -121,7 +141,9 @@ void InterruptableSensorBase::EnableInterrupts() { } void InterruptableSensorBase::DisableInterrupts() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } wpi_assert(m_interrupt != HAL_kInvalidHandle); int32_t status = 0; HAL_DisableInterrupts(m_interrupt, &status); @@ -129,7 +151,9 @@ void InterruptableSensorBase::DisableInterrupts() { } double InterruptableSensorBase::ReadRisingTimestamp() { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } wpi_assert(m_interrupt != HAL_kInvalidHandle); int32_t status = 0; int64_t timestamp = HAL_ReadInterruptRisingTimestamp(m_interrupt, &status); @@ -138,7 +162,9 @@ double InterruptableSensorBase::ReadRisingTimestamp() { } double InterruptableSensorBase::ReadFallingTimestamp() { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } wpi_assert(m_interrupt != HAL_kInvalidHandle); int32_t status = 0; int64_t timestamp = HAL_ReadInterruptFallingTimestamp(m_interrupt, &status); @@ -148,7 +174,9 @@ double InterruptableSensorBase::ReadFallingTimestamp() { void InterruptableSensorBase::SetUpSourceEdge(bool risingEdge, bool fallingEdge) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } if (m_interrupt == HAL_kInvalidHandle) { wpi_setWPIErrorWithContext( NullParameter, diff --git a/wpilibc/src/main/native/cpp/IterativeRobot.cpp b/wpilibc/src/main/native/cpp/IterativeRobot.cpp index 3243ee13ed..ffc4e8e175 100644 --- a/wpilibc/src/main/native/cpp/IterativeRobot.cpp +++ b/wpilibc/src/main/native/cpp/IterativeRobot.cpp @@ -32,7 +32,9 @@ void IterativeRobot::StartCompetition() { while (true) { // Wait for driver station data so the loop doesn't hog the CPU DriverStation::GetInstance().WaitForData(); - if (m_exit) break; + if (m_exit) { + break; + } LoopFunc(); } diff --git a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp index 3069d73c45..91929037b7 100644 --- a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp +++ b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp @@ -182,7 +182,9 @@ void IterativeRobotBase::LoopFunc() { m_watchdog.Disable(); // Flush NetworkTables - if (m_ntFlushEnabled) nt::NetworkTableInstance::GetDefault().Flush(); + if (m_ntFlushEnabled) { + nt::NetworkTableInstance::GetDefault().Flush(); + } // Warn on loop time overruns if (m_watchdog.IsExpired()) { diff --git a/wpilibc/src/main/native/cpp/Joystick.cpp b/wpilibc/src/main/native/cpp/Joystick.cpp index 05a05466cc..71e41f9412 100644 --- a/wpilibc/src/main/native/cpp/Joystick.cpp +++ b/wpilibc/src/main/native/cpp/Joystick.cpp @@ -21,27 +21,45 @@ Joystick::Joystick(int port) : GenericHID(port) { HAL_Report(HALUsageReporting::kResourceType_Joystick, port + 1); } -void Joystick::SetXChannel(int channel) { m_axes[Axis::kX] = channel; } +void Joystick::SetXChannel(int channel) { + m_axes[Axis::kX] = channel; +} -void Joystick::SetYChannel(int channel) { m_axes[Axis::kY] = channel; } +void Joystick::SetYChannel(int channel) { + m_axes[Axis::kY] = channel; +} -void Joystick::SetZChannel(int channel) { m_axes[Axis::kZ] = channel; } +void Joystick::SetZChannel(int channel) { + m_axes[Axis::kZ] = channel; +} -void Joystick::SetTwistChannel(int channel) { m_axes[Axis::kTwist] = channel; } +void Joystick::SetTwistChannel(int channel) { + m_axes[Axis::kTwist] = channel; +} void Joystick::SetThrottleChannel(int channel) { m_axes[Axis::kThrottle] = channel; } -int Joystick::GetXChannel() const { return m_axes[Axis::kX]; } +int Joystick::GetXChannel() const { + return m_axes[Axis::kX]; +} -int Joystick::GetYChannel() const { return m_axes[Axis::kY]; } +int Joystick::GetYChannel() const { + return m_axes[Axis::kY]; +} -int Joystick::GetZChannel() const { return m_axes[Axis::kZ]; } +int Joystick::GetZChannel() const { + return m_axes[Axis::kZ]; +} -int Joystick::GetTwistChannel() const { return m_axes[Axis::kTwist]; } +int Joystick::GetTwistChannel() const { + return m_axes[Axis::kTwist]; +} -int Joystick::GetThrottleChannel() const { return m_axes[Axis::kThrottle]; } +int Joystick::GetThrottleChannel() const { + return m_axes[Axis::kThrottle]; +} double Joystick::GetX(JoystickHand hand) const { return GetRawAxis(m_axes[Axis::kX]); @@ -51,15 +69,21 @@ double Joystick::GetY(JoystickHand hand) const { return GetRawAxis(m_axes[Axis::kY]); } -double Joystick::GetZ() const { return GetRawAxis(m_axes[Axis::kZ]); } +double Joystick::GetZ() const { + return GetRawAxis(m_axes[Axis::kZ]); +} -double Joystick::GetTwist() const { return GetRawAxis(m_axes[Axis::kTwist]); } +double Joystick::GetTwist() const { + return GetRawAxis(m_axes[Axis::kTwist]); +} double Joystick::GetThrottle() const { return GetRawAxis(m_axes[Axis::kThrottle]); } -bool Joystick::GetTrigger() const { return GetRawButton(Button::kTrigger); } +bool Joystick::GetTrigger() const { + return GetRawButton(Button::kTrigger); +} bool Joystick::GetTriggerPressed() { return GetRawButtonPressed(Button::kTrigger); @@ -69,11 +93,17 @@ bool Joystick::GetTriggerReleased() { return GetRawButtonReleased(Button::kTrigger); } -bool Joystick::GetTop() const { return GetRawButton(Button::kTop); } +bool Joystick::GetTop() const { + return GetRawButton(Button::kTop); +} -bool Joystick::GetTopPressed() { return GetRawButtonPressed(Button::kTop); } +bool Joystick::GetTopPressed() { + return GetRawButtonPressed(Button::kTop); +} -bool Joystick::GetTopReleased() { return GetRawButtonReleased(Button::kTop); } +bool Joystick::GetTopReleased() { + return GetRawButtonReleased(Button::kTop); +} double Joystick::GetMagnitude() const { return std::sqrt(std::pow(GetX(), 2) + std::pow(GetY(), 2)); diff --git a/wpilibc/src/main/native/cpp/NidecBrushless.cpp b/wpilibc/src/main/native/cpp/NidecBrushless.cpp index c71bfd7ec2..1ea2b95f9b 100644 --- a/wpilibc/src/main/native/cpp/NidecBrushless.cpp +++ b/wpilibc/src/main/native/cpp/NidecBrushless.cpp @@ -36,11 +36,17 @@ void NidecBrushless::Set(double speed) { Feed(); } -double NidecBrushless::Get() const { return m_speed; } +double NidecBrushless::Get() const { + return m_speed; +} -void NidecBrushless::SetInverted(bool isInverted) { m_isInverted = isInverted; } +void NidecBrushless::SetInverted(bool isInverted) { + m_isInverted = isInverted; +} -bool NidecBrushless::GetInverted() const { return m_isInverted; } +bool NidecBrushless::GetInverted() const { + return m_isInverted; +} void NidecBrushless::Disable() { m_disabled = true; @@ -48,9 +54,13 @@ void NidecBrushless::Disable() { m_pwm.SetDisabled(); } -void NidecBrushless::Enable() { m_disabled = false; } +void NidecBrushless::Enable() { + m_disabled = false; +} -void NidecBrushless::PIDWrite(double output) { Set(output); } +void NidecBrushless::PIDWrite(double output) { + Set(output); +} void NidecBrushless::StopMotor() { m_dio.UpdateDutyCycle(0.5); @@ -61,7 +71,9 @@ void NidecBrushless::GetDescription(wpi::raw_ostream& desc) const { desc << "Nidec " << GetChannel(); } -int NidecBrushless::GetChannel() const { return m_pwm.GetChannel(); } +int NidecBrushless::GetChannel() const { + return m_pwm.GetChannel(); +} void NidecBrushless::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Nidec Brushless"); diff --git a/wpilibc/src/main/native/cpp/Notifier.cpp b/wpilibc/src/main/native/cpp/Notifier.cpp index 420c06a3eb..5b6b56f8aa 100644 --- a/wpilibc/src/main/native/cpp/Notifier.cpp +++ b/wpilibc/src/main/native/cpp/Notifier.cpp @@ -18,8 +18,9 @@ using namespace frc; Notifier::Notifier(std::function handler) { - if (handler == nullptr) + if (handler == nullptr) { wpi_setWPIErrorWithContext(NullParameter, "handler must not be nullptr"); + } m_handler = handler; int32_t status = 0; m_notifier = HAL_InitializeNotifier(&status); @@ -29,9 +30,13 @@ Notifier::Notifier(std::function handler) { for (;;) { int32_t status = 0; HAL_NotifierHandle notifier = m_notifier.load(); - if (notifier == 0) break; + if (notifier == 0) { + break; + } uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status); - if (curTime == 0 || status != 0) break; + if (curTime == 0 || status != 0) { + break; + } std::function handler; { @@ -47,14 +52,17 @@ Notifier::Notifier(std::function handler) { } // call callback - if (handler) handler(); + if (handler) { + handler(); + } } }); } Notifier::Notifier(int priority, std::function handler) { - if (handler == nullptr) + if (handler == nullptr) { wpi_setWPIErrorWithContext(NullParameter, "handler must not be nullptr"); + } m_handler = handler; int32_t status = 0; m_notifier = HAL_InitializeNotifier(&status); @@ -65,9 +73,13 @@ Notifier::Notifier(int priority, std::function handler) { HAL_SetCurrentThreadPriority(true, priority, &status); for (;;) { HAL_NotifierHandle notifier = m_notifier.load(); - if (notifier == 0) break; + if (notifier == 0) { + break; + } uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status); - if (curTime == 0 || status != 0) break; + if (curTime == 0 || status != 0) { + break; + } std::function handler; { @@ -83,7 +95,9 @@ Notifier::Notifier(int priority, std::function handler) { } // call callback - if (handler) handler(); + if (handler) { + handler(); + } } }); } @@ -96,7 +110,9 @@ Notifier::~Notifier() { wpi_setHALError(status); // Join the thread to ensure the handler has exited. - if (m_thread.joinable()) m_thread.join(); + if (m_thread.joinable()) { + m_thread.join(); + } HAL_CleanNotifier(handle, &status); } @@ -174,7 +190,9 @@ void Notifier::UpdateAlarm(uint64_t triggerTime) { int32_t status = 0; // Return if we are being destructed, or were not created successfully auto notifier = m_notifier.load(); - if (notifier == 0) return; + if (notifier == 0) { + return; + } HAL_UpdateNotifierAlarm(notifier, triggerTime, &status); wpi_setHALError(status); } diff --git a/wpilibc/src/main/native/cpp/PIDBase.cpp b/wpilibc/src/main/native/cpp/PIDBase.cpp index 78f044d454..f4a2de1ff0 100644 --- a/wpilibc/src/main/native/cpp/PIDBase.cpp +++ b/wpilibc/src/main/native/cpp/PIDBase.cpp @@ -133,12 +133,13 @@ void PIDBase::SetSetpoint(double setpoint) { std::scoped_lock lock(m_thisMutex); if (m_maximumInput > m_minimumInput) { - if (setpoint > m_maximumInput) + if (setpoint > m_maximumInput) { m_setpoint = m_maximumInput; - else if (setpoint < m_minimumInput) + } else if (setpoint < m_minimumInput) { m_setpoint = m_minimumInput; - else + } else { m_setpoint = setpoint; + } } else { m_setpoint = setpoint; } @@ -163,7 +164,9 @@ double PIDBase::GetError() const { } } -double PIDBase::GetAvgError() const { return GetError(); } +double PIDBase::GetAvgError() const { + return GetError(); +} void PIDBase::SetPIDSourceType(PIDSourceType pidSource) { m_pidInput->SetPIDSourceType(pidSource); @@ -221,7 +224,9 @@ void PIDBase::Reset() { m_result = 0; } -void PIDBase::PIDWrite(double output) { SetSetpoint(output); } +void PIDBase::PIDWrite(double output) { + SetSetpoint(output); +} void PIDBase::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("PIDController"); @@ -240,7 +245,9 @@ void PIDBase::InitSendable(SendableBuilder& builder) { } void PIDBase::Calculate() { - if (m_pidInput == nullptr || m_pidOutput == nullptr) return; + if (m_pidInput == nullptr || m_pidOutput == nullptr) { + return; + } bool enabled; { diff --git a/wpilibc/src/main/native/cpp/PIDSource.cpp b/wpilibc/src/main/native/cpp/PIDSource.cpp index 2af166e725..3a9e3ea88c 100644 --- a/wpilibc/src/main/native/cpp/PIDSource.cpp +++ b/wpilibc/src/main/native/cpp/PIDSource.cpp @@ -10,4 +10,6 @@ void PIDSource::SetPIDSourceType(PIDSourceType pidSource) { m_pidSource = pidSource; } -PIDSourceType PIDSource::GetPIDSourceType() const { return m_pidSource; } +PIDSourceType PIDSource::GetPIDSourceType() const { + return m_pidSource; +} diff --git a/wpilibc/src/main/native/cpp/PWM.cpp b/wpilibc/src/main/native/cpp/PWM.cpp index eee04c38ac..086553b712 100644 --- a/wpilibc/src/main/native/cpp/PWM.cpp +++ b/wpilibc/src/main/native/cpp/PWM.cpp @@ -59,14 +59,18 @@ PWM::~PWM() { wpi_setHALError(status); } -void PWM::StopMotor() { SetDisabled(); } +void PWM::StopMotor() { + SetDisabled(); +} void PWM::GetDescription(wpi::raw_ostream& desc) const { desc << "PWM " << GetChannel(); } void PWM::SetRaw(uint16_t value) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetPWMRaw(m_handle, value, &status); @@ -74,7 +78,9 @@ void PWM::SetRaw(uint16_t value) { } uint16_t PWM::GetRaw() const { - if (StatusIsFatal()) return 0; + if (StatusIsFatal()) { + return 0; + } int32_t status = 0; uint16_t value = HAL_GetPWMRaw(m_handle, &status); @@ -84,14 +90,18 @@ uint16_t PWM::GetRaw() const { } void PWM::SetPosition(double pos) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetPWMPosition(m_handle, pos, &status); wpi_setHALError(status); } double PWM::GetPosition() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double position = HAL_GetPWMPosition(m_handle, &status); wpi_setHALError(status); @@ -99,7 +109,9 @@ double PWM::GetPosition() const { } void PWM::SetSpeed(double speed) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetPWMSpeed(m_handle, speed, &status); wpi_setHALError(status); @@ -108,7 +120,9 @@ void PWM::SetSpeed(double speed) { } double PWM::GetSpeed() const { - if (StatusIsFatal()) return 0.0; + if (StatusIsFatal()) { + return 0.0; + } int32_t status = 0; double speed = HAL_GetPWMSpeed(m_handle, &status); wpi_setHALError(status); @@ -116,7 +130,9 @@ double PWM::GetSpeed() const { } void PWM::SetDisabled() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; @@ -125,7 +141,9 @@ void PWM::SetDisabled() { } void PWM::SetPeriodMultiplier(PeriodMultiplier mult) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; @@ -149,7 +167,9 @@ void PWM::SetPeriodMultiplier(PeriodMultiplier mult) { } void PWM::SetZeroLatch() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; @@ -158,7 +178,9 @@ void PWM::SetZeroLatch() { } void PWM::EnableDeadbandElimination(bool eliminateDeadband) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetPWMEliminateDeadband(m_handle, eliminateDeadband, &status); wpi_setHALError(status); @@ -166,7 +188,9 @@ void PWM::EnableDeadbandElimination(bool eliminateDeadband) { void PWM::SetBounds(double max, double deadbandMax, double center, double deadbandMin, double min) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetPWMConfig(m_handle, max, deadbandMax, center, deadbandMin, min, &status); @@ -175,7 +199,9 @@ void PWM::SetBounds(double max, double deadbandMax, double center, void PWM::SetRawBounds(int max, int deadbandMax, int center, int deadbandMin, int min) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetPWMConfigRaw(m_handle, max, deadbandMax, center, deadbandMin, min, &status); @@ -190,7 +216,9 @@ void PWM::GetRawBounds(int* max, int* deadbandMax, int* center, wpi_setHALError(status); } -int PWM::GetChannel() const { return m_channel; } +int PWM::GetChannel() const { + return m_channel; +} void PWM::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("PWM"); diff --git a/wpilibc/src/main/native/cpp/PWMSpeedController.cpp b/wpilibc/src/main/native/cpp/PWMSpeedController.cpp index 875189b2b9..51d6810476 100644 --- a/wpilibc/src/main/native/cpp/PWMSpeedController.cpp +++ b/wpilibc/src/main/native/cpp/PWMSpeedController.cpp @@ -12,19 +12,29 @@ void PWMSpeedController::Set(double speed) { SetSpeed(m_isInverted ? -speed : speed); } -double PWMSpeedController::Get() const { return GetSpeed(); } +double PWMSpeedController::Get() const { + return GetSpeed(); +} void PWMSpeedController::SetInverted(bool isInverted) { m_isInverted = isInverted; } -bool PWMSpeedController::GetInverted() const { return m_isInverted; } +bool PWMSpeedController::GetInverted() const { + return m_isInverted; +} -void PWMSpeedController::Disable() { SetDisabled(); } +void PWMSpeedController::Disable() { + SetDisabled(); +} -void PWMSpeedController::StopMotor() { PWM::StopMotor(); } +void PWMSpeedController::StopMotor() { + PWM::StopMotor(); +} -void PWMSpeedController::PIDWrite(double output) { Set(output); } +void PWMSpeedController::PIDWrite(double output) { + Set(output); +} PWMSpeedController::PWMSpeedController(int channel) : PWM(channel) {} diff --git a/wpilibc/src/main/native/cpp/PowerDistributionPanel.cpp b/wpilibc/src/main/native/cpp/PowerDistributionPanel.cpp index 71e2daf805..b955f7f2ae 100644 --- a/wpilibc/src/main/native/cpp/PowerDistributionPanel.cpp +++ b/wpilibc/src/main/native/cpp/PowerDistributionPanel.cpp @@ -133,7 +133,9 @@ void PowerDistributionPanel::ClearStickyFaults() { } } -int PowerDistributionPanel::GetModule() const { return m_module; } +int PowerDistributionPanel::GetModule() const { + return m_module; +} void PowerDistributionPanel::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("PowerDistributionPanel"); diff --git a/wpilibc/src/main/native/cpp/Preferences.cpp b/wpilibc/src/main/native/cpp/Preferences.cpp index b43af510d2..b221d5af10 100644 --- a/wpilibc/src/main/native/cpp/Preferences.cpp +++ b/wpilibc/src/main/native/cpp/Preferences.cpp @@ -22,7 +22,9 @@ Preferences* Preferences::GetInstance() { return &instance; } -std::vector Preferences::GetKeys() { return m_table->GetKeys(); } +std::vector Preferences::GetKeys() { + return m_table->GetKeys(); +} std::string Preferences::GetString(wpi::StringRef key, wpi::StringRef defaultValue) { @@ -119,7 +121,9 @@ bool Preferences::ContainsKey(wpi::StringRef key) { return m_table->ContainsKey(key); } -void Preferences::Remove(wpi::StringRef key) { m_table->Delete(key); } +void Preferences::Remove(wpi::StringRef key) { + m_table->Delete(key); +} void Preferences::RemoveAll() { for (auto preference : GetKeys()) { diff --git a/wpilibc/src/main/native/cpp/Relay.cpp b/wpilibc/src/main/native/cpp/Relay.cpp index 639452d2a6..395b1eb617 100644 --- a/wpilibc/src/main/native/cpp/Relay.cpp +++ b/wpilibc/src/main/native/cpp/Relay.cpp @@ -81,12 +81,18 @@ Relay::~Relay() { HAL_SetRelay(m_forwardHandle, false, &status); HAL_SetRelay(m_reverseHandle, false, &status); // ignore errors, as we want to make sure a free happens. - if (m_forwardHandle != HAL_kInvalidHandle) HAL_FreeRelayPort(m_forwardHandle); - if (m_reverseHandle != HAL_kInvalidHandle) HAL_FreeRelayPort(m_reverseHandle); + if (m_forwardHandle != HAL_kInvalidHandle) { + HAL_FreeRelayPort(m_forwardHandle); + } + if (m_reverseHandle != HAL_kInvalidHandle) { + HAL_FreeRelayPort(m_reverseHandle); + } } void Relay::Set(Relay::Value value) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; @@ -170,9 +176,13 @@ Relay::Value Relay::Get() const { wpi_setHALError(status); } -int Relay::GetChannel() const { return m_channel; } +int Relay::GetChannel() const { + return m_channel; +} -void Relay::StopMotor() { Set(kOff); } +void Relay::StopMotor() { + Set(kOff); +} void Relay::GetDescription(wpi::raw_ostream& desc) const { desc << "Relay " << GetChannel(); @@ -197,13 +207,14 @@ void Relay::InitSendable(SendableBuilder& builder) { } }, [=](wpi::StringRef value) { - if (value == "Off") + if (value == "Off") { Set(kOff); - else if (value == "Forward") + } else if (value == "Forward") { Set(kForward); - else if (value == "Reverse") + } else if (value == "Reverse") { Set(kReverse); - else if (value == "On") + } else if (value == "On") { Set(kOn); + } }); } diff --git a/wpilibc/src/main/native/cpp/Resource.cpp b/wpilibc/src/main/native/cpp/Resource.cpp index 27ad7f3e3e..dd16112d98 100644 --- a/wpilibc/src/main/native/cpp/Resource.cpp +++ b/wpilibc/src/main/native/cpp/Resource.cpp @@ -51,7 +51,9 @@ uint32_t Resource::Allocate(uint32_t index, const std::string& resourceDesc) { void Resource::Free(uint32_t index) { std::unique_lock lock(m_allocateMutex); - if (index == std::numeric_limits::max()) return; + if (index == std::numeric_limits::max()) { + return; + } if (index >= m_isAllocated.size()) { wpi_setWPIError(NotAllocated); return; diff --git a/wpilibc/src/main/native/cpp/RobotDrive.cpp b/wpilibc/src/main/native/cpp/RobotDrive.cpp index 8d64b39389..8293282873 100644 --- a/wpilibc/src/main/native/cpp/RobotDrive.cpp +++ b/wpilibc/src/main/native/cpp/RobotDrive.cpp @@ -125,13 +125,17 @@ void RobotDrive::Drive(double outputMagnitude, double curve) { if (curve < 0) { double value = std::log(-curve); double ratio = (value - m_sensitivity) / (value + m_sensitivity); - if (ratio == 0) ratio = 0.0000000001; + if (ratio == 0) { + ratio = 0.0000000001; + } leftOutput = outputMagnitude / ratio; rightOutput = outputMagnitude; } else if (curve > 0) { double value = std::log(curve); double ratio = (value - m_sensitivity) / (value + m_sensitivity); - if (ratio == 0) ratio = 0.0000000001; + if (ratio == 0) { + ratio = 0.0000000001; + } leftOutput = outputMagnitude; rightOutput = outputMagnitude / ratio; } else { @@ -339,12 +343,14 @@ void RobotDrive::SetLeftRightMotorOutputs(double leftOutput, double rightOutput) { wpi_assert(m_rearLeftMotor != nullptr && m_rearRightMotor != nullptr); - if (m_frontLeftMotor != nullptr) + if (m_frontLeftMotor != nullptr) { m_frontLeftMotor->Set(Limit(leftOutput) * m_maxOutput); + } m_rearLeftMotor->Set(Limit(leftOutput) * m_maxOutput); - if (m_frontRightMotor != nullptr) + if (m_frontRightMotor != nullptr) { m_frontRightMotor->Set(-Limit(rightOutput) * m_maxOutput); + } m_rearRightMotor->Set(-Limit(rightOutput) * m_maxOutput); Feed(); @@ -375,21 +381,33 @@ void RobotDrive::SetSensitivity(double sensitivity) { m_sensitivity = sensitivity; } -void RobotDrive::SetMaxOutput(double maxOutput) { m_maxOutput = maxOutput; } +void RobotDrive::SetMaxOutput(double maxOutput) { + m_maxOutput = maxOutput; +} void RobotDrive::GetDescription(wpi::raw_ostream& desc) const { desc << "RobotDrive"; } void RobotDrive::StopMotor() { - if (m_frontLeftMotor != nullptr) m_frontLeftMotor->StopMotor(); - if (m_frontRightMotor != nullptr) m_frontRightMotor->StopMotor(); - if (m_rearLeftMotor != nullptr) m_rearLeftMotor->StopMotor(); - if (m_rearRightMotor != nullptr) m_rearRightMotor->StopMotor(); + if (m_frontLeftMotor != nullptr) { + m_frontLeftMotor->StopMotor(); + } + if (m_frontRightMotor != nullptr) { + m_frontRightMotor->StopMotor(); + } + if (m_rearLeftMotor != nullptr) { + m_rearLeftMotor->StopMotor(); + } + if (m_rearRightMotor != nullptr) { + m_rearRightMotor->StopMotor(); + } Feed(); } -void RobotDrive::InitRobotDrive() { SetSafetyEnabled(true); } +void RobotDrive::InitRobotDrive() { + SetSafetyEnabled(true); +} double RobotDrive::Limit(double number) { if (number > 1.0) { @@ -405,7 +423,9 @@ void RobotDrive::Normalize(double* wheelSpeeds) { double maxMagnitude = std::fabs(wheelSpeeds[0]); for (int i = 1; i < kMaxNumberOfMotors; i++) { double temp = std::fabs(wheelSpeeds[i]); - if (maxMagnitude < temp) maxMagnitude = temp; + if (maxMagnitude < temp) { + maxMagnitude = temp; + } } if (maxMagnitude > 1.0) { for (int i = 0; i < kMaxNumberOfMotors; i++) { diff --git a/wpilibc/src/main/native/cpp/RobotState.cpp b/wpilibc/src/main/native/cpp/RobotState.cpp index ebd8b03326..b39b6d1466 100644 --- a/wpilibc/src/main/native/cpp/RobotState.cpp +++ b/wpilibc/src/main/native/cpp/RobotState.cpp @@ -28,4 +28,6 @@ bool RobotState::IsAutonomous() { return DriverStation::GetInstance().IsAutonomous(); } -bool RobotState::IsTest() { return DriverStation::GetInstance().IsTest(); } +bool RobotState::IsTest() { + return DriverStation::GetInstance().IsTest(); +} diff --git a/wpilibc/src/main/native/cpp/SPI.cpp b/wpilibc/src/main/native/cpp/SPI.cpp index 1a45a97dd0..6788beadba 100644 --- a/wpilibc/src/main/native/cpp/SPI.cpp +++ b/wpilibc/src/main/native/cpp/SPI.cpp @@ -76,7 +76,9 @@ void SPI::Accumulator::Update() { // get amount of data available int32_t numToRead = HAL_ReadSPIAutoReceivedData(m_port, m_buf, 0, 0, &status); - if (status != 0) return; // error reading + if (status != 0) { + return; // error reading + } // only get whole responses; +1 is for timestamp numToRead -= numToRead % m_xferSize; @@ -84,11 +86,15 @@ void SPI::Accumulator::Update() { numToRead = m_xferSize * kAccumulateDepth; done = false; } - if (numToRead == 0) return; // no samples + if (numToRead == 0) { + return; // no samples + } // read buffered data HAL_ReadSPIAutoReceivedData(m_port, m_buf, numToRead, 0, &status); - if (status != 0) return; // error reading + if (status != 0) { + return; // error reading + } // loop over all responses for (int32_t off = 0; off < numToRead; off += m_xferSize) { @@ -115,7 +121,9 @@ void SPI::Accumulator::Update() { int32_t data = static_cast(resp >> m_dataShift); data &= m_dataMax - 1; // 2s complement conversion if signed MSB is set - if (m_isSigned && (data & m_dataMsbMask) != 0) data -= m_dataMax; + if (m_isSigned && (data & m_dataMsbMask) != 0) { + data -= m_dataMax; + } // center offset int32_t dataNoCenter = data; data -= m_center; @@ -124,18 +132,19 @@ void SPI::Accumulator::Update() { m_value += data; if (m_count != 0) { // timestamps use the 1us FPGA clock; also handle rollover - if (timestamp >= m_lastTimestamp) + if (timestamp >= m_lastTimestamp) { m_integratedValue += dataNoCenter * static_cast(timestamp - m_lastTimestamp) * 1e-6 - m_integratedCenter; - else + } else { m_integratedValue += dataNoCenter * static_cast((1ULL << 32) - m_lastTimestamp + timestamp) * 1e-6 - m_integratedCenter; + } } } ++m_count; @@ -158,9 +167,13 @@ SPI::SPI(Port port) : m_port(static_cast(port)) { static_cast(port) + 1); } -SPI::~SPI() { HAL_CloseSPI(m_port); } +SPI::~SPI() { + HAL_CloseSPI(m_port); +} -void SPI::SetClockRate(int hz) { HAL_SetSPISpeed(m_port, hz); } +void SPI::SetClockRate(int hz) { + HAL_SetSPISpeed(m_port, hz); +} void SPI::SetMSBFirst() { m_msbFirst = true; @@ -356,7 +369,9 @@ void SPI::FreeAccumulator() { } void SPI::ResetAccumulator() { - if (!m_accum) return; + if (!m_accum) { + return; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->m_value = 0; m_accum->m_count = 0; @@ -366,43 +381,57 @@ void SPI::ResetAccumulator() { } void SPI::SetAccumulatorCenter(int center) { - if (!m_accum) return; + if (!m_accum) { + return; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->m_center = center; } void SPI::SetAccumulatorDeadband(int deadband) { - if (!m_accum) return; + if (!m_accum) { + return; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->m_deadband = deadband; } int SPI::GetAccumulatorLastValue() const { - if (!m_accum) return 0; + if (!m_accum) { + return 0; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_lastValue; } int64_t SPI::GetAccumulatorValue() const { - if (!m_accum) return 0; + if (!m_accum) { + return 0; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_value; } int64_t SPI::GetAccumulatorCount() const { - if (!m_accum) return 0; + if (!m_accum) { + return 0; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_count; } double SPI::GetAccumulatorAverage() const { - if (!m_accum) return 0; + if (!m_accum) { + return 0; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); - if (m_accum->m_count == 0) return 0.0; + if (m_accum->m_count == 0) { + return 0.0; + } return static_cast(m_accum->m_value) / m_accum->m_count; } @@ -419,23 +448,31 @@ void SPI::GetAccumulatorOutput(int64_t& value, int64_t& count) const { } void SPI::SetAccumulatorIntegratedCenter(double center) { - if (!m_accum) return; + if (!m_accum) { + return; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->m_integratedCenter = center; } double SPI::GetAccumulatorIntegratedValue() const { - if (!m_accum) return 0; + if (!m_accum) { + return 0; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_integratedValue; } double SPI::GetAccumulatorIntegratedAverage() const { - if (!m_accum) return 0; + if (!m_accum) { + return 0; + } std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); - if (m_accum->m_count <= 1) return 0.0; + if (m_accum->m_count <= 1) { + return 0.0; + } // count-1 due to not integrating the first value received return m_accum->m_integratedValue / (m_accum->m_count - 1); } diff --git a/wpilibc/src/main/native/cpp/SensorUtil.cpp b/wpilibc/src/main/native/cpp/SensorUtil.cpp index d3f28016f6..fee3218934 100644 --- a/wpilibc/src/main/native/cpp/SensorUtil.cpp +++ b/wpilibc/src/main/native/cpp/SensorUtil.cpp @@ -24,7 +24,9 @@ const int SensorUtil::kPwmChannels = HAL_GetNumPWMChannels(); const int SensorUtil::kRelayChannels = HAL_GetNumRelayHeaders(); const int SensorUtil::kPDPChannels = HAL_GetNumPDPChannels(); -int SensorUtil::GetDefaultSolenoidModule() { return 0; } +int SensorUtil::GetDefaultSolenoidModule() { + return 0; +} bool SensorUtil::CheckSolenoidModule(int moduleNumber) { return HAL_CheckSolenoidModule(moduleNumber); diff --git a/wpilibc/src/main/native/cpp/SerialPort.cpp b/wpilibc/src/main/native/cpp/SerialPort.cpp index c05eba0238..70c7fb52d1 100644 --- a/wpilibc/src/main/native/cpp/SerialPort.cpp +++ b/wpilibc/src/main/native/cpp/SerialPort.cpp @@ -20,7 +20,9 @@ SerialPort::SerialPort(int baudRate, Port port, int dataBits, HAL_InitializeSerialPort(static_cast(port), &status); wpi_setHALError(status); // Don't continue if initialization failed - if (status < 0) return; + if (status < 0) { + return; + } HAL_SetSerialBaudRate(m_portHandle, baudRate, &status); wpi_setHALError(status); HAL_SetSerialDataBits(m_portHandle, dataBits, &status); @@ -54,7 +56,9 @@ SerialPort::SerialPort(int baudRate, const wpi::Twine& portName, Port port, static_cast(port), portNameC, &status); wpi_setHALError(status); // Don't continue if initialization failed - if (status < 0) return; + if (status < 0) { + return; + } HAL_SetSerialBaudRate(m_portHandle, baudRate, &status); wpi_setHALError(status); HAL_SetSerialDataBits(m_portHandle, dataBits, &status); diff --git a/wpilibc/src/main/native/cpp/Servo.cpp b/wpilibc/src/main/native/cpp/Servo.cpp index 2f33b5782e..7ab18f21f3 100644 --- a/wpilibc/src/main/native/cpp/Servo.cpp +++ b/wpilibc/src/main/native/cpp/Servo.cpp @@ -28,11 +28,17 @@ Servo::Servo(int channel) : PWM(channel) { SendableRegistry::GetInstance().SetName(this, "Servo", channel); } -void Servo::Set(double value) { SetPosition(value); } +void Servo::Set(double value) { + SetPosition(value); +} -void Servo::SetOffline() { SetRaw(0); } +void Servo::SetOffline() { + SetRaw(0); +} -double Servo::Get() const { return GetPosition(); } +double Servo::Get() const { + return GetPosition(); +} void Servo::SetAngle(double degrees) { if (degrees < kMinServoAngle) { @@ -48,9 +54,13 @@ double Servo::GetAngle() const { return GetPosition() * GetServoAngleRange() + kMinServoAngle; } -double Servo::GetMaxAngle() const { return kMaxServoAngle; } +double Servo::GetMaxAngle() const { + return kMaxServoAngle; +} -double Servo::GetMinAngle() const { return kMinServoAngle; } +double Servo::GetMinAngle() const { + return kMinServoAngle; +} void Servo::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Servo"); diff --git a/wpilibc/src/main/native/cpp/Solenoid.cpp b/wpilibc/src/main/native/cpp/Solenoid.cpp index bdce939ea3..5fb2c2bb2e 100644 --- a/wpilibc/src/main/native/cpp/Solenoid.cpp +++ b/wpilibc/src/main/native/cpp/Solenoid.cpp @@ -49,10 +49,14 @@ Solenoid::Solenoid(int moduleNumber, int channel) m_channel); } -Solenoid::~Solenoid() { HAL_FreeSolenoidPort(m_solenoidHandle); } +Solenoid::~Solenoid() { + HAL_FreeSolenoidPort(m_solenoidHandle); +} void Solenoid::Set(bool on) { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetSolenoid(m_solenoidHandle, on, &status); @@ -60,7 +64,9 @@ void Solenoid::Set(bool on) { } bool Solenoid::Get() const { - if (StatusIsFatal()) return false; + if (StatusIsFatal()) { + return false; + } int32_t status = 0; bool value = HAL_GetSolenoid(m_solenoidHandle, &status); @@ -69,7 +75,9 @@ bool Solenoid::Get() const { return value; } -void Solenoid::Toggle() { Set(!Get()); } +void Solenoid::Toggle() { + Set(!Get()); +} bool Solenoid::IsBlackListed() const { int value = GetPCMSolenoidBlackList(m_moduleNumber) & (1 << m_channel); @@ -78,14 +86,18 @@ bool Solenoid::IsBlackListed() const { void Solenoid::SetPulseDuration(double durationSeconds) { int32_t durationMS = durationSeconds * 1000; - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_SetOneShotDuration(m_solenoidHandle, durationMS, &status); wpi_setHALError(status); } void Solenoid::StartPulse() { - if (StatusIsFatal()) return; + if (StatusIsFatal()) { + return; + } int32_t status = 0; HAL_FireOneShot(m_solenoidHandle, &status); wpi_setHALError(status); diff --git a/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp b/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp index a6b131f109..ce9aa32203 100644 --- a/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp +++ b/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp @@ -19,8 +19,9 @@ SpeedControllerGroup::SpeedControllerGroup( } void SpeedControllerGroup::Initialize() { - for (auto& speedController : m_speedControllers) + for (auto& speedController : m_speedControllers) { SendableRegistry::GetInstance().AddChild(this, &speedController.get()); + } static int instances = 0; ++instances; SendableRegistry::GetInstance().Add(this, "SpeedControllerGroup", instances); @@ -43,7 +44,9 @@ void SpeedControllerGroup::SetInverted(bool isInverted) { m_isInverted = isInverted; } -bool SpeedControllerGroup::GetInverted() const { return m_isInverted; } +bool SpeedControllerGroup::GetInverted() const { + return m_isInverted; +} void SpeedControllerGroup::Disable() { for (auto speedController : m_speedControllers) { @@ -57,7 +60,9 @@ void SpeedControllerGroup::StopMotor() { } } -void SpeedControllerGroup::PIDWrite(double output) { Set(output); } +void SpeedControllerGroup::PIDWrite(double output) { + Set(output); +} void SpeedControllerGroup::InitSendable(SendableBuilder& builder) { builder.SetSmartDashboardType("Speed Controller"); diff --git a/wpilibc/src/main/native/cpp/TimedRobot.cpp b/wpilibc/src/main/native/cpp/TimedRobot.cpp index ebc0124677..2704d51010 100644 --- a/wpilibc/src/main/native/cpp/TimedRobot.cpp +++ b/wpilibc/src/main/native/cpp/TimedRobot.cpp @@ -42,7 +42,9 @@ void TimedRobot::StartCompetition() { wpi_setHALError(status); uint64_t curTime = HAL_WaitForNotifierAlarm(m_notifier, &status); - if (curTime == 0 || status != 0) break; + if (curTime == 0 || status != 0) { + break; + } callback.func(); diff --git a/wpilibc/src/main/native/cpp/Timer.cpp b/wpilibc/src/main/native/cpp/Timer.cpp index c1a3aedb4e..36701000ad 100644 --- a/wpilibc/src/main/native/cpp/Timer.cpp +++ b/wpilibc/src/main/native/cpp/Timer.cpp @@ -8,23 +8,37 @@ namespace frc { -void Wait(double seconds) { frc2::Wait(units::second_t(seconds)); } +void Wait(double seconds) { + frc2::Wait(units::second_t(seconds)); +} -double GetTime() { return frc2::GetTime().to(); } +double GetTime() { + return frc2::GetTime().to(); +} } // namespace frc using namespace frc; -Timer::Timer() { Reset(); } +Timer::Timer() { + Reset(); +} -double Timer::Get() const { return m_timer.Get().to(); } +double Timer::Get() const { + return m_timer.Get().to(); +} -void Timer::Reset() { m_timer.Reset(); } +void Timer::Reset() { + m_timer.Reset(); +} -void Timer::Start() { m_timer.Start(); } +void Timer::Start() { + m_timer.Start(); +} -void Timer::Stop() { m_timer.Stop(); } +void Timer::Stop() { + m_timer.Stop(); +} bool Timer::HasPeriodPassed(double period) { return m_timer.HasPeriodPassed(units::second_t(period)); diff --git a/wpilibc/src/main/native/cpp/Tracer.cpp b/wpilibc/src/main/native/cpp/Tracer.cpp index a17bddd027..a0fe5f693d 100644 --- a/wpilibc/src/main/native/cpp/Tracer.cpp +++ b/wpilibc/src/main/native/cpp/Tracer.cpp @@ -12,9 +12,13 @@ using namespace frc; -Tracer::Tracer() { ResetTimer(); } +Tracer::Tracer() { + ResetTimer(); +} -void Tracer::ResetTimer() { m_startTime = hal::fpga_clock::now(); } +void Tracer::ResetTimer() { + m_startTime = hal::fpga_clock::now(); +} void Tracer::ClearEpochs() { ResetTimer(); @@ -31,7 +35,9 @@ void Tracer::PrintEpochs() { wpi::SmallString<128> buf; wpi::raw_svector_ostream os(buf); PrintEpochs(os); - if (!buf.empty()) DriverStation::ReportWarning(buf); + if (!buf.empty()) { + DriverStation::ReportWarning(buf); + } } void Tracer::PrintEpochs(wpi::raw_ostream& os) { diff --git a/wpilibc/src/main/native/cpp/Ultrasonic.cpp b/wpilibc/src/main/native/cpp/Ultrasonic.cpp index eaa67b8e21..be2b90170e 100644 --- a/wpilibc/src/main/native/cpp/Ultrasonic.cpp +++ b/wpilibc/src/main/native/cpp/Ultrasonic.cpp @@ -97,12 +97,16 @@ void Ultrasonic::Ping() { } bool Ultrasonic::IsRangeValid() const { - if (m_simRangeValid) return m_simRangeValid.Get(); + if (m_simRangeValid) { + return m_simRangeValid.Get(); + } return m_counter.Get() > 1; } void Ultrasonic::SetAutomaticMode(bool enabling) { - if (enabling == m_automaticEnabled) return; // ignore the case of no change + if (enabling == m_automaticEnabled) { + return; // ignore the case of no change + } m_automaticEnabled = enabling; @@ -137,20 +141,30 @@ void Ultrasonic::SetAutomaticMode(bool enabling) { double Ultrasonic::GetRangeInches() const { if (IsRangeValid()) { - if (m_simRange) return m_simRange.Get(); + if (m_simRange) { + return m_simRange.Get(); + } return m_counter.GetPeriod() * kSpeedOfSoundInchesPerSec / 2.0; } else { return 0; } } -double Ultrasonic::GetRangeMM() const { return GetRangeInches() * 25.4; } +double Ultrasonic::GetRangeMM() const { + return GetRangeInches() * 25.4; +} -bool Ultrasonic::IsEnabled() const { return m_enabled; } +bool Ultrasonic::IsEnabled() const { + return m_enabled; +} -void Ultrasonic::SetEnabled(bool enable) { m_enabled = enable; } +void Ultrasonic::SetEnabled(bool enable) { + m_enabled = enable; +} -void Ultrasonic::SetDistanceUnits(DistanceUnit units) { m_units = units; } +void Ultrasonic::SetDistanceUnits(DistanceUnit units) { + m_units = units; +} Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits() const { return m_units; @@ -209,7 +223,9 @@ void Ultrasonic::Initialize() { void Ultrasonic::UltrasonicChecker() { while (m_automaticEnabled) { for (auto& sensor : m_sensors) { - if (!m_automaticEnabled) break; + if (!m_automaticEnabled) { + break; + } if (sensor->IsEnabled()) { sensor->m_pingChannel->Pulse(kPingTime); // do the ping diff --git a/wpilibc/src/main/native/cpp/Watchdog.cpp b/wpilibc/src/main/native/cpp/Watchdog.cpp index e57cf90495..bf1026def0 100644 --- a/wpilibc/src/main/native/cpp/Watchdog.cpp +++ b/wpilibc/src/main/native/cpp/Watchdog.cpp @@ -60,7 +60,9 @@ Watchdog::Impl::~Impl() { wpi_setGlobalHALError(status); // Join the thread to ensure the handler has exited. - if (m_thread.joinable()) m_thread.join(); + if (m_thread.joinable()) { + m_thread.join(); + } HAL_CleanNotifier(handle, &status); } @@ -69,15 +71,18 @@ void Watchdog::Impl::UpdateAlarm() { int32_t status = 0; // Return if we are being destructed, or were not created successfully auto notifier = m_notifier.load(); - if (notifier == 0) return; - if (m_watchdogs.empty()) + if (notifier == 0) { + return; + } + if (m_watchdogs.empty()) { HAL_CancelNotifierAlarm(notifier, &status); - else + } else { HAL_UpdateNotifierAlarm( notifier, static_cast(m_watchdogs.top()->m_expirationTime.to() * 1e6), &status); + } wpi_setGlobalHALError(status); } @@ -85,13 +90,19 @@ void Watchdog::Impl::Main() { for (;;) { int32_t status = 0; HAL_NotifierHandle notifier = m_notifier.load(); - if (notifier == 0) break; + if (notifier == 0) { + break; + } uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status); - if (curTime == 0 || status != 0) break; + if (curTime == 0 || status != 0) { + break; + } std::unique_lock lock(m_mutex); - if (m_watchdogs.empty()) continue; + if (m_watchdogs.empty()) { + continue; + } // If the condition variable timed out, that means a Watchdog timeout // has occurred, so call its timeout function. @@ -128,9 +139,13 @@ Watchdog::Watchdog(double timeout, std::function callback) Watchdog::Watchdog(units::second_t timeout, std::function callback) : m_timeout(timeout), m_callback(callback), m_impl(GetImpl()) {} -Watchdog::~Watchdog() { Disable(); } +Watchdog::~Watchdog() { + Disable(); +} -Watchdog::Watchdog(Watchdog&& rhs) { *this = std::move(rhs); } +Watchdog::Watchdog(Watchdog&& rhs) { + *this = std::move(rhs); +} Watchdog& Watchdog::operator=(Watchdog&& rhs) { m_impl = rhs.m_impl; @@ -186,9 +201,13 @@ void Watchdog::AddEpoch(wpi::StringRef epochName) { m_tracer.AddEpoch(epochName); } -void Watchdog::PrintEpochs() { m_tracer.PrintEpochs(); } +void Watchdog::PrintEpochs() { + m_tracer.PrintEpochs(); +} -void Watchdog::Reset() { Enable(); } +void Watchdog::Reset() { + Enable(); +} void Watchdog::Enable() { m_startTime = frc2::Timer::GetFPGATimestamp(); diff --git a/wpilibc/src/main/native/cpp/controller/HolonomicDriveController.cpp b/wpilibc/src/main/native/cpp/controller/HolonomicDriveController.cpp index 4e9e01e037..fc0cf93e9a 100644 --- a/wpilibc/src/main/native/cpp/controller/HolonomicDriveController.cpp +++ b/wpilibc/src/main/native/cpp/controller/HolonomicDriveController.cpp @@ -64,4 +64,6 @@ ChassisSpeeds HolonomicDriveController::Calculate( angleRef); } -void HolonomicDriveController::SetEnabled(bool enabled) { m_enabled = enabled; } +void HolonomicDriveController::SetEnabled(bool enabled) { + m_enabled = enabled; +} diff --git a/wpilibc/src/main/native/cpp/controller/PIDController.cpp b/wpilibc/src/main/native/cpp/controller/PIDController.cpp index c8a0042a5a..a0087ba668 100644 --- a/wpilibc/src/main/native/cpp/controller/PIDController.cpp +++ b/wpilibc/src/main/native/cpp/controller/PIDController.cpp @@ -30,25 +30,41 @@ void PIDController::SetPID(double Kp, double Ki, double Kd) { m_Kd = Kd; } -void PIDController::SetP(double Kp) { m_Kp = Kp; } +void PIDController::SetP(double Kp) { + m_Kp = Kp; +} -void PIDController::SetI(double Ki) { m_Ki = Ki; } +void PIDController::SetI(double Ki) { + m_Ki = Ki; +} -void PIDController::SetD(double Kd) { m_Kd = Kd; } +void PIDController::SetD(double Kd) { + m_Kd = Kd; +} -double PIDController::GetP() const { return m_Kp; } +double PIDController::GetP() const { + return m_Kp; +} -double PIDController::GetI() const { return m_Ki; } +double PIDController::GetI() const { + return m_Ki; +} -double PIDController::GetD() const { return m_Kd; } +double PIDController::GetD() const { + return m_Kd; +} units::second_t PIDController::GetPeriod() const { return units::second_t(m_period); } -void PIDController::SetSetpoint(double setpoint) { m_setpoint = setpoint; } +void PIDController::SetSetpoint(double setpoint) { + m_setpoint = setpoint; +} -double PIDController::GetSetpoint() const { return m_setpoint; } +double PIDController::GetSetpoint() const { + return m_setpoint; +} bool PIDController::AtSetpoint() const { double positionError; @@ -72,9 +88,13 @@ void PIDController::EnableContinuousInput(double minimumInput, m_maximumInput = maximumInput; } -void PIDController::DisableContinuousInput() { m_continuous = false; } +void PIDController::DisableContinuousInput() { + m_continuous = false; +} -bool PIDController::IsContinuousInputEnabled() const { return m_continuous; } +bool PIDController::IsContinuousInputEnabled() const { + return m_continuous; +} void PIDController::SetIntegratorRange(double minimumIntegral, double maximumIntegral) { @@ -88,9 +108,13 @@ void PIDController::SetTolerance(double positionTolerance, m_velocityTolerance = velocityTolerance; } -double PIDController::GetPositionError() const { return m_positionError; } +double PIDController::GetPositionError() const { + return m_positionError; +} -double PIDController::GetVelocityError() const { return m_velocityError; } +double PIDController::GetVelocityError() const { + return m_velocityError; +} double PIDController::Calculate(double measurement) { m_measurement = measurement; diff --git a/wpilibc/src/main/native/cpp/controller/RamseteController.cpp b/wpilibc/src/main/native/cpp/controller/RamseteController.cpp index bf4998768c..2371165d3c 100644 --- a/wpilibc/src/main/native/cpp/controller/RamseteController.cpp +++ b/wpilibc/src/main/native/cpp/controller/RamseteController.cpp @@ -72,4 +72,6 @@ ChassisSpeeds RamseteController::Calculate( desiredState.velocity * desiredState.curvature); } -void RamseteController::SetEnabled(bool enabled) { m_enabled = enabled; } +void RamseteController::SetEnabled(bool enabled) { + m_enabled = enabled; +} diff --git a/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp b/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp index cabea9898f..594cfbcf0c 100644 --- a/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp +++ b/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp @@ -15,13 +15,21 @@ using namespace frc; -RobotDriveBase::RobotDriveBase() { SetSafetyEnabled(true); } +RobotDriveBase::RobotDriveBase() { + SetSafetyEnabled(true); +} -void RobotDriveBase::SetDeadband(double deadband) { m_deadband = deadband; } +void RobotDriveBase::SetDeadband(double deadband) { + m_deadband = deadband; +} -void RobotDriveBase::SetMaxOutput(double maxOutput) { m_maxOutput = maxOutput; } +void RobotDriveBase::SetMaxOutput(double maxOutput) { + m_maxOutput = maxOutput; +} -void RobotDriveBase::FeedWatchdog() { Feed(); } +void RobotDriveBase::FeedWatchdog() { + Feed(); +} double RobotDriveBase::ApplyDeadband(double value, double deadband) { if (std::abs(value) > deadband) { diff --git a/wpilibc/src/main/native/cpp/drive/Vector2d.cpp b/wpilibc/src/main/native/cpp/drive/Vector2d.cpp index dcccbc7497..58ad6fc5b4 100644 --- a/wpilibc/src/main/native/cpp/drive/Vector2d.cpp +++ b/wpilibc/src/main/native/cpp/drive/Vector2d.cpp @@ -29,7 +29,9 @@ double Vector2d::Dot(const Vector2d& vec) const { return x * vec.x + y * vec.y; } -double Vector2d::Magnitude() const { return std::sqrt(x * x + y * y); } +double Vector2d::Magnitude() const { + return std::sqrt(x * x + y * y); +} double Vector2d::ScalarProject(const Vector2d& vec) const { return Dot(vec) / vec.Magnitude(); diff --git a/wpilibc/src/main/native/cpp/filters/Filter.cpp b/wpilibc/src/main/native/cpp/filters/Filter.cpp index 287b870808..1676c94894 100644 --- a/wpilibc/src/main/native/cpp/filters/Filter.cpp +++ b/wpilibc/src/main/native/cpp/filters/Filter.cpp @@ -22,4 +22,6 @@ PIDSourceType Filter::GetPIDSourceType() const { return m_source->GetPIDSourceType(); } -double Filter::PIDGetSource() { return m_source->PIDGet(); } +double Filter::PIDGetSource() { + return m_source->PIDGet(); +} diff --git a/wpilibc/src/main/native/cpp/frc2/Timer.cpp b/wpilibc/src/main/native/cpp/frc2/Timer.cpp index f21e6f1414..5cc058ace4 100644 --- a/wpilibc/src/main/native/cpp/frc2/Timer.cpp +++ b/wpilibc/src/main/native/cpp/frc2/Timer.cpp @@ -31,7 +31,9 @@ units::second_t GetTime() { using namespace frc2; -Timer::Timer() { Reset(); } +Timer::Timer() { + Reset(); +} Timer::Timer(const Timer& rhs) : m_startTime(rhs.m_startTime), @@ -101,7 +103,9 @@ void Timer::Stop() { } } -bool Timer::HasElapsed(units::second_t period) const { return Get() > period; } +bool Timer::HasElapsed(units::second_t period) const { + return Get() > period; +} bool Timer::HasPeriodPassed(units::second_t period) { return AdvanceIfElapsed(period); diff --git a/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp b/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp index a2d307bd71..0c13b4da72 100644 --- a/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp +++ b/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp @@ -82,7 +82,9 @@ void LiveWindow::DisableAllTelemetry() { std::scoped_lock lock(m_impl->mutex); m_impl->telemetryEnabled = false; m_impl->registry.ForeachLiveWindow(m_impl->dataHandle, [&](auto& cbdata) { - if (!cbdata.data) cbdata.data = std::make_shared(); + if (!cbdata.data) { + cbdata.data = std::make_shared(); + } std::static_pointer_cast(cbdata.data)->telemetryEnabled = false; }); @@ -95,18 +97,24 @@ bool LiveWindow::IsEnabled() const { void LiveWindow::SetEnabled(bool enabled) { std::scoped_lock lock(m_impl->mutex); - if (m_impl->liveWindowEnabled == enabled) return; + if (m_impl->liveWindowEnabled == enabled) { + return; + } m_impl->startLiveWindow = enabled; m_impl->liveWindowEnabled = enabled; // Force table generation now to make sure everything is defined UpdateValuesUnsafe(); if (enabled) { - if (this->enabled) this->enabled(); + if (this->enabled) { + this->enabled(); + } } else { m_impl->registry.ForeachLiveWindow(m_impl->dataHandle, [&](auto& cbdata) { cbdata.builder.StopLiveWindowMode(); }); - if (this->disabled) this->disabled(); + if (this->disabled) { + this->disabled(); + } } m_impl->enabledEntry.SetBoolean(enabled); } @@ -118,30 +126,41 @@ void LiveWindow::UpdateValues() { void LiveWindow::UpdateValuesUnsafe() { // Only do this if either LiveWindow mode or telemetry is enabled. - if (!m_impl->liveWindowEnabled && !m_impl->telemetryEnabled) return; + if (!m_impl->liveWindowEnabled && !m_impl->telemetryEnabled) { + return; + } m_impl->registry.ForeachLiveWindow(m_impl->dataHandle, [&](auto& cbdata) { - if (!cbdata.sendable || cbdata.parent) return; + if (!cbdata.sendable || cbdata.parent) { + return; + } - if (!cbdata.data) cbdata.data = std::make_shared(); + if (!cbdata.data) { + cbdata.data = std::make_shared(); + } auto& comp = *std::static_pointer_cast(cbdata.data); - if (!m_impl->liveWindowEnabled && !comp.telemetryEnabled) return; + if (!m_impl->liveWindowEnabled && !comp.telemetryEnabled) { + return; + } if (comp.firstTime) { // By holding off creating the NetworkTable entries, it allows the // components to be redefined. This allows default sensor and actuator // values to be created that are replaced with the custom names from // users calling setName. - if (cbdata.name.empty()) return; + if (cbdata.name.empty()) { + return; + } auto ssTable = m_impl->liveWindowTable->GetSubTable(cbdata.subsystem); std::shared_ptr table; // Treat name==subsystem as top level of subsystem - if (cbdata.name == cbdata.subsystem) + if (cbdata.name == cbdata.subsystem) { table = ssTable; - else + } else { table = ssTable->GetSubTable(cbdata.name); + } table->GetEntry(".name").SetString(cbdata.name); cbdata.builder.SetTable(table); cbdata.sendable->InitSendable(cbdata.builder); @@ -150,7 +169,9 @@ void LiveWindow::UpdateValuesUnsafe() { comp.firstTime = false; } - if (m_impl->startLiveWindow) cbdata.builder.StartLiveWindowMode(); + if (m_impl->startLiveWindow) { + cbdata.builder.StartLiveWindowMode(); + } cbdata.builder.UpdateTable(); }); diff --git a/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp b/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp index 020e20d884..9b812d41e5 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp @@ -6,4 +6,6 @@ using namespace frc; -wpi::StringRef LayoutType::GetLayoutName() const { return m_layoutName; } +wpi::StringRef LayoutType::GetLayoutName() const { + return m_layoutName; +} diff --git a/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp b/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp index 0750d79994..7c7e535151 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp @@ -10,13 +10,17 @@ using namespace frc; -void Shuffleboard::Update() { GetInstance().Update(); } +void Shuffleboard::Update() { + GetInstance().Update(); +} ShuffleboardTab& Shuffleboard::GetTab(wpi::StringRef title) { return GetInstance().GetTab(title); } -void Shuffleboard::SelectTab(int index) { GetInstance().SelectTab(index); } +void Shuffleboard::SelectTab(int index) { + GetInstance().SelectTab(index); +} void Shuffleboard::SelectTab(wpi::StringRef title) { GetInstance().SelectTab(title); @@ -36,7 +40,9 @@ void Shuffleboard::StartRecording() { GetRecordingController().StartRecording(); } -void Shuffleboard::StopRecording() { GetRecordingController().StopRecording(); } +void Shuffleboard::StopRecording() { + GetRecordingController().StopRecording(); +} void Shuffleboard::SetRecordingFileNameFormat(wpi::StringRef format) { GetRecordingController().SetRecordingFileNameFormat(format); diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp index 7c64f481d3..cd45c56578 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp @@ -65,7 +65,9 @@ ShuffleboardContainer& ShuffleboardComponentBase::GetParent() { return m_parent; } -const std::string& ShuffleboardComponentBase::GetType() const { return m_type; } +const std::string& ShuffleboardComponentBase::GetType() const { + return m_type; +} const wpi::StringMap>& ShuffleboardComponentBase::GetProperties() const { diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp index 512f35db64..1c91ca72e7 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp @@ -9,7 +9,9 @@ using namespace frc; ShuffleboardTab::ShuffleboardTab(ShuffleboardRoot& root, wpi::StringRef title) : ShuffleboardValue(title), ShuffleboardContainer(title), m_root(root) {} -ShuffleboardRoot& ShuffleboardTab::GetRoot() { return m_root; } +ShuffleboardRoot& ShuffleboardTab::GetRoot() { + return m_root; +} void ShuffleboardTab::BuildInto(std::shared_ptr parentTable, std::shared_ptr metaTable) { diff --git a/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp b/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp index 771e415ab7..79f7d1440d 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp @@ -6,4 +6,6 @@ using namespace frc; -wpi::StringRef WidgetType::GetWidgetName() const { return m_widgetName; } +wpi::StringRef WidgetType::GetWidgetName() const { + return m_widgetName; +} diff --git a/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp b/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp index ad49dbcb98..c2f1b0044b 100644 --- a/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp @@ -20,8 +20,9 @@ AddressableLEDSim::AddressableLEDSim(const AddressableLED& addressableLED) AddressableLEDSim AddressableLEDSim::CreateForChannel(int pwmChannel) { int index = HALSIM_FindAddressableLEDForChannel(pwmChannel); - if (index < 0) + if (index < 0) { throw std::out_of_range("no addressable LED found for PWM channel"); + } return AddressableLEDSim{index}; } diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp index 8df3402d16..625a3c0669 100644 --- a/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp @@ -71,4 +71,6 @@ void AnalogGyroSim::SetInitialized(bool initialized) { HALSIM_SetAnalogGyroInitialized(m_index, initialized); } -void AnalogGyroSim::ResetData() { HALSIM_ResetAnalogGyroData(m_index); } +void AnalogGyroSim::ResetData() { + HALSIM_ResetAnalogGyroData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp index 8e8878b652..14a659674d 100644 --- a/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp @@ -176,4 +176,6 @@ void AnalogInputSim::SetAccumulatorDeadband(int accumulatorDeadband) { HALSIM_SetAnalogInAccumulatorDeadband(m_index, accumulatorDeadband); } -void AnalogInputSim::ResetData() { HALSIM_ResetAnalogInData(m_index); } +void AnalogInputSim::ResetData() { + HALSIM_ResetAnalogInData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp index 136a9f38c5..c2b01cf87f 100644 --- a/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp @@ -53,4 +53,6 @@ void AnalogOutputSim::SetInitialized(bool initialized) { HALSIM_SetAnalogOutInitialized(m_index, initialized); } -void AnalogOutputSim::ResetData() { HALSIM_ResetAnalogOutData(m_index); } +void AnalogOutputSim::ResetData() { + HALSIM_ResetAnalogOutData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp index 6b1e261f5a..09e0a8d09f 100644 --- a/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp @@ -20,7 +20,9 @@ AnalogTriggerSim::AnalogTriggerSim(const AnalogTrigger& analogTrigger) AnalogTriggerSim AnalogTriggerSim::CreateForChannel(int channel) { int index = HALSIM_FindAnalogTriggerForChannel(channel); - if (index < 0) throw std::out_of_range("no analog trigger found for channel"); + if (index < 0) { + throw std::out_of_range("no analog trigger found for channel"); + } return AnalogTriggerSim{index}; } @@ -83,4 +85,6 @@ void AnalogTriggerSim::SetTriggerUpperBound(double triggerUpperBound) { HALSIM_SetAnalogTriggerTriggerUpperBound(m_index, triggerUpperBound); } -void AnalogTriggerSim::ResetData() { HALSIM_ResetAnalogTriggerData(m_index); } +void AnalogTriggerSim::ResetData() { + HALSIM_ResetAnalogTriggerData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp b/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp index d65601f092..54f7057eef 100644 --- a/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp +++ b/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp @@ -74,4 +74,6 @@ CallbackStore::~CallbackStore() { } } -void CallbackStore::SetUid(int32_t uid) { this->uid = uid; } +void CallbackStore::SetUid(int32_t uid) { + this->uid = uid; +} diff --git a/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp b/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp index cac22923b5..8b73b7c8f2 100644 --- a/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp @@ -47,9 +47,13 @@ std::unique_ptr DIOSim::RegisterValueCallback( return store; } -bool DIOSim::GetValue() const { return HALSIM_GetDIOValue(m_index); } +bool DIOSim::GetValue() const { + return HALSIM_GetDIOValue(m_index); +} -void DIOSim::SetValue(bool value) { HALSIM_SetDIOValue(m_index, value); } +void DIOSim::SetValue(bool value) { + HALSIM_SetDIOValue(m_index, value); +} std::unique_ptr DIOSim::RegisterPulseLengthCallback( NotifyCallback callback, bool initialNotify) { @@ -77,7 +81,9 @@ std::unique_ptr DIOSim::RegisterIsInputCallback( return store; } -bool DIOSim::GetIsInput() const { return HALSIM_GetDIOIsInput(m_index); } +bool DIOSim::GetIsInput() const { + return HALSIM_GetDIOIsInput(m_index); +} void DIOSim::SetIsInput(bool isInput) { HALSIM_SetDIOIsInput(m_index, isInput); @@ -92,10 +98,14 @@ std::unique_ptr DIOSim::RegisterFilterIndexCallback( return store; } -int DIOSim::GetFilterIndex() const { return HALSIM_GetDIOFilterIndex(m_index); } +int DIOSim::GetFilterIndex() const { + return HALSIM_GetDIOFilterIndex(m_index); +} void DIOSim::SetFilterIndex(int filterIndex) { HALSIM_SetDIOFilterIndex(m_index, filterIndex); } -void DIOSim::ResetData() { HALSIM_ResetDIOData(m_index); } +void DIOSim::ResetData() { + HALSIM_ResetDIOData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp b/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp index 7d56fb5062..eb1e02ec9a 100644 --- a/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp @@ -20,7 +20,9 @@ DigitalPWMSim::DigitalPWMSim(const DigitalOutput& digitalOutput) DigitalPWMSim DigitalPWMSim::CreateForChannel(int channel) { int index = HALSIM_FindDigitalPWMForChannel(channel); - if (index < 0) throw std::out_of_range("no digital PWM found for channel"); + if (index < 0) { + throw std::out_of_range("no digital PWM found for channel"); + } return DigitalPWMSim{index}; } @@ -71,8 +73,14 @@ std::unique_ptr DigitalPWMSim::RegisterPinCallback( return store; } -int DigitalPWMSim::GetPin() const { return HALSIM_GetDigitalPWMPin(m_index); } +int DigitalPWMSim::GetPin() const { + return HALSIM_GetDigitalPWMPin(m_index); +} -void DigitalPWMSim::SetPin(int pin) { HALSIM_SetDigitalPWMPin(m_index, pin); } +void DigitalPWMSim::SetPin(int pin) { + HALSIM_SetDigitalPWMPin(m_index, pin); +} -void DigitalPWMSim::ResetData() { HALSIM_ResetDigitalPWMData(m_index); } +void DigitalPWMSim::ResetData() { + HALSIM_ResetDigitalPWMData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp b/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp index 1c038f2a96..6530c3dc91 100644 --- a/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp @@ -24,7 +24,9 @@ std::unique_ptr DriverStationSim::RegisterEnabledCallback( return store; } -bool DriverStationSim::GetEnabled() { return HALSIM_GetDriverStationEnabled(); } +bool DriverStationSim::GetEnabled() { + return HALSIM_GetDriverStationEnabled(); +} void DriverStationSim::SetEnabled(bool enabled) { HALSIM_SetDriverStationEnabled(enabled); @@ -56,9 +58,13 @@ std::unique_ptr DriverStationSim::RegisterTestCallback( return store; } -bool DriverStationSim::GetTest() { return HALSIM_GetDriverStationTest(); } +bool DriverStationSim::GetTest() { + return HALSIM_GetDriverStationTest(); +} -void DriverStationSim::SetTest(bool test) { HALSIM_SetDriverStationTest(test); } +void DriverStationSim::SetTest(bool test) { + HALSIM_SetDriverStationTest(test); +} std::unique_ptr DriverStationSim::RegisterEStopCallback( NotifyCallback callback, bool initialNotify) { @@ -69,7 +75,9 @@ std::unique_ptr DriverStationSim::RegisterEStopCallback( return store; } -bool DriverStationSim::GetEStop() { return HALSIM_GetDriverStationEStop(); } +bool DriverStationSim::GetEStop() { + return HALSIM_GetDriverStationEStop(); +} void DriverStationSim::SetEStop(bool eStop) { HALSIM_SetDriverStationEStop(eStop); @@ -249,4 +257,6 @@ void DriverStationSim::SetReplayNumber(int replayNumber) { HALSIM_SetReplayNumber(replayNumber); } -void DriverStationSim::ResetData() { HALSIM_ResetDriverStationData(); } +void DriverStationSim::ResetData() { + HALSIM_ResetDriverStationData(); +} diff --git a/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp b/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp index 6a0a7f648e..6bc2b4ca25 100644 --- a/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp @@ -20,7 +20,9 @@ DutyCycleSim::DutyCycleSim(const DutyCycle& dutyCycle) DutyCycleSim DutyCycleSim::CreateForChannel(int channel) { int index = HALSIM_FindDutyCycleForChannel(channel); - if (index < 0) throw std::out_of_range("no duty cycle found for channel"); + if (index < 0) { + throw std::out_of_range("no duty cycle found for channel"); + } return DutyCycleSim{index}; } @@ -79,4 +81,6 @@ void DutyCycleSim::SetOutput(double period) { HALSIM_SetDutyCycleOutput(m_index, period); } -void DutyCycleSim::ResetData() { HALSIM_ResetDutyCycleData(m_index); } +void DutyCycleSim::ResetData() { + HALSIM_ResetDutyCycleData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp b/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp index c02fa762d3..146328d5cf 100644 --- a/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp @@ -20,11 +20,15 @@ EncoderSim::EncoderSim(const Encoder& encoder) EncoderSim EncoderSim::CreateForChannel(int channel) { int index = HALSIM_FindEncoderForChannel(channel); - if (index < 0) throw std::out_of_range("no encoder found for channel"); + if (index < 0) { + throw std::out_of_range("no encoder found for channel"); + } return EncoderSim{index}; } -EncoderSim EncoderSim::CreateForIndex(int index) { return EncoderSim{index}; } +EncoderSim EncoderSim::CreateForIndex(int index) { + return EncoderSim{index}; +} std::unique_ptr EncoderSim::RegisterInitializedCallback( NotifyCallback callback, bool initialNotify) { @@ -52,9 +56,13 @@ std::unique_ptr EncoderSim::RegisterCountCallback( return store; } -int EncoderSim::GetCount() const { return HALSIM_GetEncoderCount(m_index); } +int EncoderSim::GetCount() const { + return HALSIM_GetEncoderCount(m_index); +} -void EncoderSim::SetCount(int count) { HALSIM_SetEncoderCount(m_index, count); } +void EncoderSim::SetCount(int count) { + HALSIM_SetEncoderCount(m_index, count); +} std::unique_ptr EncoderSim::RegisterPeriodCallback( NotifyCallback callback, bool initialNotify) { @@ -82,7 +90,9 @@ std::unique_ptr EncoderSim::RegisterResetCallback( return store; } -bool EncoderSim::GetReset() const { return HALSIM_GetEncoderReset(m_index); } +bool EncoderSim::GetReset() const { + return HALSIM_GetEncoderReset(m_index); +} void EncoderSim::SetReset(bool reset) { HALSIM_SetEncoderReset(m_index, reset); @@ -173,14 +183,22 @@ void EncoderSim::SetDistancePerPulse(double distancePerPulse) { HALSIM_SetEncoderDistancePerPulse(m_index, distancePerPulse); } -void EncoderSim::ResetData() { HALSIM_ResetEncoderData(m_index); } +void EncoderSim::ResetData() { + HALSIM_ResetEncoderData(m_index); +} void EncoderSim::SetDistance(double distance) { HALSIM_SetEncoderDistance(m_index, distance); } -double EncoderSim::GetDistance() { return HALSIM_GetEncoderDistance(m_index); } +double EncoderSim::GetDistance() { + return HALSIM_GetEncoderDistance(m_index); +} -void EncoderSim::SetRate(double rate) { HALSIM_SetEncoderRate(m_index, rate); } +void EncoderSim::SetRate(double rate) { + HALSIM_SetEncoderRate(m_index, rate); +} -double EncoderSim::GetRate() { return HALSIM_GetEncoderRate(m_index); } +double EncoderSim::GetRate() { + return HALSIM_GetEncoderRate(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp b/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp index 30f8543293..f4981e9c8a 100644 --- a/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp @@ -15,7 +15,9 @@ GenericHIDSim::GenericHIDSim(const GenericHID& joystick) GenericHIDSim::GenericHIDSim(int port) : m_port{port} {} -void GenericHIDSim::NotifyNewData() { DriverStationSim::NotifyNewData(); } +void GenericHIDSim::NotifyNewData() { + DriverStationSim::NotifyNewData(); +} void GenericHIDSim::SetRawButton(int button, bool value) { DriverStationSim::SetJoystickButton(m_port, button, value); @@ -29,7 +31,9 @@ void GenericHIDSim::SetPOV(int pov, int value) { DriverStationSim::SetJoystickPOV(m_port, pov, value); } -void GenericHIDSim::SetPOV(int value) { SetPOV(0, value); } +void GenericHIDSim::SetPOV(int value) { + SetPOV(0, value); +} void GenericHIDSim::SetAxisCount(int count) { DriverStationSim::SetJoystickAxisCount(m_port, count); diff --git a/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp b/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp index 5c82670943..d10382274d 100644 --- a/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp @@ -55,6 +55,10 @@ void JoystickSim::SetThrottle(double value) { value); } -void JoystickSim::SetTrigger(bool state) { SetRawButton(1, state); } +void JoystickSim::SetTrigger(bool state) { + SetRawButton(1, state); +} -void JoystickSim::SetTop(bool state) { SetRawButton(2, state); } +void JoystickSim::SetTop(bool state) { + SetRawButton(2, state); +} diff --git a/wpilibc/src/main/native/cpp/simulation/PCMSim.cpp b/wpilibc/src/main/native/cpp/simulation/PCMSim.cpp index 6f32bf9b4f..57196eb0a0 100644 --- a/wpilibc/src/main/native/cpp/simulation/PCMSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/PCMSim.cpp @@ -152,4 +152,6 @@ void PCMSim::SetAllSolenoidOutputs(uint8_t outputs) { HALSIM_SetPCMAllSolenoids(m_index, outputs); } -void PCMSim::ResetData() { HALSIM_ResetPCMData(m_index); } +void PCMSim::ResetData() { + HALSIM_ResetPCMData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/PDPSim.cpp b/wpilibc/src/main/native/cpp/simulation/PDPSim.cpp index 7d2353d476..788789700c 100644 --- a/wpilibc/src/main/native/cpp/simulation/PDPSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/PDPSim.cpp @@ -61,7 +61,9 @@ std::unique_ptr PDPSim::RegisterVoltageCallback( return store; } -double PDPSim::GetVoltage() const { return HALSIM_GetPDPVoltage(m_index); } +double PDPSim::GetVoltage() const { + return HALSIM_GetPDPVoltage(m_index); +} void PDPSim::SetVoltage(double voltage) { HALSIM_SetPDPVoltage(m_index, voltage); @@ -92,4 +94,6 @@ void PDPSim::SetAllCurrents(const double* currents) { HALSIM_SetPDPAllCurrents(m_index, currents); } -void PDPSim::ResetData() { HALSIM_ResetPDPData(m_index); } +void PDPSim::ResetData() { + HALSIM_ResetPDPData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp b/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp index 64b1ca0f31..f5d69dba75 100644 --- a/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp @@ -44,7 +44,9 @@ std::unique_ptr PWMSim::RegisterRawValueCallback( return store; } -int PWMSim::GetRawValue() const { return HALSIM_GetPWMRawValue(m_index); } +int PWMSim::GetRawValue() const { + return HALSIM_GetPWMRawValue(m_index); +} void PWMSim::SetRawValue(int rawValue) { HALSIM_SetPWMRawValue(m_index, rawValue); @@ -59,9 +61,13 @@ std::unique_ptr PWMSim::RegisterSpeedCallback( return store; } -double PWMSim::GetSpeed() const { return HALSIM_GetPWMSpeed(m_index); } +double PWMSim::GetSpeed() const { + return HALSIM_GetPWMSpeed(m_index); +} -void PWMSim::SetSpeed(double speed) { HALSIM_SetPWMSpeed(m_index, speed); } +void PWMSim::SetSpeed(double speed) { + HALSIM_SetPWMSpeed(m_index, speed); +} std::unique_ptr PWMSim::RegisterPositionCallback( NotifyCallback callback, bool initialNotify) { @@ -72,7 +78,9 @@ std::unique_ptr PWMSim::RegisterPositionCallback( return store; } -double PWMSim::GetPosition() const { return HALSIM_GetPWMPosition(m_index); } +double PWMSim::GetPosition() const { + return HALSIM_GetPWMPosition(m_index); +} void PWMSim::SetPosition(double position) { HALSIM_SetPWMPosition(m_index, position); @@ -87,7 +95,9 @@ std::unique_ptr PWMSim::RegisterPeriodScaleCallback( return store; } -int PWMSim::GetPeriodScale() const { return HALSIM_GetPWMPeriodScale(m_index); } +int PWMSim::GetPeriodScale() const { + return HALSIM_GetPWMPeriodScale(m_index); +} void PWMSim::SetPeriodScale(int periodScale) { HALSIM_SetPWMPeriodScale(m_index, periodScale); @@ -102,10 +112,14 @@ std::unique_ptr PWMSim::RegisterZeroLatchCallback( return store; } -bool PWMSim::GetZeroLatch() const { return HALSIM_GetPWMZeroLatch(m_index); } +bool PWMSim::GetZeroLatch() const { + return HALSIM_GetPWMZeroLatch(m_index); +} void PWMSim::SetZeroLatch(bool zeroLatch) { HALSIM_SetPWMZeroLatch(m_index, zeroLatch); } -void PWMSim::ResetData() { HALSIM_ResetPWMData(m_index); } +void PWMSim::ResetData() { + HALSIM_ResetPWMData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp b/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp index dc2ea4e0db..84ce120d9f 100644 --- a/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp @@ -61,7 +61,9 @@ std::unique_ptr RelaySim::RegisterForwardCallback( return store; } -bool RelaySim::GetForward() const { return HALSIM_GetRelayForward(m_index); } +bool RelaySim::GetForward() const { + return HALSIM_GetRelayForward(m_index); +} void RelaySim::SetForward(bool forward) { HALSIM_SetRelayForward(m_index, forward); @@ -76,10 +78,14 @@ std::unique_ptr RelaySim::RegisterReverseCallback( return store; } -bool RelaySim::GetReverse() const { return HALSIM_GetRelayReverse(m_index); } +bool RelaySim::GetReverse() const { + return HALSIM_GetRelayReverse(m_index); +} void RelaySim::SetReverse(bool reverse) { HALSIM_SetRelayReverse(m_index, reverse); } -void RelaySim::ResetData() { HALSIM_ResetRelayData(m_index); } +void RelaySim::ResetData() { + HALSIM_ResetRelayData(m_index); +} diff --git a/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp b/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp index d4bbb9fd8e..17e038c12b 100644 --- a/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp @@ -21,7 +21,9 @@ std::unique_ptr RoboRioSim::RegisterFPGAButtonCallback( return store; } -bool RoboRioSim::GetFPGAButton() { return HALSIM_GetRoboRioFPGAButton(); } +bool RoboRioSim::GetFPGAButton() { + return HALSIM_GetRoboRioFPGAButton(); +} void RoboRioSim::SetFPGAButton(bool fPGAButton) { HALSIM_SetRoboRioFPGAButton(fPGAButton); @@ -104,7 +106,9 @@ std::unique_ptr RoboRioSim::RegisterUserActive6VCallback( return store; } -bool RoboRioSim::GetUserActive6V() { return HALSIM_GetRoboRioUserActive6V(); } +bool RoboRioSim::GetUserActive6V() { + return HALSIM_GetRoboRioUserActive6V(); +} void RoboRioSim::SetUserActive6V(bool userActive6V) { HALSIM_SetRoboRioUserActive6V(userActive6V); @@ -153,7 +157,9 @@ std::unique_ptr RoboRioSim::RegisterUserActive5VCallback( return store; } -bool RoboRioSim::GetUserActive5V() { return HALSIM_GetRoboRioUserActive5V(); } +bool RoboRioSim::GetUserActive5V() { + return HALSIM_GetRoboRioUserActive5V(); +} void RoboRioSim::SetUserActive5V(bool userActive5V) { HALSIM_SetRoboRioUserActive5V(userActive5V); @@ -202,7 +208,9 @@ std::unique_ptr RoboRioSim::RegisterUserActive3V3Callback( return store; } -bool RoboRioSim::GetUserActive3V3() { return HALSIM_GetRoboRioUserActive3V3(); } +bool RoboRioSim::GetUserActive3V3() { + return HALSIM_GetRoboRioUserActive3V3(); +} void RoboRioSim::SetUserActive3V3(bool userActive3V3) { HALSIM_SetRoboRioUserActive3V3(userActive3V3); @@ -217,7 +225,9 @@ std::unique_ptr RoboRioSim::RegisterUserFaults6VCallback( return store; } -int RoboRioSim::GetUserFaults6V() { return HALSIM_GetRoboRioUserFaults6V(); } +int RoboRioSim::GetUserFaults6V() { + return HALSIM_GetRoboRioUserFaults6V(); +} void RoboRioSim::SetUserFaults6V(int userFaults6V) { HALSIM_SetRoboRioUserFaults6V(userFaults6V); @@ -232,7 +242,9 @@ std::unique_ptr RoboRioSim::RegisterUserFaults5VCallback( return store; } -int RoboRioSim::GetUserFaults5V() { return HALSIM_GetRoboRioUserFaults5V(); } +int RoboRioSim::GetUserFaults5V() { + return HALSIM_GetRoboRioUserFaults5V(); +} void RoboRioSim::SetUserFaults5V(int userFaults5V) { HALSIM_SetRoboRioUserFaults5V(userFaults5V); @@ -247,10 +259,14 @@ std::unique_ptr RoboRioSim::RegisterUserFaults3V3Callback( return store; } -int RoboRioSim::GetUserFaults3V3() { return HALSIM_GetRoboRioUserFaults3V3(); } +int RoboRioSim::GetUserFaults3V3() { + return HALSIM_GetRoboRioUserFaults3V3(); +} void RoboRioSim::SetUserFaults3V3(int userFaults3V3) { HALSIM_SetRoboRioUserFaults3V3(userFaults3V3); } -void ResetData() { HALSIM_ResetRoboRioData(); } +void ResetData() { + HALSIM_ResetRoboRioData(); +} diff --git a/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp b/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp index 65ffc2629a..9483af30c8 100644 --- a/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp @@ -12,7 +12,9 @@ using namespace frc; using namespace frc::sim; -SPIAccelerometerSim::SPIAccelerometerSim(int index) { m_index = index; } +SPIAccelerometerSim::SPIAccelerometerSim(int index) { + m_index = index; +} std::unique_ptr SPIAccelerometerSim::RegisterActiveCallback( NotifyCallback callback, bool initialNotify) { diff --git a/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp b/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp index 85146bdc07..eee7d44e2b 100644 --- a/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp @@ -37,8 +37,12 @@ std::vector SimDeviceSim::GetEnumOptions(hal::SimEnum val) { const char** options = HALSIM_GetSimValueEnumOptions(val, &numOptions); std::vector rv; rv.reserve(numOptions); - for (int32_t i = 0; i < numOptions; ++i) rv.emplace_back(options[i]); + for (int32_t i = 0; i < numOptions; ++i) { + rv.emplace_back(options[i]); + } return rv; } -void SimDeviceSim::ResetData() { HALSIM_ResetSimDeviceData(); } +void SimDeviceSim::ResetData() { + HALSIM_ResetSimDeviceData(); +} diff --git a/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp b/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp index ec6745c7bc..9c95acefa0 100644 --- a/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp +++ b/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp @@ -9,21 +9,37 @@ namespace frc { namespace sim { -void SetRuntimeType(HAL_RuntimeType type) { HALSIM_SetRuntimeType(type); } +void SetRuntimeType(HAL_RuntimeType type) { + HALSIM_SetRuntimeType(type); +} -void WaitForProgramStart() { HALSIM_WaitForProgramStart(); } +void WaitForProgramStart() { + HALSIM_WaitForProgramStart(); +} -void SetProgramStarted() { HALSIM_SetProgramStarted(); } +void SetProgramStarted() { + HALSIM_SetProgramStarted(); +} -bool GetProgramStarted() { return HALSIM_GetProgramStarted(); } +bool GetProgramStarted() { + return HALSIM_GetProgramStarted(); +} -void RestartTiming() { HALSIM_RestartTiming(); } +void RestartTiming() { + HALSIM_RestartTiming(); +} -void PauseTiming() { HALSIM_PauseTiming(); } +void PauseTiming() { + HALSIM_PauseTiming(); +} -void ResumeTiming() { HALSIM_ResumeTiming(); } +void ResumeTiming() { + HALSIM_ResumeTiming(); +} -bool IsTimingPaused() { return HALSIM_IsTimingPaused(); } +bool IsTimingPaused() { + return HALSIM_IsTimingPaused(); +} void StepTiming(units::second_t delta) { HALSIM_StepTiming(static_cast(delta.to() * 1e6)); diff --git a/wpilibc/src/main/native/cpp/smartdashboard/Field2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/Field2d.cpp index ce43a7067f..14d14ee7b2 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/Field2d.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/Field2d.cpp @@ -50,12 +50,16 @@ FieldObject2d* Field2d::GetObject(const wpi::Twine& name) { std::scoped_lock lock(m_mutex); std::string nameStr = name.str(); for (auto&& obj : m_objects) { - if (obj->m_name == nameStr) return obj.get(); + if (obj->m_name == nameStr) { + return obj.get(); + } } m_objects.emplace_back(std::make_unique( std::move(nameStr), FieldObject2d::private_init{})); auto obj = m_objects.back().get(); - if (m_table) obj->m_entry = m_table->GetEntry(obj->m_name); + if (m_table) { + obj->m_entry = m_table->GetEntry(obj->m_name); + } return obj; } diff --git a/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp index e4e6036aae..9fa3ebebbb 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp @@ -32,7 +32,9 @@ void FieldObject2d::SetPose(units::meter_t x, units::meter_t y, Pose2d FieldObject2d::GetPose() const { std::scoped_lock lock(m_mutex); UpdateFromEntry(); - if (m_poses.empty()) return {}; + if (m_poses.empty()) { + return {}; + } return m_poses[0]; } @@ -61,7 +63,9 @@ wpi::ArrayRef FieldObject2d::GetPoses( } void FieldObject2d::UpdateEntry(bool setDefault) { - if (!m_entry) return; + if (!m_entry) { + return; + } wpi::SmallVector arr; for (auto&& pose : m_poses) { auto& translation = pose.Translation(); @@ -69,19 +73,26 @@ void FieldObject2d::UpdateEntry(bool setDefault) { arr.push_back(translation.Y().to()); arr.push_back(pose.Rotation().Degrees().to()); } - if (setDefault) + if (setDefault) { m_entry.SetDefaultDoubleArray(arr); - else + } else { m_entry.SetDoubleArray(arr); + } } void FieldObject2d::UpdateFromEntry() const { - if (!m_entry) return; + if (!m_entry) { + return; + } auto val = m_entry.GetValue(); - if (!val || !val->IsDoubleArray()) return; + if (!val || !val->IsDoubleArray()) { + return; + } auto arr = val->GetDoubleArray(); auto size = arr.size(); - if ((size % 3) != 0) return; + if ((size % 3) != 0) { + return; + } m_poses.resize(size / 3); for (size_t i = 0; i < size / 3; ++i) { m_poses[i] = diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp index 8b4271fcbd..2b92c0f531 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp @@ -9,8 +9,9 @@ using namespace frc; SendableBase::SendableBase(bool addLiveWindow) { - if (addLiveWindow) + if (addLiveWindow) { SendableRegistry::GetInstance().AddLW(this, ""); - else + } else { SendableRegistry::GetInstance().Add(this, ""); + } } diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp index a641ea3b2f..c98cda9fb5 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp @@ -20,14 +20,20 @@ std::shared_ptr SendableBuilderImpl::GetTable() { return m_table; } -bool SendableBuilderImpl::HasTable() const { return m_table != nullptr; } +bool SendableBuilderImpl::HasTable() const { + return m_table != nullptr; +} -bool SendableBuilderImpl::IsActuator() const { return m_actuator; } +bool SendableBuilderImpl::IsActuator() const { + return m_actuator; +} void SendableBuilderImpl::UpdateTable() { uint64_t time = nt::Now(); for (auto& property : m_properties) { - if (property.update) property.update(property.entry, time); + if (property.update) { + property.update(property.entry, time); + } } for (auto& updateTable : m_updateTables) { updateTable(); @@ -35,26 +41,40 @@ void SendableBuilderImpl::UpdateTable() { } void SendableBuilderImpl::StartListeners() { - for (auto& property : m_properties) property.StartListener(); - if (m_controllableEntry) m_controllableEntry.SetBoolean(true); + for (auto& property : m_properties) { + property.StartListener(); + } + if (m_controllableEntry) { + m_controllableEntry.SetBoolean(true); + } } void SendableBuilderImpl::StopListeners() { - for (auto& property : m_properties) property.StopListener(); - if (m_controllableEntry) m_controllableEntry.SetBoolean(false); + for (auto& property : m_properties) { + property.StopListener(); + } + if (m_controllableEntry) { + m_controllableEntry.SetBoolean(false); + } } void SendableBuilderImpl::StartLiveWindowMode() { - if (m_safeState) m_safeState(); + if (m_safeState) { + m_safeState(); + } StartListeners(); } void SendableBuilderImpl::StopLiveWindowMode() { StopListeners(); - if (m_safeState) m_safeState(); + if (m_safeState) { + m_safeState(); + } } -void SendableBuilderImpl::ClearProperties() { m_properties.clear(); } +void SendableBuilderImpl::ClearProperties() { + m_properties.clear(); +} void SendableBuilderImpl::SetSmartDashboardType(const wpi::Twine& type) { m_table->GetEntry(".type").SetString(type); @@ -92,7 +112,9 @@ void SendableBuilderImpl::AddBooleanProperty(const wpi::Twine& key, [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsBoolean()) return; + if (!event.value->IsBoolean()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetBoolean()); }); }, @@ -116,7 +138,9 @@ void SendableBuilderImpl::AddDoubleProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsDouble()) return; + if (!event.value->IsDouble()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetDouble()); }); }, @@ -140,7 +164,9 @@ void SendableBuilderImpl::AddStringProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsString()) return; + if (!event.value->IsString()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetString()); }); }, @@ -164,7 +190,9 @@ void SendableBuilderImpl::AddBooleanArrayProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsBooleanArray()) return; + if (!event.value->IsBooleanArray()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetBooleanArray()); }); }, @@ -188,7 +216,9 @@ void SendableBuilderImpl::AddDoubleArrayProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsDoubleArray()) return; + if (!event.value->IsDoubleArray()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetDoubleArray()); }); }, @@ -212,7 +242,9 @@ void SendableBuilderImpl::AddStringArrayProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsStringArray()) return; + if (!event.value->IsStringArray()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetStringArray()); }); }, @@ -236,7 +268,9 @@ void SendableBuilderImpl::AddRawProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsRaw()) return; + if (!event.value->IsRaw()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetRaw()); }); }, @@ -284,7 +318,9 @@ void SendableBuilderImpl::AddSmallStringProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsString()) return; + if (!event.value->IsString()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetString()); }); }, @@ -310,7 +346,9 @@ void SendableBuilderImpl::AddSmallBooleanArrayProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsBooleanArray()) return; + if (!event.value->IsBooleanArray()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetBooleanArray()); }); }, @@ -337,7 +375,9 @@ void SendableBuilderImpl::AddSmallDoubleArrayProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsDoubleArray()) return; + if (!event.value->IsDoubleArray()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetDoubleArray()); }); }, @@ -365,7 +405,9 @@ void SendableBuilderImpl::AddSmallStringArrayProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsStringArray()) return; + if (!event.value->IsStringArray()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetStringArray()); }); }, @@ -391,7 +433,9 @@ void SendableBuilderImpl::AddSmallRawProperty( [=](nt::NetworkTableEntry entry) -> NT_EntryListener { return entry.AddListener( [=](const nt::EntryNotification& event) { - if (!event.value->IsRaw()) return; + if (!event.value->IsRaw()) { + return; + } SmartDashboard::PostListenerTask( [=] { setter(event.value->GetRaw()); }); }, diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableRegistry.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableRegistry.cpp index 02bac59b45..de40d0565a 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SendableRegistry.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SendableRegistry.cpp @@ -51,9 +51,12 @@ struct SendableRegistry::Impl { SendableRegistry::Impl::Component& SendableRegistry::Impl::GetOrAdd( void* sendable, UID* uid) { UID& compUid = componentMap[sendable]; - if (compUid == 0) + if (compUid == 0) { compUid = components.emplace_back(std::make_unique()) + 1; - if (uid) *uid = compUid; + } + if (uid) { + *uid = compUid; + } return *components[compUid - 1]; } @@ -146,13 +149,17 @@ void SendableRegistry::AddChild(Sendable* parent, void* child) { bool SendableRegistry::Remove(Sendable* sendable) { std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); - if (it == m_impl->componentMap.end()) return false; + if (it == m_impl->componentMap.end()) { + return false; + } UID compUid = it->getSecond(); m_impl->components.erase(compUid - 1); m_impl->componentMap.erase(it); // update any parent pointers for (auto&& comp : m_impl->components) { - if (comp->parent == sendable) comp->parent = nullptr; + if (comp->parent == sendable) { + comp->parent = nullptr; + } } return true; } @@ -161,8 +168,9 @@ void SendableRegistry::Move(Sendable* to, Sendable* from) { std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(from); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } UID compUid = it->getSecond(); m_impl->componentMap.erase(it); m_impl->componentMap[to] = compUid; @@ -175,7 +183,9 @@ void SendableRegistry::Move(Sendable* to, Sendable* from) { } // update any parent pointers for (auto&& comp : m_impl->components) { - if (comp->parent == from) comp->parent = to; + if (comp->parent == from) { + comp->parent = to; + } } } @@ -188,8 +198,9 @@ std::string SendableRegistry::GetName(const Sendable* sendable) const { std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) - return std::string{}; + !m_impl->components[it->getSecond() - 1]) { + return {}; + } return m_impl->components[it->getSecond() - 1]->name; } @@ -197,8 +208,9 @@ void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& name) { std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } m_impl->components[it->getSecond() - 1]->name = name.str(); } @@ -207,8 +219,9 @@ void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& moduleType, std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } m_impl->components[it->getSecond() - 1]->SetName(moduleType, channel); } @@ -217,8 +230,9 @@ void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& moduleType, std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } m_impl->components[it->getSecond() - 1]->SetName(moduleType, moduleNumber, channel); } @@ -228,8 +242,9 @@ void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& subsystem, std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } auto& comp = *m_impl->components[it->getSecond() - 1]; comp.name = name.str(); comp.subsystem = subsystem.str(); @@ -239,8 +254,9 @@ std::string SendableRegistry::GetSubsystem(const Sendable* sendable) const { std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) - return std::string{}; + !m_impl->components[it->getSecond() - 1]) { + return {}; + } return m_impl->components[it->getSecond() - 1]->subsystem; } @@ -249,8 +265,9 @@ void SendableRegistry::SetSubsystem(Sendable* sendable, std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } m_impl->components[it->getSecond() - 1]->subsystem = subsystem.str(); } @@ -265,14 +282,16 @@ std::shared_ptr SendableRegistry::SetData(Sendable* sendable, int handle, std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return nullptr; + } auto& comp = *m_impl->components[it->getSecond() - 1]; std::shared_ptr rv; - if (static_cast(handle) < comp.data.size()) + if (static_cast(handle) < comp.data.size()) { rv = std::move(comp.data[handle]); - else + } else { comp.data.resize(handle + 1); + } comp.data[handle] = std::move(data); return rv; } @@ -283,10 +302,13 @@ std::shared_ptr SendableRegistry::GetData(Sendable* sendable, std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return nullptr; + } auto& comp = *m_impl->components[it->getSecond() - 1]; - if (static_cast(handle) >= comp.data.size()) return nullptr; + if (static_cast(handle) >= comp.data.size()) { + return nullptr; + } return comp.data[handle]; } @@ -294,8 +316,9 @@ void SendableRegistry::EnableLiveWindow(Sendable* sendable) { std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } m_impl->components[it->getSecond() - 1]->liveWindow = true; } @@ -303,8 +326,9 @@ void SendableRegistry::DisableLiveWindow(Sendable* sendable) { std::scoped_lock lock(m_impl->mutex); auto it = m_impl->componentMap.find(sendable); if (it == m_impl->componentMap.end() || - !m_impl->components[it->getSecond() - 1]) + !m_impl->components[it->getSecond() - 1]) { return; + } m_impl->components[it->getSecond() - 1]->liveWindow = false; } @@ -317,10 +341,13 @@ SendableRegistry::UID SendableRegistry::GetUniqueId(Sendable* sendable) { } Sendable* SendableRegistry::GetSendable(UID uid) { - if (uid == 0) return nullptr; - std::scoped_lock lock(m_impl->mutex); - if ((uid - 1) >= m_impl->components.size() || !m_impl->components[uid - 1]) + if (uid == 0) { return nullptr; + } + std::scoped_lock lock(m_impl->mutex); + if ((uid - 1) >= m_impl->components.size() || !m_impl->components[uid - 1]) { + return nullptr; + } return m_impl->components[uid - 1]->sendable; } @@ -328,8 +355,9 @@ void SendableRegistry::Publish(UID sendableUid, std::shared_ptr table) { std::scoped_lock lock(m_impl->mutex); if (sendableUid == 0 || (sendableUid - 1) >= m_impl->components.size() || - !m_impl->components[sendableUid - 1]) + !m_impl->components[sendableUid - 1]) { return; + } auto& comp = *m_impl->components[sendableUid - 1]; comp.builder = SendableBuilderImpl{}; // clear any current builder comp.builder.SetTable(table); @@ -339,11 +367,14 @@ void SendableRegistry::Publish(UID sendableUid, } void SendableRegistry::Update(UID sendableUid) { - if (sendableUid == 0) return; + if (sendableUid == 0) { + return; + } std::scoped_lock lock(m_impl->mutex); if ((sendableUid - 1) >= m_impl->components.size() || - !m_impl->components[sendableUid - 1]) + !m_impl->components[sendableUid - 1]) { return; + } m_impl->components[sendableUid - 1]->builder.UpdateTable(); } @@ -353,11 +384,14 @@ void SendableRegistry::ForeachLiveWindow( assert(dataHandle >= 0); std::scoped_lock lock(m_impl->mutex); wpi::SmallVector components; - for (auto&& comp : m_impl->components) components.emplace_back(comp.get()); + for (auto&& comp : m_impl->components) { + components.emplace_back(comp.get()); + } for (auto comp : components) { if (comp && comp->sendable && comp->liveWindow) { - if (static_cast(dataHandle) >= comp->data.size()) + if (static_cast(dataHandle) >= comp->data.size()) { comp->data.resize(dataHandle + 1); + } CallbackData cbdata{comp->sendable, comp->name, comp->subsystem, comp->parent, comp->data[dataHandle], comp->builder}; diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp index acbeda455a..35feb9de11 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp @@ -40,7 +40,9 @@ Singleton& Singleton::GetInstance() { return instance; } -void SmartDashboard::init() { Singleton::GetInstance(); } +void SmartDashboard::init() { + Singleton::GetInstance(); +} bool SmartDashboard::ContainsKey(wpi::StringRef key) { return Singleton::GetInstance().table->ContainsKey(key); @@ -106,7 +108,9 @@ void SmartDashboard::PutData(Sendable* value) { return; } auto name = SendableRegistry::GetInstance().GetName(value); - if (!name.empty()) PutData(name, value); + if (!name.empty()) { + PutData(name, value); + } } Sendable* SmartDashboard::GetData(wpi::StringRef key) { @@ -256,5 +260,7 @@ void SmartDashboard::UpdateValues() { auto& inst = Singleton::GetInstance(); listenerExecutor.RunListenerTasks(); std::scoped_lock lock(inst.tablesToDataMutex); - for (auto& i : inst.tablesToData) registry.Update(i.getValue()); + for (auto& i : inst.tablesToData) { + registry.Update(i.getValue()); + } } diff --git a/wpilibc/src/main/native/cppcs/RobotBase.cpp b/wpilibc/src/main/native/cppcs/RobotBase.cpp index 086f381eeb..4cab99cfd0 100644 --- a/wpilibc/src/main/native/cppcs/RobotBase.cpp +++ b/wpilibc/src/main/native/cppcs/RobotBase.cpp @@ -145,27 +145,41 @@ static void SetupMathShared() { std::make_unique()); } -bool RobotBase::IsEnabled() const { return m_ds.IsEnabled(); } +bool RobotBase::IsEnabled() const { + return m_ds.IsEnabled(); +} -bool RobotBase::IsDisabled() const { return m_ds.IsDisabled(); } +bool RobotBase::IsDisabled() const { + return m_ds.IsDisabled(); +} -bool RobotBase::IsAutonomous() const { return m_ds.IsAutonomous(); } +bool RobotBase::IsAutonomous() const { + return m_ds.IsAutonomous(); +} bool RobotBase::IsAutonomousEnabled() const { return m_ds.IsAutonomousEnabled(); } -bool RobotBase::IsOperatorControl() const { return m_ds.IsOperatorControl(); } +bool RobotBase::IsOperatorControl() const { + return m_ds.IsOperatorControl(); +} bool RobotBase::IsOperatorControlEnabled() const { return m_ds.IsOperatorControlEnabled(); } -bool RobotBase::IsTest() const { return m_ds.IsTest(); } +bool RobotBase::IsTest() const { + return m_ds.IsTest(); +} -bool RobotBase::IsNewDataAvailable() const { return m_ds.IsNewControlData(); } +bool RobotBase::IsNewDataAvailable() const { + return m_ds.IsNewControlData(); +} -std::thread::id RobotBase::GetThreadId() { return m_threadId; } +std::thread::id RobotBase::GetThreadId() { + return m_threadId; +} RobotBase::RobotBase() : m_ds(DriverStation::GetInstance()) { m_threadId = std::this_thread::get_id(); @@ -208,4 +222,6 @@ RobotBase::RobotBase(RobotBase&&) noexcept RobotBase::~RobotBase() {} -RobotBase& RobotBase::operator=(RobotBase&&) noexcept { return *this; } +RobotBase& RobotBase::operator=(RobotBase&&) noexcept { + return *this; +} diff --git a/wpilibc/src/main/native/include/frc/RobotBase.h b/wpilibc/src/main/native/include/frc/RobotBase.h index 14efe30863..ffc59eec50 100644 --- a/wpilibc/src/main/native/include/frc/RobotBase.h +++ b/wpilibc/src/main/native/include/frc/RobotBase.h @@ -74,15 +74,18 @@ int StartRobot() { HAL_RunMain(); // signal loop to exit - if (robot) robot->EndCompetition(); + if (robot) { + robot->EndCompetition(); + } // prefer to join, but detach to exit if it doesn't exit in a timely manner using namespace std::chrono_literals; std::unique_lock lock{m}; - if (cv.wait_for(lock, 1s, [] { return exited; })) + if (cv.wait_for(lock, 1s, [] { return exited; })) { thr.join(); - else + } else { thr.detach(); + } } else { impl::RunRobot(m, &robot); } diff --git a/wpilibc/src/main/native/include/frc/RobotDrive.h b/wpilibc/src/main/native/include/frc/RobotDrive.h index 25940d8348..c728c20a33 100644 --- a/wpilibc/src/main/native/include/frc/RobotDrive.h +++ b/wpilibc/src/main/native/include/frc/RobotDrive.h @@ -442,10 +442,18 @@ class RobotDrive : public MotorSafety { private: int GetNumMotors() { int motors = 0; - if (m_frontLeftMotor) motors++; - if (m_frontRightMotor) motors++; - if (m_rearLeftMotor) motors++; - if (m_rearRightMotor) motors++; + if (m_frontLeftMotor) { + motors++; + } + if (m_frontRightMotor) { + motors++; + } + if (m_rearLeftMotor) { + motors++; + } + if (m_rearRightMotor) { + motors++; + } return motors; } }; diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h b/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h index 5c33c2295a..e5b0c62ea1 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h @@ -83,8 +83,9 @@ inline SendableCameraWrapper& SendableCameraWrapper::Wrap( inline SendableCameraWrapper& SendableCameraWrapper::Wrap(CS_Source source) { auto& wrapper = detail::GetSendableCameraWrapper(source); - if (!wrapper) + if (!wrapper) { wrapper = std::make_shared(source, private_init{}); + } return *wrapper; } #endif diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h index bc40c079bd..087227761b 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h @@ -180,8 +180,9 @@ class SendableBuilderImpl : public SendableBuilder { ~Property() { StopListener(); } void StartListener() { - if (entry && listener == 0 && createListener) + if (entry && listener == 0 && createListener) { listener = createListener(entry); + } } void StopListener() { diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc index f2454a70fd..9ad8ff101a 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc @@ -31,7 +31,8 @@ auto SendableChooser::GetSelected() std::string selected = m_defaultChoice; { std::scoped_lock lock(m_mutex); - if (m_haveSelected) selected = m_selected; + if (m_haveSelected) + selected = m_selected; } if (selected.empty()) { return decltype(_unwrap_smart_ptr(m_choices[""])){}; @@ -85,7 +86,8 @@ void SendableChooser::InitSendable(SendableBuilder& builder) { std::scoped_lock lock(m_mutex); m_haveSelected = true; m_selected = val; - for (auto& entry : m_activeEntries) entry.SetString(val); + for (auto& entry : m_activeEntries) + entry.SetString(val); }); } diff --git a/wpilibc/src/main/native/include/frc/util/Color.h b/wpilibc/src/main/native/include/frc/util/Color.h index 07d4cae8b3..3a58f12111 100644 --- a/wpilibc/src/main/native/include/frc/util/Color.h +++ b/wpilibc/src/main/native/include/frc/util/Color.h @@ -806,7 +806,9 @@ inline bool operator==(const Color& c1, const Color& c2) { return c1.red == c2.red && c1.green == c2.green && c1.blue == c2.blue; } -inline bool operator!=(const Color& c1, const Color& c2) { return !(c1 == c2); } +inline bool operator!=(const Color& c1, const Color& c2) { + return !(c1 == c2); +} /* * FIRST Colors diff --git a/wpilibc/src/test/native/cpp/MockSpeedController.cpp b/wpilibc/src/test/native/cpp/MockSpeedController.cpp index be40e3372a..f4d3459f8b 100644 --- a/wpilibc/src/test/native/cpp/MockSpeedController.cpp +++ b/wpilibc/src/test/native/cpp/MockSpeedController.cpp @@ -10,16 +10,26 @@ void MockSpeedController::Set(double speed) { m_speed = m_isInverted ? -speed : speed; } -double MockSpeedController::Get() const { return m_speed; } +double MockSpeedController::Get() const { + return m_speed; +} void MockSpeedController::SetInverted(bool isInverted) { m_isInverted = isInverted; } -bool MockSpeedController::GetInverted() const { return m_isInverted; } +bool MockSpeedController::GetInverted() const { + return m_isInverted; +} -void MockSpeedController::Disable() { m_speed = 0; } +void MockSpeedController::Disable() { + m_speed = 0; +} -void MockSpeedController::StopMotor() { Disable(); } +void MockSpeedController::StopMotor() { + Disable(); +} -void MockSpeedController::PIDWrite(double output) { Set(output); } +void MockSpeedController::PIDWrite(double output) { + Set(output); +} diff --git a/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp index 00995487a2..90420c6f7e 100644 --- a/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp +++ b/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp @@ -27,7 +27,9 @@ TEST(SimDeviceSimTests, TestEnumerateDevices) { bool foundit = false; SimDeviceSim::EnumerateDevices( "te", [&](const char* name, HAL_SimDeviceHandle handle) { - if (wpi::StringRef(name) == "test") foundit = true; + if (wpi::StringRef(name) == "test") { + foundit = true; + } }); EXPECT_TRUE(foundit); } diff --git a/wpilibcExamples/src/main/cpp/commands/command/ReplaceMeCommand.cpp b/wpilibcExamples/src/main/cpp/commands/command/ReplaceMeCommand.cpp index c4eee91d9d..24726b013c 100644 --- a/wpilibcExamples/src/main/cpp/commands/command/ReplaceMeCommand.cpp +++ b/wpilibcExamples/src/main/cpp/commands/command/ReplaceMeCommand.cpp @@ -16,7 +16,9 @@ void ReplaceMeCommand::Initialize() {} void ReplaceMeCommand::Execute() {} // Make this return true when this Command no longer needs to run execute() -bool ReplaceMeCommand::IsFinished() { return false; } +bool ReplaceMeCommand::IsFinished() { + return false; +} // Called once after isFinished returns true void ReplaceMeCommand::End() {} diff --git a/wpilibcExamples/src/main/cpp/commands/command2/ReplaceMeCommand2.cpp b/wpilibcExamples/src/main/cpp/commands/command2/ReplaceMeCommand2.cpp index 4741e2cb87..c17d267c31 100644 --- a/wpilibcExamples/src/main/cpp/commands/command2/ReplaceMeCommand2.cpp +++ b/wpilibcExamples/src/main/cpp/commands/command2/ReplaceMeCommand2.cpp @@ -18,4 +18,6 @@ void ReplaceMeCommand2::Execute() {} void ReplaceMeCommand2::End(bool interrupted) {} // Returns true when the command should end. -bool ReplaceMeCommand2::IsFinished() { return false; } +bool ReplaceMeCommand2::IsFinished() { + return false; +} diff --git a/wpilibcExamples/src/main/cpp/commands/pidcommand/ReplaceMePIDCommand.cpp b/wpilibcExamples/src/main/cpp/commands/pidcommand/ReplaceMePIDCommand.cpp index 4f9db7b2d7..1bcc830887 100644 --- a/wpilibcExamples/src/main/cpp/commands/pidcommand/ReplaceMePIDCommand.cpp +++ b/wpilibcExamples/src/main/cpp/commands/pidcommand/ReplaceMePIDCommand.cpp @@ -20,4 +20,6 @@ ReplaceMePIDCommand::ReplaceMePIDCommand() }) {} // Returns true when the command should end. -bool ReplaceMePIDCommand::IsFinished() { return false; } +bool ReplaceMePIDCommand::IsFinished() { + return false; +} diff --git a/wpilibcExamples/src/main/cpp/commands/profiledpidcommand/ReplaceMeProfiledPIDCommand.cpp b/wpilibcExamples/src/main/cpp/commands/profiledpidcommand/ReplaceMeProfiledPIDCommand.cpp index da607eb432..880a222a3a 100644 --- a/wpilibcExamples/src/main/cpp/commands/profiledpidcommand/ReplaceMeProfiledPIDCommand.cpp +++ b/wpilibcExamples/src/main/cpp/commands/profiledpidcommand/ReplaceMeProfiledPIDCommand.cpp @@ -31,4 +31,6 @@ ReplaceMeProfiledPIDCommand::ReplaceMeProfiledPIDCommand() }) {} // Returns true when the command should end. -bool ReplaceMeProfiledPIDCommand::IsFinished() { return false; } +bool ReplaceMeProfiledPIDCommand::IsFinished() { + return false; +} diff --git a/wpilibcExamples/src/main/cpp/commands/trigger/ReplaceMeTrigger.cpp b/wpilibcExamples/src/main/cpp/commands/trigger/ReplaceMeTrigger.cpp index da65338ae3..bdea9ecbfe 100644 --- a/wpilibcExamples/src/main/cpp/commands/trigger/ReplaceMeTrigger.cpp +++ b/wpilibcExamples/src/main/cpp/commands/trigger/ReplaceMeTrigger.cpp @@ -6,4 +6,6 @@ ReplaceMeTrigger::ReplaceMeTrigger() {} -bool ReplaceMeTrigger::Get() { return false; } +bool ReplaceMeTrigger::Get() { + return false; +} diff --git a/wpilibcExamples/src/main/cpp/examples/AddressableLED/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/AddressableLED/cpp/Robot.cpp index 8c08bccd66..d59b370b4e 100644 --- a/wpilibcExamples/src/main/cpp/examples/AddressableLED/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/AddressableLED/cpp/Robot.cpp @@ -52,5 +52,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp index eb76a92b59..46e1d475c2 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp @@ -25,5 +25,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp index 9670678492..faf2f76149 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp @@ -30,5 +30,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp index 97d3c8da2f..2803c5c9a7 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp @@ -17,14 +17,18 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You * can use it to reset any subsystem information you want to clear when the * robot is disabled. */ -void Robot::DisabledInit() { m_container.DisablePIDSubsystems(); } +void Robot::DisabledInit() { + m_container.DisablePIDSubsystems(); +} void Robot::DisabledPeriodic() {} @@ -64,5 +68,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp index e4ae58d43f..3e5b98dd9c 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp @@ -55,7 +55,9 @@ void RobotContainer::ConfigureButtonBindings() { .WhenReleased([this] { m_drive.SetMaxOutput(1); }); } -void RobotContainer::DisablePIDSubsystems() { m_arm.Disable(); } +void RobotContainer::DisablePIDSubsystems() { + m_arm.Disable(); +} frc2::Command* RobotContainer::GetAutonomousCommand() { // Runs the chosen command in autonomous diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp index 75784cadcf..5ba38b8736 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp @@ -35,9 +35,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp index ec41c04893..03d341598d 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp @@ -35,9 +35,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); diff --git a/wpilibcExamples/src/main/cpp/examples/ArmSimulation/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArmSimulation/cpp/Robot.cpp index 325ce7f2fa..febf77dedc 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmSimulation/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmSimulation/cpp/Robot.cpp @@ -101,5 +101,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/AxisCameraSample/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/AxisCameraSample/cpp/Robot.cpp index 4ae8a31da9..5051fb71ed 100644 --- a/wpilibcExamples/src/main/cpp/examples/AxisCameraSample/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/AxisCameraSample/cpp/Robot.cpp @@ -58,5 +58,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/CANPDP/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/CANPDP/cpp/Robot.cpp index 3e1e21a7c9..d510e5f244 100644 --- a/wpilibcExamples/src/main/cpp/examples/CANPDP/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/CANPDP/cpp/Robot.cpp @@ -35,5 +35,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/DMA/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/DMA/cpp/Robot.cpp index 8bb0dc6c15..3eff035898 100644 --- a/wpilibcExamples/src/main/cpp/examples/DMA/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DMA/cpp/Robot.cpp @@ -75,5 +75,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Robot.cpp index eea965ec04..7f1f748ebd 100644 --- a/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Robot.cpp @@ -45,5 +45,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Robot.cpp index eea965ec04..7f1f748ebd 100644 --- a/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Robot.cpp @@ -45,5 +45,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/DutyCycleEncoder/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/DutyCycleEncoder/cpp/Robot.cpp index 6359697019..294f019910 100644 --- a/wpilibcExamples/src/main/cpp/examples/DutyCycleEncoder/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DutyCycleEncoder/cpp/Robot.cpp @@ -37,5 +37,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/DutyCycleInput/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/DutyCycleInput/cpp/Robot.cpp index faa98ca6b2..69d41bcfbc 100644 --- a/wpilibcExamples/src/main/cpp/examples/DutyCycleInput/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DutyCycleInput/cpp/Robot.cpp @@ -28,5 +28,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ElevatorProfiledPID/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ElevatorProfiledPID/cpp/Robot.cpp index a03f3e9080..927271a6f9 100644 --- a/wpilibcExamples/src/main/cpp/examples/ElevatorProfiledPID/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ElevatorProfiledPID/cpp/Robot.cpp @@ -48,5 +48,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/cpp/Robot.cpp index b28d2fcbaf..7608bd59f1 100644 --- a/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/cpp/Robot.cpp @@ -100,5 +100,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/cpp/Robot.cpp index 9d5fa9cb65..cf5fe9906a 100644 --- a/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/cpp/Robot.cpp @@ -61,5 +61,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/Encoder/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/Encoder/cpp/Robot.cpp index 1279ebbdc8..8a74d53556 100644 --- a/wpilibcExamples/src/main/cpp/examples/Encoder/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Encoder/cpp/Robot.cpp @@ -79,5 +79,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp index ec41c04893..03d341598d 100644 --- a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp @@ -35,9 +35,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); diff --git a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/ShooterSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/ShooterSubsystem.cpp index d8d62c82ce..d225e52898 100644 --- a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/ShooterSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/ShooterSubsystem.cpp @@ -26,10 +26,18 @@ void ShooterSubsystem::UseOutput(double output, double setpoint) { m_shooterFeedforward.Calculate(kShooterTargetRPS)); } -bool ShooterSubsystem::AtSetpoint() { return m_controller.AtSetpoint(); } +bool ShooterSubsystem::AtSetpoint() { + return m_controller.AtSetpoint(); +} -double ShooterSubsystem::GetMeasurement() { return m_shooterEncoder.GetRate(); } +double ShooterSubsystem::GetMeasurement() { + return m_shooterEncoder.GetRate(); +} -void ShooterSubsystem::RunFeeder() { m_feederMotor.Set(kFeederSpeed); } +void ShooterSubsystem::RunFeeder() { + m_feederMotor.Set(kFeederSpeed); +} -void ShooterSubsystem::StopFeeder() { m_feederMotor.Set(0); } +void ShooterSubsystem::StopFeeder() { + m_feederMotor.Set(0); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/CloseClaw.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/CloseClaw.cpp index a185d0acf8..d10c31009e 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/CloseClaw.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/CloseClaw.cpp @@ -12,10 +12,14 @@ CloseClaw::CloseClaw(Claw* claw) : m_claw(claw) { } // Called just before this Command runs the first time -void CloseClaw::Initialize() { m_claw->Close(); } +void CloseClaw::Initialize() { + m_claw->Close(); +} // Make this return true when this Command no longer needs to run execute() -bool CloseClaw::IsFinished() { return m_claw->IsGripping(); } +bool CloseClaw::IsFinished() { + return m_claw->IsGripping(); +} // Called once after isFinished returns true void CloseClaw::End(bool) { diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/DriveStraight.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/DriveStraight.cpp index bcf9d5981d..4e1ea8f405 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/DriveStraight.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/DriveStraight.cpp @@ -25,4 +25,6 @@ void DriveStraight::Initialize() { frc2::PIDCommand::Initialize(); } -bool DriveStraight::IsFinished() { return m_controller.AtSetpoint(); } +bool DriveStraight::IsFinished() { + return m_controller.AtSetpoint(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/OpenClaw.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/OpenClaw.cpp index aaa7e12bae..e05b7bd31b 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/OpenClaw.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/OpenClaw.cpp @@ -19,4 +19,6 @@ void OpenClaw::Initialize() { } // Called once after isFinished returns true -void OpenClaw::End(bool) { m_claw->Stop(); } +void OpenClaw::End(bool) { + m_claw->Stop(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/SetDistanceToBox.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/SetDistanceToBox.cpp index 41b91ea175..31864fb96f 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/SetDistanceToBox.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/SetDistanceToBox.cpp @@ -25,4 +25,6 @@ void SetDistanceToBox::Initialize() { frc2::PIDCommand::Initialize(); } -bool SetDistanceToBox::IsFinished() { return m_controller.AtSetpoint(); } +bool SetDistanceToBox::IsFinished() { + return m_controller.AtSetpoint(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/TankDrive.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/TankDrive.cpp index 15403e340a..663e3470d0 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/TankDrive.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/commands/TankDrive.cpp @@ -14,10 +14,16 @@ TankDrive::TankDrive(std::function left, } // Called repeatedly when this Command is scheduled to run -void TankDrive::Execute() { m_drivetrain->Drive(m_left(), m_right()); } +void TankDrive::Execute() { + m_drivetrain->Drive(m_left(), m_right()); +} // Make this return true when this Command no longer needs to run execute() -bool TankDrive::IsFinished() { return false; } +bool TankDrive::IsFinished() { + return false; +} // Called once after isFinished returns true -void TankDrive::End(bool) { m_drivetrain->Drive(0, 0); } +void TankDrive::End(bool) { + m_drivetrain->Drive(0, 0); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Claw.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Claw.cpp index 09aef4f4f5..b1560daec3 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Claw.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Claw.cpp @@ -12,16 +12,26 @@ Claw::Claw() { AddChild("Motor", &m_motor); } -void Claw::Open() { m_motor.Set(-1); } +void Claw::Open() { + m_motor.Set(-1); +} -void Claw::Close() { m_motor.Set(1); } +void Claw::Close() { + m_motor.Set(1); +} -void Claw::Stop() { m_motor.Set(0); } +void Claw::Stop() { + m_motor.Set(0); +} -bool Claw::IsGripping() { return m_contact.Get(); } +bool Claw::IsGripping() { + return m_contact.Get(); +} void Claw::Log() { frc::SmartDashboard::PutBoolean("Claw switch", IsGripping()); } -void Claw::Periodic() { Log(); } +void Claw::Periodic() { + Log(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/DriveTrain.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/DriveTrain.cpp index 8b94508ea0..00becede5f 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/DriveTrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/DriveTrain.cpp @@ -50,7 +50,9 @@ void DriveTrain::Drive(double left, double right) { m_robotDrive.TankDrive(left, right); } -double DriveTrain::GetHeading() { return m_gyro.GetAngle(); } +double DriveTrain::GetHeading() { + return m_gyro.GetAngle(); +} void DriveTrain::Reset() { m_gyro.Reset(); @@ -67,4 +69,6 @@ double DriveTrain::GetDistanceToObstacle() { return m_rangefinder.GetAverageVoltage(); } -void DriveTrain::Periodic() { Log(); } +void DriveTrain::Periodic() { + Log(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Elevator.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Elevator.cpp index c2cf8a72d9..0c195e3022 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Elevator.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Elevator.cpp @@ -21,12 +21,18 @@ Elevator::Elevator() AddChild("Pot", &m_pot); } -void Elevator::Log() { frc::SmartDashboard::PutData("Wrist Pot", &m_pot); } +void Elevator::Log() { + frc::SmartDashboard::PutData("Wrist Pot", &m_pot); +} -double Elevator::GetMeasurement() { return m_pot.Get(); } +double Elevator::GetMeasurement() { + return m_pot.Get(); +} void Elevator::UseOutput(double output, double setpoint) { m_motor.Set(output); } -void Elevator::Periodic() { Log(); } +void Elevator::Periodic() { + Log(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Wrist.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Wrist.cpp index fc422edf1f..fb3ab35da2 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Wrist.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Wrist.cpp @@ -23,8 +23,14 @@ void Wrist::Log() { frc::SmartDashboard::PutNumber("Wrist Angle", GetMeasurement()); } -double Wrist::GetMeasurement() { return m_pot.Get(); } +double Wrist::GetMeasurement() { + return m_pot.Get(); +} -void Wrist::UseOutput(double output, double setpoint) { m_motor.Set(output); } +void Wrist::UseOutput(double output, double setpoint) { + m_motor.Set(output); +} -void Wrist::Periodic() { Log(); } +void Wrist::Periodic() { + Log(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp index 9529fb3cdb..a658ec37fd 100644 --- a/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp @@ -53,5 +53,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp index 71b0381adf..90d8931e03 100644 --- a/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp @@ -53,5 +53,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngle.cpp b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngle.cpp index 58d999a7d8..7d11e04bd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngle.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngle.cpp @@ -30,4 +30,6 @@ TurnToAngle::TurnToAngle(units::degree_t target, DriveSubsystem* drive) AddRequirements({drive}); } -bool TurnToAngle::IsFinished() { return GetController().AtSetpoint(); } +bool TurnToAngle::IsFinished() { + return GetController().AtSetpoint(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngleProfiled.cpp b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngleProfiled.cpp index 5bfc6e0de3..a359625088 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngleProfiled.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/commands/TurnToAngleProfiled.cpp @@ -33,4 +33,6 @@ TurnToAngleProfiled::TurnToAngleProfiled(units::degree_t target, AddRequirements({drive}); } -bool TurnToAngleProfiled::IsFinished() { return GetController().AtGoal(); } +bool TurnToAngleProfiled::IsFinished() { + return GetController().AtGoal(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp index 6c86e1bc09..fe37a37fe5 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp @@ -35,9 +35,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); diff --git a/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp index c168122cd5..d140356ec1 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp @@ -56,5 +56,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp index ec41c04893..03d341598d 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp @@ -35,9 +35,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/DriveDistance.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/DriveDistance.cpp index c701674868..7ee1b2c930 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/DriveDistance.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/DriveDistance.cpp @@ -17,9 +17,13 @@ void DriveDistance::Initialize() { m_drive->ArcadeDrive(m_speed, 0); } -void DriveDistance::Execute() { m_drive->ArcadeDrive(m_speed, 0); } +void DriveDistance::Execute() { + m_drive->ArcadeDrive(m_speed, 0); +} -void DriveDistance::End(bool interrupted) { m_drive->ArcadeDrive(0, 0); } +void DriveDistance::End(bool interrupted) { + m_drive->ArcadeDrive(0, 0); +} bool DriveDistance::IsFinished() { return std::abs(m_drive->GetAverageEncoderDistance()) >= m_distance; diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/GrabHatch.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/GrabHatch.cpp index 28695ed709..96ebbcb3f0 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/GrabHatch.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/GrabHatch.cpp @@ -8,6 +8,10 @@ GrabHatch::GrabHatch(HatchSubsystem* subsystem) : m_hatch(subsystem) { AddRequirements({subsystem}); } -void GrabHatch::Initialize() { m_hatch->GrabHatch(); } +void GrabHatch::Initialize() { + m_hatch->GrabHatch(); +} -bool GrabHatch::IsFinished() { return true; } +bool GrabHatch::IsFinished() { + return true; +} diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/HalveDriveSpeed.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/HalveDriveSpeed.cpp index 9b40c01d48..0f561b3342 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/HalveDriveSpeed.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/HalveDriveSpeed.cpp @@ -7,6 +7,10 @@ HalveDriveSpeed::HalveDriveSpeed(DriveSubsystem* subsystem) : m_drive(subsystem) {} -void HalveDriveSpeed::Initialize() { m_drive->SetMaxOutput(0.5); } +void HalveDriveSpeed::Initialize() { + m_drive->SetMaxOutput(0.5); +} -void HalveDriveSpeed::End(bool interrupted) { m_drive->SetMaxOutput(1); } +void HalveDriveSpeed::End(bool interrupted) { + m_drive->SetMaxOutput(1); +} diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/ReleaseHatch.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/ReleaseHatch.cpp index 79d61ffcf6..7e6c9e8c2e 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/ReleaseHatch.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/commands/ReleaseHatch.cpp @@ -8,6 +8,10 @@ ReleaseHatch::ReleaseHatch(HatchSubsystem* subsystem) : m_hatch(subsystem) { AddRequirements({subsystem}); } -void ReleaseHatch::Initialize() { m_hatch->ReleaseHatch(); } +void ReleaseHatch::Initialize() { + m_hatch->ReleaseHatch(); +} -bool ReleaseHatch::IsFinished() { return true; } +bool ReleaseHatch::IsFinished() { + return true; +} diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp index ec41c04893..03d341598d 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp @@ -35,9 +35,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); diff --git a/wpilibcExamples/src/main/cpp/examples/HidRumble/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/HidRumble/cpp/Robot.cpp index d66987e603..5fcb1cac99 100644 --- a/wpilibcExamples/src/main/cpp/examples/HidRumble/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HidRumble/cpp/Robot.cpp @@ -28,5 +28,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp index 1095f78a43..923b4253cc 100644 --- a/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp @@ -71,5 +71,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumBot/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumBot/cpp/Robot.cpp index 4088e0dc72..94cb195e7f 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumBot/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumBot/cpp/Robot.cpp @@ -54,5 +54,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp index 69c073be18..bd80ad9284 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp @@ -77,7 +77,9 @@ frc::Encoder& DriveSubsystem::GetFrontLeftEncoder() { return m_frontLeftEncoder; } -frc::Encoder& DriveSubsystem::GetRearLeftEncoder() { return m_rearLeftEncoder; } +frc::Encoder& DriveSubsystem::GetRearLeftEncoder() { + return m_rearLeftEncoder; +} frc::Encoder& DriveSubsystem::GetFrontRightEncoder() { return m_frontRightEncoder; @@ -103,11 +105,17 @@ units::degree_t DriveSubsystem::GetHeading() const { return m_gyro.GetRotation2d().Degrees(); } -void DriveSubsystem::ZeroHeading() { m_gyro.Reset(); } +void DriveSubsystem::ZeroHeading() { + m_gyro.Reset(); +} -double DriveSubsystem::GetTurnRate() { return -m_gyro.GetRate(); } +double DriveSubsystem::GetTurnRate() { + return -m_gyro.GetRate(); +} -frc::Pose2d DriveSubsystem::GetPose() { return m_odometry.GetPose(); } +frc::Pose2d DriveSubsystem::GetPose() { + return m_odometry.GetPose(); +} void DriveSubsystem::ResetOdometry(frc::Pose2d pose) { m_odometry.ResetPosition(pose, m_gyro.GetRotation2d()); diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp index 3118a5b8b1..0e983848c4 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp @@ -46,5 +46,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumDrivePoseEstimator/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumDrivePoseEstimator/cpp/Robot.cpp index 4088e0dc72..94cb195e7f 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumDrivePoseEstimator/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumDrivePoseEstimator/cpp/Robot.cpp @@ -54,5 +54,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/MotorControl/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MotorControl/cpp/Robot.cpp index d5e75cd130..b5e69050b2 100644 --- a/wpilibcExamples/src/main/cpp/examples/MotorControl/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MotorControl/cpp/Robot.cpp @@ -24,5 +24,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/MotorControlEncoder/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MotorControlEncoder/cpp/Robot.cpp index 6dd7d042b9..7c9f456945 100644 --- a/wpilibcExamples/src/main/cpp/examples/MotorControlEncoder/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MotorControlEncoder/cpp/Robot.cpp @@ -45,5 +45,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/OI.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/OI.cpp index 0c794f3e23..1aff3fb8cf 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/OI.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/OI.cpp @@ -35,4 +35,6 @@ OI::OI() { new SetCollectionSpeed(Collector::kReverse)); } -frc::Joystick& OI::GetJoystick() { return m_joystick; } +frc::Joystick& OI::GetJoystick() { + return m_joystick; +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/Robot.cpp index b7fa25fea0..ac81a9dfe7 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/Robot.cpp @@ -61,9 +61,13 @@ void Robot::TeleopPeriodic() { void Robot::TestPeriodic() {} -void Robot::DisabledInit() { shooter.Unlatch(); } +void Robot::DisabledInit() { + shooter.Unlatch(); +} -void Robot::DisabledPeriodic() { Log(); } +void Robot::DisabledPeriodic() { + Log(); +} /** * Log interesting values to the SmartDashboard. @@ -78,5 +82,7 @@ void Robot::Log() { } #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CheckForHotGoal.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CheckForHotGoal.cpp index e14e76a21c..0e8fe4deca 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CheckForHotGoal.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CheckForHotGoal.cpp @@ -6,7 +6,9 @@ #include "Robot.h" -CheckForHotGoal::CheckForHotGoal(double time) { SetTimeout(time); } +CheckForHotGoal::CheckForHotGoal(double time) { + SetTimeout(time); +} // Make this return true when this Command no longer needs to run execute() bool CheckForHotGoal::IsFinished() { diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CloseClaw.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CloseClaw.cpp index ecc851960f..a1a9d7f4dd 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CloseClaw.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/CloseClaw.cpp @@ -6,7 +6,11 @@ #include "Robot.h" -CloseClaw::CloseClaw() { Requires(&Robot::collector); } +CloseClaw::CloseClaw() { + Requires(&Robot::collector); +} // Called just before this Command runs the first time -void CloseClaw::Initialize() { Robot::collector.Close(); } +void CloseClaw::Initialize() { + Robot::collector.Close(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveForward.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveForward.cpp index e64901e444..0bc74fae80 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveForward.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveForward.cpp @@ -14,9 +14,13 @@ void DriveForward::init(double dist, double maxSpeed) { m_driveForwardSpeed = maxSpeed; } -DriveForward::DriveForward() { init(10, 0.5); } +DriveForward::DriveForward() { + init(10, 0.5); +} -DriveForward::DriveForward(double dist) { init(dist, 0.5); } +DriveForward::DriveForward(double dist) { + init(dist, 0.5); +} DriveForward::DriveForward(double dist, double maxSpeed) { init(dist, maxSpeed); @@ -45,4 +49,6 @@ bool DriveForward::IsFinished() { } // Called once after isFinished returns true -void DriveForward::End() { Robot::drivetrain.Stop(); } +void DriveForward::End() { + Robot::drivetrain.Stop(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveWithJoystick.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveWithJoystick.cpp index aa1ee7a605..42e7cd7172 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveWithJoystick.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/DriveWithJoystick.cpp @@ -6,7 +6,9 @@ #include "Robot.h" -DriveWithJoystick::DriveWithJoystick() { Requires(&Robot::drivetrain); } +DriveWithJoystick::DriveWithJoystick() { + Requires(&Robot::drivetrain); +} // Called repeatedly when this Command is scheduled to run void DriveWithJoystick::Execute() { @@ -15,7 +17,11 @@ void DriveWithJoystick::Execute() { } // Make this return true when this Command no longer needs to run execute() -bool DriveWithJoystick::IsFinished() { return false; } +bool DriveWithJoystick::IsFinished() { + return false; +} // Called once after isFinished returns true -void DriveWithJoystick::End() { Robot::drivetrain.Stop(); } +void DriveWithJoystick::End() { + Robot::drivetrain.Stop(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/ExtendShooter.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/ExtendShooter.cpp index d7cfc76537..0d939776ce 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/ExtendShooter.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/ExtendShooter.cpp @@ -11,7 +11,11 @@ ExtendShooter::ExtendShooter() : frc::TimedCommand(1.0) { } // Called just before this Command runs the first time -void ExtendShooter::Initialize() { Robot::shooter.ExtendBoth(); } +void ExtendShooter::Initialize() { + Robot::shooter.ExtendBoth(); +} // Called once after isFinished returns true -void ExtendShooter::End() { Robot::shooter.RetractBoth(); } +void ExtendShooter::End() { + Robot::shooter.RetractBoth(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/OpenClaw.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/OpenClaw.cpp index 3377012e61..2bbad93c7b 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/OpenClaw.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/OpenClaw.cpp @@ -6,10 +6,16 @@ #include "Robot.h" -OpenClaw::OpenClaw() { Requires(&Robot::collector); } +OpenClaw::OpenClaw() { + Requires(&Robot::collector); +} // Called just before this Command runs the first time -void OpenClaw::Initialize() { Robot::collector.Open(); } +void OpenClaw::Initialize() { + Robot::collector.Open(); +} // Make this return true when this Command no longer needs to run execute() -bool OpenClaw::IsFinished() { return Robot::collector.IsOpen(); } +bool OpenClaw::IsFinished() { + return Robot::collector.IsOpen(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetCollectionSpeed.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetCollectionSpeed.cpp index de69adf895..d75071c569 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetCollectionSpeed.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetCollectionSpeed.cpp @@ -12,4 +12,6 @@ SetCollectionSpeed::SetCollectionSpeed(double speed) { } // Called just before this Command runs the first time -void SetCollectionSpeed::Initialize() { Robot::collector.SetSpeed(m_speed); } +void SetCollectionSpeed::Initialize() { + Robot::collector.SetSpeed(m_speed); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetPivotSetpoint.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetPivotSetpoint.cpp index 6be51d100e..1889008437 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetPivotSetpoint.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/SetPivotSetpoint.cpp @@ -18,4 +18,6 @@ void SetPivotSetpoint::Initialize() { } // Make this return true when this Command no longer needs to run execute() -bool SetPivotSetpoint::IsFinished() { return Robot::pivot.OnTarget(); } +bool SetPivotSetpoint::IsFinished() { + return Robot::pivot.OnTarget(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForBall.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForBall.cpp index c8d8970f74..1c028817e7 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForBall.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForBall.cpp @@ -6,7 +6,11 @@ #include "Robot.h" -WaitForBall::WaitForBall() { Requires(&Robot::collector); } +WaitForBall::WaitForBall() { + Requires(&Robot::collector); +} // Make this return true when this Command no longer needs to run execute() -bool WaitForBall::IsFinished() { return Robot::collector.HasBall(); } +bool WaitForBall::IsFinished() { + return Robot::collector.HasBall(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForPressure.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForPressure.cpp index 78cabf2e34..880600b088 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForPressure.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/commands/WaitForPressure.cpp @@ -6,7 +6,11 @@ #include "Robot.h" -WaitForPressure::WaitForPressure() { Requires(&Robot::pneumatics); } +WaitForPressure::WaitForPressure() { + Requires(&Robot::pneumatics); +} // Make this return true when this Command no longer needs to run execute() -bool WaitForPressure::IsFinished() { return Robot::pneumatics.IsPressurized(); } +bool WaitForPressure::IsFinished() { + return Robot::pneumatics.IsPressurized(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Collector.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Collector.cpp index 95ce9ff0b1..5d8a0d3cbd 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Collector.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Collector.cpp @@ -18,16 +18,24 @@ bool Collector::HasBall() { return m_ballDetector.Get(); // TODO: prepend ! to reflect real robot } -void Collector::SetSpeed(double speed) { m_rollerMotor.Set(-speed); } +void Collector::SetSpeed(double speed) { + m_rollerMotor.Set(-speed); +} -void Collector::Stop() { m_rollerMotor.Set(0); } +void Collector::Stop() { + m_rollerMotor.Set(0); +} bool Collector::IsOpen() { return m_openDetector.Get(); // TODO: prepend ! to reflect real robot } -void Collector::Open() { m_piston.Set(true); } +void Collector::Open() { + m_piston.Set(true); +} -void Collector::Close() { m_piston.Set(false); } +void Collector::Close() { + m_piston.Set(false); +} void Collector::InitDefaultCommand() {} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/DriveTrain.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/DriveTrain.cpp index 9897cd3188..e39972384d 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/DriveTrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/DriveTrain.cpp @@ -58,10 +58,18 @@ void DriveTrain::TankDrive(double leftAxis, double rightAxis) { m_robotDrive.TankDrive(leftAxis, rightAxis); } -void DriveTrain::Stop() { m_robotDrive.TankDrive(0.0, 0.0); } +void DriveTrain::Stop() { + m_robotDrive.TankDrive(0.0, 0.0); +} -frc::Encoder& DriveTrain::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveTrain::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveTrain::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveTrain::GetRightEncoder() { + return m_rightEncoder; +} -double DriveTrain::GetAngle() { return m_gyro.GetAngle(); } +double DriveTrain::GetAngle() { + return m_gyro.GetAngle(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Pivot.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Pivot.cpp index ae7897ba7c..c8cf025619 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Pivot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Pivot.cpp @@ -22,9 +22,13 @@ Pivot::Pivot() : frc::PIDSubsystem("Pivot", 7.0, 0.0, 8.0) { void InitDefaultCommand() {} -double Pivot::ReturnPIDInput() { return m_pot.Get(); } +double Pivot::ReturnPIDInput() { + return m_pot.Get(); +} -void Pivot::UsePIDOutput(double output) { m_motor.PIDWrite(output); } +void Pivot::UsePIDOutput(double output) { + m_motor.PIDWrite(output); +} bool Pivot::IsAtUpperLimit() { return m_upperLimitSwitch.Get(); // TODO: inverted from real robot @@ -36,4 +40,6 @@ bool Pivot::IsAtLowerLimit() { // (prefix with !) } -double Pivot::GetAngle() { return m_pot.Get(); } +double Pivot::GetAngle() { + return m_pot.Get(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Shooter.cpp b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Shooter.cpp index 2e56447fe6..b8449a7333 100644 --- a/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Shooter.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PacGoat/cpp/subsystems/Shooter.cpp @@ -27,31 +27,55 @@ void Shooter::RetractBoth() { m_piston2.Set(frc::DoubleSolenoid::kReverse); } -void Shooter::Extend1() { m_piston1.Set(frc::DoubleSolenoid::kForward); } +void Shooter::Extend1() { + m_piston1.Set(frc::DoubleSolenoid::kForward); +} -void Shooter::Retract1() { m_piston1.Set(frc::DoubleSolenoid::kReverse); } +void Shooter::Retract1() { + m_piston1.Set(frc::DoubleSolenoid::kReverse); +} -void Shooter::Extend2() { m_piston2.Set(frc::DoubleSolenoid::kReverse); } +void Shooter::Extend2() { + m_piston2.Set(frc::DoubleSolenoid::kReverse); +} -void Shooter::Retract2() { m_piston2.Set(frc::DoubleSolenoid::kForward); } +void Shooter::Retract2() { + m_piston2.Set(frc::DoubleSolenoid::kForward); +} -void Shooter::Off1() { m_piston1.Set(frc::DoubleSolenoid::kOff); } +void Shooter::Off1() { + m_piston1.Set(frc::DoubleSolenoid::kOff); +} -void Shooter::Off2() { m_piston2.Set(frc::DoubleSolenoid::kOff); } +void Shooter::Off2() { + m_piston2.Set(frc::DoubleSolenoid::kOff); +} -void Shooter::Unlatch() { m_latchPiston.Set(true); } +void Shooter::Unlatch() { + m_latchPiston.Set(true); +} -void Shooter::Latch() { m_latchPiston.Set(false); } +void Shooter::Latch() { + m_latchPiston.Set(false); +} -void Shooter::ToggleLatchPosition() { m_latchPiston.Set(!m_latchPiston.Get()); } +void Shooter::ToggleLatchPosition() { + m_latchPiston.Set(!m_latchPiston.Get()); +} -bool Shooter::Piston1IsExtended() { return !m_piston1ReedSwitchFront.Get(); } +bool Shooter::Piston1IsExtended() { + return !m_piston1ReedSwitchFront.Get(); +} -bool Shooter::Piston1IsRetracted() { return !m_piston1ReedSwitchBack.Get(); } +bool Shooter::Piston1IsRetracted() { + return !m_piston1ReedSwitchBack.Get(); +} void Shooter::OffBoth() { m_piston1.Set(frc::DoubleSolenoid::kOff); m_piston2.Set(frc::DoubleSolenoid::kOff); } -bool Shooter::GoalIsHot() { return m_hotGoalSensor.Get(); } +bool Shooter::GoalIsHot() { + return m_hotGoalSensor.Get(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/PotentiometerPID/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/PotentiometerPID/cpp/Robot.cpp index d49a28f871..d075f10346 100644 --- a/wpilibcExamples/src/main/cpp/examples/PotentiometerPID/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/PotentiometerPID/cpp/Robot.cpp @@ -66,5 +66,7 @@ class Robot : public frc::TimedRobot { constexpr std::array Robot::kSetPoints; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp index 84d6f2d8ef..b754deb277 100644 --- a/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp @@ -25,5 +25,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/subsystems/DriveSubsystem.cpp index 9a873966e8..6775b4be70 100644 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/subsystems/DriveSubsystem.cpp @@ -50,9 +50,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); @@ -62,9 +66,13 @@ units::degree_t DriveSubsystem::GetHeading() const { return m_gyro.GetRotation2d().Degrees(); } -double DriveSubsystem::GetTurnRate() { return -m_gyro.GetRate(); } +double DriveSubsystem::GetTurnRate() { + return -m_gyro.GetRate(); +} -frc::Pose2d DriveSubsystem::GetPose() { return m_odometry.GetPose(); } +frc::Pose2d DriveSubsystem::GetPose() { + return m_odometry.GetPose(); +} frc::DifferentialDriveWheelSpeeds DriveSubsystem::GetWheelSpeeds() { return {units::meters_per_second_t(m_leftEncoder.GetRate()), diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Drivetrain.cpp index 93dc8d46f3..7a6b2bd457 100644 --- a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Drivetrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Drivetrain.cpp @@ -31,4 +31,6 @@ void Drivetrain::ResetOdometry(const frc::Pose2d& pose) { m_odometry.ResetPosition(pose, m_gyro.GetRotation2d()); } -frc::Pose2d Drivetrain::GetPose() const { return m_odometry.GetPose(); } +frc::Pose2d Drivetrain::GetPose() const { + return m_odometry.GetPose(); +} diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Robot.cpp index fb0c50eac4..3dc807f57c 100644 --- a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Robot.cpp @@ -82,5 +82,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/Relay/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/Relay/cpp/Robot.cpp index 62a619eaed..b4db999a39 100644 --- a/wpilibcExamples/src/main/cpp/examples/Relay/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Relay/cpp/Robot.cpp @@ -53,5 +53,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/SchedulerEventLogging/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SchedulerEventLogging/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/SchedulerEventLogging/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SchedulerEventLogging/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp index 51bef5bbf8..b75a55d42c 100644 --- a/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp @@ -77,5 +77,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp index eed0101281..5efcdb3e96 100644 --- a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp @@ -69,5 +69,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/Solenoid/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/Solenoid/cpp/Robot.cpp index 3189138979..88ea489154 100644 --- a/wpilibcExamples/src/main/cpp/examples/Solenoid/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Solenoid/cpp/Robot.cpp @@ -65,5 +65,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp index 234e91b9db..87ed27a0a5 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp @@ -142,5 +142,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Robot.cpp index c8b30fc3da..fe132a1f4b 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Robot.cpp @@ -19,7 +19,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -79,5 +81,7 @@ void Robot::SimulationPeriodic() { } #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/RobotContainer.cpp index f2e8a5db21..f1a6512bf2 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/RobotContainer.cpp @@ -35,9 +35,13 @@ RobotContainer::RobotContainer() { {&m_drive})); } -void RobotContainer::ZeroAllOutputs() { m_drive.TankDriveVolts(0_V, 0_V); } +void RobotContainer::ZeroAllOutputs() { + m_drive.TankDriveVolts(0_V, 0_V); +} -const DriveSubsystem& RobotContainer::GetRobotDrive() const { return m_drive; } +const DriveSubsystem& RobotContainer::GetRobotDrive() const { + return m_drive; +} void RobotContainer::ConfigureButtonBindings() { // Configure your button bindings here diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/subsystems/DriveSubsystem.cpp index 6c041a365f..ec5d30cc79 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/subsystems/DriveSubsystem.cpp @@ -75,9 +75,13 @@ double DriveSubsystem::GetAverageEncoderDistance() { return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; } -frc::Encoder& DriveSubsystem::GetLeftEncoder() { return m_leftEncoder; } +frc::Encoder& DriveSubsystem::GetLeftEncoder() { + return m_leftEncoder; +} -frc::Encoder& DriveSubsystem::GetRightEncoder() { return m_rightEncoder; } +frc::Encoder& DriveSubsystem::GetRightEncoder() { + return m_rightEncoder; +} void DriveSubsystem::SetMaxOutput(double maxOutput) { m_drive.SetMaxOutput(maxOutput); @@ -87,9 +91,13 @@ units::degree_t DriveSubsystem::GetHeading() const { return m_gyro.GetRotation2d().Degrees(); } -double DriveSubsystem::GetTurnRate() { return -m_gyro.GetRate(); } +double DriveSubsystem::GetTurnRate() { + return -m_gyro.GetRate(); +} -frc::Pose2d DriveSubsystem::GetPose() { return m_odometry.GetPose(); } +frc::Pose2d DriveSubsystem::GetPose() { + return m_odometry.GetPose(); +} frc::DifferentialDriveWheelSpeeds DriveSubsystem::GetWheelSpeeds() { return {units::meters_per_second_t(m_leftEncoder.GetRate()), diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp index d539f72f0c..52a29bb249 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp @@ -140,5 +140,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheel/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheel/cpp/Robot.cpp index 8e663b1054..f523e457df 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheel/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheel/cpp/Robot.cpp @@ -116,5 +116,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheelSysId/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheelSysId/cpp/Robot.cpp index d4c46f8ed1..4ef923a0fb 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheelSysId/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceFlywheelSysId/cpp/Robot.cpp @@ -117,5 +117,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveBot/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SwerveBot/cpp/Robot.cpp index c1e82076cb..28782bfbf3 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveBot/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SwerveBot/cpp/Robot.cpp @@ -54,5 +54,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/subsystems/DriveSubsystem.cpp index dbad66bc3c..094669d7fd 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/subsystems/DriveSubsystem.cpp @@ -85,11 +85,17 @@ units::degree_t DriveSubsystem::GetHeading() const { return m_gyro.GetRotation2d().Degrees(); } -void DriveSubsystem::ZeroHeading() { m_gyro.Reset(); } +void DriveSubsystem::ZeroHeading() { + m_gyro.Reset(); +} -double DriveSubsystem::GetTurnRate() { return -m_gyro.GetRate(); } +double DriveSubsystem::GetTurnRate() { + return -m_gyro.GetRate(); +} -frc::Pose2d DriveSubsystem::GetPose() { return m_odometry.GetPose(); } +frc::Pose2d DriveSubsystem::GetPose() { + return m_odometry.GetPose(); +} void DriveSubsystem::ResetOdometry(frc::Pose2d pose) { m_odometry.ResetPosition(pose, diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveDrivePoseEstimator/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SwerveDrivePoseEstimator/cpp/Robot.cpp index c1e82076cb..28782bfbf3 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveDrivePoseEstimator/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SwerveDrivePoseEstimator/cpp/Robot.cpp @@ -54,5 +54,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp index ed33032123..f9811b107c 100644 --- a/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp @@ -28,5 +28,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/Ultrasonic/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/Ultrasonic/cpp/Robot.cpp index 7d58cb760c..1d71b37d0a 100644 --- a/wpilibcExamples/src/main/cpp/examples/Ultrasonic/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Ultrasonic/cpp/Robot.cpp @@ -55,5 +55,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp index 60ec07590c..625fa44647 100644 --- a/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp @@ -63,5 +63,7 @@ class Robot : public frc::TimedRobot { }; #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/templates/commandbased/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/templates/commandbased/cpp/Robot.cpp index 928bac17f4..8cd7b02dd3 100644 --- a/wpilibcExamples/src/main/cpp/templates/commandbased/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/templates/commandbased/cpp/Robot.cpp @@ -17,7 +17,9 @@ void Robot::RobotInit() {} *

This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ -void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} /** * This function is called once each time the robot enters Disabled mode. You @@ -64,5 +66,7 @@ void Robot::TeleopPeriodic() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/Robot.cpp index d430bc6de5..111834c215 100644 --- a/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/Robot.cpp @@ -33,7 +33,9 @@ void Robot::RobotPeriodic() {} */ void Robot::DisabledInit() {} -void Robot::DisabledPeriodic() { frc::Scheduler::GetInstance()->Run(); } +void Robot::DisabledPeriodic() { + frc::Scheduler::GetInstance()->Run(); +} /** * This autonomous (along with the chooser code above) shows how to select @@ -62,7 +64,9 @@ void Robot::AutonomousInit() { } } -void Robot::AutonomousPeriodic() { frc::Scheduler::GetInstance()->Run(); } +void Robot::AutonomousPeriodic() { + frc::Scheduler::GetInstance()->Run(); +} void Robot::TeleopInit() { // This makes sure that the autonomous stops running when @@ -75,10 +79,14 @@ void Robot::TeleopInit() { } } -void Robot::TeleopPeriodic() { frc::Scheduler::GetInstance()->Run(); } +void Robot::TeleopPeriodic() { + frc::Scheduler::GetInstance()->Run(); +} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/ExampleCommand.cpp b/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/ExampleCommand.cpp index 06ac2456be..1a861ce325 100644 --- a/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/ExampleCommand.cpp +++ b/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/ExampleCommand.cpp @@ -18,7 +18,9 @@ void ExampleCommand::Initialize() {} void ExampleCommand::Execute() {} // Make this return true when this Command no longer needs to run execute() -bool ExampleCommand::IsFinished() { return false; } +bool ExampleCommand::IsFinished() { + return false; +} // Called once after isFinished returns true void ExampleCommand::End() {} diff --git a/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/MyAutoCommand.cpp b/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/MyAutoCommand.cpp index 82a501af88..051e252cde 100644 --- a/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/MyAutoCommand.cpp +++ b/wpilibcExamples/src/main/cpp/templates/oldcommandbased/cpp/commands/MyAutoCommand.cpp @@ -18,7 +18,9 @@ void MyAutoCommand::Initialize() {} void MyAutoCommand::Execute() {} // Make this return true when this Command no longer needs to run execute() -bool MyAutoCommand::IsFinished() { return false; } +bool MyAutoCommand::IsFinished() { + return false; +} // Called once after isFinished returns true void MyAutoCommand::End() {} diff --git a/wpilibcExamples/src/main/cpp/templates/robotbaseskeleton/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/templates/robotbaseskeleton/cpp/Robot.cpp index 300a74212a..4650f7f039 100644 --- a/wpilibcExamples/src/main/cpp/templates/robotbaseskeleton/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/templates/robotbaseskeleton/cpp/Robot.cpp @@ -33,32 +33,44 @@ void Robot::StartCompetition() { m_ds.InDisabled(true); Disabled(); m_ds.InDisabled(false); - while (IsDisabled()) m_ds.WaitForData(); + while (IsDisabled()) { + m_ds.WaitForData(); + } } else if (IsAutonomous()) { m_ds.InAutonomous(true); Autonomous(); m_ds.InAutonomous(false); - while (IsAutonomousEnabled()) m_ds.WaitForData(); + while (IsAutonomousEnabled()) { + m_ds.WaitForData(); + } } else if (IsTest()) { lw.SetEnabled(true); frc::Shuffleboard::EnableActuatorWidgets(); m_ds.InTest(true); Test(); m_ds.InTest(false); - while (IsTest() && IsEnabled()) m_ds.WaitForData(); + while (IsTest() && IsEnabled()) { + m_ds.WaitForData(); + } lw.SetEnabled(false); frc::Shuffleboard::DisableActuatorWidgets(); } else { m_ds.InOperatorControl(true); Teleop(); m_ds.InOperatorControl(false); - while (IsOperatorControlEnabled()) m_ds.WaitForData(); + while (IsOperatorControlEnabled()) { + m_ds.WaitForData(); + } } } } -void Robot::EndCompetition() { m_exit = true; } +void Robot::EndCompetition() { + m_exit = true; +} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp index 49d998a882..6c04fbc9b4 100644 --- a/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp @@ -69,5 +69,7 @@ void Robot::TestInit() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcExamples/src/main/cpp/templates/timedskeleton/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/templates/timedskeleton/cpp/Robot.cpp index a9addb34d9..92f5df11f0 100644 --- a/wpilibcExamples/src/main/cpp/templates/timedskeleton/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/templates/timedskeleton/cpp/Robot.cpp @@ -20,5 +20,7 @@ void Robot::TestInit() {} void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS -int main() { return frc::StartRobot(); } +int main() { + return frc::StartRobot(); +} #endif diff --git a/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp b/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp index 16d65f8239..e53f09f4a6 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp @@ -14,7 +14,9 @@ using namespace frc; unsigned notifierCounter; -void notifierHandler(void*) { notifierCounter++; } +void notifierHandler(void*) { + notifierCounter++; +} /** * Test if the Wait function works diff --git a/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp b/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp index 4a1c62065e..27d785ec1c 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp @@ -23,7 +23,9 @@ class TestEnvironment : public testing::Environment { void SetUp() override { /* Only set up once. This allows gtest_repeat to be used to automatically repeat tests. */ - if (m_alreadySetUp) return; + if (m_alreadySetUp) { + return; + } m_alreadySetUp = true; if (!HAL_Initialize(500, 0)) { diff --git a/wpilibcIntegrationTests/src/main/native/cpp/command/MockCommand.cpp b/wpilibcIntegrationTests/src/main/native/cpp/command/MockCommand.cpp index 1ed689f949..a5eec80769 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/command/MockCommand.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/command/MockCommand.cpp @@ -19,24 +19,38 @@ MockCommand::MockCommand() { m_interruptedCount = 0; } -bool MockCommand::HasInitialized() { return GetInitializeCount() > 0; } +bool MockCommand::HasInitialized() { + return GetInitializeCount() > 0; +} -bool MockCommand::HasEnd() { return GetEndCount() > 0; } +bool MockCommand::HasEnd() { + return GetEndCount() > 0; +} -bool MockCommand::HasInterrupted() { return GetInterruptedCount() > 0; } +bool MockCommand::HasInterrupted() { + return GetInterruptedCount() > 0; +} -void MockCommand::Initialize() { ++m_initializeCount; } +void MockCommand::Initialize() { + ++m_initializeCount; +} -void MockCommand::Execute() { ++m_executeCount; } +void MockCommand::Execute() { + ++m_executeCount; +} bool MockCommand::IsFinished() { ++m_isFinishedCount; return IsHasFinished(); } -void MockCommand::End() { ++m_endCount; } +void MockCommand::End() { + ++m_endCount; +} -void MockCommand::Interrupted() { ++m_interruptedCount; } +void MockCommand::Interrupted() { + ++m_interruptedCount; +} void MockCommand::ResetCounters() { m_initializeCount = 0; diff --git a/wpilibcIntegrationTests/src/main/native/cpp/command/MockConditionalCommand.cpp b/wpilibcIntegrationTests/src/main/native/cpp/command/MockConditionalCommand.cpp index 33767ce788..c4b00f7f55 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/command/MockConditionalCommand.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/command/MockConditionalCommand.cpp @@ -20,30 +20,42 @@ void MockConditionalCommand::SetCondition(bool condition) { m_condition = condition; } -bool MockConditionalCommand::Condition() { return m_condition; } +bool MockConditionalCommand::Condition() { + return m_condition; +} bool MockConditionalCommand::HasInitialized() { return GetInitializeCount() > 0; } -bool MockConditionalCommand::HasEnd() { return GetEndCount() > 0; } +bool MockConditionalCommand::HasEnd() { + return GetEndCount() > 0; +} bool MockConditionalCommand::HasInterrupted() { return GetInterruptedCount() > 0; } -void MockConditionalCommand::Initialize() { ++m_initializeCount; } +void MockConditionalCommand::Initialize() { + ++m_initializeCount; +} -void MockConditionalCommand::Execute() { ++m_executeCount; } +void MockConditionalCommand::Execute() { + ++m_executeCount; +} bool MockConditionalCommand::IsFinished() { ++m_isFinishedCount; return ConditionalCommand::IsFinished(); } -void MockConditionalCommand::End() { ++m_endCount; } +void MockConditionalCommand::End() { + ++m_endCount; +} -void MockConditionalCommand::Interrupted() { ++m_interruptedCount; } +void MockConditionalCommand::Interrupted() { + ++m_interruptedCount; +} void MockConditionalCommand::ResetCounters() { m_initializeCount = 0; diff --git a/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp b/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp index bec00db419..8dd6482985 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp @@ -24,14 +24,15 @@ static void LoggerFunc(unsigned int level, const char* file, unsigned int line, } wpi::StringRef levelmsg; - if (level >= 50) + if (level >= 50) { levelmsg = "CRITICAL: "; - else if (level >= 40) + } else if (level >= 40) { levelmsg = "ERROR: "; - else if (level >= 30) + } else if (level >= 30) { levelmsg = "WARNING: "; - else + } else { return; + } oss << "DS: " << levelmsg << msg << " (" << file << ':' << line << ")\n"; wpi::errs() << oss.str(); } @@ -50,7 +51,9 @@ static void generateEnabledDsPacket(wpi::SmallVectorImpl& data, using namespace frc; void MockDS::start() { - if (m_active) return; + if (m_active) { + return; + } m_active = true; m_thread = std::thread([&]() { wpi::Logger logger(LoggerFunc); @@ -82,5 +85,7 @@ void MockDS::start() { void MockDS::stop() { m_active = false; - if (m_thread.joinable()) m_thread.join(); + if (m_thread.joinable()) { + m_thread.join(); + } } diff --git a/wpimath/src/dev/native/cpp/main.cpp b/wpimath/src/dev/native/cpp/main.cpp index 32da52b70f..e94f09cc01 100644 --- a/wpimath/src/dev/native/cpp/main.cpp +++ b/wpimath/src/dev/native/cpp/main.cpp @@ -6,4 +6,6 @@ #include -int main() { std::cout << wpi::math::pi << std::endl; } +int main() { + std::cout << wpi::math::pi << std::endl; +} diff --git a/wpimath/src/main/native/cpp/MathShared.cpp b/wpimath/src/main/native/cpp/MathShared.cpp index 944c2f7e19..178b878e8c 100644 --- a/wpimath/src/main/native/cpp/MathShared.cpp +++ b/wpimath/src/main/native/cpp/MathShared.cpp @@ -21,7 +21,9 @@ static wpi::mutex setLock; MathShared& MathSharedStore::GetMathShared() { std::scoped_lock lock(setLock); - if (!mathShared) mathShared = std::make_unique(); + if (!mathShared) { + mathShared = std::make_unique(); + } return *mathShared; } diff --git a/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp b/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp index 388e3455ed..9f1e3afdf5 100644 --- a/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp @@ -56,7 +56,9 @@ Rotation2d& Rotation2d::operator-=(const Rotation2d& other) { return *this; } -Rotation2d Rotation2d::operator-() const { return Rotation2d(-m_value); } +Rotation2d Rotation2d::operator-() const { + return Rotation2d(-m_value); +} Rotation2d Rotation2d::operator*(double scalar) const { return Rotation2d(m_value * scalar); diff --git a/wpimath/src/main/native/cpp/geometry/Translation2d.cpp b/wpimath/src/main/native/cpp/geometry/Translation2d.cpp index 62239f4ca6..6323b60746 100644 --- a/wpimath/src/main/native/cpp/geometry/Translation2d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Translation2d.cpp @@ -48,7 +48,9 @@ Translation2d& Translation2d::operator-=(const Translation2d& other) { return *this; } -Translation2d Translation2d::operator-() const { return {-m_x, -m_y}; } +Translation2d Translation2d::operator-() const { + return {-m_x, -m_y}; +} Translation2d Translation2d::operator*(double scalar) const { return {scalar * m_x, scalar * m_y}; diff --git a/wpimath/src/main/native/cpp/jni/WPIMathJNI.cpp b/wpimath/src/main/native/cpp/jni/WPIMathJNI.cpp index e8e01d9158..2c8f505b73 100644 --- a/wpimath/src/main/native/cpp/jni/WPIMathJNI.cpp +++ b/wpimath/src/main/native/cpp/jni/WPIMathJNI.cpp @@ -26,8 +26,9 @@ bool check_stabilizable(const Eigen::Ref& A, for (int i = 0; i < n; i++) { if (es.eigenvalues()[i].real() * es.eigenvalues()[i].real() + es.eigenvalues()[i].imag() * es.eigenvalues()[i].imag() < - 1) + 1) { continue; + } Eigen::MatrixXcd E(n, n + m); E << es.eigenvalues()[i] * Eigen::MatrixXcd::Identity(n, n) - A, B; diff --git a/wpimath/src/main/native/cpp/trajectory/Trajectory.cpp b/wpimath/src/main/native/cpp/trajectory/Trajectory.cpp index 41d88e93f6..9e08fb38f0 100644 --- a/wpimath/src/main/native/cpp/trajectory/Trajectory.cpp +++ b/wpimath/src/main/native/cpp/trajectory/Trajectory.cpp @@ -31,7 +31,9 @@ Trajectory::State Trajectory::State::Interpolate(State endValue, const auto deltaT = newT - t; // If delta time is negative, flip the order of interpolation. - if (deltaT < 0_s) return endValue.Interpolate(*this, 1.0 - i); + if (deltaT < 0_s) { + return endValue.Interpolate(*this, 1.0 - i); + } // Check whether the robot is reversing at this stage. const auto reversing = @@ -65,8 +67,12 @@ Trajectory::Trajectory(const std::vector& states) : m_states(states) { } Trajectory::State Trajectory::Sample(units::second_t t) const { - if (t <= m_states.front().t) return m_states.front(); - if (t >= m_totalTime) return m_states.back(); + if (t <= m_states.front().t) { + return m_states.front(); + } + if (t >= m_totalTime) { + return m_states.back(); + } // Use binary search to get the element with a timestamp no less than the // requested timestamp. This starts at 1 because we use the previous state diff --git a/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp b/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp index 41341a4cb4..475c7c4257 100644 --- a/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp +++ b/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp @@ -19,10 +19,11 @@ const Trajectory TrajectoryGenerator::kDoNothingTrajectory( std::function TrajectoryGenerator::s_errorFunc; void TrajectoryGenerator::ReportError(const char* error) { - if (s_errorFunc) + if (s_errorFunc) { s_errorFunc(error); - else + } else { wpi::errs() << "TrajectoryGenerator error: " << error << "\n"; + } } Trajectory TrajectoryGenerator::GenerateTrajectory( @@ -112,8 +113,11 @@ Trajectory TrajectoryGenerator::GenerateTrajectory( const std::vector& waypoints, const TrajectoryConfig& config) { auto newWaypoints = waypoints; const Transform2d flip{Translation2d(), Rotation2d(180_deg)}; - if (config.IsReversed()) - for (auto& waypoint : newWaypoints) waypoint += flip; + if (config.IsReversed()) { + for (auto& waypoint : newWaypoints) { + waypoint += flip; + } + } std::vector points; try { diff --git a/wpimath/src/main/native/cpp/trajectory/TrajectoryParameterizer.cpp b/wpimath/src/main/native/cpp/trajectory/TrajectoryParameterizer.cpp index 4a2a87a819..98181dc6f0 100644 --- a/wpimath/src/main/native/cpp/trajectory/TrajectoryParameterizer.cpp +++ b/wpimath/src/main/native/cpp/trajectory/TrajectoryParameterizer.cpp @@ -85,7 +85,9 @@ Trajectory TrajectoryParameterizer::TimeParameterizeTrajectory( // Now enforce all acceleration limits. EnforceAccelerationLimits(reversed, constraints, &constrainedState); - if (ds.to() < kEpsilon) break; + if (ds.to() < kEpsilon) { + break; + } // If the actual acceleration for this state is higher than the max // acceleration that we applied, then we need to reduce the max @@ -130,14 +132,18 @@ Trajectory TrajectoryParameterizer::TimeParameterizeTrajectory( successor.minAcceleration * ds * 2.0); // No more limits to impose! This state can be finalized. - if (newMaxVelocity >= constrainedState.maxVelocity) break; + if (newMaxVelocity >= constrainedState.maxVelocity) { + break; + } constrainedState.maxVelocity = newMaxVelocity; // Check all acceleration constraints with the new max velocity. EnforceAccelerationLimits(reversed, constraints, &constrainedState); - if (ds.to() > -kEpsilon) break; + if (ds.to() > -kEpsilon) { + break; + } // If the actual acceleration for this state is lower than the min // acceleration, then we need to lower the min acceleration of the diff --git a/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h b/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h index 9ea0b8c626..5565b8a628 100644 --- a/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h +++ b/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h @@ -14,7 +14,9 @@ double NormalizeAngle(double angle) { static constexpr double tau = 2 * wpi::math::pi; angle -= std::floor(angle / tau) * tau; - if (angle > wpi::math::pi) angle -= tau; + if (angle > wpi::math::pi) { + angle -= tau; + } return angle; } } // namespace diff --git a/wpiutil/examples/webserver/webserver.cpp b/wpiutil/examples/webserver/webserver.cpp index 67d19cdaaa..1147c686f3 100644 --- a/wpiutil/examples/webserver/webserver.cpp +++ b/wpiutil/examples/webserver/webserver.cpp @@ -33,11 +33,15 @@ void MyHttpServerConnection::ProcessRequest() { } wpi::StringRef path; - if (url.HasPath()) path = url.GetPath(); + if (url.HasPath()) { + path = url.GetPath(); + } wpi::errs() << "path: \"" << path << "\"\n"; wpi::StringRef query; - if (url.HasQuery()) query = url.GetQuery(); + if (url.HasQuery()) { + query = url.GetQuery(); + } wpi::errs() << "query: \"" << query << "\"\n"; const bool isGET = m_request.GetMethod() == wpi::HTTP_GET; @@ -66,7 +70,9 @@ int main() { // when we get a connection, accept it and start reading tcp->connection.connect([srv = tcp.get()] { auto tcp = srv->Accept(); - if (!tcp) return; + if (!tcp) { + return; + } wpi::errs() << "Got a connection\n"; auto conn = std::make_shared(tcp); tcp->SetData(conn); diff --git a/wpiutil/src/main/native/cpp/Base64.cpp b/wpiutil/src/main/native/cpp/Base64.cpp index 35ac76c5a8..4d13b1a613 100644 --- a/wpiutil/src/main/native/cpp/Base64.cpp +++ b/wpiutil/src/main/native/cpp/Base64.cpp @@ -82,9 +82,13 @@ static const unsigned char pr2six[256] = { size_t Base64Decode(raw_ostream& os, StringRef encoded) { const unsigned char* end = encoded.bytes_begin(); - while (pr2six[*end] <= 63 && end != encoded.bytes_end()) ++end; + while (pr2six[*end] <= 63 && end != encoded.bytes_end()) { + ++end; + } size_t nprbytes = end - encoded.bytes_begin(); - if (nprbytes == 0) return 0; + if (nprbytes == 0) { + return 0; + } const unsigned char* cur = encoded.bytes_begin(); @@ -97,12 +101,15 @@ size_t Base64Decode(raw_ostream& os, StringRef encoded) { } // Note: (nprbytes == 1) would be an error, so just ignore that case - if (nprbytes > 1) + if (nprbytes > 1) { os << static_cast(pr2six[cur[0]] << 2 | pr2six[cur[1]] >> 4); - if (nprbytes > 2) + } + if (nprbytes > 2) { os << static_cast(pr2six[cur[1]] << 4 | pr2six[cur[2]] >> 2); - if (nprbytes > 3) + } + if (nprbytes > 3) { os << static_cast(pr2six[cur[2]] << 6 | pr2six[cur[3]]); + } return (end - encoded.bytes_begin()) + ((4 - nprbytes) & 3); } @@ -127,7 +134,9 @@ static const char basis_64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; void Base64Encode(raw_ostream& os, StringRef plain) { - if (plain.empty()) return; + if (plain.empty()) { + return; + } size_t len = plain.size(); size_t i; diff --git a/wpiutil/src/main/native/cpp/EventLoopRunner.cpp b/wpiutil/src/main/native/cpp/EventLoopRunner.cpp index 71b9103c0d..41768c19ce 100644 --- a/wpiutil/src/main/native/cpp/EventLoopRunner.cpp +++ b/wpiutil/src/main/native/cpp/EventLoopRunner.cpp @@ -18,7 +18,9 @@ class EventLoopRunner::Thread : public SafeThread { Thread() : m_loop(uv::Loop::Create()) { // set up async handles - if (!m_loop) return; + if (!m_loop) { + return; + } // run function m_doExec = UvExecFunc::Create( @@ -29,7 +31,9 @@ class EventLoopRunner::Thread : public SafeThread { } void Main() { - if (m_loop) m_loop->Run(); + if (m_loop) { + m_loop->Run(); + } } // the loop @@ -39,9 +43,13 @@ class EventLoopRunner::Thread : public SafeThread { std::weak_ptr m_doExec; }; -EventLoopRunner::EventLoopRunner() { m_owner.Start(); } +EventLoopRunner::EventLoopRunner() { + m_owner.Start(); +} -EventLoopRunner::~EventLoopRunner() { Stop(); } +EventLoopRunner::~EventLoopRunner() { + Stop(); +} void EventLoopRunner::Stop() { ExecAsync([](uv::Loop& loop) { @@ -69,10 +77,14 @@ void EventLoopRunner::ExecSync(LoopFunc func) { f = doExec->Call(func); } } - if (f.valid()) f.wait(); + if (f.valid()) { + f.wait(); + } } std::shared_ptr EventLoopRunner::GetLoop() { - if (auto thr = m_owner.GetThread()) return thr->m_loop; + if (auto thr = m_owner.GetThread()) { + return thr->m_loop; + } return nullptr; } diff --git a/wpiutil/src/main/native/cpp/HttpParser.cpp b/wpiutil/src/main/native/cpp/HttpParser.cpp index 5fda50f391..4733befb48 100644 --- a/wpiutil/src/main/native/cpp/HttpParser.cpp +++ b/wpiutil/src/main/native/cpp/HttpParser.cpp @@ -34,7 +34,9 @@ HttpParser::HttpParser(Type type) { m_settings.on_url = [](http_parser* p, const char* at, size_t length) -> int { auto& self = *static_cast(p->data); // append to buffer - if ((self.m_urlBuf.size() + length) > self.m_maxLength) return 1; + if ((self.m_urlBuf.size() + length) > self.m_maxLength) { + return 1; + } self.m_urlBuf += StringRef{at, length}; self.m_state = kUrl; return 0; @@ -45,7 +47,9 @@ HttpParser::HttpParser(Type type) { size_t length) -> int { auto& self = *static_cast(p->data); // use valueBuf for the status - if ((self.m_valueBuf.size() + length) > self.m_maxLength) return 1; + if ((self.m_valueBuf.size() + length) > self.m_maxLength) { + return 1; + } self.m_valueBuf += StringRef{at, length}; self.m_state = kStatus; return 0; @@ -59,19 +63,25 @@ HttpParser::HttpParser(Type type) { // once we're in header, we know the URL is complete if (self.m_state == kUrl) { self.url(self.m_urlBuf); - if (self.m_aborted) return 1; + if (self.m_aborted) { + return 1; + } } // once we're in header, we know the status is complete if (self.m_state == kStatus) { self.status(self.m_valueBuf); - if (self.m_aborted) return 1; + if (self.m_aborted) { + return 1; + } } // if we previously were in value state, that means we finished a header if (self.m_state == kValue) { self.header(self.m_fieldBuf, self.m_valueBuf); - if (self.m_aborted) return 1; + if (self.m_aborted) { + return 1; + } } // clear field and value when we enter this state @@ -82,7 +92,9 @@ HttpParser::HttpParser(Type type) { } // append data to field buffer - if ((self.m_fieldBuf.size() + length) > self.m_maxLength) return 1; + if ((self.m_fieldBuf.size() + length) > self.m_maxLength) { + return 1; + } self.m_fieldBuf += StringRef{at, length}; return 0; }; @@ -99,7 +111,9 @@ HttpParser::HttpParser(Type type) { } // append data to value buffer - if ((self.m_valueBuf.size() + length) > self.m_maxLength) return 1; + if ((self.m_valueBuf.size() + length) > self.m_maxLength) { + return 1; + } self.m_valueBuf += StringRef{at, length}; return 0; }; @@ -111,19 +125,25 @@ HttpParser::HttpParser(Type type) { // if we previously were in url state, that means we finished the url if (self.m_state == kUrl) { self.url(self.m_urlBuf); - if (self.m_aborted) return 1; + if (self.m_aborted) { + return 1; + } } // if we previously were in status state, that means we finished the status if (self.m_state == kStatus) { self.status(self.m_valueBuf); - if (self.m_aborted) return 1; + if (self.m_aborted) { + return 1; + } } // if we previously were in value state, that means we finished a header if (self.m_state == kValue) { self.header(self.m_fieldBuf, self.m_valueBuf); - if (self.m_aborted) return 1; + if (self.m_aborted) { + return 1; + } } self.headersComplete(self.ShouldKeepAlive()); diff --git a/wpiutil/src/main/native/cpp/HttpServerConnection.cpp b/wpiutil/src/main/native/cpp/HttpServerConnection.cpp index dbb4cc451a..b7352abbcc 100644 --- a/wpiutil/src/main/native/cpp/HttpServerConnection.cpp +++ b/wpiutil/src/main/native/cpp/HttpServerConnection.cpp @@ -60,15 +60,23 @@ void HttpServerConnection::BuildHeader(raw_ostream& os, int code, const Twine& extra) { os << "HTTP/" << m_request.GetMajor() << '.' << m_request.GetMinor() << ' ' << code << ' ' << codeText << "\r\n"; - if (contentLength == 0) m_keepAlive = false; - if (!m_keepAlive) os << "Connection: close\r\n"; + if (contentLength == 0) { + m_keepAlive = false; + } + if (!m_keepAlive) { + os << "Connection: close\r\n"; + } BuildCommonHeaders(os); os << "Content-Type: " << contentType << "\r\n"; - if (contentLength != 0) os << "Content-Length: " << contentLength << "\r\n"; + if (contentLength != 0) { + os << "Content-Length: " << contentLength << "\r\n"; + } os << "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: *\r\n"; SmallString<128> extraBuf; StringRef extraStr = extra.toStringRef(extraBuf); - if (!extraStr.empty()) os << extraStr; + if (!extraStr.empty()) { + os << extraStr; + } os << "\r\n"; // header ends with a blank line } @@ -76,8 +84,12 @@ void HttpServerConnection::SendData(ArrayRef bufs, bool closeAfter) { m_stream.Write(bufs, [closeAfter, stream = &m_stream]( MutableArrayRef bufs, uv::Error) { - for (auto&& buf : bufs) buf.Deallocate(); - if (closeAfter) stream->Close(); + for (auto&& buf : bufs) { + buf.Deallocate(); + } + if (closeAfter) { + stream->Close(); + } }); } @@ -100,8 +112,9 @@ void HttpServerConnection::SendStaticResponse(int code, const Twine& codeText, // TODO: handle remote side not accepting gzip (very rare) StringRef contentEncodingHeader; - if (gzipped /* && m_acceptGzip*/) + if (gzipped /* && m_acceptGzip*/) { contentEncodingHeader = "Content-Encoding: gzip\r\n"; + } SmallVector bufs; raw_uv_ostream os{bufs, 4096}; @@ -113,8 +126,12 @@ void HttpServerConnection::SendStaticResponse(int code, const Twine& codeText, m_stream.Write(bufs, [closeAfter = !m_keepAlive, stream = &m_stream]( MutableArrayRef bufs, uv::Error) { // don't deallocate the static content - for (auto&& buf : bufs.drop_back()) buf.Deallocate(); - if (closeAfter) stream->Close(); + for (auto&& buf : bufs.drop_back()) { + buf.Deallocate(); + } + if (closeAfter) { + stream->Close(); + } }); } diff --git a/wpiutil/src/main/native/cpp/HttpUtil.cpp b/wpiutil/src/main/native/cpp/HttpUtil.cpp index 531749e27f..086fdc87b7 100644 --- a/wpiutil/src/main/native/cpp/HttpUtil.cpp +++ b/wpiutil/src/main/native/cpp/HttpUtil.cpp @@ -23,10 +23,11 @@ StringRef UnescapeURI(const Twine& str, SmallVectorImpl& buf, // pass non-escaped characters to output if (*i != '%') { // decode + to space - if (*i == '+') + if (*i == '+') { buf.push_back(' '); - else + } else { buf.push_back(*i); + } continue; } @@ -92,17 +93,23 @@ HttpQueryMap::HttpQueryMap(wpi::StringRef query) { bool err = false; auto name = wpi::UnescapeURI(nameEsc, nameBuf, &err); // note: ignores duplicates - if (!err) m_elems.try_emplace(name, valueEsc); + if (!err) { + m_elems.try_emplace(name, valueEsc); + } } } std::optional HttpQueryMap::Get( wpi::StringRef name, wpi::SmallVectorImpl& buf) const { auto it = m_elems.find(name); - if (it == m_elems.end()) return {}; + if (it == m_elems.end()) { + return {}; + } bool err = false; auto val = wpi::UnescapeURI(it->second, buf, &err); - if (err) return {}; + if (err) { + return {}; + } return val; } @@ -128,12 +135,16 @@ HttpPath::HttpPath(wpi::StringRef path) { } bool HttpPath::startswith(size_t start, ArrayRef match) const { - if (m_pathEnds.size() < (start + match.size())) return false; + if (m_pathEnds.size() < (start + match.size())) { + return false; + } bool first = start == 0; auto p = m_pathEnds.begin() + start; for (auto m : match) { auto val = m_pathBuf.slice(first ? 0 : *(p - 1), *p); - if (val != m) return false; + if (val != m) { + return false; + } first = false; ++p; } @@ -142,16 +153,24 @@ bool HttpPath::startswith(size_t start, ArrayRef match) const { bool ParseHttpHeaders(raw_istream& is, SmallVectorImpl* contentType, SmallVectorImpl* contentLength) { - if (contentType) contentType->clear(); - if (contentLength) contentLength->clear(); + if (contentType) { + contentType->clear(); + } + if (contentLength) { + contentLength->clear(); + } bool inContentType = false; bool inContentLength = false; SmallString<64> lineBuf; for (;;) { StringRef line = is.getline(lineBuf, 1024).rtrim(); - if (is.has_error()) return false; - if (line.empty()) return true; // empty line signals end of headers + if (is.has_error()) { + return false; + } + if (line.empty()) { + return true; // empty line signals end of headers + } // header fields start at the beginning of the line if (!std::isspace(line[0])) { @@ -160,22 +179,24 @@ bool ParseHttpHeaders(raw_istream& is, SmallVectorImpl* contentType, StringRef field; std::tie(field, line) = line.split(':'); field = field.rtrim(); - if (field.equals_lower("content-type")) + if (field.equals_lower("content-type")) { inContentType = true; - else if (field.equals_lower("content-length")) + } else if (field.equals_lower("content-length")) { inContentLength = true; - else + } else { continue; // ignore other fields + } } // collapse whitespace line = line.ltrim(); // save field data - if (inContentType && contentType) + if (inContentType && contentType) { contentType->append(line.begin(), line.end()); - else if (inContentLength && contentLength) + } else if (inContentLength && contentLength) { contentLength->append(line.begin(), line.end()); + } } } @@ -191,7 +212,9 @@ bool FindMultipartBoundary(raw_istream& is, StringRef boundary, if (!saveBuf) { do { is.read(searchBuf.data(), 1); - if (is.has_error()) return false; + if (is.has_error()) { + return false; + } } while (searchBuf[0] == '\r' || searchBuf[0] == '\n'); searchPos = 1; } @@ -202,19 +225,26 @@ bool FindMultipartBoundary(raw_istream& is, StringRef boundary, // there's a bunch of continuous -'s in the output, but that's unlikely. for (;;) { is.read(searchBuf.data() + searchPos, searchBuf.size() - searchPos); - if (is.has_error()) return false; + if (is.has_error()) { + return false; + } // Did we find the boundary? if (searchBuf[0] == '-' && searchBuf[1] == '-' && - searchBuf.substr(2) == boundary) + searchBuf.substr(2) == boundary) { return true; + } // Fast-scan for '-' size_t pos = searchBuf.find('-', searchBuf[0] == '-' ? 1 : 0); if (pos == StringRef::npos) { - if (saveBuf) saveBuf->append(searchBuf.data(), searchBuf.size()); + if (saveBuf) { + saveBuf->append(searchBuf.data(), searchBuf.size()); + } } else { - if (saveBuf) saveBuf->append(searchBuf.data(), pos); + if (saveBuf) { + saveBuf->append(searchBuf.data(), pos); + } // move '-' and following to start of buffer (next read will fill) std::memmove(searchBuf.data(), searchBuf.data() + pos, @@ -305,7 +335,9 @@ HttpLocation::HttpLocation(const Twine& url_, bool* error, // split out next param and value StringRef rawParam, rawValue; std::tie(rawParam, query) = query.split('&'); - if (rawParam.empty()) continue; // ignore "&&" + if (rawParam.empty()) { + continue; // ignore "&&" + } std::tie(rawParam, rawValue) = rawParam.split('='); // unescape param @@ -350,8 +382,9 @@ bool HttpConnection::Handshake(const HttpRequest& request, // send GET request os << "GET /" << request.path << " HTTP/1.1\r\n"; os << "Host: " << request.host << "\r\n"; - if (!request.auth.empty()) + if (!request.auth.empty()) { os << "Authorization: Basic " << request.auth << "\r\n"; + } os << "\r\n"; os.flush(); @@ -404,8 +437,12 @@ void HttpMultipartScanner::Reset(bool saveSkipped) { } StringRef HttpMultipartScanner::Execute(StringRef in) { - if (m_state == kDone) Reset(m_saveSkipped); - if (m_saveSkipped) m_buf += in; + if (m_state == kDone) { + Reset(m_saveSkipped); + } + if (m_saveSkipped) { + m_buf += in; + } size_t pos = 0; if (m_state == kBoundary) { @@ -451,7 +488,9 @@ StringRef HttpMultipartScanner::Execute(StringRef in) { if (ch == '\n') { // Found the LF; return remaining input buffer (following it) m_state = kDone; - if (m_saveSkipped) m_buf.resize(m_buf.size() - in.size() + pos); + if (m_saveSkipped) { + m_buf.resize(m_buf.size() - in.size() + pos); + } return in.drop_front(pos); } } diff --git a/wpiutil/src/main/native/cpp/PortForwarder.cpp b/wpiutil/src/main/native/cpp/PortForwarder.cpp index 910f11d956..f385f26c4a 100644 --- a/wpiutil/src/main/native/cpp/PortForwarder.cpp +++ b/wpiutil/src/main/native/cpp/PortForwarder.cpp @@ -37,7 +37,9 @@ static void CopyStream(uv::Stream& in, std::weak_ptr outWeak) { return; } out->Write(buf2, [](auto bufs, uv::Error) { - for (auto buf : bufs) buf.Deallocate(); + for (auto buf : bufs) { + buf.Deallocate(); + } }); }); } @@ -55,7 +57,9 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, host = remoteHost.str(), remotePort] { auto& loop = serverPtr->GetLoopRef(); auto client = serverPtr->Accept(); - if (!client) return; + if (!client) { + return; + } // close on error client->error.connect( @@ -70,7 +74,9 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, [remotePtr = remote.get(), clientWeak = std::weak_ptr(client)](uv::Error err) { remotePtr->Close(); - if (auto client = clientWeak.lock()) client->Close(); + if (auto client = clientWeak.lock()) { + client->Close(); + } }); // convert port to string @@ -83,7 +89,9 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, [clientWeak = std::weak_ptr(client), remoteWeak = std::weak_ptr(remote)](const addrinfo& addr) { auto remote = remoteWeak.lock(); - if (!remote) return; + if (!remote) { + return; + } // connect to remote address/port remote->Connect(*addr.ai_addr, [remotePtr = remote.get(), @@ -98,11 +106,15 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, // close both when either side closes client->end.connect([clientPtr = client.get(), remoteWeak] { clientPtr->Close(); - if (auto remote = remoteWeak.lock()) remote->Close(); + if (auto remote = remoteWeak.lock()) { + remote->Close(); + } }); remotePtr->end.connect([remotePtr, clientWeak] { remotePtr->Close(); - if (auto client = clientWeak.lock()) client->Close(); + if (auto client = clientWeak.lock()) { + client->Close(); + } }); // copy bidirectionally @@ -121,10 +133,12 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, remoteWeak = std::weak_ptr(remote)] { if (auto connected = connectedWeak.lock()) { if (!*connected) { - if (auto client = clientWeak.lock()) + if (auto client = clientWeak.lock()) { client->Close(); - if (auto remote = remoteWeak.lock()) + } + if (auto remote = remoteWeak.lock()) { remote->Close(); + } } } }); diff --git a/wpiutil/src/main/native/cpp/SafeThread.cpp b/wpiutil/src/main/native/cpp/SafeThread.cpp index b48e499aaa..bbecc5c232 100644 --- a/wpiutil/src/main/native/cpp/SafeThread.cpp +++ b/wpiutil/src/main/native/cpp/SafeThread.cpp @@ -9,7 +9,9 @@ using namespace wpi; detail::SafeThreadProxyBase::SafeThreadProxyBase( std::shared_ptr thr) : m_thread(std::move(thr)) { - if (!m_thread) return; + if (!m_thread) { + return; + } m_lock = std::unique_lock(m_thread->m_mutex); if (!m_thread->m_active) { m_lock.unlock(); @@ -19,15 +21,18 @@ detail::SafeThreadProxyBase::SafeThreadProxyBase( } detail::SafeThreadOwnerBase::~SafeThreadOwnerBase() { - if (m_joinAtExit) + if (m_joinAtExit) { Join(); - else + } else { Stop(); + } } void detail::SafeThreadOwnerBase::Start(std::shared_ptr thr) { std::scoped_lock lock(m_mutex); - if (auto thr = m_thread.lock()) return; + if (auto thr = m_thread.lock()) { + return; + } m_stdThread = std::thread([=] { thr->Main(); }); thr->m_threadId = m_stdThread.get_id(); m_thread = thr; @@ -40,7 +45,9 @@ void detail::SafeThreadOwnerBase::Stop() { thr->m_cond.notify_all(); m_thread.reset(); } - if (m_stdThread.joinable()) m_stdThread.detach(); + if (m_stdThread.joinable()) { + m_stdThread.detach(); + } } void detail::SafeThreadOwnerBase::Join() { @@ -59,7 +66,9 @@ void detail::SafeThreadOwnerBase::Join() { void detail::swap(SafeThreadOwnerBase& lhs, SafeThreadOwnerBase& rhs) noexcept { using std::swap; - if (&lhs == &rhs) return; + if (&lhs == &rhs) { + return; + } std::scoped_lock lock(lhs.m_mutex, rhs.m_mutex); std::swap(lhs.m_stdThread, rhs.m_stdThread); std::swap(lhs.m_thread, rhs.m_thread); diff --git a/wpiutil/src/main/native/cpp/TCPAcceptor.cpp b/wpiutil/src/main/native/cpp/TCPAcceptor.cpp index 90d9496837..adbff00dcf 100644 --- a/wpiutil/src/main/native/cpp/TCPAcceptor.cpp +++ b/wpiutil/src/main/native/cpp/TCPAcceptor.cpp @@ -73,7 +73,9 @@ TCPAcceptor::~TCPAcceptor() { } int TCPAcceptor::start() { - if (m_listening) return 0; + if (m_listening) { + return 0; + } m_lsd = socket(PF_INET, SOCK_STREAM, 0); if (m_lsd < 0) { @@ -153,7 +155,8 @@ void TCPAcceptor::shutdown() { address.sin_port = htons(m_port); int result = -1, sd = socket(AF_INET, SOCK_STREAM, 0); - if (sd < 0) return; + if (sd < 0) + return; // Set socket to non-blocking u_long mode = 1; @@ -176,7 +179,9 @@ void TCPAcceptor::shutdown() { } std::unique_ptr TCPAcceptor::accept() { - if (!m_listening || m_shutdown) return nullptr; + if (!m_listening || m_shutdown) { + return nullptr; + } struct sockaddr_in address; #ifdef _WIN32 @@ -187,9 +192,10 @@ std::unique_ptr TCPAcceptor::accept() { std::memset(&address, 0, sizeof(address)); int sd = ::accept(m_lsd, (struct sockaddr*)&address, &len); if (sd < 0) { - if (!m_shutdown) + if (!m_shutdown) { WPI_ERROR(m_logger, "accept() on port " << m_port << " failed: " << SocketStrerror()); + } return nullptr; } if (m_shutdown) { diff --git a/wpiutil/src/main/native/cpp/TCPConnector.cpp b/wpiutil/src/main/native/cpp/TCPConnector.cpp index 6110133b93..f0b807bbed 100644 --- a/wpiutil/src/main/native/cpp/TCPConnector.cpp +++ b/wpiutil/src/main/native/cpp/TCPConnector.cpp @@ -144,9 +144,10 @@ std::unique_ptr TCPConnector::connect(const char* server, "could not set socket to non-blocking: " << SocketStrerror()); } else { arg |= O_NONBLOCK; - if (fcntl(sd, F_SETFL, arg) < 0) + if (fcntl(sd, F_SETFL, arg) < 0) { WPI_WARNING(logger, "could not set socket to non-blocking: " << SocketStrerror()); + } } #endif @@ -171,10 +172,10 @@ std::unique_ptr TCPConnector::connect(const char* server, WPI_ERROR(logger, "select() to " << server << " port " << port << " error " << valopt << " - " << SocketStrerror(valopt)); - } - // connection established - else + } else { + // connection established result = 0; + } } else { WPI_INFO(logger, "connect() to " << server << " port " << port << " timed out"); @@ -199,9 +200,10 @@ std::unique_ptr TCPConnector::connect(const char* server, "could not set socket to blocking: " << SocketStrerror()); } else { arg &= (~O_NONBLOCK); - if (fcntl(sd, F_SETFL, arg) < 0) + if (fcntl(sd, F_SETFL, arg) < 0) { WPI_WARNING(logger, "could not set socket to blocking: " << SocketStrerror()); + } } #endif diff --git a/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp b/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp index 0fc1c8fb2e..dc4f4b106c 100644 --- a/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp +++ b/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp @@ -26,7 +26,9 @@ using namespace wpi; std::unique_ptr TCPConnector::connect_parallel( ArrayRef> servers, Logger& logger, int timeout) { - if (servers.empty()) return nullptr; + if (servers.empty()) { + return nullptr; + } // structure to make sure we don't start duplicate workers struct GlobalState { @@ -72,7 +74,9 @@ std::unique_ptr TCPConnector::connect_parallel( // attempt to the same server { std::scoped_lock lock(local->mtx); - if (local->active.count(active_tracker) > 0) continue; // already in set + if (local->active.count(active_tracker) > 0) { + continue; // already in set + } } ++num_workers; @@ -99,7 +103,9 @@ std::unique_ptr TCPConnector::connect_parallel( // successful connection if (stream) { std::scoped_lock lock(result->mtx); - if (!result->done.exchange(true)) result->stream = std::move(stream); + if (!result->done.exchange(true)) { + result->stream = std::move(stream); + } } } ++result->count; diff --git a/wpiutil/src/main/native/cpp/TCPStream.cpp b/wpiutil/src/main/native/cpp/TCPStream.cpp index 4af3e6f5fe..1eaa3e983e 100644 --- a/wpiutil/src/main/native/cpp/TCPStream.cpp +++ b/wpiutil/src/main/native/cpp/TCPStream.cpp @@ -57,7 +57,9 @@ TCPStream::TCPStream(int sd, sockaddr_in* address) m_peerPort = ntohs(address->sin_port); } -TCPStream::~TCPStream() { close(); } +TCPStream::~TCPStream() { + close(); +} size_t TCPStream::send(const char* buffer, size_t len, Error* err) { if (m_sd < 0) { @@ -101,10 +103,11 @@ size_t TCPStream::send(const char* buffer, size_t len, Error* err) { ssize_t rv = ::send(m_sd, buffer, len, 0); #endif if (rv < 0) { - if (!m_blocking && (errno == EAGAIN || errno == EWOULDBLOCK)) + if (!m_blocking && (errno == EAGAIN || errno == EWOULDBLOCK)) { *err = kWouldBlock; - else + } else { *err = kConnectionReset; + } return 0; } #endif @@ -139,13 +142,14 @@ size_t TCPStream::receive(char* buffer, size_t len, Error* err, int timeout) { } if (rv < 0) { #ifdef _WIN32 - if (!m_blocking && WSAGetLastError() == WSAEWOULDBLOCK) + if (!m_blocking && WSAGetLastError() == WSAEWOULDBLOCK) { #else - if (!m_blocking && (errno == EAGAIN || errno == EWOULDBLOCK)) + if (!m_blocking && (errno == EAGAIN || errno == EWOULDBLOCK)) { #endif *err = kWouldBlock; - else + } else { *err = kConnectionReset; + } return 0; } return static_cast(rv); @@ -164,35 +168,52 @@ void TCPStream::close() { m_sd = -1; } -StringRef TCPStream::getPeerIP() const { return m_peerIP; } +StringRef TCPStream::getPeerIP() const { + return m_peerIP; +} -int TCPStream::getPeerPort() const { return m_peerPort; } +int TCPStream::getPeerPort() const { + return m_peerPort; +} void TCPStream::setNoDelay() { - if (m_sd < 0) return; + if (m_sd < 0) { + return; + } int optval = 1; setsockopt(m_sd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&optval), sizeof optval); } bool TCPStream::setBlocking(bool enabled) { - if (m_sd < 0) return true; // silently accept + if (m_sd < 0) { + return true; // silently accept + } #ifdef _WIN32 u_long mode = enabled ? 0 : 1; - if (ioctlsocket(m_sd, FIONBIO, &mode) == SOCKET_ERROR) return false; + if (ioctlsocket(m_sd, FIONBIO, &mode) == SOCKET_ERROR) { + return false; + } #else int flags = fcntl(m_sd, F_GETFL, nullptr); - if (flags < 0) return false; - if (enabled) + if (flags < 0) { + return false; + } + if (enabled) { flags &= ~O_NONBLOCK; - else + } else { flags |= O_NONBLOCK; - if (fcntl(m_sd, F_SETFL, flags) < 0) return false; + } + if (fcntl(m_sd, F_SETFL, flags) < 0) { + return false; + } #endif return true; } -int TCPStream::getNativeHandle() const { return m_sd; } +int TCPStream::getNativeHandle() const { + return m_sd; +} bool TCPStream::WaitForReadEvent(int timeout) { fd_set sdset; diff --git a/wpiutil/src/main/native/cpp/UDPClient.cpp b/wpiutil/src/main/native/cpp/UDPClient.cpp index c8e10dfd33..afaad9fec9 100644 --- a/wpiutil/src/main/native/cpp/UDPClient.cpp +++ b/wpiutil/src/main/native/cpp/UDPClient.cpp @@ -41,7 +41,9 @@ UDPClient::~UDPClient() { } UDPClient& UDPClient::operator=(UDPClient&& other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } shutdown(); m_logger = other.m_logger; m_lsd = other.m_lsd; @@ -52,10 +54,14 @@ UDPClient& UDPClient::operator=(UDPClient&& other) { return *this; } -int UDPClient::start() { return start(0); } +int UDPClient::start() { + return start(0); +} int UDPClient::start(int port) { - if (m_lsd > 0) return 0; + if (m_lsd > 0) { + return 0; + } #ifdef _WIN32 WSAData wsaData; @@ -186,14 +192,18 @@ int UDPClient::send(StringRef data, const Twine& server, int port) { } int UDPClient::receive(uint8_t* data_received, int receive_len) { - if (m_port == 0) return -1; // return if not receiving + if (m_port == 0) { + return -1; // return if not receiving + } return recv(m_lsd, reinterpret_cast(data_received), receive_len, 0); } int UDPClient::receive(uint8_t* data_received, int receive_len, SmallVectorImpl* addr_received, int* port_received) { - if (m_port == 0) return -1; // return if not receiving + if (m_port == 0) { + return -1; // return if not receiving + } struct sockaddr_in remote; socklen_t remote_len = sizeof(remote); @@ -222,13 +232,17 @@ int UDPClient::receive(uint8_t* data_received, int receive_len, } int UDPClient::set_timeout(double timeout) { - if (timeout < 0) return -1; + if (timeout < 0) { + return -1; + } struct timeval tv; tv.tv_sec = timeout; // truncating will give seconds timeout -= tv.tv_sec; // remove seconds portion tv.tv_usec = timeout * 1000000; // fractions of a second to us int ret = setsockopt(m_lsd, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&tv), sizeof(tv)); - if (ret < 0) WPI_ERROR(m_logger, "set timeout failed"); + if (ret < 0) { + WPI_ERROR(m_logger, "set timeout failed"); + } return ret; } diff --git a/wpiutil/src/main/native/cpp/WebSocket.cpp b/wpiutil/src/main/native/cpp/WebSocket.cpp index 0fe4f00c4f..7c4c775896 100644 --- a/wpiutil/src/main/native/cpp/WebSocket.cpp +++ b/wpiutil/src/main/native/cpp/WebSocket.cpp @@ -23,7 +23,9 @@ class WebSocketWriteReq : public uv::WriteReq { std::function, uv::Error)> callback) { finish.connect([=](uv::Error err) { MutableArrayRef bufs{m_bufs}; - for (auto&& buf : bufs.slice(0, m_startUser)) buf.Deallocate(); + for (auto&& buf : bufs.slice(0, m_startUser)) { + buf.Deallocate(); + } callback(bufs.slice(m_startUser), err); }); } @@ -41,7 +43,9 @@ class WebSocket::ClientHandshakeData { static std::default_random_engine gen{rd()}; std::uniform_int_distribution dist(0, 255); char nonce[16]; // the nonce sent to the server - for (char& v : nonce) v = static_cast(dist(gen)); + for (char& v : nonce) { + v = static_cast(dist(gen)); + } raw_svector_ostream os(key); Base64Encode(os, StringRef{nonce, 16}); } @@ -111,18 +115,24 @@ std::shared_ptr WebSocket::CreateServer(uv::Stream& stream, void WebSocket::Close(uint16_t code, const Twine& reason) { SendClose(code, reason); - if (m_state != FAILED && m_state != CLOSED) m_state = CLOSING; + if (m_state != FAILED && m_state != CLOSED) { + m_state = CLOSING; + } } void WebSocket::Fail(uint16_t code, const Twine& reason) { - if (m_state == FAILED || m_state == CLOSED) return; + if (m_state == FAILED || m_state == CLOSED) { + return; + } SendClose(code, reason); SetClosed(code, reason, true); Shutdown(); } void WebSocket::Terminate(uint16_t code, const Twine& reason) { - if (m_state == FAILED || m_state == CLOSED) return; + if (m_state == FAILED || m_state == CLOSED) { + return; + } SetClosed(code, reason); Shutdown(); } @@ -149,10 +159,11 @@ void WebSocket::StartClient(const Twine& uri, const Twine& host, os << "Sec-WebSocket-Protocol: "; bool first = true; for (auto protocol : protocols) { - if (!first) + if (!first) { os << ", "; - else + } else { first = false; + } os << protocol; // also save for later checking against server response m_clientHandshake->protocols.emplace_back(protocol); @@ -161,42 +172,52 @@ void WebSocket::StartClient(const Twine& uri, const Twine& host, } // other headers - for (auto&& header : options.extraHeaders) + for (auto&& header : options.extraHeaders) { os << header.first << ": " << header.second << "\r\n"; + } // finish headers os << "\r\n"; // Send client request m_stream.Write(bufs, [](auto bufs, uv::Error) { - for (auto& buf : bufs) buf.Deallocate(); + for (auto& buf : bufs) { + buf.Deallocate(); + } }); // Set up client response handling m_clientHandshake->parser.status.connect([this](StringRef status) { unsigned int code = m_clientHandshake->parser.GetStatusCode(); - if (code != 101) Terminate(code, status); + if (code != 101) { + Terminate(code, status); + } }); m_clientHandshake->parser.header.connect( [this](StringRef name, StringRef value) { value = value.trim(); if (name.equals_lower("upgrade")) { - if (!value.equals_lower("websocket")) + if (!value.equals_lower("websocket")) { return Terminate(1002, "invalid upgrade response value"); + } m_clientHandshake->hasUpgrade = true; } else if (name.equals_lower("connection")) { - if (!value.equals_lower("upgrade")) + if (!value.equals_lower("upgrade")) { return Terminate(1002, "invalid connection response value"); + } m_clientHandshake->hasConnection = true; } else if (name.equals_lower("sec-websocket-accept")) { // Check against expected response SmallString<64> acceptBuf; - if (!value.equals(AcceptHash(m_clientHandshake->key, acceptBuf))) + if (!value.equals(AcceptHash(m_clientHandshake->key, acceptBuf))) { return Terminate(1002, "invalid accept key"); + } m_clientHandshake->hasAccept = true; } else if (name.equals_lower("sec-websocket-extensions")) { // No extensions are supported - if (!value.empty()) return Terminate(1010, "unsupported extension"); + if (!value.empty()) { + return Terminate(1010, "unsupported extension"); + } } else if (name.equals_lower("sec-websocket-protocol")) { // Make sure it was one of the provided protocols bool match = false; @@ -206,7 +227,9 @@ void WebSocket::StartClient(const Twine& uri, const Twine& host, break; } } - if (!match) return Terminate(1003, "unsupported protocol"); + if (!match) { + return Terminate(1003, "unsupported protocol"); + } m_clientHandshake->hasProtocol = true; m_protocol = value; } @@ -248,7 +271,9 @@ void WebSocket::StartServer(StringRef key, StringRef version, os << "Upgrade: WebSocket\r\n"; os << "Sec-WebSocket-Version: 13\r\n\r\n"; m_stream.Write(bufs, [this](auto bufs, uv::Error) { - for (auto& buf : bufs) buf.Deallocate(); + for (auto& buf : bufs) { + buf.Deallocate(); + } // XXX: Should we support sending a new handshake on the same connection? // XXX: "this->" is required by GCC 5.5 (bug) this->Terminate(1003, "unsupported protocol version"); @@ -264,14 +289,18 @@ void WebSocket::StartServer(StringRef key, StringRef version, SmallString<64> acceptBuf; os << "Sec-WebSocket-Accept: " << AcceptHash(key, acceptBuf) << "\r\n"; - if (!protocol.empty()) os << "Sec-WebSocket-Protocol: " << protocol << "\r\n"; + if (!protocol.empty()) { + os << "Sec-WebSocket-Protocol: " << protocol << "\r\n"; + } // end headers os << "\r\n"; // Send server response m_stream.Write(bufs, [this](auto bufs, uv::Error) { - for (auto& buf : bufs) buf.Deallocate(); + for (auto& buf : bufs) { + buf.Deallocate(); + } if (m_state == CONNECTING) { m_state = OPEN; open(m_protocol); @@ -289,12 +318,16 @@ void WebSocket::SendClose(uint16_t code, const Twine& reason) { reason.print(os); } Send(kFlagFin | kOpClose, bufs, [](auto bufs, uv::Error) { - for (auto&& buf : bufs) buf.Deallocate(); + for (auto&& buf : bufs) { + buf.Deallocate(); + } }); } void WebSocket::SetClosed(uint16_t code, const Twine& reason, bool failed) { - if (m_state == FAILED || m_state == CLOSED) return; + if (m_state == FAILED || m_state == CLOSED) { + return; + } m_state = failed ? FAILED : CLOSED; SmallString<64> reasonBuf; closed(code, reason.toStringRef(reasonBuf)); @@ -306,7 +339,9 @@ void WebSocket::Shutdown() { void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { // ignore incoming data if we're failed or closed - if (m_state == FAILED || m_state == CLOSED) return; + if (m_state == FAILED || m_state == CLOSED) { + return; + } StringRef data{buf.base, size}; @@ -315,9 +350,12 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { if (m_clientHandshake) { data = m_clientHandshake->parser.Execute(data); // check for parser failure - if (m_clientHandshake->parser.HasError()) + if (m_clientHandshake->parser.HasError()) { return Terminate(1003, "invalid response"); - if (m_state != OPEN) return; // not done with handshake yet + } + if (m_state != OPEN) { + return; // not done with handshake yet + } // we're done with the handshake, so release its memory m_clientHandshake.reset(); @@ -336,26 +374,37 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { size_t toCopy = (std::min)(2u - m_header.size(), data.size()); m_header.append(data.bytes_begin(), data.bytes_begin() + toCopy); data = data.drop_front(toCopy); - if (m_header.size() < 2u) return; // need more data + if (m_header.size() < 2u) { + return; // need more data + } // Validate RSV bits are zero - if ((m_header[0] & 0x70) != 0) return Fail(1002, "nonzero RSV"); + if ((m_header[0] & 0x70) != 0) { + return Fail(1002, "nonzero RSV"); + } } // Once we have first two bytes, we can calculate the header size if (m_headerSize == 0) { m_headerSize = 2; uint8_t len = m_header[1] & kLenMask; - if (len == 126) + if (len == 126) { m_headerSize += 2; - else if (len == 127) + } else if (len == 127) { m_headerSize += 8; + } bool masking = (m_header[1] & kFlagMasking) != 0; - if (masking) m_headerSize += 4; // masking key + if (masking) { + m_headerSize += 4; // masking key + } // On server side, incoming messages MUST be masked // On client side, incoming messages MUST NOT be masked - if (m_server && !masking) return Fail(1002, "client data not masked"); - if (!m_server && masking) return Fail(1002, "server data masked"); + if (m_server && !masking) { + return Fail(1002, "client data not masked"); + } + if (!m_server && masking) { + return Fail(1002, "server data masked"); + } } // Need to complete header to calculate message size @@ -363,16 +412,18 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { size_t toCopy = (std::min)(m_headerSize - m_header.size(), data.size()); m_header.append(data.bytes_begin(), data.bytes_begin() + toCopy); data = data.drop_front(toCopy); - if (m_header.size() < m_headerSize) return; // need more data + if (m_header.size() < m_headerSize) { + return; // need more data + } } if (m_header.size() >= m_headerSize) { // get payload length uint8_t len = m_header[1] & kLenMask; - if (len == 126) + if (len == 126) { m_frameSize = (static_cast(m_header[2]) << 8) | static_cast(m_header[3]); - else if (len == 127) + } else if (len == 127) { m_frameSize = (static_cast(m_header[2]) << 56) | (static_cast(m_header[3]) << 48) | (static_cast(m_header[4]) << 40) | @@ -381,12 +432,14 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { (static_cast(m_header[7]) << 16) | (static_cast(m_header[8]) << 8) | static_cast(m_header[9]); - else + } else { m_frameSize = len; + } // limit maximum size - if ((m_payload.size() + m_frameSize) > m_maxMessageSize) + if ((m_payload.size() + m_frameSize) > m_maxMessageSize) { return Fail(1009, "message too large"); + } } } @@ -407,7 +460,9 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { for (uint8_t& ch : MutableArrayRef{m_payload}.slice(m_frameStart)) { ch ^= key[n++]; - if (n >= 4) n = 0; + if (n >= 4) { + n = 0; + } } } @@ -418,32 +473,48 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { case kOpCont: switch (m_fragmentOpcode) { case kOpText: - if (!m_combineFragments || fin) + if (!m_combineFragments || fin) { text(StringRef{reinterpret_cast(m_payload.data()), m_payload.size()}, fin); + } break; case kOpBinary: - if (!m_combineFragments || fin) binary(m_payload, fin); + if (!m_combineFragments || fin) { + binary(m_payload, fin); + } break; default: // no preceding message? return Fail(1002, "invalid continuation message"); } - if (fin) m_fragmentOpcode = 0; + if (fin) { + m_fragmentOpcode = 0; + } break; case kOpText: - if (m_fragmentOpcode != 0) return Fail(1002, "incomplete fragment"); - if (!m_combineFragments || fin) + if (m_fragmentOpcode != 0) { + return Fail(1002, "incomplete fragment"); + } + if (!m_combineFragments || fin) { text(StringRef{reinterpret_cast(m_payload.data()), m_payload.size()}, fin); - if (!fin) m_fragmentOpcode = opcode; + } + if (!fin) { + m_fragmentOpcode = opcode; + } break; case kOpBinary: - if (m_fragmentOpcode != 0) return Fail(1002, "incomplete fragment"); - if (!m_combineFragments || fin) binary(m_payload, fin); - if (!fin) m_fragmentOpcode = opcode; + if (m_fragmentOpcode != 0) { + return Fail(1002, "incomplete fragment"); + } + if (!m_combineFragments || fin) { + binary(m_payload, fin); + } + if (!fin) { + m_fragmentOpcode = opcode; + } break; case kOpClose: { uint16_t code; @@ -461,18 +532,26 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { .drop_front(2); } // Echo the close if we didn't previously send it - if (m_state != CLOSING) SendClose(code, reason); + if (m_state != CLOSING) { + SendClose(code, reason); + } SetClosed(code, reason); // If we're the server, shutdown the connection. - if (m_server) Shutdown(); + if (m_server) { + Shutdown(); + } break; } case kOpPing: - if (!fin) return Fail(1002, "cannot fragment control frames"); + if (!fin) { + return Fail(1002, "cannot fragment control frames"); + } ping(m_payload); break; case kOpPong: - if (!fin) return Fail(1002, "cannot fragment control frames"); + if (!fin) { + return Fail(1002, "cannot fragment control frames"); + } pong(m_payload); break; default: @@ -482,7 +561,9 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { // Prepare for next message m_header.clear(); m_headerSize = 0; - if (!m_combineFragments || fin) m_payload.clear(); + if (!m_combineFragments || fin) { + m_payload.clear(); + } m_frameStart = m_payload.size(); m_frameSize = UINT64_MAX; } @@ -496,10 +577,11 @@ void WebSocket::Send( // If we're not open, emit an error and don't send the data if (m_state != OPEN) { int err; - if (m_state == CONNECTING) + if (m_state == CONNECTING) { err = UV_EAGAIN; - else + } else { err = UV_ESHUTDOWN; + } SmallVector bufs{data.begin(), data.end()}; callback(bufs, uv::Error{err}); return; @@ -513,7 +595,9 @@ void WebSocket::Send( // payload length uint64_t size = 0; - for (auto&& buf : data) size += buf.len; + for (auto&& buf : data) { + size += buf.len; + } if (size < 126) { os << static_cast((m_server ? 0x00 : kFlagMasking) | size); } else if (size <= 0xffff) { @@ -541,14 +625,18 @@ void WebSocket::Send( static std::default_random_engine gen{rd()}; std::uniform_int_distribution dist(0, 255); uint8_t key[4]; - for (uint8_t& v : key) v = dist(gen); + for (uint8_t& v : key) { + v = dist(gen); + } os << ArrayRef{key, 4}; // copy and mask data int n = 0; for (auto&& buf : data) { for (auto&& ch : buf.data()) { os << static_cast(static_cast(ch) ^ key[n++]); - if (n >= 4) n = 0; + if (n >= 4) { + n = 0; + } } } req->m_startUser = req->m_bufs.size(); diff --git a/wpiutil/src/main/native/cpp/WebSocketServer.cpp b/wpiutil/src/main/native/cpp/WebSocketServer.cpp index d73055ad49..956489c438 100644 --- a/wpiutil/src/main/native/cpp/WebSocketServer.cpp +++ b/wpiutil/src/main/native/cpp/WebSocketServer.cpp @@ -15,7 +15,9 @@ WebSocketServerHelper::WebSocketServerHelper(HttpParser& req) { if (name.equals_lower("host")) { m_gotHost = true; } else if (name.equals_lower("upgrade")) { - if (value.equals_lower("websocket")) m_websocket = true; + if (value.equals_lower("websocket")) { + m_websocket = true; + } } else if (name.equals_lower("sec-websocket-key")) { m_key = value; } else if (name.equals_lower("sec-websocket-version")) { @@ -26,22 +28,29 @@ WebSocketServerHelper::WebSocketServerHelper(HttpParser& req) { value.split(protocols, ",", -1, false); for (auto protocol : protocols) { protocol = protocol.trim(); - if (!protocol.empty()) m_protocols.emplace_back(protocol); + if (!protocol.empty()) { + m_protocols.emplace_back(protocol); + } } } }); req.headersComplete.connect([&req, this](bool) { - if (req.IsUpgrade() && IsUpgrade()) upgrade(); + if (req.IsUpgrade() && IsUpgrade()) { + upgrade(); + } }); } std::pair WebSocketServerHelper::MatchProtocol( ArrayRef protocols) { - if (protocols.empty() && m_protocols.empty()) + if (protocols.empty() && m_protocols.empty()) { return std::make_pair(true, StringRef{}); + } for (auto protocol : protocols) { for (auto&& clientProto : m_protocols) { - if (protocol == clientProto) return std::make_pair(true, protocol); + if (protocol == clientProto) { + return std::make_pair(true, protocol); + } } } return std::make_pair(false, StringRef{}); @@ -59,24 +68,31 @@ WebSocketServer::WebSocketServer(uv::Stream& stream, m_req.header.connect([this](StringRef name, StringRef value) { if (name.equals_lower("host")) { if (m_options.checkHost) { - if (!m_options.checkHost(value)) Abort(401, "Unrecognized Host"); + if (!m_options.checkHost(value)) { + Abort(401, "Unrecognized Host"); + } } } }); m_req.url.connect([this](StringRef name) { if (m_options.checkUrl) { - if (!m_options.checkUrl(name)) Abort(404, "Not Found"); + if (!m_options.checkUrl(name)) { + Abort(404, "Not Found"); + } } }); m_req.headersComplete.connect([this](bool) { // We only accept websocket connections - if (!m_helper.IsUpgrade() || !m_req.IsUpgrade()) + if (!m_helper.IsUpgrade() || !m_req.IsUpgrade()) { Abort(426, "Upgrade Required"); + } }); // Handle upgrade event m_helper.upgrade.connect([this] { - if (m_aborted) return; + if (m_aborted) { + return; + } // Negotiate sub-protocol SmallVector protocols{m_protocols.begin(), m_protocols.end()}; @@ -103,9 +119,13 @@ WebSocketServer::WebSocketServer(uv::Stream& stream, stream.StartRead(); m_dataConn = stream.data.connect_connection([this](uv::Buffer& buf, size_t size) { - if (m_aborted) return; + if (m_aborted) { + return; + } m_req.Execute(StringRef{buf.base, size}); - if (m_req.HasError()) Abort(400, "Bad Request"); + if (m_req.HasError()) { + Abort(400, "Bad Request"); + } }); m_errorConn = stream.error.connect_connection([this](uv::Error) { m_stream.Close(); }); @@ -122,7 +142,9 @@ std::shared_ptr WebSocketServer::Create( } void WebSocketServer::Abort(uint16_t code, StringRef reason) { - if (m_aborted) return; + if (m_aborted) { + return; + } m_aborted = true; // Build response @@ -131,10 +153,14 @@ void WebSocketServer::Abort(uint16_t code, StringRef reason) { // Handle unsupported version os << "HTTP/1.1 " << code << ' ' << reason << "\r\n"; - if (code == 426) os << "Upgrade: WebSocket\r\n"; + if (code == 426) { + os << "Upgrade: WebSocket\r\n"; + } os << "\r\n"; m_stream.Write(bufs, [this](auto bufs, uv::Error) { - for (auto& buf : bufs) buf.Deallocate(); + for (auto& buf : bufs) { + buf.Deallocate(); + } m_stream.Shutdown([this] { m_stream.Close(); }); }); } diff --git a/wpiutil/src/main/native/cpp/future.cpp b/wpiutil/src/main/native/cpp/future.cpp index a1f8cb9a06..109eeb93ca 100644 --- a/wpiutil/src/main/native/cpp/future.cpp +++ b/wpiutil/src/main/native/cpp/future.cpp @@ -25,10 +25,14 @@ uint64_t PromiseFactoryBase::CreateRequest() { } bool PromiseFactoryBase::EraseRequest(uint64_t request) { - if (request == 0) return false; + if (request == 0) { + return false; + } auto it = std::find_if(m_requests.begin(), m_requests.end(), [=](auto r) { return r == request; }); - if (it == m_requests.end()) return false; // no waiters + if (it == m_requests.end()) { + return false; // no waiters + } m_requests.erase(it); return true; } @@ -44,7 +48,9 @@ future PromiseFactory::MakeReadyFuture() { void PromiseFactory::SetValue(uint64_t request) { std::unique_lock lock(GetResultMutex()); - if (!EraseRequest(request)) return; + if (!EraseRequest(request)) { + return; + } auto it = std::find_if(m_thens.begin(), m_thens.end(), [=](const auto& x) { return x.request == request; }); if (it != m_thens.end()) { @@ -102,7 +108,9 @@ void PromiseFactory::WaitResult(uint64_t request) { // Did we get a response to *our* request? auto it = std::find_if(m_results.begin(), m_results.end(), [=](const auto& r) { return r == request; }); - if (it != m_results.end()) return; + if (it != m_results.end()) { + return; + } // No, keep waiting for a response Wait(lock); } diff --git a/wpiutil/src/main/native/cpp/hostname.cpp b/wpiutil/src/main/native/cpp/hostname.cpp index dee429b666..939ed223e7 100644 --- a/wpiutil/src/main/native/cpp/hostname.cpp +++ b/wpiutil/src/main/native/cpp/hostname.cpp @@ -24,7 +24,9 @@ std::string GetHostname() { } else if (err == UV_ENOBUFS) { char* name2 = static_cast(std::malloc(size)); err = uv_os_gethostname(name2, &size); - if (err == 0) rv.assign(name2, size); + if (err == 0) { + rv.assign(name2, size); + } std::free(name2); } @@ -44,7 +46,9 @@ StringRef GetHostname(SmallVectorImpl& name) { } else if (err == UV_ENOBUFS) { name.resize(size); err = uv_os_gethostname(name.data(), &size); - if (err != 0) size = 0; + if (err != 0) { + size = 0; + } } return StringRef{name.data(), size}; diff --git a/wpiutil/src/main/native/cpp/jni/WPIUtilJNI.cpp b/wpiutil/src/main/native/cpp/jni/WPIUtilJNI.cpp index bfde133433..67e91f09bf 100644 --- a/wpiutil/src/main/native/cpp/jni/WPIUtilJNI.cpp +++ b/wpiutil/src/main/native/cpp/jni/WPIUtilJNI.cpp @@ -15,8 +15,9 @@ extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; + } return JNI_VERSION_1_6; } diff --git a/wpiutil/src/main/native/cpp/leb128.cpp b/wpiutil/src/main/native/cpp/leb128.cpp index 15ff3089d8..14fb10400b 100644 --- a/wpiutil/src/main/native/cpp/leb128.cpp +++ b/wpiutil/src/main/native/cpp/leb128.cpp @@ -24,8 +24,9 @@ uint64_t WriteUleb128(SmallVectorImpl& dest, uint64_t val) { unsigned char byte = val & 0x7f; val >>= 7; - if (val != 0) + if (val != 0) { byte |= 0x80; // mark this byte to show that more bytes will follow + } dest.push_back(byte); count++; @@ -47,7 +48,9 @@ uint64_t ReadUleb128(const char* addr, uint64_t* ret) { result |= (byte & 0x7f) << shift; shift += 7; - if (!(byte & 0x80)) break; + if (!(byte & 0x80)) { + break; + } } *ret = result; @@ -62,12 +65,16 @@ bool ReadUleb128(raw_istream& is, uint64_t* ret) { while (1) { unsigned char byte; is.read(reinterpret_cast(&byte), 1); - if (is.has_error()) return false; + if (is.has_error()) { + return false; + } result |= (byte & 0x7f) << shift; shift += 7; - if (!(byte & 0x80)) break; + if (!(byte & 0x80)) { + break; + } } *ret = result; diff --git a/wpiutil/src/main/native/cpp/raw_istream.cpp b/wpiutil/src/main/native/cpp/raw_istream.cpp index e4f436b820..0438ef550d 100644 --- a/wpiutil/src/main/native/cpp/raw_istream.cpp +++ b/wpiutil/src/main/native/cpp/raw_istream.cpp @@ -38,17 +38,25 @@ StringRef raw_istream::getline(SmallVectorImpl& buf, int maxLen) { for (int i = 0; i < maxLen; ++i) { char c; read(c); - if (has_error()) return StringRef{buf.data(), buf.size()}; - if (c == '\r') continue; + if (has_error()) { + return StringRef{buf.data(), buf.size()}; + } + if (c == '\r') { + continue; + } buf.push_back(c); - if (c == '\n') break; + if (c == '\n') { + break; + } } return StringRef{buf.data(), buf.size()}; } void raw_mem_istream::close() {} -size_t raw_mem_istream::in_avail() const { return m_left; } +size_t raw_mem_istream::in_avail() const { + return m_left; +} void raw_mem_istream::read_impl(void* data, size_t len) { if (len > m_left) { @@ -73,7 +81,9 @@ static int getFD(const Twine& Filename, std::error_code& EC) { int FD; EC = sys::fs::openFileForRead(Filename, FD); - if (EC) return -1; + if (EC) { + return -1; + } EC = std::error_code(); return FD; @@ -89,7 +99,9 @@ raw_fd_istream::raw_fd_istream(int fd, bool shouldClose, size_t bufSize) } raw_fd_istream::~raw_fd_istream() { - if (m_shouldClose) close(); + if (m_shouldClose) { + close(); + } std::free(m_buf); } @@ -100,7 +112,9 @@ void raw_fd_istream::close() { } } -size_t raw_fd_istream::in_avail() const { return m_end - m_cur; } +size_t raw_fd_istream::in_avail() const { + return m_end - m_cur; +} void raw_fd_istream::read_impl(void* data, size_t len) { char* cdata = static_cast(data); diff --git a/wpiutil/src/main/native/cpp/raw_socket_istream.cpp b/wpiutil/src/main/native/cpp/raw_socket_istream.cpp index c6f69bef0d..c6b759e1d7 100644 --- a/wpiutil/src/main/native/cpp/raw_socket_istream.cpp +++ b/wpiutil/src/main/native/cpp/raw_socket_istream.cpp @@ -24,6 +24,10 @@ void raw_socket_istream::read_impl(void* data, size_t len) { set_read_count(pos); } -void raw_socket_istream::close() { m_stream.close(); } +void raw_socket_istream::close() { + m_stream.close(); +} -size_t raw_socket_istream::in_avail() const { return 0; } +size_t raw_socket_istream::in_avail() const { + return 0; +} diff --git a/wpiutil/src/main/native/cpp/raw_socket_ostream.cpp b/wpiutil/src/main/native/cpp/raw_socket_ostream.cpp index 5d9cbb6eaf..af01c848a9 100644 --- a/wpiutil/src/main/native/cpp/raw_socket_ostream.cpp +++ b/wpiutil/src/main/native/cpp/raw_socket_ostream.cpp @@ -10,7 +10,9 @@ using namespace wpi; raw_socket_ostream::~raw_socket_ostream() { flush(); - if (m_shouldClose) close(); + if (m_shouldClose) { + close(); + } } void raw_socket_ostream::write_impl(const char* data, size_t len) { @@ -27,10 +29,14 @@ void raw_socket_ostream::write_impl(const char* data, size_t len) { } } -uint64_t raw_socket_ostream::current_pos() const { return 0; } +uint64_t raw_socket_ostream::current_pos() const { + return 0; +} void raw_socket_ostream::close() { - if (!m_shouldClose) return; + if (!m_shouldClose) { + return; + } flush(); m_stream.close(); } diff --git a/wpiutil/src/main/native/cpp/raw_uv_ostream.cpp b/wpiutil/src/main/native/cpp/raw_uv_ostream.cpp index ba01e265b7..f055a2a210 100644 --- a/wpiutil/src/main/native/cpp/raw_uv_ostream.cpp +++ b/wpiutil/src/main/native/cpp/raw_uv_ostream.cpp @@ -32,6 +32,8 @@ void raw_uv_ostream::write_impl(const char* data, size_t len) { uint64_t raw_uv_ostream::current_pos() const { uint64_t size = 0; - for (auto&& buf : m_bufs) size += buf.len; + for (auto&& buf : m_bufs) { + size += buf.len; + } return size; } diff --git a/wpiutil/src/main/native/cpp/sha1.cpp b/wpiutil/src/main/native/cpp/sha1.cpp index e1346f427f..3ad297a4dc 100644 --- a/wpiutil/src/main/native/cpp/sha1.cpp +++ b/wpiutil/src/main/native/cpp/sha1.cpp @@ -212,7 +212,9 @@ static void buffer_to_block(const unsigned char* buffer, } } -SHA1::SHA1() { reset(digest, buf_size, transforms); } +SHA1::SHA1() { + reset(digest, buf_size, transforms); +} void SHA1::Update(StringRef s) { raw_mem_istream is(makeArrayRef(s.data(), s.size())); diff --git a/wpiutil/src/main/native/cpp/timestamp.cpp b/wpiutil/src/main/native/cpp/timestamp.cpp index 786937ae8f..64820783e5 100644 --- a/wpiutil/src/main/native/cpp/timestamp.cpp +++ b/wpiutil/src/main/native/cpp/timestamp.cpp @@ -92,14 +92,22 @@ void wpi::SetNowImpl(uint64_t (*func)(void)) { now_impl = func ? func : NowDefault; } -uint64_t wpi::Now() { return (now_impl.load())(); } +uint64_t wpi::Now() { + return (now_impl.load())(); +} extern "C" { -uint64_t WPI_NowDefault(void) { return wpi::NowDefault(); } +uint64_t WPI_NowDefault(void) { + return wpi::NowDefault(); +} -void WPI_SetNowImpl(uint64_t (*func)(void)) { wpi::SetNowImpl(func); } +void WPI_SetNowImpl(uint64_t (*func)(void)) { + wpi::SetNowImpl(func); +} -uint64_t WPI_Now(void) { return wpi::Now(); } +uint64_t WPI_Now(void) { + return wpi::Now(); +} } // extern "C" diff --git a/wpiutil/src/main/native/cpp/uv/Async.cpp b/wpiutil/src/main/native/cpp/uv/Async.cpp index 1e8885b575..06c4e90a0e 100644 --- a/wpiutil/src/main/native/cpp/uv/Async.cpp +++ b/wpiutil/src/main/native/cpp/uv/Async.cpp @@ -10,10 +10,11 @@ namespace wpi { namespace uv { Async<>::~Async() noexcept { - if (auto loop = m_loop.lock()) + if (auto loop = m_loop.lock()) { Close(); - else + } else { ForceClosed(); + } } std::shared_ptr> Async<>::Create(const std::shared_ptr& loop) { diff --git a/wpiutil/src/main/native/cpp/uv/FsEvent.cpp b/wpiutil/src/main/native/cpp/uv/FsEvent.cpp index f955579a61..e91104e340 100644 --- a/wpiutil/src/main/native/cpp/uv/FsEvent.cpp +++ b/wpiutil/src/main/native/cpp/uv/FsEvent.cpp @@ -29,10 +29,11 @@ void FsEvent::Start(const Twine& path, unsigned int flags) { &uv_fs_event_start, GetRaw(), [](uv_fs_event_t* handle, const char* filename, int events, int status) { FsEvent& h = *static_cast(handle->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.fsEvent(filename, events); + } }, path.toNullTerminatedStringRef(pathBuf).data(), flags); } diff --git a/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp b/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp index c30b32e27f..b390ffdb52 100644 --- a/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp +++ b/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp @@ -23,10 +23,11 @@ void GetAddrInfo(Loop& loop, const std::shared_ptr& req, loop.GetRaw(), req->GetRaw(), [](uv_getaddrinfo_t* req, int status, addrinfo* res) { auto& h = *static_cast(req->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.resolved(*res); + } uv_freeaddrinfo(res); h.Release(); // this is always a one-shot }, @@ -34,10 +35,11 @@ void GetAddrInfo(Loop& loop, const std::shared_ptr& req, service.isNull() ? nullptr : service.toNullTerminatedStringRef(serviceStr).data(), hints); - if (err < 0) + if (err < 0) { loop.ReportError(err); - else + } else { req->Keep(); + } } void GetAddrInfo(Loop& loop, std::function callback, diff --git a/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp b/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp index 4d58999733..10e7d13e7a 100644 --- a/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp +++ b/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp @@ -21,17 +21,19 @@ void GetNameInfo(Loop& loop, const std::shared_ptr& req, [](uv_getnameinfo_t* req, int status, const char* hostname, const char* service) { auto& h = *static_cast(req->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.resolved(hostname, service); + } h.Release(); // this is always a one-shot }, &addr, flags); - if (err < 0) + if (err < 0) { loop.ReportError(err); - else + } else { req->Keep(); + } } void GetNameInfo(Loop& loop, @@ -46,10 +48,11 @@ void GetNameInfo4(Loop& loop, const std::shared_ptr& req, const Twine& ip, unsigned int port, int flags) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { loop.ReportError(err); - else + } else { GetNameInfo(loop, req, reinterpret_cast(addr), flags); + } } void GetNameInfo4(Loop& loop, @@ -57,20 +60,22 @@ void GetNameInfo4(Loop& loop, const Twine& ip, unsigned int port, int flags) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { loop.ReportError(err); - else + } else { GetNameInfo(loop, callback, reinterpret_cast(addr), flags); + } } void GetNameInfo6(Loop& loop, const std::shared_ptr& req, const Twine& ip, unsigned int port, int flags) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { loop.ReportError(err); - else + } else { GetNameInfo(loop, req, reinterpret_cast(addr), flags); + } } void GetNameInfo6(Loop& loop, @@ -78,10 +83,11 @@ void GetNameInfo6(Loop& loop, const Twine& ip, unsigned int port, int flags) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { loop.ReportError(err); - else + } else { GetNameInfo(loop, callback, reinterpret_cast(addr), flags); + } } } // namespace uv diff --git a/wpiutil/src/main/native/cpp/uv/Handle.cpp b/wpiutil/src/main/native/cpp/uv/Handle.cpp index 3b7332449e..1d34249e32 100644 --- a/wpiutil/src/main/native/cpp/uv/Handle.cpp +++ b/wpiutil/src/main/native/cpp/uv/Handle.cpp @@ -30,4 +30,6 @@ void Handle::AllocBuf(uv_handle_t* handle, size_t size, uv_buf_t* buf) { *buf = h.m_allocBuf(size); } -void Handle::DefaultFreeBuf(Buffer& buf) { buf.Deallocate(); } +void Handle::DefaultFreeBuf(Buffer& buf) { + buf.Deallocate(); +} diff --git a/wpiutil/src/main/native/cpp/uv/Loop.cpp b/wpiutil/src/main/native/cpp/uv/Loop.cpp index 423d95e475..df0236d4e6 100644 --- a/wpiutil/src/main/native/cpp/uv/Loop.cpp +++ b/wpiutil/src/main/native/cpp/uv/Loop.cpp @@ -26,7 +26,9 @@ Loop::~Loop() noexcept { std::shared_ptr Loop::Create() { auto loop = std::make_shared(private_init{}); - if (uv_loop_init(&loop->m_loopStruct) < 0) return nullptr; + if (uv_loop_init(&loop->m_loopStruct) < 0) { + return nullptr; + } loop->m_loop = &loop->m_loopStruct; loop->m_loop->data = loop.get(); return loop; @@ -35,14 +37,18 @@ std::shared_ptr Loop::Create() { std::shared_ptr Loop::GetDefault() { static std::shared_ptr loop = std::make_shared(private_init{}); loop->m_loop = uv_default_loop(); - if (!loop->m_loop) return nullptr; + if (!loop->m_loop) { + return nullptr; + } loop->m_loop->data = loop.get(); return loop; } void Loop::Close() { int err = uv_loop_close(m_loop); - if (err < 0) ReportError(err); + if (err < 0) { + ReportError(err); + } } void Loop::Walk(std::function callback) { @@ -58,5 +64,7 @@ void Loop::Walk(std::function callback) { void Loop::Fork() { int err = uv_loop_fork(m_loop); - if (err < 0) ReportError(err); + if (err < 0) { + ReportError(err); + } } diff --git a/wpiutil/src/main/native/cpp/uv/NetworkStream.cpp b/wpiutil/src/main/native/cpp/uv/NetworkStream.cpp index bfe2a76c45..62c3aaf43b 100644 --- a/wpiutil/src/main/native/cpp/uv/NetworkStream.cpp +++ b/wpiutil/src/main/native/cpp/uv/NetworkStream.cpp @@ -15,10 +15,11 @@ void NetworkStream::Listen(int backlog) { Invoke(&uv_listen, GetRawStream(), backlog, [](uv_stream_t* handle, int status) { auto& h = *static_cast(handle->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.connection(); + } }); } diff --git a/wpiutil/src/main/native/cpp/uv/Pipe.cpp b/wpiutil/src/main/native/cpp/uv/Pipe.cpp index bb0b68564b..e26c0831a3 100644 --- a/wpiutil/src/main/native/cpp/uv/Pipe.cpp +++ b/wpiutil/src/main/native/cpp/uv/Pipe.cpp @@ -23,13 +23,19 @@ std::shared_ptr Pipe::Create(Loop& loop, bool ipc) { } void Pipe::Reuse(std::function callback, bool ipc) { - if (IsClosing()) return; - if (!m_reuseData) m_reuseData = std::make_unique(); + if (IsClosing()) { + return; + } + if (!m_reuseData) { + m_reuseData = std::make_unique(); + } m_reuseData->callback = callback; m_reuseData->ipc = ipc; uv_close(GetRawHandle(), [](uv_handle_t* handle) { Pipe& h = *static_cast(handle->data); - if (!h.m_reuseData) return; + if (!h.m_reuseData) { + return; + } auto data = std::move(h.m_reuseData); auto err = uv_pipe_init(h.GetLoopRef().GetRaw(), h.GetRaw(), data->ipc ? 1 : 0); @@ -43,7 +49,9 @@ void Pipe::Reuse(std::function callback, bool ipc) { std::shared_ptr Pipe::Accept() { auto client = Create(GetLoopRef(), GetRaw()->ipc); - if (!client) return nullptr; + if (!client) { + return nullptr; + } if (!Accept(client)) { client->Release(); return nullptr; @@ -51,7 +59,9 @@ std::shared_ptr Pipe::Accept() { return client; } -Pipe* Pipe::DoAccept() { return Accept().get(); } +Pipe* Pipe::DoAccept() { + return Accept().get(); +} void Pipe::Bind(const Twine& name) { SmallString<128> nameBuf; @@ -66,10 +76,11 @@ void Pipe::Connect(const Twine& name, name.toNullTerminatedStringRef(nameBuf).data(), [](uv_connect_t* req, int status) { auto& h = *static_cast(req->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.connected(); + } h.Release(); // this is always a one-shot }); req->Keep(); diff --git a/wpiutil/src/main/native/cpp/uv/Poll.cpp b/wpiutil/src/main/native/cpp/uv/Poll.cpp index 91295a9168..6426441489 100644 --- a/wpiutil/src/main/native/cpp/uv/Poll.cpp +++ b/wpiutil/src/main/native/cpp/uv/Poll.cpp @@ -32,14 +32,20 @@ std::shared_ptr Poll::CreateSocket(Loop& loop, uv_os_sock_t sock) { } void Poll::Reuse(int fd, std::function callback) { - if (IsClosing()) return; - if (!m_reuseData) m_reuseData = std::make_unique(); + if (IsClosing()) { + return; + } + if (!m_reuseData) { + m_reuseData = std::make_unique(); + } m_reuseData->callback = callback; m_reuseData->isSocket = false; m_reuseData->fd = fd; uv_close(GetRawHandle(), [](uv_handle_t* handle) { Poll& h = *static_cast(handle->data); - if (!h.m_reuseData || h.m_reuseData->isSocket) return; // just in case + if (!h.m_reuseData || h.m_reuseData->isSocket) { + return; // just in case + } auto data = std::move(h.m_reuseData); int err = uv_poll_init(h.GetLoopRef().GetRaw(), h.GetRaw(), data->fd); if (err < 0) { @@ -51,14 +57,20 @@ void Poll::Reuse(int fd, std::function callback) { } void Poll::ReuseSocket(uv_os_sock_t sock, std::function callback) { - if (IsClosing()) return; - if (!m_reuseData) m_reuseData = std::make_unique(); + if (IsClosing()) { + return; + } + if (!m_reuseData) { + m_reuseData = std::make_unique(); + } m_reuseData->callback = callback; m_reuseData->isSocket = true; m_reuseData->sock = sock; uv_close(GetRawHandle(), [](uv_handle_t* handle) { Poll& h = *static_cast(handle->data); - if (!h.m_reuseData || !h.m_reuseData->isSocket) return; // just in case + if (!h.m_reuseData || !h.m_reuseData->isSocket) { + return; // just in case + } auto data = std::move(h.m_reuseData); int err = uv_poll_init(h.GetLoopRef().GetRaw(), h.GetRaw(), data->sock); if (err < 0) { @@ -73,10 +85,11 @@ void Poll::Start(int events) { Invoke(&uv_poll_start, GetRaw(), events, [](uv_poll_t* handle, int status, int events) { Poll& h = *static_cast(handle->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.pollEvent(events); + } }); } diff --git a/wpiutil/src/main/native/cpp/uv/Process.cpp b/wpiutil/src/main/native/cpp/uv/Process.cpp index c02bbe6dfc..6480306f26 100644 --- a/wpiutil/src/main/native/cpp/uv/Process.cpp +++ b/wpiutil/src/main/native/cpp/uv/Process.cpp @@ -65,28 +65,36 @@ std::shared_ptr Process::SpawnArray(Loop& loop, const Twine& file, break; case Option::kStdioIgnore: { size_t index = o.m_data.stdio.index; - if (index >= stdioBuf.size()) stdioBuf.resize(index + 1); + if (index >= stdioBuf.size()) { + stdioBuf.resize(index + 1); + } stdioBuf[index].flags = UV_IGNORE; stdioBuf[index].data.fd = 0; break; } case Option::kStdioInheritFd: { size_t index = o.m_data.stdio.index; - if (index >= stdioBuf.size()) stdioBuf.resize(index + 1); + if (index >= stdioBuf.size()) { + stdioBuf.resize(index + 1); + } stdioBuf[index].flags = UV_INHERIT_FD; stdioBuf[index].data.fd = o.m_data.stdio.fd; break; } case Option::kStdioInheritPipe: { size_t index = o.m_data.stdio.index; - if (index >= stdioBuf.size()) stdioBuf.resize(index + 1); + if (index >= stdioBuf.size()) { + stdioBuf.resize(index + 1); + } stdioBuf[index].flags = UV_INHERIT_STREAM; stdioBuf[index].data.stream = o.m_data.stdio.pipe->GetRawStream(); break; } case Option::kStdioCreatePipe: { size_t index = o.m_data.stdio.index; - if (index >= stdioBuf.size()) stdioBuf.resize(index + 1); + if (index >= stdioBuf.size()) { + stdioBuf.resize(index + 1); + } stdioBuf[index].flags = static_cast(UV_CREATE_PIPE | o.m_data.stdio.flags); stdioBuf[index].data.stream = o.m_data.stdio.pipe->GetRawStream(); @@ -97,7 +105,9 @@ std::shared_ptr Process::SpawnArray(Loop& loop, const Twine& file, } } - if (argsBuf.empty()) argsBuf.push_back(const_cast(coptions.file)); + if (argsBuf.empty()) { + argsBuf.push_back(const_cast(coptions.file)); + } argsBuf.push_back(nullptr); coptions.args = argsBuf.data(); diff --git a/wpiutil/src/main/native/cpp/uv/Stream.cpp b/wpiutil/src/main/native/cpp/uv/Stream.cpp index d84adac0bd..dc9fc27e80 100644 --- a/wpiutil/src/main/native/cpp/uv/Stream.cpp +++ b/wpiutil/src/main/native/cpp/uv/Stream.cpp @@ -38,18 +38,22 @@ void Stream::Shutdown(const std::shared_ptr& req) { if (Invoke(&uv_shutdown, req->GetRaw(), GetRawStream(), [](uv_shutdown_t* req, int status) { auto& h = *static_cast(req->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.complete(); + } h.Release(); // this is always a one-shot - })) + })) { req->Keep(); + } } void Stream::Shutdown(std::function callback) { auto req = std::make_shared(); - if (callback) req->complete.connect(callback); + if (callback) { + req->complete.connect(callback); + } Shutdown(req); } @@ -60,12 +64,13 @@ void Stream::StartRead() { Buffer data = *buf; // nread=0 is simply ignored - if (nread == UV_EOF) + if (nread == UV_EOF) { h.end(); - else if (nread > 0) + } else if (nread > 0) { h.data(data, static_cast(nread)); - else if (nread < 0) + } else if (nread < 0) { h.ReportError(nread); + } // free the buffer h.FreeBuf(data); @@ -77,11 +82,14 @@ void Stream::Write(ArrayRef bufs, if (Invoke(&uv_write, req->GetRaw(), GetRawStream(), bufs.data(), bufs.size(), [](uv_write_t* r, int status) { auto& h = *static_cast(r->data); - if (status < 0) h.ReportError(status); + if (status < 0) { + h.ReportError(status); + } h.finish(Error(status)); h.Release(); // this is always a one-shot - })) + })) { req->Keep(); + } } void Stream::Write( diff --git a/wpiutil/src/main/native/cpp/uv/Tcp.cpp b/wpiutil/src/main/native/cpp/uv/Tcp.cpp index 6784500c32..3c5925901c 100644 --- a/wpiutil/src/main/native/cpp/uv/Tcp.cpp +++ b/wpiutil/src/main/native/cpp/uv/Tcp.cpp @@ -23,13 +23,19 @@ std::shared_ptr Tcp::Create(Loop& loop, unsigned int flags) { } void Tcp::Reuse(std::function callback, unsigned int flags) { - if (IsClosing()) return; - if (!m_reuseData) m_reuseData = std::make_unique(); + if (IsClosing()) { + return; + } + if (!m_reuseData) { + m_reuseData = std::make_unique(); + } m_reuseData->callback = callback; m_reuseData->flags = flags; uv_close(GetRawHandle(), [](uv_handle_t* handle) { Tcp& h = *static_cast(handle->data); - if (!h.m_reuseData) return; // just in case + if (!h.m_reuseData) { + return; // just in case + } auto data = std::move(h.m_reuseData); int err = uv_tcp_init_ex(h.GetLoopRef().GetRaw(), h.GetRaw(), data->flags); if (err < 0) { @@ -42,7 +48,9 @@ void Tcp::Reuse(std::function callback, unsigned int flags) { std::shared_ptr Tcp::Accept() { auto client = Create(GetLoopRef()); - if (!client) return nullptr; + if (!client) { + return nullptr; + } if (!Accept(client)) { client->Release(); return nullptr; @@ -50,32 +58,37 @@ std::shared_ptr Tcp::Accept() { return client; } -Tcp* Tcp::DoAccept() { return Accept().get(); } +Tcp* Tcp::DoAccept() { + return Accept().get(); +} void Tcp::Bind(const Twine& ip, unsigned int port, unsigned int flags) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Bind(reinterpret_cast(addr), flags); + } } void Tcp::Bind6(const Twine& ip, unsigned int port, unsigned int flags) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Bind(reinterpret_cast(addr), flags); + } } sockaddr_storage Tcp::GetSock() { sockaddr_storage name; int len = sizeof(name); if (!Invoke(&uv_tcp_getsockname, GetRaw(), reinterpret_cast(&name), - &len)) + &len)) { std::memset(&name, 0, sizeof(name)); + } return name; } @@ -83,8 +96,9 @@ sockaddr_storage Tcp::GetPeer() { sockaddr_storage name; int len = sizeof(name); if (!Invoke(&uv_tcp_getpeername, GetRaw(), reinterpret_cast(&name), - &len)) + &len)) { std::memset(&name, 0, sizeof(name)); + } return name; } @@ -93,13 +107,15 @@ void Tcp::Connect(const sockaddr& addr, if (Invoke(&uv_tcp_connect, req->GetRaw(), GetRaw(), &addr, [](uv_connect_t* req, int status) { auto& h = *static_cast(req->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.connected(); + } h.Release(); // this is always a one-shot - })) + })) { req->Keep(); + } } void Tcp::Connect(const sockaddr& addr, std::function callback) { @@ -112,40 +128,44 @@ void Tcp::Connect(const Twine& ip, unsigned int port, const std::shared_ptr& req) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Connect(reinterpret_cast(addr), req); + } } void Tcp::Connect(const Twine& ip, unsigned int port, std::function callback) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Connect(reinterpret_cast(addr), callback); + } } void Tcp::Connect6(const Twine& ip, unsigned int port, const std::shared_ptr& req) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Connect(reinterpret_cast(addr), req); + } } void Tcp::Connect6(const Twine& ip, unsigned int port, std::function callback) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Connect(reinterpret_cast(addr), callback); + } } } // namespace uv diff --git a/wpiutil/src/main/native/cpp/uv/Timer.cpp b/wpiutil/src/main/native/cpp/uv/Timer.cpp index ef6a3cd0b7..ee9363cb0d 100644 --- a/wpiutil/src/main/native/cpp/uv/Timer.cpp +++ b/wpiutil/src/main/native/cpp/uv/Timer.cpp @@ -22,7 +22,9 @@ std::shared_ptr Timer::Create(Loop& loop) { void Timer::SingleShot(Loop& loop, Time timeout, std::function func) { auto h = Create(loop); - if (!h) return; + if (!h) { + return; + } h->timeout.connect([theTimer = h.get(), func]() { func(); theTimer->Close(); diff --git a/wpiutil/src/main/native/cpp/uv/Udp.cpp b/wpiutil/src/main/native/cpp/uv/Udp.cpp index 3d402d839c..cbf0f0d0c9 100644 --- a/wpiutil/src/main/native/cpp/uv/Udp.cpp +++ b/wpiutil/src/main/native/cpp/uv/Udp.cpp @@ -51,45 +51,50 @@ std::shared_ptr Udp::Create(Loop& loop, unsigned int flags) { void Udp::Bind(const Twine& ip, unsigned int port, unsigned int flags) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Bind(reinterpret_cast(addr), flags); + } } void Udp::Bind6(const Twine& ip, unsigned int port, unsigned int flags) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Bind(reinterpret_cast(addr), flags); + } } void Udp::Connect(const Twine& ip, unsigned int port) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Connect(reinterpret_cast(addr)); + } } void Udp::Connect6(const Twine& ip, unsigned int port) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); - if (err < 0) + if (err < 0) { ReportError(err); - else + } else { Connect(reinterpret_cast(addr)); + } } sockaddr_storage Udp::GetPeer() { sockaddr_storage name; int len = sizeof(name); if (!Invoke(&uv_udp_getpeername, GetRaw(), reinterpret_cast(&name), - &len)) + &len)) { std::memset(&name, 0, sizeof(name)); + } return name; } @@ -97,8 +102,9 @@ sockaddr_storage Udp::GetSock() { sockaddr_storage name; int len = sizeof(name); if (!Invoke(&uv_udp_getsockname, GetRaw(), reinterpret_cast(&name), - &len)) + &len)) { std::memset(&name, 0, sizeof(name)); + } return name; } @@ -123,11 +129,14 @@ void Udp::Send(const sockaddr& addr, ArrayRef bufs, if (Invoke(&uv_udp_send, req->GetRaw(), GetRaw(), bufs.data(), bufs.size(), &addr, [](uv_udp_send_t* r, int status) { auto& h = *static_cast(r->data); - if (status < 0) h.ReportError(status); + if (status < 0) { + h.ReportError(status); + } h.complete(Error(status)); h.Release(); // this is always a one-shot - })) + })) { req->Keep(); + } } void Udp::Send(const sockaddr& addr, ArrayRef bufs, @@ -139,11 +148,14 @@ void Udp::Send(ArrayRef bufs, const std::shared_ptr& req) { if (Invoke(&uv_udp_send, req->GetRaw(), GetRaw(), bufs.data(), bufs.size(), nullptr, [](uv_udp_send_t* r, int status) { auto& h = *static_cast(r->data); - if (status < 0) h.ReportError(status); + if (status < 0) { + h.ReportError(status); + } h.complete(Error(status)); h.Release(); // this is always a one-shot - })) + })) { req->Keep(); + } } void Udp::Send(ArrayRef bufs, @@ -159,10 +171,11 @@ void Udp::StartRecv() { Buffer data = *buf; // nread=0 is simply ignored - if (nread > 0) + if (nread > 0) { h.received(data, static_cast(nread), *addr, flags); - else if (nread < 0) + } else if (nread < 0) { h.ReportError(nread); + } // free the buffer h.FreeBuf(data); diff --git a/wpiutil/src/main/native/cpp/uv/Work.cpp b/wpiutil/src/main/native/cpp/uv/Work.cpp index 8309b9ae16..c825cab267 100644 --- a/wpiutil/src/main/native/cpp/uv/Work.cpp +++ b/wpiutil/src/main/native/cpp/uv/Work.cpp @@ -22,23 +22,29 @@ void QueueWork(Loop& loop, const std::shared_ptr& req) { }, [](uv_work_t* req, int status) { auto& h = *static_cast(req->data); - if (status < 0) + if (status < 0) { h.ReportError(status); - else + } else { h.afterWork(); + } h.Release(); // this is always a one-shot }); - if (err < 0) + if (err < 0) { loop.ReportError(err); - else + } else { req->Keep(); + } } void QueueWork(Loop& loop, std::function work, std::function afterWork) { auto req = std::make_shared(); - if (work) req->work.connect(work); - if (afterWork) req->afterWork.connect(afterWork); + if (work) { + req->work.connect(work); + } + if (afterWork) { + req->afterWork.connect(afterWork); + } QueueWork(loop, req); } diff --git a/wpiutil/src/main/native/include/wpi/Algorithm.h b/wpiutil/src/main/native/include/wpi/Algorithm.h index 7de65b0c49..d0744dcbf9 100644 --- a/wpiutil/src/main/native/include/wpi/Algorithm.h +++ b/wpiutil/src/main/native/include/wpi/Algorithm.h @@ -4,6 +4,7 @@ #pragma once +#include #include namespace wpi { diff --git a/wpiutil/src/main/native/include/wpi/HttpUtil.h b/wpiutil/src/main/native/include/wpi/HttpUtil.h index fd79a0a81b..0df8286dcc 100644 --- a/wpiutil/src/main/native/include/wpi/HttpUtil.h +++ b/wpiutil/src/main/native/include/wpi/HttpUtil.h @@ -161,7 +161,9 @@ class HttpPath { return equals(start, makeArrayRef(match.begin(), match.end())); } bool equals(size_t start, ArrayRef match) const { - if (m_pathEnds.size() != (start + match.size())) return false; + if (m_pathEnds.size() != (start + match.size())) { + return false; + } return startswith(start, match); } bool equals(size_t start, StringRef match) const { diff --git a/wpiutil/src/main/native/include/wpi/HttpWebSocketServerConnection.inl b/wpiutil/src/main/native/include/wpi/HttpWebSocketServerConnection.inl index c8a37c9d4a..def11dca97 100644 --- a/wpiutil/src/main/native/include/wpi/HttpWebSocketServerConnection.inl +++ b/wpiutil/src/main/native/include/wpi/HttpWebSocketServerConnection.inl @@ -22,7 +22,8 @@ HttpWebSocketServerConnection::HttpWebSocketServerConnection( StringRef protocol = m_helper.MatchProtocol(protocols).second; // Check that the upgrade is valid - if (!IsValidWsUpgrade(protocol)) return; + if (!IsValidWsUpgrade(protocol)) + return; // Disconnect HttpServerConnection header reader m_dataConn.disconnect(); diff --git a/wpiutil/src/main/native/include/wpi/Logger.h b/wpiutil/src/main/native/include/wpi/Logger.h index 0079e3e796..512b9e069a 100644 --- a/wpiutil/src/main/native/include/wpi/Logger.h +++ b/wpiutil/src/main/native/include/wpi/Logger.h @@ -41,7 +41,9 @@ class Logger { void Log(unsigned int level, const char* file, unsigned int line, const char* msg) { - if (!m_func || level < m_min_level) return; + if (!m_func || level < m_min_level) { + return; + } m_func(level, file, line, msg); } diff --git a/wpiutil/src/main/native/include/wpi/UidVector.h b/wpiutil/src/main/native/include/wpi/UidVector.h index 387284273d..ad4bcb6169 100644 --- a/wpiutil/src/main/native/include/wpi/UidVector.h +++ b/wpiutil/src/main/native/include/wpi/UidVector.h @@ -24,7 +24,9 @@ class UidVectorIterator { UidVectorIterator() = default; explicit UidVectorIterator(It it, It end) : m_it(it), m_end(end) { // advance to first non-empty element - while (m_it != m_end && !*m_it) ++m_it; + while (m_it != m_end && !*m_it) { + ++m_it; + } } reference operator*() const noexcept { return *m_it; } @@ -104,7 +106,9 @@ class UidVector { // Removes the identified element by replacing it with a default-constructed // one. The element is added to the freelist for later reuse. void erase(size_type uid) { - if (uid >= m_vector.size() || !m_vector[uid]) return; + if (uid >= m_vector.size() || !m_vector[uid]) { + return; + } m_free.push_back(uid); m_vector[uid] = T(); --m_active_count; diff --git a/wpiutil/src/main/native/include/wpi/WebSocket.h b/wpiutil/src/main/native/include/wpi/WebSocket.h index 437b35d428..156d530846 100644 --- a/wpiutil/src/main/native/include/wpi/WebSocket.h +++ b/wpiutil/src/main/native/include/wpi/WebSocket.h @@ -246,7 +246,9 @@ class WebSocket : public std::enable_shared_from_this { */ void SendPing(std::function callback = nullptr) { SendPing(ArrayRef{}, [callback](auto bufs, uv::Error err) { - if (callback) callback(err); + if (callback) { + callback(err); + } }); } @@ -269,7 +271,9 @@ class WebSocket : public std::enable_shared_from_this { */ void SendPong(std::function callback = nullptr) { SendPong(ArrayRef{}, [callback](auto bufs, uv::Error err) { - if (callback) callback(err); + if (callback) { + callback(err); + } }); } diff --git a/wpiutil/src/main/native/include/wpi/WorkerThread.h b/wpiutil/src/main/native/include/wpi/WorkerThread.h index 1a7840cdd1..915821b014 100644 --- a/wpiutil/src/main/native/include/wpi/WorkerThread.h +++ b/wpiutil/src/main/native/include/wpi/WorkerThread.h @@ -105,8 +105,9 @@ void RunWorkerThreadRequest(WorkerThreadThread& thr, WorkerThreadRequest& req) { R result = std::apply(req.work, std::move(req.params)); if (req.afterWork) { - if (auto async = thr.m_async.m_async.lock()) + if (auto async = thr.m_async.m_async.lock()) { async->Send(std::move(req.afterWork), std::move(result)); + } } else { thr.m_promises.SetValue(req.promiseId, std::move(result)); } @@ -117,8 +118,9 @@ void RunWorkerThreadRequest(WorkerThreadThread& thr, WorkerThreadRequest& req) { std::apply(req.work, req.params); if (req.afterWork) { - if (auto async = thr.m_async.m_async.lock()) + if (auto async = thr.m_async.m_async.lock()) { async->Send(std::move(req.afterWork)); + } } else { thr.m_promises.SetValue(req.promiseId); } @@ -130,14 +132,18 @@ void WorkerThreadThread::Main() { while (m_active) { std::unique_lock lock(m_mutex); m_cond.wait(lock, [&] { return !m_active || !m_requests.empty(); }); - if (!m_active) break; + if (!m_active) { + break; + } // don't want to hold the lock while executing the callbacks requests.swap(m_requests); lock.unlock(); for (auto&& req : requests) { - if (!m_active) break; // requests may be long-running + if (!m_active) { + break; // requests may be long-running + } RunWorkerThreadRequest(*this, req); } requests.clear(); @@ -169,7 +175,9 @@ class WorkerThread final { * @param loop the loop to use for running afterWork routines */ void SetLoop(uv::Loop& loop) { - if (auto thr = m_owner.GetThread()) thr->m_async.SetLoop(loop); + if (auto thr = m_owner.GetThread()) { + thr->m_async.SetLoop(loop); + } } /** @@ -186,7 +194,9 @@ class WorkerThread final { * Subsequent calls to QueueWorkThen will no longer run afterWork. */ void UnsetLoop() { - if (auto thr = m_owner.GetThread()) thr->m_async.UnsetLoop(); + if (auto thr = m_owner.GetThread()) { + thr->m_async.UnsetLoop(); + } } /** @@ -197,10 +207,11 @@ class WorkerThread final { * @return The handle (if nullptr, no handle is set) */ std::shared_ptr GetHandle() const { - if (auto thr = m_owner.GetThread()) + if (auto thr = m_owner.GetThread()) { return thr->m_async.m_async.lock(); - else + } else { return nullptr; + } } /** diff --git a/wpiutil/src/main/native/include/wpi/future.h b/wpiutil/src/main/native/include/wpi/future.h index bf7672fe47..2d453d271e 100644 --- a/wpiutil/src/main/native/include/wpi/future.h +++ b/wpiutil/src/main/native/include/wpi/future.h @@ -294,7 +294,9 @@ class future final { * Ignores the result of the future if it has not been retrieved. */ ~future() { - if (m_promises) m_promises->IgnoreResult(m_request); + if (m_promises) { + m_promises->IgnoreResult(m_request); + } } future& operator=(future&& oth) noexcept { @@ -313,10 +315,11 @@ class future final { * @return The value provided by the corresponding promise.set_value(). */ T get() { - if (m_promises) + if (m_promises) { return m_promises->GetResult(m_request); - else + } else { return T(); + } } template @@ -355,7 +358,9 @@ class future final { * If the value has already been provided, returns immediately. */ void wait() const { - if (m_promises) m_promises->WaitResult(m_request); + if (m_promises) { + m_promises->WaitResult(m_request); + } } /** @@ -416,7 +421,9 @@ class future final { * Ignores the result of the future if it has not been retrieved. */ ~future() { - if (m_promises) m_promises->IgnoreResult(m_request); + if (m_promises) { + m_promises->IgnoreResult(m_request); + } } future& operator=(future&& oth) noexcept { @@ -433,7 +440,9 @@ class future final { * Can only be called once. The future will be marked invalid after the call. */ void get() { - if (m_promises) m_promises->GetResult(m_request); + if (m_promises) { + m_promises->GetResult(m_request); + } } template @@ -471,7 +480,9 @@ class future final { * If the value has already been provided, returns immediately. */ void wait() const { - if (m_promises) m_promises->WaitResult(m_request); + if (m_promises) { + m_promises->WaitResult(m_request); + } } /** @@ -537,7 +548,9 @@ class promise final { * Sets the promised value to a default-constructed T if not already set. */ ~promise() { - if (m_promises) m_promises->SetValue(m_request, T()); + if (m_promises) { + m_promises->SetValue(m_request, T()); + } } promise& operator=(promise&& oth) noexcept { @@ -572,7 +585,9 @@ class promise final { * @param value The value to provide to the waiting future */ void set_value(const T& value) { - if (m_promises) m_promises->SetValue(m_request, value); + if (m_promises) { + m_promises->SetValue(m_request, value); + } m_promises = nullptr; } @@ -583,7 +598,9 @@ class promise final { * @param value The value to provide to the waiting future */ void set_value(T&& value) { - if (m_promises) m_promises->SetValue(m_request, std::move(value)); + if (m_promises) { + m_promises->SetValue(m_request, std::move(value)); + } m_promises = nullptr; } @@ -622,7 +639,9 @@ class promise final { * Sets the promised value if not already set. */ ~promise() { - if (m_promises) m_promises->SetValue(m_request); + if (m_promises) { + m_promises->SetValue(m_request); + } } promise& operator=(promise&& oth) noexcept { @@ -657,7 +676,9 @@ class promise final { * Only effective once (subsequent calls will be ignored). */ void set_value() { - if (m_promises) m_promises->SetValue(m_request); + if (m_promises) { + m_promises->SetValue(m_request); + } m_promises = nullptr; } @@ -707,7 +728,9 @@ inline promise PromiseFactory::CreatePromise(uint64_t request) { template void PromiseFactory::SetValue(uint64_t request, const T& value) { std::unique_lock lock(GetResultMutex()); - if (!EraseRequest(request)) return; + if (!EraseRequest(request)) { + return; + } auto it = std::find_if(m_thens.begin(), m_thens.end(), [=](const auto& x) { return x.request == request; }); if (it != m_thens.end()) { @@ -726,7 +749,9 @@ void PromiseFactory::SetValue(uint64_t request, const T& value) { template void PromiseFactory::SetValue(uint64_t request, T&& value) { std::unique_lock lock(GetResultMutex()); - if (!EraseRequest(request)) return; + if (!EraseRequest(request)) { + return; + } auto it = std::find_if(m_thens.begin(), m_thens.end(), [=](const auto& x) { return x.request == request; }); if (it != m_thens.end()) { @@ -793,7 +818,9 @@ void PromiseFactory::WaitResult(uint64_t request) { // Did we get a response to *our* request? auto it = std::find_if(m_results.begin(), m_results.end(), [=](const auto& r) { return r.first == request; }); - if (it != m_results.end()) return; + if (it != m_results.end()) { + return; + } // No, keep waiting for a response Wait(lock); } @@ -810,10 +837,16 @@ bool PromiseFactory::WaitResultUntil( // Did we get a response to *our* request? auto it = std::find_if(m_results.begin(), m_results.end(), [=](const auto& r) { return r.first == request; }); - if (it != m_results.end()) return true; - if (timeout) break; + if (it != m_results.end()) { + return true; + } + if (timeout) { + break; + } // No, keep waiting for a response - if (!WaitUntil(lock, timeout_time)) timeout = true; + if (!WaitUntil(lock, timeout_time)) { + timeout = true; + } } return false; } @@ -842,10 +875,16 @@ bool PromiseFactory::WaitResultUntil( // Did we get a response to *our* request? auto it = std::find_if(m_results.begin(), m_results.end(), [=](const auto& r) { return r == request; }); - if (it != m_results.end()) return true; - if (timeout) break; + if (it != m_results.end()) { + return true; + } + if (timeout) { + break; + } // No, keep waiting for a response - if (!WaitUntil(lock, timeout_time)) timeout = true; + if (!WaitUntil(lock, timeout_time)) { + timeout = true; + } } return false; } diff --git a/wpiutil/src/main/native/include/wpi/jni_util.h b/wpiutil/src/main/native/include/wpi/jni_util.h index a419555e61..1a493131be 100644 --- a/wpiutil/src/main/native/include/wpi/jni_util.h +++ b/wpiutil/src/main/native/include/wpi/jni_util.h @@ -44,13 +44,17 @@ class JClass { JClass(JNIEnv* env, const char* name) { jclass local = env->FindClass(name); - if (!local) return; + if (!local) { + return; + } m_cls = static_cast(env->NewGlobalRef(local)); env->DeleteLocalRef(local); } void free(JNIEnv* env) { - if (m_cls) env->DeleteGlobalRef(m_cls); + if (m_cls) { + env->DeleteGlobalRef(m_cls); + } m_cls = nullptr; } @@ -77,7 +81,9 @@ class JGlobal { } void free(JNIEnv* env) { - if (m_cls) env->DeleteGlobalRef(m_cls); + if (m_cls) { + env->DeleteGlobalRef(m_cls); + } m_cls = nullptr; } @@ -107,7 +113,9 @@ class JLocal { return *this; } ~JLocal() { - if (m_obj) m_env->DeleteLocalRef(m_obj); + if (m_obj) { + m_env->DeleteLocalRef(m_obj); + } } operator T() { return m_obj; } T obj() { return m_obj; } @@ -166,7 +174,9 @@ class JArrayRefInner { StringRef str() const { auto arr = static_cast(this)->array(); - if (arr.empty()) return StringRef{}; + if (arr.empty()) { + return {}; + } return StringRef{reinterpret_cast(arr.data()), arr.size()}; } }; @@ -180,7 +190,9 @@ class JArrayRefBase : public JArrayRefInner, T> { operator ArrayRef() const { return array(); } ArrayRef array() const { - if (!this->m_elements) return ArrayRef{}; + if (!this->m_elements) { + return {}; + } return ArrayRef{this->m_elements, this->m_size}; } @@ -242,30 +254,34 @@ class JArrayRefBase : public JArrayRefInner, T> { env, \ static_cast(bb ? env->GetDirectBufferAddress(bb) : nullptr), \ len) { \ - if (!bb) \ + if (!bb) { \ errs() << "JArrayRef was passed a null pointer at \n" \ << GetJavaStackTrace(env); \ + } \ } \ J##F##ArrayRef(JNIEnv* env, T##Array jarr, int len) \ : detail::JArrayRefBase(env, jarr, len) { \ - if (jarr) \ + if (jarr) { \ m_elements = env->Get##F##ArrayElements(jarr, nullptr); \ - else \ + } else { \ errs() << "JArrayRef was passed a null pointer at \n" \ << GetJavaStackTrace(env); \ + } \ } \ J##F##ArrayRef(JNIEnv* env, T##Array jarr) \ : detail::JArrayRefBase(env, jarr) { \ - if (jarr) \ + if (jarr) { \ m_elements = env->Get##F##ArrayElements(jarr, nullptr); \ - else \ + } else { \ errs() << "JArrayRef was passed a null pointer at \n" \ << GetJavaStackTrace(env); \ + } \ } \ ~J##F##ArrayRef() { \ - if (m_jarr && m_elements) \ + if (m_jarr && m_elements) { \ m_env->Release##F##ArrayElements(static_cast(m_jarr), \ m_elements, JNI_ABORT); \ + } \ } \ }; \ \ @@ -273,25 +289,28 @@ class JArrayRefBase : public JArrayRefInner, T> { public: \ CriticalJ##F##ArrayRef(JNIEnv* env, T##Array jarr, int len) \ : detail::JArrayRefBase(env, jarr, len) { \ - if (jarr) \ + if (jarr) { \ m_elements = \ static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); \ - else \ + } else { \ errs() << "JArrayRef was passed a null pointer at \n" \ << GetJavaStackTrace(env); \ + } \ } \ CriticalJ##F##ArrayRef(JNIEnv* env, T##Array jarr) \ : detail::JArrayRefBase(env, jarr) { \ - if (jarr) \ + if (jarr) { \ m_elements = \ static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); \ - else \ + } else { \ errs() << "JArrayRef was passed a null pointer at \n" \ << GetJavaStackTrace(env); \ + } \ } \ ~CriticalJ##F##ArrayRef() { \ - if (m_jarr && m_elements) \ + if (m_jarr && m_elements) { \ m_env->ReleasePrimitiveArrayCritical(m_jarr, m_elements, JNI_ABORT); \ + } \ } \ }; @@ -327,12 +346,17 @@ template arr) { jintArray jarr = env->NewIntArray(arr.size()); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } jint* elements = static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); - if (!elements) return nullptr; - for (size_t i = 0; i < arr.size(); ++i) + if (!elements) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { elements[i] = static_cast(arr[i]); + } env->ReleasePrimitiveArrayCritical(jarr, elements, 0); return jarr; } @@ -343,7 +367,9 @@ template struct ConvertIntArray { static jintArray ToJava(JNIEnv* env, ArrayRef arr) { jintArray jarr = env->NewIntArray(arr.size()); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } env->SetIntArrayRegion(jarr, 0, arr.size(), reinterpret_cast(arr.data())); return jarr; @@ -375,7 +401,9 @@ inline jintArray MakeJIntArray(JNIEnv* env, const std::vector& arr) { // Convert a StringRef into a jbyteArray. inline jbyteArray MakeJByteArray(JNIEnv* env, StringRef str) { jbyteArray jarr = env->NewByteArray(str.size()); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } env->SetByteArrayRegion(jarr, 0, str.size(), reinterpret_cast(str.data())); return jarr; @@ -384,12 +412,17 @@ inline jbyteArray MakeJByteArray(JNIEnv* env, StringRef str) { // Convert an array of integers into a jbooleanArray. inline jbooleanArray MakeJBooleanArray(JNIEnv* env, ArrayRef arr) { jbooleanArray jarr = env->NewBooleanArray(arr.size()); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } jboolean* elements = static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); - if (!elements) return nullptr; - for (size_t i = 0; i < arr.size(); ++i) + if (!elements) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { elements[i] = arr[i] ? JNI_TRUE : JNI_FALSE; + } env->ReleasePrimitiveArrayCritical(jarr, elements, 0); return jarr; } @@ -397,12 +430,17 @@ inline jbooleanArray MakeJBooleanArray(JNIEnv* env, ArrayRef arr) { // Convert an array of booleans into a jbooleanArray. inline jbooleanArray MakeJBooleanArray(JNIEnv* env, ArrayRef arr) { jbooleanArray jarr = env->NewBooleanArray(arr.size()); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } jboolean* elements = static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); - if (!elements) return nullptr; - for (size_t i = 0; i < arr.size(); ++i) + if (!elements) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { elements[i] = arr[i] ? JNI_TRUE : JNI_FALSE; + } env->ReleasePrimitiveArrayCritical(jarr, elements, 0); return jarr; } @@ -412,7 +450,9 @@ inline jbooleanArray MakeJBooleanArray(JNIEnv* env, ArrayRef arr) { #define WPI_JNI_MAKEJARRAY(T, F) \ inline T##Array MakeJ##F##Array(JNIEnv* env, ArrayRef arr) { \ T##Array jarr = env->New##F##Array(arr.size()); \ - if (!jarr) return nullptr; \ + if (!jarr) { \ + return nullptr; \ + } \ env->Set##F##ArrayRegion(jarr, 0, arr.size(), arr.data()); \ return jarr; \ } @@ -429,9 +469,13 @@ WPI_JNI_MAKEJARRAY(jdouble, Double) // Convert an array of std::string into a jarray of jstring. inline jobjectArray MakeJStringArray(JNIEnv* env, ArrayRef arr) { static JClass stringCls{env, "java/lang/String"}; - if (!stringCls) return nullptr; + if (!stringCls) { + return nullptr; + } jobjectArray jarr = env->NewObjectArray(arr.size(), stringCls, nullptr); - if (!jarr) return nullptr; + if (!jarr) { + return nullptr; + } for (size_t i = 0; i < arr.size(); ++i) { JLocal elem{env, MakeJString(env, arr[i])}; env->SetObjectArrayElement(jarr, i, elem.obj()); @@ -477,9 +521,13 @@ class JCallbackManager : public SafeThreadOwner> { template void JCallbackManager::SetFunc(JNIEnv* env, jobject func, jmethodID mid) { auto thr = this->GetThread(); - if (!thr) return; + if (!thr) { + return; + } // free global reference - if (thr->m_func) env->DeleteGlobalRef(thr->m_func); + if (thr->m_func) { + env->DeleteGlobalRef(thr->m_func); + } // create global reference thr->m_func = env->NewGlobalRef(func); thr->m_mid = mid; @@ -489,7 +537,9 @@ template template void JCallbackManager::Send(Args&&... args) { auto thr = this->GetThread(); - if (!thr) return; + if (!thr) { + return; + } thr->m_queue.emplace(std::forward(args)...); thr->m_cond.notify_one(); } @@ -503,14 +553,20 @@ void JCallbackThread::Main() { args.group = nullptr; jint rs = T::GetJVM()->AttachCurrentThreadAsDaemon( reinterpret_cast(&env), &args); - if (rs != JNI_OK) return; + if (rs != JNI_OK) { + return; + } std::unique_lock lock(m_mutex); while (m_active) { m_cond.wait(lock, [&] { return !(m_active && m_queue.empty()); }); - if (!m_active) break; + if (!m_active) { + break; + } while (!m_queue.empty()) { - if (!m_active) break; + if (!m_active) { + break; + } auto item = std::move(m_queue.front()); m_queue.pop(); auto func = m_func; @@ -526,7 +582,9 @@ void JCallbackThread::Main() { } JavaVM* jvm = T::GetJVM(); - if (jvm) jvm->DetachCurrentThread(); + if (jvm) { + jvm->DetachCurrentThread(); + } } template @@ -542,37 +600,46 @@ inline std::string GetJavaStackTrace(JNIEnv* env, std::string* func, StringRef excludeFuncPrefix) { // create a throwable static JClass throwableCls(env, "java/lang/Throwable"); - if (!throwableCls) return ""; + if (!throwableCls) { + return ""; + } static jmethodID constructorId = nullptr; - if (!constructorId) + if (!constructorId) { constructorId = env->GetMethodID(throwableCls, "", "()V"); + } JLocal throwable(env, env->NewObject(throwableCls, constructorId)); // retrieve information from the exception. // get method id // getStackTrace returns an array of StackTraceElement static jmethodID getStackTraceId = nullptr; - if (!getStackTraceId) + if (!getStackTraceId) { getStackTraceId = env->GetMethodID(throwableCls, "getStackTrace", "()[Ljava/lang/StackTraceElement;"); + } // call getStackTrace JLocal stackTrace( env, static_cast( env->CallObjectMethod(throwable, getStackTraceId))); - if (!stackTrace) return ""; + if (!stackTrace) { + return ""; + } // get length of the array jsize stackTraceLength = env->GetArrayLength(stackTrace); // get toString methodId of StackTraceElement class static JClass stackTraceElementCls(env, "java/lang/StackTraceElement"); - if (!stackTraceElementCls) return ""; + if (!stackTraceElementCls) { + return ""; + } static jmethodID toStringId = nullptr; - if (!toStringId) + if (!toStringId) { toStringId = env->GetMethodID(stackTraceElementCls, "toString", "()Ljava/lang/String;"); + } bool haveLoc = false; std::string buf; @@ -587,7 +654,9 @@ inline std::string GetJavaStackTrace(JNIEnv* env, std::string* func, env, static_cast( env->CallObjectMethod(curStackTraceElement, toStringId))); - if (!stackElementString) return ""; + if (!stackElementString) { + return ""; + } // add a line to res JStringRef elem(env, stackElementString); @@ -617,9 +686,10 @@ class JException : public JClass { public: JException() = default; JException(JNIEnv* env, const char* name) : JClass(env, name) { - if (m_cls) + if (m_cls) { m_constructor = env->GetMethodID(m_cls, "", "(Ljava/lang/String;)V"); + } } void Throw(JNIEnv* env, jstring msg) { diff --git a/wpiutil/src/main/native/include/wpi/raw_istream.h b/wpiutil/src/main/native/include/wpi/raw_istream.h index bf5dae8986..ce897569e2 100644 --- a/wpiutil/src/main/native/include/wpi/raw_istream.h +++ b/wpiutil/src/main/native/include/wpi/raw_istream.h @@ -47,7 +47,9 @@ class raw_istream { size_t readsome(void* data, size_t len) { size_t readlen = (std::min)(in_avail(), len); - if (readlen == 0) return 0; + if (readlen == 0) { + return 0; + } read_impl(data, readlen); return m_read_count; } diff --git a/wpiutil/src/main/native/include/wpi/spinlock.h b/wpiutil/src/main/native/include/wpi/spinlock.h index c3f86744b5..9e777fa829 100644 --- a/wpiutil/src/main/native/include/wpi/spinlock.h +++ b/wpiutil/src/main/native/include/wpi/spinlock.h @@ -27,8 +27,11 @@ class spinlock { LLVM_ATTRIBUTE_ALWAYS_INLINE void lock() { - for (unsigned int i = 1; !try_lock(); ++i) - if ((i & 0xff) == 0) std::this_thread::yield(); + for (unsigned int i = 1; !try_lock(); ++i) { + if ((i & 0xff) == 0) { + std::this_thread::yield(); + } + } } LLVM_ATTRIBUTE_ALWAYS_INLINE @@ -55,8 +58,9 @@ class recursive_spinlock1 { std::memory_order_release); } else { if (owner_thread_id.load(std::memory_order_acquire) != - std::this_thread::get_id()) + std::this_thread::get_id()) { return false; + } } ++recursive_counter; return true; @@ -64,8 +68,11 @@ class recursive_spinlock1 { LLVM_ATTRIBUTE_ALWAYS_INLINE void lock() { - for (unsigned int i = 1; !try_lock(); ++i) - if ((i & 0xffff) == 0) std::this_thread::yield(); + for (unsigned int i = 1; !try_lock(); ++i) { + if ((i & 0xffff) == 0) { + std::this_thread::yield(); + } + } } LLVM_ATTRIBUTE_ALWAYS_INLINE @@ -97,7 +104,9 @@ class recursive_spinlock2 { auto us = std::this_thread::get_id(); if (!owner_thread_id.compare_exchange_weak(owner, us, std::memory_order_acquire)) { - if (owner != us) return false; + if (owner != us) { + return false; + } } ++recursive_counter; return true; @@ -105,8 +114,11 @@ class recursive_spinlock2 { LLVM_ATTRIBUTE_ALWAYS_INLINE void lock() { - for (unsigned int i = 1; !try_lock(); ++i) - if ((i & 0xffff) == 0) std::this_thread::yield(); + for (unsigned int i = 1; !try_lock(); ++i) { + if ((i & 0xffff) == 0) { + std::this_thread::yield(); + } + } } LLVM_ATTRIBUTE_ALWAYS_INLINE @@ -115,8 +127,9 @@ class recursive_spinlock2 { std::this_thread::get_id()); assert(recursive_counter > 0); - if (--recursive_counter == 0) + if (--recursive_counter == 0) { owner_thread_id.store(std::thread::id{}, std::memory_order_release); + } } }; diff --git a/wpiutil/src/main/native/include/wpi/uv/Async.h b/wpiutil/src/main/native/include/wpi/uv/Async.h index 2bc7d63765..28696413f2 100644 --- a/wpiutil/src/main/native/include/wpi/uv/Async.h +++ b/wpiutil/src/main/native/include/wpi/uv/Async.h @@ -40,10 +40,11 @@ class Async final : public HandleImpl, uv_async_t> { Async(const std::shared_ptr& loop, const private_init&) : m_loop{loop} {} ~Async() noexcept override { - if (auto loop = m_loop.lock()) + if (auto loop = m_loop.lock()) { this->Close(); - else + } else { this->ForceClosed(); + } } /** @@ -66,7 +67,9 @@ class Async final : public HandleImpl, uv_async_t> { uv_async_init(loop->GetRaw(), h->GetRaw(), [](uv_async_t* handle) { auto& h = *static_cast(handle->data); std::scoped_lock lock(h.m_mutex); - for (auto&& v : h.m_data) std::apply(h.wakeup, v); + for (auto&& v : h.m_data) { + std::apply(h.wakeup, v); + } h.m_data.clear(); }); if (err < 0) { @@ -96,7 +99,9 @@ class Async final : public HandleImpl, uv_async_t> { std::scoped_lock lock(m_mutex); m_data.emplace_back(std::forward_as_tuple(std::forward(u)...)); } - if (loop) this->Invoke(&uv_async_send, this->GetRaw()); + if (loop) { + this->Invoke(&uv_async_send, this->GetRaw()); + } } /** @@ -146,7 +151,9 @@ class Async<> final : public HandleImpl, uv_async_t> { * An async event will be emitted on the loop thread. */ void Send() { - if (auto loop = m_loop.lock()) Invoke(&uv_async_send, GetRaw()); + if (auto loop = m_loop.lock()) { + Invoke(&uv_async_send, GetRaw()); + } } /** diff --git a/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h b/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h index bd823236f5..10efd35064 100644 --- a/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h +++ b/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h @@ -41,10 +41,11 @@ class AsyncFunction final std::function, T...)> func, const private_init&) : wakeup{func}, m_loop{loop} {} ~AsyncFunction() noexcept override { - if (auto loop = m_loop.lock()) + if (auto loop = m_loop.lock()) { this->Close(); - else + } else { this->ForceClosed(); + } } /** @@ -86,10 +87,11 @@ class AsyncFunction final // waiting for it for (auto&& v : h.m_params) { auto p = h.m_promises.CreatePromise(v.first); - if (h.wakeup) + if (h.wakeup) { std::apply(h.wakeup, std::tuple_cat(std::make_tuple(std::move(p)), std::move(v.second))); + } } h.m_params.clear(); // wake up any threads that might be waiting for the result @@ -136,7 +138,9 @@ class AsyncFunction final } // signal the loop - if (loop) this->Invoke(&uv_async_send, this->GetRaw()); + if (loop) { + this->Invoke(&uv_async_send, this->GetRaw()); + } // return future return m_promises.CreateFuture(req); diff --git a/wpiutil/src/main/native/include/wpi/uv/Buffer.h b/wpiutil/src/main/native/include/wpi/uv/Buffer.h index fcf00a7042..7ff8df63f1 100644 --- a/wpiutil/src/main/native/include/wpi/uv/Buffer.h +++ b/wpiutil/src/main/native/include/wpi/uv/Buffer.h @@ -113,7 +113,9 @@ class SimpleBufferPool { * Allocate a buffer. */ Buffer Allocate() { - if (m_pool.empty()) return Buffer::Allocate(m_size); + if (m_pool.empty()) { + return Buffer::Allocate(m_size); + } auto buf = m_pool.back(); m_pool.pop_back(); buf.len = m_size; @@ -131,14 +133,18 @@ class SimpleBufferPool { * allocated with the same size as the buffer pool allocation size. */ void Release(MutableArrayRef bufs) { - for (auto& buf : bufs) m_pool.emplace_back(buf.Move()); + for (auto& buf : bufs) { + m_pool.emplace_back(buf.Move()); + } } /** * Clear the pool, releasing all buffers. */ void Clear() { - for (auto& buf : m_pool) buf.Deallocate(); + for (auto& buf : m_pool) { + buf.Deallocate(); + } m_pool.clear(); } diff --git a/wpiutil/src/main/native/include/wpi/uv/Handle.h b/wpiutil/src/main/native/include/wpi/uv/Handle.h index fbed1f9360..3fdbd3f7a0 100644 --- a/wpiutil/src/main/native/include/wpi/uv/Handle.h +++ b/wpiutil/src/main/native/include/wpi/uv/Handle.h @@ -249,7 +249,9 @@ class Handle : public std::enable_shared_from_this { template bool Invoke(F&& f, Args&&... args) const { auto err = std::forward(f)(std::forward(args)...); - if (err < 0) ReportError(err); + if (err < 0) { + ReportError(err); + } return err == 0; } diff --git a/wpiutil/src/main/native/include/wpi/uv/Tty.h b/wpiutil/src/main/native/include/wpi/uv/Tty.h index db3cd057e8..0d57cb8ded 100644 --- a/wpiutil/src/main/native/include/wpi/uv/Tty.h +++ b/wpiutil/src/main/native/include/wpi/uv/Tty.h @@ -59,7 +59,9 @@ class Tty final : public StreamImpl { */ void SetMode(uv_tty_mode_t mode) { int err = uv_tty_set_mode(GetRaw(), mode); - if (err < 0) ReportError(err); + if (err < 0) { + ReportError(err); + } } /** diff --git a/wpiutil/src/main/native/include/wpi/uv/util.h b/wpiutil/src/main/native/include/wpi/uv/util.h index 195c4a2e7d..76b42d33e7 100644 --- a/wpiutil/src/main/native/include/wpi/uv/util.h +++ b/wpiutil/src/main/native/include/wpi/uv/util.h @@ -63,10 +63,12 @@ int AddrToName(const sockaddr_in6& addr, T* ip, unsigned int* port) { */ template int AddrToName(const sockaddr_storage& addr, T* ip, unsigned int* port) { - if (addr.ss_family == AF_INET) + if (addr.ss_family == AF_INET) { return AddrToName(reinterpret_cast(addr), ip, port); - if (addr.ss_family == AF_INET6) + } + if (addr.ss_family == AF_INET6) { return AddrToName(reinterpret_cast(addr), ip, port); + } char name[1]; ip->assign(name, name); return -1; @@ -82,10 +84,11 @@ template int AddrToName(const in_addr& addr, T* ip) { char name[128]; int err = uv_inet_ntop(AF_INET, &addr, name, 128); - if (err == 0) + if (err == 0) { ip->assign(name, name + std::strlen(name)); - else + } else { ip->assign(name, name); + } return err; } @@ -99,10 +102,11 @@ template int AddrToName(const in6_addr& addr, T* ip) { char name[128]; int err = uv_inet_ntop(AF_INET6, &addr, name, 128); - if (err == 0) + if (err == 0) { ip->assign(name, name + std::strlen(name)); - else + } else { ip->assign(name, name); + } return err; } diff --git a/wpiutil/src/main/native/windows/Demangle.cpp b/wpiutil/src/main/native/windows/Demangle.cpp index 97d202ddc2..dc55c70bcf 100644 --- a/wpiutil/src/main/native/windows/Demangle.cpp +++ b/wpiutil/src/main/native/windows/Demangle.cpp @@ -23,7 +23,8 @@ std::string Demangle(const Twine& mangledSymbol) { DWORD sz = UnDecorateSymbolName(mangledSymbol.toNullTerminatedStringRef(buf).data(), buffer, sizeof(buffer), UNDNAME_COMPLETE); - if (sz == 0) return mangledSymbol.str(); + if (sz == 0) + return mangledSymbol.str(); return std::string(buffer, sz); } diff --git a/wpiutil/src/netconsoleServer/native/cpp/main.cpp b/wpiutil/src/netconsoleServer/native/cpp/main.cpp index 1e96ec2cde..383e01536b 100644 --- a/wpiutil/src/netconsoleServer/native/cpp/main.cpp +++ b/wpiutil/src/netconsoleServer/native/cpp/main.cpp @@ -78,11 +78,15 @@ static void CopyUdp(uv::Stream& in, std::shared_ptr out, uv::Buffer& buf, size_t len) { // build buffers wpi::SmallVector bufs; - if (!NewlineBuffer(*rem, buf, len, bufs, false, 0)) return; + if (!NewlineBuffer(*rem, buf, len, bufs, false, 0)) { + return; + } // send output outPtr->Send(addr, bufs, [](auto bufs2, uv::Error) { - for (auto buf : bufs2) buf.Deallocate(); + for (auto buf : bufs2) { + buf.Deallocate(); + } }); }, out); @@ -98,12 +102,15 @@ static void CopyTcp(uv::Stream& in, std::shared_ptr out) { uv::Buffer& buf, size_t len) { // build buffers wpi::SmallVector bufs; - if (!NewlineBuffer(data->rem, buf, len, bufs, true, data->seq++)) + if (!NewlineBuffer(data->rem, buf, len, bufs, true, data->seq++)) { return; + } // send output outPtr->Write(bufs, [](auto bufs2, uv::Error) { - for (auto buf : bufs2) buf.Deallocate(); + for (auto buf : bufs2) { + buf.Deallocate(); + } }); }, out); @@ -114,7 +121,9 @@ static void CopyStream(uv::Stream& in, std::shared_ptr out) { uv::Buffer buf2 = buf.Dup(); buf2.len = len; out->Write(buf2, [](auto bufs, uv::Error) { - for (auto buf : bufs) buf.Deallocate(); + for (auto buf : bufs) { + buf.Deallocate(); + } }); }); } @@ -165,12 +174,20 @@ int main(int argc, char* argv[]) { auto stderrTty = uv::Tty::Create(loop, 2, false); // pass through our console to child's (bidirectional) - if (stdinTty) CopyStream(*stdinTty, stdinPipe); - if (stdoutTty) CopyStream(*stdoutPipe, stdoutTty); - if (stderrTty) CopyStream(*stderrPipe, stderrTty); + if (stdinTty) { + CopyStream(*stdinTty, stdinPipe); + } + if (stdoutTty) { + CopyStream(*stdoutPipe, stdoutTty); + } + if (stderrTty) { + CopyStream(*stderrPipe, stderrTty); + } // when our stdin closes, also close child stdin - if (stdinTty) stdinTty->end.connect([stdinPipe] { stdinPipe->Close(); }); + if (stdinTty) { + stdinTty->end.connect([stdinPipe] { stdinPipe->Close(); }); + } if (useUdp) { auto udp = uv::Udp::Create(loop); @@ -186,7 +203,9 @@ int main(int argc, char* argv[]) { // when we get a connection, accept it tcp->connection.connect([srv = tcp.get(), stdoutPipe, stderrPipe] { auto tcp = srv->Accept(); - if (!tcp) return; + if (!tcp) { + return; + } // close on error tcp->error.connect([s = tcp.get()](wpi::uv::Error err) { s->Close(); }); @@ -224,7 +243,9 @@ int main(int argc, char* argv[]) { uv::Process::StdioCreatePipe(2, *stderrPipe, UV_WRITABLE_PIPE)); // pass our args as the child args (argv[1] becomes child argv[0], etc) - for (int i = programArgc; i < argc; ++i) options.emplace_back(argv[i]); + for (int i = programArgc; i < argc; ++i) { + options.emplace_back(argv[i]); + } auto proc = uv::Process::SpawnArray(loop, argv[programArgc], options); if (!proc) { @@ -234,7 +255,9 @@ int main(int argc, char* argv[]) { proc->exited.connect([](int64_t status, int) { std::exit(status); }); // start reading - if (stdinTty) stdinTty->StartRead(); + if (stdinTty) { + stdinTty->StartRead(); + } stdoutPipe->StartRead(); stderrPipe->StartRead(); diff --git a/wpiutil/src/netconsoleTee/native/cpp/main.cpp b/wpiutil/src/netconsoleTee/native/cpp/main.cpp index b401902a82..100e9e59e9 100644 --- a/wpiutil/src/netconsoleTee/native/cpp/main.cpp +++ b/wpiutil/src/netconsoleTee/native/cpp/main.cpp @@ -69,11 +69,15 @@ static void CopyUdp(uv::Stream& in, std::shared_ptr out, int port, uv::Buffer& buf, size_t len) { // build buffers wpi::SmallVector bufs; - if (!NewlineBuffer(*rem, buf, len, bufs, false, 0)) return; + if (!NewlineBuffer(*rem, buf, len, bufs, false, 0)) { + return; + } // send output outPtr->Send(addr, bufs, [](auto bufs2, uv::Error) { - for (auto buf : bufs2) buf.Deallocate(); + for (auto buf : bufs2) { + buf.Deallocate(); + } }); }, out); @@ -89,12 +93,15 @@ static void CopyTcp(uv::Stream& in, std::shared_ptr out) { uv::Buffer& buf, size_t len) { // build buffers wpi::SmallVector bufs; - if (!NewlineBuffer(data->rem, buf, len, bufs, true, data->seq++)) + if (!NewlineBuffer(data->rem, buf, len, bufs, true, data->seq++)) { return; + } // send output outPtr->Write(bufs, [](auto bufs2, uv::Error) { - for (auto buf : bufs2) buf.Deallocate(); + for (auto buf : bufs2) { + buf.Deallocate(); + } }); }, out); @@ -105,7 +112,9 @@ static void CopyStream(uv::Stream& in, std::shared_ptr out) { uv::Buffer buf2 = buf.Dup(); buf2.len = len; out->Write(buf2, [](auto bufs, uv::Error) { - for (auto buf : bufs) buf.Deallocate(); + for (auto buf : bufs) { + buf.Deallocate(); + } }); }); } @@ -156,10 +165,14 @@ int main(int argc, char* argv[]) { auto stdoutTty = uv::Tty::Create(loop, 1, false); // don't bother continuing if we don't have a stdin - if (!stdinTty) return EXIT_SUCCESS; + if (!stdinTty) { + return EXIT_SUCCESS; + } // pass through our input to output - if (stdoutTty) CopyStream(*stdinTty, stdoutTty); + if (stdoutTty) { + CopyStream(*stdinTty, stdoutTty); + } // when our stdin closes, exit stdinTty->end.connect([] { std::exit(EXIT_SUCCESS); }); @@ -177,7 +190,9 @@ int main(int argc, char* argv[]) { // when we get a connection, accept it tcp->connection.connect([srv = tcp.get(), stdinTty] { auto tcp = srv->Accept(); - if (!tcp) return; + if (!tcp) { + return; + } // close on error tcp->error.connect([s = tcp.get()](wpi::uv::Error err) { s->Close(); }); @@ -191,7 +206,9 @@ int main(int argc, char* argv[]) { } // start reading - if (stdinTty) stdinTty->StartRead(); + if (stdinTty) { + stdinTty->StartRead(); + } // run the loop! loop->Run(); diff --git a/wpiutil/src/test/native/cpp/Base64Test.cpp b/wpiutil/src/test/native/cpp/Base64Test.cpp index 1d0b87a80c..b7fd057db6 100644 --- a/wpiutil/src/test/native/cpp/Base64Test.cpp +++ b/wpiutil/src/test/native/cpp/Base64Test.cpp @@ -24,10 +24,11 @@ std::ostream& operator<<(std::ostream& os, const Base64TestParam& param) { class Base64Test : public ::testing::TestWithParam { protected: StringRef GetPlain() { - if (GetParam().plain_len < 0) + if (GetParam().plain_len < 0) { return StringRef(GetParam().plain); - else + } else { return StringRef(GetParam().plain, GetParam().plain_len); + } } }; diff --git a/wpiutil/src/test/native/cpp/UidVectorTest.cpp b/wpiutil/src/test/native/cpp/UidVectorTest.cpp index 9c2c048b65..f9e1624e9a 100644 --- a/wpiutil/src/test/native/cpp/UidVectorTest.cpp +++ b/wpiutil/src/test/native/cpp/UidVectorTest.cpp @@ -36,7 +36,9 @@ TEST(UidVectorTest, Iterate) { v.emplace_back(2); v.emplace_back(1); std::vector out; - for (auto&& val : v) out.push_back(val); + for (auto&& val : v) { + out.push_back(val); + } ASSERT_EQ(out.size(), 2u); EXPECT_EQ(out[0], 2); EXPECT_EQ(out[1], 1); diff --git a/wpiutil/src/test/native/cpp/WebSocketClientTest.cpp b/wpiutil/src/test/native/cpp/WebSocketClientTest.cpp index 2edeb28d27..3dc6c97437 100644 --- a/wpiutil/src/test/native/cpp/WebSocketClientTest.cpp +++ b/wpiutil/src/test/native/cpp/WebSocketClientTest.cpp @@ -19,7 +19,9 @@ class WebSocketClientTest : public WebSocketTest { // Bare bones server req.header.connect([this](StringRef name, StringRef value) { // save key (required for valid response) - if (name.equals_lower("sec-websocket-key")) clientKey = value; + if (name.equals_lower("sec-websocket-key")) { + clientKey = value; + } }); req.headersComplete.connect([this](bool) { // send response @@ -33,23 +35,30 @@ class WebSocketClientTest : public WebSocketTest { SHA1 hash; hash.Update(clientKey); hash.Update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); - if (mockBadAccept) hash.Update("1"); + if (mockBadAccept) { + hash.Update("1"); + } SmallString<64> hashBuf; SmallString<64> acceptBuf; os << "Sec-WebSocket-Accept: " << Base64Encode(hash.RawFinal(hashBuf), acceptBuf) << "\r\n"; - if (!mockProtocol.empty()) + if (!mockProtocol.empty()) { os << "Sec-WebSocket-Protocol: " << mockProtocol << "\r\n"; + } os << "\r\n"; conn->Write(bufs, [](auto bufs, uv::Error) { - for (auto& buf : bufs) buf.Deallocate(); + for (auto& buf : bufs) { + buf.Deallocate(); + } }); serverHeadersDone = true; - if (connected) connected(); + if (connected) { + connected(); + } }); serverPipe->Listen([this] { @@ -59,9 +68,13 @@ class WebSocketClientTest : public WebSocketTest { StringRef data{buf.base, size}; if (!serverHeadersDone) { data = req.Execute(data); - if (req.HasError()) Finish(); + if (req.HasError()) { + Finish(); + } ASSERT_EQ(req.GetError(), HPE_OK) << http_errno_name(req.GetError()); - if (data.empty()) return; + if (data.empty()) { + return; + } } wireData.insert(wireData.end(), data.bytes_begin(), data.bytes_end()); }); @@ -86,8 +99,9 @@ TEST_F(WebSocketClientTest, Open) { auto ws = WebSocket::CreateClient(*clientPipe, "/test", pipeName); ws->closed.connect([&](uint16_t code, StringRef reason) { Finish(); - if (code != 1005 && code != 1006) + if (code != 1005 && code != 1006) { FAIL() << "Code: " << code << " Reason: " << reason; + } }); ws->open.connect([&](StringRef protocol) { ++gotOpen; @@ -98,7 +112,9 @@ TEST_F(WebSocketClientTest, Open) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotOpen, 1); } @@ -122,7 +138,9 @@ TEST_F(WebSocketClientTest, BadAccept) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotClosed, 1); } @@ -136,8 +154,9 @@ TEST_F(WebSocketClientTest, ProtocolGood) { {"myProtocol", "myProtocol2"}); ws->closed.connect([&](uint16_t code, StringRef msg) { Finish(); - if (code != 1005 && code != 1006) + if (code != 1005 && code != 1006) { FAIL() << "Code: " << code << "Message: " << msg; + } }); ws->open.connect([&](StringRef protocol) { ++gotOpen; @@ -148,7 +167,9 @@ TEST_F(WebSocketClientTest, ProtocolGood) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotOpen, 1); } @@ -172,7 +193,9 @@ TEST_F(WebSocketClientTest, ProtocolRespNotReq) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotClosed, 1); } @@ -195,7 +218,9 @@ TEST_F(WebSocketClientTest, ProtocolReqNotResp) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotClosed, 1); } @@ -210,7 +235,9 @@ class WebSocketClientDataTest : public WebSocketClientTest, WebSocketClientDataTest() { clientPipe->Connect(pipeName, [&] { ws = WebSocket::CreateClient(*clientPipe, "/test", pipeName); - if (setupWebSocket) setupWebSocket(); + if (setupWebSocket) { + setupWebSocket(); + } }); } diff --git a/wpiutil/src/test/native/cpp/WebSocketIntegrationTest.cpp b/wpiutil/src/test/native/cpp/WebSocketIntegrationTest.cpp index cbc84194fe..abd3f83876 100644 --- a/wpiutil/src/test/native/cpp/WebSocketIntegrationTest.cpp +++ b/wpiutil/src/test/native/cpp/WebSocketIntegrationTest.cpp @@ -29,8 +29,9 @@ TEST_F(WebSocketIntegrationTest, Open) { auto ws = WebSocket::CreateClient(*clientPipe, "/test", pipeName); ws->closed.connect([&](uint16_t code, StringRef reason) { Finish(); - if (code != 1005 && code != 1006) + if (code != 1005 && code != 1006) { FAIL() << "Code: " << code << " Reason: " << reason; + } }); ws->open.connect([&, s = ws.get()](StringRef) { ++gotClientOpen; @@ -62,8 +63,9 @@ TEST_F(WebSocketIntegrationTest, Protocol) { WebSocket::CreateClient(*clientPipe, "/test", pipeName, {"proto1"}); ws->closed.connect([&](uint16_t code, StringRef reason) { Finish(); - if (code != 1005 && code != 1006) + if (code != 1005 && code != 1006) { FAIL() << "Code: " << code << " Reason: " << reason; + } }); ws->open.connect([&, s = ws.get()](StringRef protocol) { ++gotClientOpen; @@ -94,8 +96,9 @@ TEST_F(WebSocketIntegrationTest, ServerSendBinary) { auto ws = WebSocket::CreateClient(*clientPipe, "/test", pipeName); ws->closed.connect([&](uint16_t code, StringRef reason) { Finish(); - if (code != 1005 && code != 1006) + if (code != 1005 && code != 1006) { FAIL() << "Code: " << code << " Reason: " << reason; + } }); ws->binary.connect([&](ArrayRef data, bool) { ++gotData; @@ -128,8 +131,9 @@ TEST_F(WebSocketIntegrationTest, ClientSendText) { auto ws = WebSocket::CreateClient(*clientPipe, "/test", pipeName); ws->closed.connect([&](uint16_t code, StringRef reason) { Finish(); - if (code != 1005 && code != 1006) + if (code != 1005 && code != 1006) { FAIL() << "Code: " << code << " Reason: " << reason; + } }); ws->open.connect([&, s = ws.get()](StringRef) { s->SendText(uv::Buffer{"hello"}, [&](auto, uv::Error) {}); diff --git a/wpiutil/src/test/native/cpp/WebSocketServerTest.cpp b/wpiutil/src/test/native/cpp/WebSocketServerTest.cpp index d085ee538d..d3d7531d46 100644 --- a/wpiutil/src/test/native/cpp/WebSocketServerTest.cpp +++ b/wpiutil/src/test/native/cpp/WebSocketServerTest.cpp @@ -21,7 +21,9 @@ class WebSocketServerTest : public WebSocketTest { serverPipe->Listen([this]() { auto conn = serverPipe->Accept(); ws = WebSocket::CreateServer(*conn, "foo", "13"); - if (setupWebSocket) setupWebSocket(); + if (setupWebSocket) { + setupWebSocket(); + } }); clientPipe->Connect(pipeName, [this]() { clientPipe->StartRead(); @@ -29,13 +31,19 @@ class WebSocketServerTest : public WebSocketTest { StringRef data{buf.base, size}; if (!headersDone) { data = resp.Execute(data); - if (resp.HasError()) Finish(); + if (resp.HasError()) { + Finish(); + } ASSERT_EQ(resp.GetError(), HPE_OK) << http_errno_name(resp.GetError()); - if (data.empty()) return; + if (data.empty()) { + return; + } } wireData.insert(wireData.end(), data.bytes_begin(), data.bytes_end()); - if (handleData) handleData(data); + if (handleData) { + handleData(data); + } }); clientPipe->end.connect([this]() { Finish(); }); }); diff --git a/wpiutil/src/test/native/cpp/WebSocketTest.cpp b/wpiutil/src/test/native/cpp/WebSocketTest.cpp index 81017e9b4a..88a95a6ebb 100644 --- a/wpiutil/src/test/native/cpp/WebSocketTest.cpp +++ b/wpiutil/src/test/native/cpp/WebSocketTest.cpp @@ -35,9 +35,13 @@ std::vector WebSocketTest::BuildHeader(uint8_t opcode, bool fin, data.push_back(len & 0xff); } else { data.push_back(127u | (masking ? 0x80u : 0x00u)); - for (int i = 56; i >= 0; i -= 8) data.push_back((len >> i) & 0xff); + for (int i = 56; i >= 0; i -= 8) { + data.push_back((len >> i) & 0xff); + } + } + if (masking) { + data.insert(data.end(), &testMask[0], &testMask[4]); } - if (masking) data.insert(data.end(), &testMask[0], &testMask[4]); return data; } @@ -53,7 +57,9 @@ std::vector WebSocketTest::BuildMessage(uint8_t opcode, bool fin, int n = 0; for (size_t i = headerSize, end = finalData.size(); i < end; ++i) { finalData[i] ^= mask[n++]; - if (n >= 4) n = 0; + if (n >= 4) { + n = 0; + } } } return finalData; @@ -62,16 +68,21 @@ std::vector WebSocketTest::BuildMessage(uint8_t opcode, bool fin, // If the message is masked, changes the mask to match the mask set by // BuildHeader() by unmasking and remasking. void WebSocketTest::AdjustMasking(MutableArrayRef message) { - if (message.size() < 2) return; - if ((message[1] & 0x80) == 0) return; // not masked + if (message.size() < 2) { + return; + } + if ((message[1] & 0x80) == 0) { + return; // not masked + } size_t maskPos; uint8_t len = message[1] & 0x7f; - if (len == 126) + if (len == 126) { maskPos = 4; - else if (len == 127) + } else if (len == 127) { maskPos = 10; - else + } else { maskPos = 2; + } uint8_t mask[4] = {message[maskPos], message[maskPos + 1], message[maskPos + 2], message[maskPos + 3]}; message[maskPos] = testMask[0]; @@ -81,7 +92,9 @@ void WebSocketTest::AdjustMasking(MutableArrayRef message) { int n = 0; for (auto& ch : message.slice(maskPos + 4)) { ch ^= mask[n] ^ testMask[n]; - if (++n >= 4) n = 0; + if (++n >= 4) { + n = 0; + } } } @@ -120,7 +133,9 @@ TEST_F(WebSocketTest, CreateClientBasic) { conn->StartRead(); conn->data.connect([&](uv::Buffer& buf, size_t size) { req.Execute(StringRef{buf.base, size}); - if (req.HasError()) Finish(); + if (req.HasError()) { + Finish(); + } ASSERT_EQ(req.GetError(), HPE_OK) << http_errno_name(req.GetError()); }); }); @@ -130,7 +145,9 @@ TEST_F(WebSocketTest, CreateClientBasic) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotHost, 1); ASSERT_EQ(gotUpgrade, 1); ASSERT_EQ(gotConnection, 1); @@ -158,7 +175,9 @@ TEST_F(WebSocketTest, CreateClientExtraHeaders) { conn->StartRead(); conn->data.connect([&](uv::Buffer& buf, size_t size) { req.Execute(StringRef{buf.base, size}); - if (req.HasError()) Finish(); + if (req.HasError()) { + Finish(); + } ASSERT_EQ(req.GetError(), HPE_OK) << http_errno_name(req.GetError()); }); }); @@ -174,7 +193,9 @@ TEST_F(WebSocketTest, CreateClientExtraHeaders) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotExtra1, 1); ASSERT_EQ(gotExtra2, 1); } @@ -196,7 +217,9 @@ TEST_F(WebSocketTest, CreateClientTimeout) { loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotClosed, 1); } @@ -240,14 +263,18 @@ TEST_F(WebSocketTest, CreateServerBasic) { clientPipe->StartRead(); clientPipe->data.connect([&](uv::Buffer& buf, size_t size) { resp.Execute(StringRef{buf.base, size}); - if (resp.HasError()) Finish(); + if (resp.HasError()) { + Finish(); + } ASSERT_EQ(resp.GetError(), HPE_OK) << http_errno_name(resp.GetError()); }); }); loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotStatus, 1); ASSERT_EQ(gotUpgrade, 1); ASSERT_EQ(gotConnection, 1); @@ -280,14 +307,18 @@ TEST_F(WebSocketTest, CreateServerProtocol) { clientPipe->StartRead(); clientPipe->data.connect([&](uv::Buffer& buf, size_t size) { resp.Execute(StringRef{buf.base, size}); - if (resp.HasError()) Finish(); + if (resp.HasError()) { + Finish(); + } ASSERT_EQ(resp.GetError(), HPE_OK) << http_errno_name(resp.GetError()); }); }); loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotProtocol, 1); ASSERT_EQ(gotOpen, 1); } @@ -327,14 +358,18 @@ TEST_F(WebSocketTest, CreateServerBadVersion) { clientPipe->StartRead(); clientPipe->data.connect([&](uv::Buffer& buf, size_t size) { resp.Execute(StringRef{buf.base, size}); - if (resp.HasError()) Finish(); + if (resp.HasError()) { + Finish(); + } ASSERT_EQ(resp.GetError(), HPE_OK) << http_errno_name(resp.GetError()); }); }); loop->Run(); - if (HasFatalFailure()) return; + if (HasFatalFailure()) { + return; + } ASSERT_EQ(gotStatus, 1); ASSERT_EQ(gotVersion, 1); ASSERT_EQ(gotUpgrade, 1); diff --git a/wpiutil/src/test/native/cpp/hostname.cpp b/wpiutil/src/test/native/cpp/hostname.cpp index f136f69e66..29cceb1cef 100644 --- a/wpiutil/src/test/native/cpp/hostname.cpp +++ b/wpiutil/src/test/native/cpp/hostname.cpp @@ -9,7 +9,9 @@ #include "wpi/SmallVector.h" namespace wpi { -TEST(HostNameTest, HostNameNotEmpty) { ASSERT_NE(GetHostname(), ""); } +TEST(HostNameTest, HostNameNotEmpty) { + ASSERT_NE(GetHostname(), ""); +} TEST(HostNameTest, HostNameNotEmptySmallVector) { SmallVector name; ASSERT_NE(GetHostname(name), ""); diff --git a/wpiutil/src/test/native/cpp/sigslot/signal-threaded.cpp b/wpiutil/src/test/native/cpp/sigslot/signal-threaded.cpp index b110f3b823..c9d34a38b7 100644 --- a/wpiutil/src/test/native/cpp/sigslot/signal-threaded.cpp +++ b/wpiutil/src/test/native/cpp/sigslot/signal-threaded.cpp @@ -45,16 +45,22 @@ namespace { std::atomic sum{0}; -void f(int i) { sum += i; } +void f(int i) { + sum += i; +} void emit_many(Signal_mt& sig) { - for (int i = 0; i < 10000; ++i) sig(1); + for (int i = 0; i < 10000; ++i) { + sig(1); + } } void connect_emit(Signal_mt& sig) { for (int i = 0; i < 100; ++i) { auto s = sig.connect_scoped(f); - for (int j = 0; j < 100; ++j) sig(1); + for (int j = 0; j < 100; ++j) { + sig(1); + } } } @@ -68,9 +74,13 @@ TEST(Signal, ThreadedMix) { Signal_mt sig; std::array threads; - for (auto& t : threads) t = std::thread(connect_emit, std::ref(sig)); + for (auto& t : threads) { + t = std::thread(connect_emit, std::ref(sig)); + } - for (auto& t : threads) t.join(); + for (auto& t : threads) { + t.join(); + } } TEST(Signal, ThreadedEmission) { @@ -80,9 +90,13 @@ TEST(Signal, ThreadedEmission) { sig.connect(f); std::array threads; - for (auto& t : threads) t = std::thread(emit_many, std::ref(sig)); + for (auto& t : threads) { + t = std::thread(emit_many, std::ref(sig)); + } - for (auto& t : threads) t.join(); + for (auto& t : threads) { + t.join(); + } ASSERT_EQ(sum, 100000); } diff --git a/wpiutil/src/test/native/cpp/sigslot/signal-tracking.cpp b/wpiutil/src/test/native/cpp/sigslot/signal-tracking.cpp index 24dcb540cf..a9b07af6d1 100644 --- a/wpiutil/src/test/native/cpp/sigslot/signal-tracking.cpp +++ b/wpiutil/src/test/native/cpp/sigslot/signal-tracking.cpp @@ -45,7 +45,9 @@ namespace { int sum = 0; -void f1(int i) { sum += i; } +void f1(int i) { + sum += i; +} struct o1 { void operator()(int i) { sum += 2 * i; } }; diff --git a/wpiutil/src/test/native/cpp/sigslot/signal.cpp b/wpiutil/src/test/native/cpp/sigslot/signal.cpp index 6bfc135c2a..af0e646c6d 100644 --- a/wpiutil/src/test/native/cpp/sigslot/signal.cpp +++ b/wpiutil/src/test/native/cpp/sigslot/signal.cpp @@ -45,8 +45,12 @@ namespace { int sum = 0; -void f1(int i) { sum += i; } -void f2(int i) /*noexcept*/ { sum += 2 * i; } +void f1(int i) { + sum += i; +} +void f2(int i) /*noexcept*/ { + sum += 2 * i; +} struct s { static void s1(int i) { sum += i; } diff --git a/wpiutil/src/test/native/cpp/uv/UvAsyncFunctionTest.cpp b/wpiutil/src/test/native/cpp/uv/UvAsyncFunctionTest.cpp index 403b92008a..bb6fe84d0e 100644 --- a/wpiutil/src/test/native/cpp/uv/UvAsyncFunctionTest.cpp +++ b/wpiutil/src/test/native/cpp/uv/UvAsyncFunctionTest.cpp @@ -29,7 +29,9 @@ TEST(UvAsyncFunction, Test) { prepare->error.connect([](Error) { FAIL(); }); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { auto call0 = async->Call(0); auto call1 = async->Call(1); @@ -56,7 +58,9 @@ TEST(UvAsyncFunction, Test) { ASSERT_EQ(async_cb_called[1], 1); ASSERT_EQ(close_cb_called, 1); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsyncFunction, Ref) { @@ -70,7 +74,9 @@ TEST(UvAsyncFunction, Ref) { auto prepare = Prepare::Create(loop); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { ASSERT_EQ(async->Call(1, val).get(), 2); }); }); prepare->Start(); @@ -86,7 +92,9 @@ TEST(UvAsyncFunction, Ref) { ASSERT_EQ(val, 1); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsyncFunction, Movable) { @@ -100,7 +108,9 @@ TEST(UvAsyncFunction, Movable) { auto prepare = Prepare::Create(loop); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { auto val = std::make_unique(1); auto val2 = async->Call(std::move(val)).get(); @@ -119,7 +129,9 @@ TEST(UvAsyncFunction, Movable) { loop->Run(); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsyncFunction, CallIgnoreResult) { @@ -133,7 +145,9 @@ TEST(UvAsyncFunction, CallIgnoreResult) { auto prepare = Prepare::Create(loop); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { async->Call(std::make_unique(1)); }); }); prepare->Start(); @@ -147,7 +161,9 @@ TEST(UvAsyncFunction, CallIgnoreResult) { loop->Run(); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsyncFunction, VoidCall) { @@ -160,7 +176,9 @@ TEST(UvAsyncFunction, VoidCall) { auto prepare = Prepare::Create(loop); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { async->Call(); }); }); prepare->Start(); @@ -173,7 +191,9 @@ TEST(UvAsyncFunction, VoidCall) { loop->Run(); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsyncFunction, WaitFor) { @@ -186,7 +206,9 @@ TEST(UvAsyncFunction, WaitFor) { auto prepare = Prepare::Create(loop); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { ASSERT_FALSE(async->Call().wait_for(std::chrono::milliseconds(10))); }); @@ -202,7 +224,9 @@ TEST(UvAsyncFunction, WaitFor) { loop->Run(); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsyncFunction, VoidWaitFor) { @@ -215,7 +239,9 @@ TEST(UvAsyncFunction, VoidWaitFor) { auto prepare = Prepare::Create(loop); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { ASSERT_FALSE(async->Call().wait_for(std::chrono::milliseconds(10))); }); @@ -231,7 +257,9 @@ TEST(UvAsyncFunction, VoidWaitFor) { loop->Run(); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } } // namespace uv diff --git a/wpiutil/src/test/native/cpp/uv/UvAsyncTest.cpp b/wpiutil/src/test/native/cpp/uv/UvAsyncTest.cpp index ebc0d6350a..1e2b237da5 100644 --- a/wpiutil/src/test/native/cpp/uv/UvAsyncTest.cpp +++ b/wpiutil/src/test/native/cpp/uv/UvAsyncTest.cpp @@ -56,7 +56,9 @@ TEST(UvAsync, Test) { prepare->error.connect([](Error) { FAIL(); }); prepare->closed.connect([&] { close_cb_called++; }); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { for (;;) { mutex.lock(); @@ -95,7 +97,9 @@ TEST(UvAsync, Test) { ASSERT_EQ(async_cb_called, 3); ASSERT_EQ(close_cb_called, 2); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsync, Data) { @@ -113,7 +117,9 @@ TEST(UvAsync, Data) { prepare->error.connect([](Error) { FAIL(); }); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { async->Send(0, [&](int v) { ASSERT_EQ(v, 0); @@ -139,7 +145,9 @@ TEST(UvAsync, Data) { ASSERT_EQ(async_cb_called[1], 1); ASSERT_EQ(close_cb_called, 1); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } TEST(UvAsync, DataRef) { @@ -153,7 +161,9 @@ TEST(UvAsync, DataRef) { auto prepare = Prepare::Create(loop); prepare->prepare.connect([&] { - if (prepare_cb_called++) return; + if (prepare_cb_called++) { + return; + } theThread = std::thread([&] { async->Send(1, val); }); }); prepare->Start(); @@ -168,7 +178,9 @@ TEST(UvAsync, DataRef) { ASSERT_EQ(val, 1); - if (theThread.joinable()) theThread.join(); + if (theThread.joinable()) { + theThread.join(); + } } } // namespace uv diff --git a/wpiutil/src/test/native/cpp/uv/UvLoopWalkTest.cpp b/wpiutil/src/test/native/cpp/uv/UvLoopWalkTest.cpp index fb37e451e0..8e27e4715a 100644 --- a/wpiutil/src/test/native/cpp/uv/UvLoopWalkTest.cpp +++ b/wpiutil/src/test/native/cpp/uv/UvLoopWalkTest.cpp @@ -44,7 +44,9 @@ TEST(UvLoop, Walk) { timer->timeout.connect([&, theTimer = timer.get()] { theTimer->GetLoopRef().Walk([&](Handle& it) { - if (&it == timer.get()) seen_timer_handle++; + if (&it == timer.get()) { + seen_timer_handle++; + } }); theTimer->Close(); }); @@ -58,7 +60,9 @@ TEST(UvLoop, Walk) { // Loop is finished, should not see our timer handle seen_timer_handle = 0; loop->Walk([&](Handle& it) { - if (&it == timer.get()) seen_timer_handle++; + if (&it == timer.get()) { + seen_timer_handle++; + } }); ASSERT_EQ(seen_timer_handle, 0); }