From 9d1bfcab7d41fdd9f869def123d4c830fb6d7060 Mon Sep 17 00:00:00 2001 From: Soufian Batta Date: Fri, 2 May 2025 21:21:39 +0000 Subject: [PATCH] Add Support on Mountain Everest 60 Device --- .editorconfig | 2 +- .../Mountain60KeyboardController.cpp | 275 ++++ .../Mountain60KeyboardController.h | 96 ++ .../MountainKeyboardController.h | 4 - .../MountainKeyboardControllerDetect.cpp | 35 +- .../RGBController_Mountain60Keyboard.cpp | 490 ++++++ .../RGBController_Mountain60Keyboard.h | 51 + Detector.h | 174 ++- DeviceDetector.h | 60 +- LogManager.cpp | 206 ++- LogManager.h | 76 +- NetworkClient.cpp | 497 +++--- NetworkClient.h | 138 +- NetworkProtocol.cpp | 19 +- NetworkProtocol.h | 77 +- NetworkServer.cpp | 918 +++++------ NetworkServer.h | 131 +- OpenRGB.pro | 5 + OpenRGBPluginInterface.h | 53 +- PluginManager.cpp | 309 ++-- PluginManager.h | 52 +- ProfileManager.cpp | 369 +++-- ProfileManager.h | 79 +- ResourceManager.cpp | 1142 +++++++------- ResourceManager.h | 273 ++-- ResourceManagerInterface.h | 69 +- SettingsManager.cpp | 33 +- SettingsManager.h | 20 +- StringUtils.cpp | 30 +- StringUtils.h | 2 +- cli.cpp | 1376 ++++++++--------- cli.h | 19 +- filesystem.h | 2 +- main.cpp | 157 +- 34 files changed, 4031 insertions(+), 3208 deletions(-) create mode 100644 Controllers/MountainKeyboardController/Mountain60KeyboardController.cpp create mode 100644 Controllers/MountainKeyboardController/Mountain60KeyboardController.h create mode 100644 Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.cpp create mode 100644 Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.h diff --git a/.editorconfig b/.editorconfig index 882d06012..3b4d4edf8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -14,4 +14,4 @@ insert_final_newline = true [*.md] trim_trailing_whitespace = false -indent_size = 4 \ No newline at end of file +indent_size = 4 diff --git a/Controllers/MountainKeyboardController/Mountain60KeyboardController.cpp b/Controllers/MountainKeyboardController/Mountain60KeyboardController.cpp new file mode 100644 index 000000000..0b7061637 --- /dev/null +++ b/Controllers/MountainKeyboardController/Mountain60KeyboardController.cpp @@ -0,0 +1,275 @@ +/*---------------------------------------------------------*\ +| Mountain60KeyboardController.cpp | +| | +| Driver for Mountain keyboard | +| | +| Soufian Batta Jan 2025 | +| | +| This file is part of the OpenRGB project | +| SPDX-License-Identifier: GPL-2.0-only | +\*---------------------------------------------------------*/ + +#include +#include +#include +#include "Mountain60KeyboardController.h" +#include "StringUtils.h" + +using namespace std::chrono_literals; + +Mountain60KeyboardController::Mountain60KeyboardController(hid_device* dev_handle, const char* path) +{ + dev = dev_handle; + location = path; +} + +Mountain60KeyboardController::~Mountain60KeyboardController() +{ + hid_close(dev); +} + +std::string Mountain60KeyboardController::GetDeviceLocation() +{ + return("HID: " + location); +} + +const char* Mountain60KeyboardController::GetPath() +{ + return location.c_str(); +} + +std::string Mountain60KeyboardController::GetSerialString() +{ + wchar_t serial_string[128]; + int ret = hid_get_serial_number_string(dev, serial_string, 128); + + if(ret != 0) + { + return(""); + } + + return(StringUtils::wstring_to_string(serial_string)); +} + +void Mountain60KeyboardController::SetDevice(hid_device* new_device) +{ + hid_close(dev); + dev = new_device; +} + +void Mountain60KeyboardController::UpdateData() +{ + unsigned char usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + unsigned char read[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + memset(usb_buf, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + + usb_buf[0x01] = MOUNTAIN60_KEYBOARD_CHECK_NUMPAD; + usb_buf[0x02] = 0x46; //constant data + usb_buf[0x03] = 0x23; //constant data + usb_buf[0x04] = 0xEA; //constant data + + hid_send_feature_report(dev, usb_buf, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + memset(read, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + hid_get_feature_report(dev, read, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); +} + +void Mountain60KeyboardController::SendModeDetails(const mode* current_mode) +{ + unsigned char usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + unsigned char color_mode [] = {MOUNTAIN60_KEYBOARD_COLOR_MODE_SINGLE,MOUNTAIN60_KEYBOARD_COLOR_MODE_DUAL}; + memset(usb_buf, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + + usb_buf[0x01] = MOUNTAIN60_KEYBOARD_SEND_CMD; + usb_buf[0x02] = 0x46; //constant data + usb_buf[0x03] = 0x23; //constant data + usb_buf[0x04] = 0xEA; //constant data + + usb_buf[0x05] = current_mode->value; + usb_buf[0x07] = current_mode->value == MOUNTAIN60_KEYBOARD_MODE_STATIC ? 0x32 : current_mode->speed * 25; + usb_buf[0x08] = current_mode->brightness * 25; + usb_buf[0x09] = current_mode->color_mode == MODE_COLORS_RANDOM ? MOUNTAIN60_KEYBOARD_COLOR_MODE_RAINBOW : color_mode[current_mode->colors.size() - 1]; + usb_buf[0x0A] = ConvertDirection(current_mode->direction,current_mode->value == MOUNTAIN60_KEYBOARD_MODE_TORNADO); + + for (int idx = 0; idx < current_mode->colors.size(); ++idx) + { + unsigned int offset = 12 + (idx * 3); + usb_buf[offset] = RGBGetRValue(current_mode->colors[idx]); + usb_buf[offset+1] = RGBGetGValue(current_mode->colors[idx]); + usb_buf[offset+2] = RGBGetBValue(current_mode->colors[idx]); + } + + hid_send_feature_report(dev, usb_buf, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + std::this_thread::sleep_for(10ms); + SaveData(current_mode->value); +} + +void Mountain60KeyboardController::SelectMode(unsigned char mode_idx) +{ + unsigned char usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + unsigned char read[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + memset(usb_buf, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + + usb_buf[0x01] = MOUNTAIN60_KEYBOARD_SELECT_MODE_CMD; + usb_buf[0x02] = 0x46; //constant data + usb_buf[0x03] = 0x23; //constant data + usb_buf[0x04] = 0xEA; //constant data + usb_buf[0x05] = 0x01; //constant data + + usb_buf[0x09] = mode_idx; + + hid_send_feature_report(dev, usb_buf, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + memset(read, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + hid_get_feature_report(dev, read, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); +} + +void Mountain60KeyboardController::SaveData(unsigned char mode_idx) +{ + unsigned char usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + unsigned char read[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + memset(usb_buf, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + + usb_buf[0x01] = MOUNTAIN60_KEYBOARD_SAVE_CMD; + usb_buf[0x02] = 0x46; //constant data + usb_buf[0x03] = 0x23; //constant data + usb_buf[0x04] = 0xEA; //constant data + + usb_buf[0x05] = mode_idx; + + hid_send_feature_report(dev, usb_buf, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + memset(read, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + hid_get_feature_report(dev, read, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); +} + +void Mountain60KeyboardController::SendDirectStartPacketCmd(unsigned int brightness) +{ + unsigned char usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + unsigned char read[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + memset(usb_buf, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + + usb_buf[0x01] = MOUNTAIN60_KEYBOARD_START_DIRECT_CMD; + usb_buf[0x02] = 0x46; //constant data + usb_buf[0x03] = 0x23; //constant data + usb_buf[0x04] = 0xEA; //constant data + usb_buf[0x06] = 0xC0; //constant data + + usb_buf[0x05] = brightness * 25; + + hid_send_feature_report(dev, usb_buf, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + memset(read, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + hid_get_feature_report(dev, read, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); +} + +void Mountain60KeyboardController::SendDirectPacketCmd(unsigned char stream_control, unsigned char *data, unsigned int data_size) +{ + unsigned char usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + memset(usb_buf, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_HEADER_SIZE); + + usb_buf[0x01] = MOUNTAIN60_KEYBOARD_MAP_DIRECT_CMD; + usb_buf[0x02] = 0x46; //constant data + usb_buf[0x03] = 0x23; //constant data + usb_buf[0x04] = 0xEA; //constant data + + usb_buf[0x05] = stream_control; + + if(data_size <= MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE) + { + unsigned char read[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + memcpy(&usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_HEADER_SIZE],data,data_size); + + if(data_size < MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE) + { + memset(&usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_HEADER_SIZE + data_size],0xFF,MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE-data_size); + } + + hid_send_feature_report(dev, usb_buf, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + memset(read, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + hid_get_feature_report(dev, read, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + } +} + +void Mountain60KeyboardController::SendDirectPacketFinishCmd() +{ + unsigned char usb_buf[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + unsigned char read[MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE]; + memset(usb_buf, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + + usb_buf[0x01] = MOUNTAIN60_KEYBOARD_END_DIRECT_CMD; + usb_buf[0x02] = 0x46; //constant data + usb_buf[0x03] = 0x23; //constant data + usb_buf[0x04] = 0xEA; //constant data + + hid_send_feature_report(dev, usb_buf, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + memset(read, 0x00, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); + hid_get_feature_report(dev, read, MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE); +} + +void Mountain60KeyboardController::SendDirect(unsigned int brightness, unsigned char* color_data, unsigned int data_size) +{ + static unsigned char prv_buffer[MOUNTAIN60_KEYBOARD_TRANSFER_BUFFER_SIZE] = {0xFF}; + unsigned char *data_ptr = color_data; + unsigned char *prv_data_ptr = prv_buffer; + unsigned int data_len = data_size; + unsigned char stream_control_flag = 0x0E; + + SendDirectStartPacketCmd(brightness); + + while(data_len>0) + { + if(data_len >= MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE) + { + Mountain60KeyboardController::SendDirectPacketCmd(stream_control_flag,data_ptr,MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE); + memcpy(prv_data_ptr,data_ptr,MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE); + + data_ptr += MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE; + prv_data_ptr += MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE; + data_len -= MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE; + } + else + { + stream_control_flag = 0x0A; + Mountain60KeyboardController::SendDirectPacketCmd(stream_control_flag,data_ptr,data_len); + memcpy(prv_data_ptr,data_ptr,data_len); + data_len = 0; + } + } + + SendDirectPacketFinishCmd(); +} + +unsigned char Mountain60KeyboardController::ConvertDirection(unsigned int direction, bool rotation) +{ + unsigned char ret; + switch(direction) + { + case MODE_DIRECTION_LEFT: + { + ret = rotation?MOUNTAIN60_KEYBOARD_DIRECTION_ANTICLK:MOUNTAIN60_KEYBOARD_DIRECTION_LEFT; + } + break; + + case MODE_DIRECTION_RIGHT: + { + ret = rotation?MOUNTAIN60_KEYBOARD_DIRECTION_CLK:MOUNTAIN60_KEYBOARD_DIRECTION_RIGHT; + } + break; + + case MODE_DIRECTION_UP: + { + ret = MOUNTAIN60_KEYBOARD_DIRECTION_UP; + } + break; + + case MODE_DIRECTION_DOWN: + { + ret = MOUNTAIN60_KEYBOARD_DIRECTION_DOWN; + } + break; + + default: + { + ret = MOUNTAIN60_KEYBOARD_DIRECTION_LEFT; + } + break; + } + return ret; +} diff --git a/Controllers/MountainKeyboardController/Mountain60KeyboardController.h b/Controllers/MountainKeyboardController/Mountain60KeyboardController.h new file mode 100644 index 000000000..3e11ce56a --- /dev/null +++ b/Controllers/MountainKeyboardController/Mountain60KeyboardController.h @@ -0,0 +1,96 @@ +/*---------------------------------------------------------*\ +| MountainKeyboardController.h | +| | +| Driver for Mountain keyboard | +| | +| Soufian Batta Jan 2023 | +| | +| This file is part of the OpenRGB project | +| SPDX-License-Identifier: GPL-2.0-only | +\*---------------------------------------------------------*/ + +#pragma once + +#include +#include +#include "RGBController.h" + +#define MOUNTAIN60_KEYBOARD_MAX_TRANSFER_COLORS 191 +#define MOUNTAIN60_KEYBOARD_TRANSFER_BUFFER_SIZE (4*MOUNTAIN60_KEYBOARD_MAX_TRANSFER_COLORS) + +#define MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE 65 +#define MOUNTAIN60_KEYBOARD_USB_BUFFER_HEADER_SIZE 9 + +#define MOUNTAIN60_KEYBOARD_USB_MAX_DIRECT_PAYLOAD_SIZE \ +(MOUNTAIN60_KEYBOARD_USB_BUFFER_SIZE-MOUNTAIN60_KEYBOARD_USB_BUFFER_HEADER_SIZE) + + enum +{ + MOUNTAIN60_KEYBOARD_CHECK_NUMPAD = 0x08, + MOUNTAIN60_KEYBOARD_SELECT_MODE_CMD = 0x16, + MOUNTAIN60_KEYBOARD_SEND_CMD = 0x17, + MOUNTAIN60_KEYBOARD_START_DIRECT_CMD = 0x34, + MOUNTAIN60_KEYBOARD_MAP_DIRECT_CMD = 0x35, + MOUNTAIN60_KEYBOARD_END_DIRECT_CMD = 0x36, + MOUNTAIN60_KEYBOARD_SAVE_CMD = 0x1A, +}; + +enum +{ + MOUNTAIN60_KEYBOARD_MODE_STATIC = 0x01, + MOUNTAIN60_KEYBOARD_MODE_COLOR_WAVE = 0x02, + MOUNTAIN60_KEYBOARD_MODE_TORNADO = 0x03, + MOUNTAIN60_KEYBOARD_MODE_BREATHING = 0x04, + MOUNTAIN60_KEYBOARD_MODE_REACTIVE = 0x05, + MOUNTAIN60_KEYBOARD_MODE_MATRIX = 0x06, + MOUNTAIN60_KEYBOARD_MODE_CUSTOM = 0x07, + MOUNTAIN60_KEYBOARD_MODE_YETI = 0x08, + MOUNTAIN60_KEYBOARD_MODE_OFF = 0x09, + MOUNTAIN60_KEYBOARD_MODE_INVALID = 0xFF, +}; + +enum +{ + MOUNTAIN60_KEYBOARD_COLOR_MODE_RAINBOW = 0x02, + MOUNTAIN60_KEYBOARD_COLOR_MODE_SINGLE = 0x00, + MOUNTAIN60_KEYBOARD_COLOR_MODE_DUAL = 0x10 +}; + +enum +{ + MOUNTAIN60_KEYBOARD_DIRECTION_UP = 0x06, + MOUNTAIN60_KEYBOARD_DIRECTION_DOWN = 0x02, + MOUNTAIN60_KEYBOARD_DIRECTION_LEFT = 0x04, + MOUNTAIN60_KEYBOARD_DIRECTION_RIGHT = 0x00, + MOUNTAIN60_KEYBOARD_DIRECTION_ANTICLK = 0x0A, + MOUNTAIN60_KEYBOARD_DIRECTION_CLK = 0x09, +}; + +class Mountain60KeyboardController +{ +public: + Mountain60KeyboardController(hid_device* dev_handle, const char* path); + ~Mountain60KeyboardController(); + + const char* GetPath(); + std::string GetSerialString(); + std::string GetDeviceLocation(); + + void UpdateData(); + void SaveData(unsigned char mode_idx); + void SelectMode(unsigned char mode_idx); + void SetDevice(hid_device * new_device); + void SendModeDetails(const mode* current_mode); + void SendDirect(unsigned int brightness,unsigned char* color_data, unsigned int color_count); + +private: + unsigned char ConvertDirection(unsigned int direction, bool rotation); + + void SendDirectStartPacketCmd(unsigned int brightness); + void SendDirectPacketCmd(unsigned char stream_control, unsigned char *data, unsigned int data_size); + void SendDirectPacketFinishCmd(); + + hid_device* dev; + std::string location; +}; +s diff --git a/Controllers/MountainKeyboardController/MountainKeyboardController.h b/Controllers/MountainKeyboardController/MountainKeyboardController.h index 944aba0e3..bb0035697 100644 --- a/Controllers/MountainKeyboardController/MountainKeyboardController.h +++ b/Controllers/MountainKeyboardController/MountainKeyboardController.h @@ -14,10 +14,6 @@ #include #include -/*-----------------------------------------------------*\ -| Mountain vendor ID | -\*-----------------------------------------------------*/ -#define MOUNTAIN_VID 0x3282 /*-----------------------------------------------------*\ | Everest keyboard product IDs | \*-----------------------------------------------------*/ diff --git a/Controllers/MountainKeyboardController/MountainKeyboardControllerDetect.cpp b/Controllers/MountainKeyboardController/MountainKeyboardControllerDetect.cpp index 3268c628d..c960a6b74 100644 --- a/Controllers/MountainKeyboardController/MountainKeyboardControllerDetect.cpp +++ b/Controllers/MountainKeyboardController/MountainKeyboardControllerDetect.cpp @@ -3,7 +3,7 @@ | | | Detector for Mountain keyboard | | | -| Wojciech Lazarski Jan 2023 | +| Wojciech Lazarski / Soufian Batta Jan 2023 | | | | This file is part of the OpenRGB project | | SPDX-License-Identifier: GPL-2.0-only | @@ -11,9 +11,24 @@ #include #include "Detector.h" +#include "QMessageLogger" #include "MountainKeyboardController.h" #include "RGBController_MountainKeyboard.h" +#include "Mountain60KeyboardController.h" +#include "RGBController_Mountain60Keyboard.h" +/*---------------------------------------------------------------*\ +| Mountain vendor ID | +\*---------------------------------------------------------------*/ +#define MOUNTAIN_VID 0x3282 + +/*----------------------------------------------------------------*\ +| Everest 60 keyboard Connection IDs | +\*----------------------------------------------------------------*/ +#define MOUNTAIN60_EVEREST_60_PID 0x0005 +#define MOUNTAIN60_EVEREST_60_INTERFACE 2 +#define MOUNTAIN60_EVEREST_60_U 0x01 +#define MOUNTAIN60_EVEREST_60_UP 0xffff /*----------------------------------------------------------------------------------------*\ | | | DetectMountainKeyboardControllers | @@ -22,6 +37,21 @@ | | \*----------------------------------------------------------------------------------------*/ +void DetectMountain60KeyboardControllers(hid_device_info* info, const std::string& name) +{ + QMessageLogger* log = new QMessageLogger(); + + log->info("Hello World 2"); + hid_device* dev = hid_open_path(info->path); + if(dev) + { + Mountain60KeyboardController* controller = new Mountain60KeyboardController(dev, info->path); + RGBController_Mountain60Keyboard* rgb_controller = new RGBController_Mountain60Keyboard(controller); + rgb_controller->name = name; + ResourceManager::get()->RegisterRGBController(rgb_controller); + } +} + void DetectMountainKeyboardControllers(hid_device_info* info, const std::string& name) { hid_device* dev = hid_open_path(info->path); @@ -33,6 +63,7 @@ void DetectMountainKeyboardControllers(hid_device_info* info, const std::string& rgb_controller->name = name; ResourceManager::get()->RegisterRGBController(rgb_controller); } -} /* DetectMountainKeyboardControllers() */ +} REGISTER_HID_DETECTOR_IPU("Mountain Everest", DetectMountainKeyboardControllers, MOUNTAIN_VID, MOUNTAIN_EVEREST_PID, 3, 0xFF00, 0x01); +REGISTER_HID_DETECTOR_IPU("Mountain Everest 60", DetectMountain60KeyboardControllers, MOUNTAIN_VID, MOUNTAIN60_EVEREST_60_PID, MOUNTAIN60_EVEREST_60_INTERFACE, MOUNTAIN60_EVEREST_60_UP, MOUNTAIN60_EVEREST_60_U); diff --git a/Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.cpp b/Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.cpp new file mode 100644 index 000000000..e381b7437 --- /dev/null +++ b/Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.cpp @@ -0,0 +1,490 @@ +/*---------------------------------------------------------*\ +| RGBController_MountainKeyboard.cpp | +| | +| RGBController for Mountain keyboard | +| | +| Soufian Batta Jan 2023 | +| | +| This file is part of the OpenRGB project | +| SPDX-License-Identifier: GPL-2.0-only | +\*---------------------------------------------------------*/ + +#include "RGBController_Mountain60Keyboard.h" +#include "RGBControllerKeyNames.h" +#include "KeyboardLayoutManager.h" + +using namespace std::chrono_literals; + +/*-------------------------------*\ +| TODO: Detect detached keypad | +\*-------------------------------*/ + +std::vector mountain60_keyboard_key_id_values = + { + /* ESC 1 2 3 4 5 6 7 8 9 0 - = BSPC */ + 0, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + /* TAB Q W E R T Y U I O P [ ] \ */ + 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, + /* CPLK A S D F G H J K L ; " ENTR */ + 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, + /* LSFT Z X C V B N M , . / RSFT ARWU DEL */ + 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97, 94, 56, + /* LCTL LWIN LALT SPC RALT RFNC FNC ARWL ARWD ARWR */ + 105, 106, 107, 110, 113, 115, 119, 120, 121, +}; + +layout_values mountain60_layout = + { + mountain60_keyboard_key_id_values, + { + /*------------------------------------------*\ + | No regional layout fix for the moment | + \*------------------------------------------*/ + }, +}; + +keyboard_keymap_overlay_values mountain60_keyboard_overlay_no_numpad = + { + KEYBOARD_SIZE::KEYBOARD_SIZE_SIXTY, + mountain60_layout, + { + /*-------------------------------------------------------------------------------------------------------------*\ + | Edit Keys | + | Zone, Row, Column, Value, Key, OpCode, | + \*-------------------------------------------------------------------------------------------------------------*/ + { 0, 4, 13, 120, KEY_EN_DOWN_ARROW, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 4, 12, 119, KEY_EN_LEFT_ARROW, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 4, 14, 121, KEY_EN_RIGHT_ARROW, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 4, 14, 121, KEY_EN_RIGHT_ARROW, KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 3, 13, 99, KEY_EN_UP_ARROW, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 12, 97, KEY_EN_RIGHT_SHIFT, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 2, 85, KEY_EN_Z, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 3, 86, KEY_EN_X, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 4, 87, KEY_EN_C, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 5, 88, KEY_EN_B, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 6, 89, KEY_EN_V, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 7, 90, KEY_EN_N, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 8, 91, KEY_EN_M, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 9, 92, KEY_EN_COMMA, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 10, 93, KEY_EN_PERIOD, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 14, 56, KEY_EN_DELETE, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 2, 13, 76, KEY_EN_ANSI_ENTER, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 0, 84, KEY_EN_LEFT_SHIFT, KEYBOARD_OPCODE_SWAP_ONLY, }, + //upper edge + { 0, 0, 0, 126, "Edge 1", KEYBOARD_OPCODE_INSERT_ROW, }, + { 0, 0, 1, 127, "Edge 2", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 2, 128, "Edge 3", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 3, 129, "Edge 4", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 4, 130, "Edge 5", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 5, 131, "Edge 6", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 6, 132, "Edge 7", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 7, 133, "Edge 8", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 8, 134, "Edge 9", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 9, 135, "Edge 10", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 10, 136, "Edge 11", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 11, 137, "Edge 12", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 12, 138, "Edge 13", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 13, 139, "Edge 14", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 14, 140, "Edge 15", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 15, 141, "Edge 16", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + //left edge + { 0, 0, 0, 169, "Edge 44", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 1, 0, 168, "Edge 43", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 2, 0, 167, "Edge 42", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 3, 0, 166, "Edge 41", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 4, 0, 165, "Edge 40", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 5, 0, 164, "Edge 39", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + //down edge + { 0, 6, 0, 1, KEY_EN_UNUSED, KEYBOARD_OPCODE_INSERT_ROW, }, + { 0, 6, 0, 163, "Edge 38", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 1, 162, "Edge 37", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 2, 161, "Edge 36", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 3, 160, "Edge 35", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 4, 159, "Edge 34", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 5, 158, "Edge 33", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 6, 157, "Edge 32", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 7, 156, "Edge 31", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 8, 155, "Edge 30", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 9, 154, "Edge 29", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 10, 153, "Edge 28", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 11, 152, "Edge 27", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 12, 151, "Edge 26", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 13, 150, "Edge 25", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 14, 149, "Edge 24", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 15, 148, "Edge 23", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + //right edge + { 0, 1, 16, 142, "Edge 17", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 2, 16, 143, "Edge 18", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 3, 16, 144, "Edge 19", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 4, 16, 145, "Edge 20", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 5, 16, 146, "Edge 21", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 16, 147, "Edge 22", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 16, 147, "Edge 22", KEYBOARD_OPCODE_SWAP_ONLY, }, + //numpad left edge + { 0, 0, 17, 191, "Numpad Edge 22", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 1, 17, 190, "Numpad Edge 21", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 2, 17, 189, "Numpad Edge 20", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 3, 17, 188, "Numpad Edge 19", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 4, 17, 187, "Numpad Edge 18", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 5, 17, 186, "Numpad Edge 17", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + //numpad upper edge + { 0, 0, 18, 170, "Numpad Edge 1", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 19, 171, "Numpad Edge 2", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 20, 172, "Numpad Edge 3", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 21, 173, "Numpad Edge 4", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 0, 22, 174, "Numpad Edge 5", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + //numpad down edge + { 0, 6, 17, 185, "Numpad Edge 12", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT }, + { 0, 6, 18, 184, "Numpad Edge 13", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 19, 183, "Numpad Edge 14", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 20, 182, "Numpad Edge 15", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 21, 181, "Numpad Edge 16", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + //numpad right edge + { 0, 1, 22, 175, "Numpad Edge 6", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 2, 22, 176, "Numpad Edge 7", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 3, 22, 177, "Numpad Edge 8", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 4, 22, 178, "Numpad Edge 9", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 5, 22, 179, "Numpad Edge 10", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 22, 180, "Numpad Edge 11", KEYBOARD_OPCODE_INSERT_SHIFT_RIGHT, }, + { 0, 6, 22, 180, "Numpad Edge 11", KEYBOARD_OPCODE_SWAP_ONLY, }, + //numpad keys + { 0, 1, 18, 38, KEY_EN_NUMPAD_LOCK, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 1, 19, 39, KEY_EN_NUMPAD_DIVIDE, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 1, 20, 40, KEY_EN_NUMPAD_TIMES, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 1, 21, 41, KEY_EN_NUMPAD_MINUS, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 2, 18, 59, KEY_EN_NUMPAD_7, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 2, 19, 60, KEY_EN_NUMPAD_8, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 2, 20, 61, KEY_EN_NUMPAD_9, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 2, 21, 62, KEY_EN_NUMPAD_PLUS, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 18, 80, KEY_EN_NUMPAD_4, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 19, 81, KEY_EN_NUMPAD_5, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 3, 20, 82, KEY_EN_NUMPAD_6, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 4, 18, 101, KEY_EN_NUMPAD_1, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 4, 19, 102, KEY_EN_NUMPAD_2, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 4, 20, 103, KEY_EN_NUMPAD_3, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 5, 18, 122, KEY_EN_NUMPAD_0, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 5, 20, 124, KEY_EN_NUMPAD_PERIOD, KEYBOARD_OPCODE_SWAP_ONLY, }, + { 0, 5, 21, 125, KEY_EN_NUMPAD_ENTER, KEYBOARD_OPCODE_SWAP_ONLY, }, + } +}; + +/**------------------------------------------------------------------*\ + @name Mountain Keyboard + @category Keyboard + @type USB + @save :white_check_mark: + @direct :white_check_mark: + @effects :white_check_mark: + @detectors DetectMountainKeyboardControllers + @comment +\*-------------------------------------------------------------------*/ + +RGBController_Mountain60Keyboard::RGBController_Mountain60Keyboard(Mountain60KeyboardController* controller_ptr) +{ + controller = controller_ptr; + name = "Mountain Everest 60 Keyboard"; + vendor = "Mountain"; + type = DEVICE_TYPE_KEYBOARD; + description = "Mountain Everest Keyboard 60%"; + location = controller->GetDeviceLocation(); + serial = controller->GetSerialString(); + + mode Direct; + Direct.name = "Direct"; + Direct.value = MOUNTAIN60_KEYBOARD_MODE_CUSTOM; + Direct.flags = MODE_FLAG_HAS_PER_LED_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_MANUAL_SAVE; + Direct.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + Direct.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Direct.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Direct.color_mode = MODE_COLORS_PER_LED; + modes.push_back(Direct); + + mode Off; + Off.name = "Off"; + Off.value = MOUNTAIN60_KEYBOARD_MODE_OFF; + Off.flags = MODE_FLAG_MANUAL_SAVE; + Off.color_mode = MODE_COLORS_NONE; + modes.push_back(Off); + + mode Static; + Static.name = "Static"; + Static.value = MOUNTAIN60_KEYBOARD_MODE_STATIC; + Static.flags = MODE_FLAG_HAS_MODE_SPECIFIC_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_MANUAL_SAVE; + Static.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + Static.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Static.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Static.color_mode = MODE_COLORS_MODE_SPECIFIC; + Static.colors_min = 1; + Static.colors_max = 1; + Static.colors.resize(1); + modes.push_back(Static); + + mode ColorWaveRainbow; + ColorWaveRainbow.name = "Rainbow Wave"; + ColorWaveRainbow.value = MOUNTAIN60_KEYBOARD_MODE_COLOR_WAVE; + ColorWaveRainbow.flags = MODE_FLAG_HAS_RANDOM_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_HAS_SPEED | MODE_FLAG_HAS_DIRECTION_LR | MODE_FLAG_HAS_DIRECTION_UD | MODE_FLAG_MANUAL_SAVE; + ColorWaveRainbow.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + ColorWaveRainbow.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + ColorWaveRainbow.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + ColorWaveRainbow.speed_min = MOUNTAIN60_KEYBOARD_SPEED_MIN; + ColorWaveRainbow.speed = MOUNTAIN60_KEYBOARD_SPEED_DEFAULT; + ColorWaveRainbow.speed_max = MOUNTAIN60_KEYBOARD_SPEED_MAX; + ColorWaveRainbow.color_mode = MODE_COLORS_RANDOM; + + modes.push_back(ColorWaveRainbow); + + mode ColorWave; + ColorWave.name = "ColorWave"; + ColorWave.value = MOUNTAIN60_KEYBOARD_MODE_COLOR_WAVE; + ColorWave.flags = MODE_FLAG_HAS_MODE_SPECIFIC_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_HAS_SPEED | MODE_FLAG_HAS_DIRECTION_LR | MODE_FLAG_HAS_DIRECTION_UD | MODE_FLAG_MANUAL_SAVE; + ColorWave.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + ColorWave.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + ColorWave.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + ColorWave.speed_min = MOUNTAIN60_KEYBOARD_SPEED_MIN; + ColorWave.speed = MOUNTAIN60_KEYBOARD_SPEED_DEFAULT; + ColorWave.speed_max = MOUNTAIN60_KEYBOARD_SPEED_MAX; + ColorWave.colors_min = 1; + ColorWave.colors_max = 2; + ColorWave.colors.resize(2); + ColorWave.color_mode = MODE_COLORS_MODE_SPECIFIC; + modes.push_back(ColorWave); + + mode Tornado; + Tornado.name = "Tornado"; + Tornado.value = MOUNTAIN60_KEYBOARD_MODE_TORNADO; + Tornado.flags = MODE_FLAG_HAS_RANDOM_COLOR | MODE_FLAG_HAS_MODE_SPECIFIC_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_HAS_SPEED | MODE_FLAG_HAS_DIRECTION_LR | MODE_FLAG_MANUAL_SAVE; + Tornado.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + Tornado.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Tornado.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Tornado.speed_min = MOUNTAIN60_KEYBOARD_SPEED_MIN; + Tornado.speed = MOUNTAIN60_KEYBOARD_SPEED_DEFAULT; + Tornado.speed_max = MOUNTAIN60_KEYBOARD_SPEED_MAX; + Tornado.colors_min = 1; + Tornado.colors_max = 1; + Tornado.colors.resize(1); + Tornado.color_mode = MODE_COLORS_MODE_SPECIFIC; + modes.push_back(Tornado); + + mode Breathing; + Breathing.name = "Breathing"; + Breathing.value = MOUNTAIN60_KEYBOARD_MODE_BREATHING; + Breathing.flags = MODE_FLAG_HAS_RANDOM_COLOR | MODE_FLAG_HAS_MODE_SPECIFIC_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_HAS_SPEED | MODE_FLAG_MANUAL_SAVE; + Breathing.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + Breathing.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Breathing.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Breathing.speed_min = MOUNTAIN60_KEYBOARD_SPEED_MIN; + Breathing.speed = MOUNTAIN60_KEYBOARD_SPEED_DEFAULT; + Breathing.speed_max = MOUNTAIN60_KEYBOARD_SPEED_MAX; + Breathing.colors_min = 1; + Breathing.colors_max = 2; + Breathing.colors.resize(2); + Breathing.color_mode = MODE_COLORS_MODE_SPECIFIC; + modes.push_back(Breathing); + + mode Reactive; + Reactive.name = "Reactive"; + Reactive.value = MOUNTAIN60_KEYBOARD_MODE_REACTIVE; + Reactive.flags = MODE_FLAG_HAS_MODE_SPECIFIC_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_HAS_SPEED | MODE_FLAG_MANUAL_SAVE; + Reactive.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + Reactive.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Reactive.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Reactive.speed_min = MOUNTAIN60_KEYBOARD_SPEED_MIN; + Reactive.speed = MOUNTAIN60_KEYBOARD_SPEED_DEFAULT; + Reactive.speed_max = MOUNTAIN60_KEYBOARD_SPEED_MAX; + Reactive.color_mode = MODE_COLORS_MODE_SPECIFIC; + Reactive.colors_min = 1; + Reactive.colors_max = 2; + Reactive.colors.resize(2); + modes.push_back(Reactive); + + mode Matrix; + Matrix.name = "Matrix"; + Matrix.value = MOUNTAIN60_KEYBOARD_MODE_MATRIX; + Matrix.flags = MODE_FLAG_HAS_MODE_SPECIFIC_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_HAS_SPEED | MODE_FLAG_MANUAL_SAVE; + Matrix.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + Matrix.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Matrix.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Matrix.speed_min = MOUNTAIN60_KEYBOARD_SPEED_MIN; + Matrix.speed = MOUNTAIN60_KEYBOARD_SPEED_DEFAULT; + Matrix.speed_max = MOUNTAIN60_KEYBOARD_SPEED_MAX; + Matrix.color_mode = MODE_COLORS_MODE_SPECIFIC; + Matrix.colors_min = 1; + Matrix.colors_max = 2; + Matrix.colors.resize(2); + modes.push_back(Matrix); + + mode Yeti; + Yeti.name = "Yeti"; + Yeti.value = MOUNTAIN60_KEYBOARD_MODE_YETI; + Yeti.flags = MODE_FLAG_HAS_MODE_SPECIFIC_COLOR | MODE_FLAG_HAS_BRIGHTNESS | MODE_FLAG_HAS_SPEED | MODE_FLAG_MANUAL_SAVE; + Yeti.brightness_min = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN; + Yeti.brightness = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Yeti.brightness_max = MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX; + Yeti.speed_min = MOUNTAIN60_KEYBOARD_SPEED_MIN; + Yeti.speed = MOUNTAIN60_KEYBOARD_SPEED_DEFAULT; + Yeti.speed_max = MOUNTAIN60_KEYBOARD_SPEED_MAX; + Yeti.color_mode = MODE_COLORS_MODE_SPECIFIC; + Yeti.colors_min = 1; + Yeti.colors_max = 2; + Yeti.colors.resize(2); + modes.push_back(Yeti); + + SetupZones(); + + /*-----------------------------------------------------*\ + | The Mountain Everest 60 keyboard need to send a | + | specific packet frequently so that leds get updated | + \*-----------------------------------------------------*/ + mountain_thread = new std::thread(&RGBController_Mountain60Keyboard::UpdateMountain, this); + mountaint_thread_running = true; + update_device = true; + found_device = true; +} + +RGBController_Mountain60Keyboard::~RGBController_Mountain60Keyboard() +{ + update_device = false; + mountaint_thread_running = false; + mountain_thread->join(); + delete mountain_thread; + + /*---------------------------------------------------------*\ + | Delete the matrix map | + \*---------------------------------------------------------*/ + for(unsigned int zone_index = 0; zone_index < zones.size(); zone_index++) + { + if(zones[zone_index].type == ZONE_TYPE_MATRIX) + { + delete zones[zone_index].matrix_map; + } + } + + delete controller; +} + +void RGBController_Mountain60Keyboard::SetupZones() +{ + KeyboardLayoutManager new_kb(KEYBOARD_LAYOUT_ANSI_QWERTY, KEYBOARD_SIZE_SIXTY, mountain60_layout); + new_kb.ChangeKeys(mountain60_keyboard_overlay_no_numpad); + + zone new_zone; + matrix_map_type * new_map = new matrix_map_type; + + new_zone.name = "Mountain Everest 60"; + new_zone.type = ZONE_TYPE_MATRIX; + new_zone.matrix_map = new_map; + new_zone.matrix_map->height = new_kb.GetRowCount(); + new_zone.matrix_map->width = new_kb.GetColumnCount(); + new_zone.matrix_map->map = new unsigned int[new_map->height * new_map->width]; + new_zone.leds_count = new_kb.GetKeyCount(); + new_zone.leds_min = new_zone.leds_count; + new_zone.leds_max = new_zone.leds_count; + + new_kb.GetKeyMap(new_map->map, KEYBOARD_MAP_FILL_TYPE_COUNT); + + for(unsigned int led_idx = 0; led_idx < new_zone.leds_count; led_idx++) + { + led new_led; + new_led.name = new_kb.GetKeyNameAt(led_idx); + new_led.value = new_kb.GetKeyValueAt(led_idx); + leds.push_back(new_led); + } + + zones.push_back(new_zone); + SetupColors(); + DeviceUpdateMode(); + update_device = true; +} + +void RGBController_Mountain60Keyboard::ResizeZone(int /*zone*/, int /*new_size*/) +{ + /*---------------------------------------------------------*\ + | This device does not support resizing zones | + \*---------------------------------------------------------*/ +} + +void RGBController_Mountain60Keyboard::DeviceUpdateLEDs() +{ + if (update_device.load()) + { + unsigned char* color_data = new unsigned char[(leds.size()*4)]; + + /*---------------------------------------------------------*\ + | Filling the color_data vector with progressive index | + | leaving space for RGB data | + \*---------------------------------------------------------*/ + for(unsigned int led_idx = 0; led_idx < leds.size(); led_idx++) + { + const unsigned int idx = led_idx * 4; + color_data[idx] = leds[led_idx].value; + color_data[idx + 1] = RGBGetRValue(colors[led_idx]); + color_data[idx + 2] = RGBGetGValue(colors[led_idx]); + color_data[idx + 3] = RGBGetBValue(colors[led_idx]); + } + + controller->SendDirect(modes[active_mode].brightness, color_data, (leds.size()*4)); + delete[] color_data; + } +} + +void RGBController_Mountain60Keyboard::UpdateZoneLEDs(int /*zone*/) +{ + DeviceUpdateLEDs(); +} + +void RGBController_Mountain60Keyboard::UpdateSingleLED(int /*led*/) +{ + DeviceUpdateLEDs(); +} + +void RGBController_Mountain60Keyboard::DeviceUpdateMode() +{ + static mode current_mode; + + if(modes[active_mode].value != current_mode.value && found_device.load()) + { + current_mode = modes[active_mode]; + controller->SelectMode(modes[active_mode].value); + } + + if(current_mode.color_mode != MODE_FLAG_HAS_PER_LED_COLOR && update_device.load()) + { + controller->SendModeDetails(&modes[active_mode]); + } +} + +void RGBController_Mountain60Keyboard::DeviceSaveMode() +{ + controller->SaveData(modes[active_mode].value); +} + +void RGBController_Mountain60Keyboard::UpdateMountain() +{ + while (mountaint_thread_running.load()) + { + std::this_thread::sleep_for(MOUNTAIN60_KEEP_LIVE_PERIOD); + + controller->UpdateData(); + + const char* Path = controller->GetPath(); + hid_device * rescan_device = hid_open_path(Path); + + if (rescan_device) + { + if (!found_device.load()) + { + controller->SetDevice(rescan_device); + found_device = true; + update_device = true; + } + } + else + { + if (found_device.load()) + { + update_device = false; + found_device = false; + } + } + } +} diff --git a/Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.h b/Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.h new file mode 100644 index 000000000..2cc67733b --- /dev/null +++ b/Controllers/MountainKeyboardController/RGBController_Mountain60Keyboard.h @@ -0,0 +1,51 @@ +/*---------------------------------------------------------*\ +| RGBController_MountainKeyboard.h | +| | +| RGBController for Mountain keyboard | +| | +| Soufian Batta Jan 2023 | +| | +| This file is part of the OpenRGB project | +| SPDX-License-Identifier: GPL-2.0-only | +\*---------------------------------------------------------*/ + +#pragma once + +#include +#include "RGBController.h" +#include "Mountain60KeyboardController.h" + +#define MOUNTAIN60_KEYBOARD_BRIGHTNESS_MIN 0 +#define MOUNTAIN60_KEYBOARD_BRIGHTNESS_MAX 4 + +#define MOUNTAIN60_KEYBOARD_SPEED_MIN 0 +#define MOUNTAIN60_KEYBOARD_SPEED_MAX 4 +#define MOUNTAIN60_KEYBOARD_SPEED_DEFAULT 2 +#define MOUNTAIN60_KEEP_LIVE_PERIOD 500ms + + +class RGBController_Mountain60Keyboard : public RGBController +{ +public: + RGBController_Mountain60Keyboard(Mountain60KeyboardController* controller_ptr); + ~RGBController_Mountain60Keyboard(); + + void SetupZones(); + + void ResizeZone(int zone, int new_size); + + void DeviceUpdateLEDs(); + void UpdateZoneLEDs(int zone); + void UpdateSingleLED(int led); + + void DeviceUpdateMode(); + void DeviceSaveMode(); + void UpdateMountain(); + +private: + Mountain60KeyboardController* controller; + std::thread* mountain_thread; + std::atomic mountaint_thread_running; + std::atomic update_device; + std::atomic found_device; +}; diff --git a/Detector.h b/Detector.h index cdaf9c89f..0ee3ff3fe 100644 --- a/Detector.h +++ b/Detector.h @@ -11,31 +11,151 @@ #include "DeviceDetector.h" -#define REGISTER_DETECTOR(name, func) static DeviceDetector device_detector_obj_##func(name, func) -#define REGISTER_I2C_DETECTOR(name, func) static I2CDeviceDetector device_detector_obj_##func(name, func) -#define REGISTER_I2C_DIMM_DETECTOR(name, func, jedec_id, dimm_type) static I2CDIMMDeviceDetector device_detector_obj_##func##jedec_id(name, func, jedec_id, dimm_type) -#define REGISTER_I2C_PCI_DETECTOR(name, func, ven, dev, subven, subdev, addr) static I2CPCIDeviceDetector device_detector_obj_##ven##dev##subven##subdev##addr##func(name, func, ven, dev, subven, subdev, addr) -#define REGISTER_I2C_BUS_DETECTOR(func) static I2CBusDetector device_detector_obj_##func(func) -#define REGISTER_HID_DETECTOR(name, func, vid, pid) static HIDDeviceDetector device_detector_obj_##vid##pid(name, func, vid, pid, HID_INTERFACE_ANY, HID_USAGE_PAGE_ANY, HID_USAGE_ANY) -#define REGISTER_HID_DETECTOR_I(name, func, vid, pid, interface) static HIDDeviceDetector device_detector_obj_##vid##pid##_##interface(name, func, vid, pid, interface, HID_USAGE_PAGE_ANY, HID_USAGE_ANY) -#define REGISTER_HID_DETECTOR_IP(name, func, vid, pid, interface, page) static HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page(name, func, vid, pid, interface, page, HID_USAGE_ANY) -#define REGISTER_HID_DETECTOR_IPU(name, func, vid, pid, interface, page, usage) static HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page##_##usage(name, func, vid, pid, interface, page, usage) -#define REGISTER_HID_DETECTOR_P(name, func, vid, pid, page) static HIDDeviceDetector device_detector_obj_##vid##pid##__##page(name, func, vid, pid, HID_INTERFACE_ANY, page, HID_USAGE_ANY) -#define REGISTER_HID_DETECTOR_PU(name, func, vid, pid, page, usage) static HIDDeviceDetector device_detector_obj_##vid##pid##__##page##_##usage(name, func, vid, pid, HID_INTERFACE_ANY, page, usage) -#define REGISTER_HID_WRAPPED_DETECTOR(name, func, vid, pid) static HIDWrappedDeviceDetector device_detector_obj_##vid##pid(name, func, vid, pid, HID_INTERFACE_ANY, HID_USAGE_PAGE_ANY, HID_USAGE_ANY) -#define REGISTER_HID_WRAPPED_DETECTOR_I(name, func, vid, pid, interface) static HIDWrappedDeviceDetector device_detector_obj_##vid##pid##_##interface(name, func, vid, pid, interface, HID_USAGE_PAGE_ANY, HID_USAGE_ANY) -#define REGISTER_HID_WRAPPED_DETECTOR_IPU(name, func, vid, pid, interface, page, usage) static HIDWrappedDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page##_##usage(name, func, vid, pid, interface, page, usage) -#define REGISTER_HID_WRAPPED_DETECTOR_PU(name, func, vid, pid, page, usage) static HIDWrappedDeviceDetector device_detector_obj_##vid##pid##__##page##_##usage(name, func, vid, pid, HID_INTERFACE_ANY, page, usage) -#define REGISTER_DYNAMIC_DETECTOR(name, func) static DynamicDetector device_detector_obj_##func(name, func) -#define REGISTER_PRE_DETECTION_HOOK(func) static PreDetectionHook device_detector_obj_##func(func) +#define REGISTER_DETECTOR(name, func) static DeviceDetector device_detector_obj_##func(name, func) +#define REGISTER_I2C_DETECTOR(name, func) \ + static I2CDeviceDetector device_detector_obj_##func(name, func) +#define REGISTER_I2C_DIMM_DETECTOR(name, func, jedec_id, dimm_type) \ + static I2CDIMMDeviceDetector device_detector_obj_##func##jedec_id(name, \ + func, \ + jedec_id, \ + dimm_type) +#define REGISTER_I2C_PCI_DETECTOR(name, func, ven, dev, subven, subdev, addr) \ + static I2CPCIDeviceDetector device_detector_obj_##ven##dev##subven##subdev##addr##func(name, \ + func, \ + ven, \ + dev, \ + subven, \ + subdev, \ + addr) +#define REGISTER_I2C_BUS_DETECTOR(func) static I2CBusDetector device_detector_obj_##func(func) +#define REGISTER_HID_DETECTOR(name, func, vid, pid) \ + static HIDDeviceDetector device_detector_obj_##vid##pid(name, \ + func, \ + vid, \ + pid, \ + HID_INTERFACE_ANY, \ + HID_USAGE_PAGE_ANY, \ + HID_USAGE_ANY) +#define REGISTER_HID_DETECTOR_I(name, func, vid, pid, interface) \ + static HIDDeviceDetector device_detector_obj_##vid##pid##_##interface(name, \ + func, \ + vid, \ + pid, \ + interface, \ + HID_USAGE_PAGE_ANY, \ + HID_USAGE_ANY) +#define REGISTER_HID_DETECTOR_IP(name, func, vid, pid, interface, page) \ + static HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page(name, \ + func, \ + vid, \ + pid, \ + interface, \ + page, \ + HID_USAGE_ANY) +#define REGISTER_HID_DETECTOR_IPU(name, func, vid, pid, interface, page, usage) \ + static HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page##_##usage( \ + name, func, vid, pid, interface, page, usage) +#define REGISTER_HID_DETECTOR_P(name, func, vid, pid, page) \ + static HIDDeviceDetector device_detector_obj_##vid##pid##__##page(name, \ + func, \ + vid, \ + pid, \ + HID_INTERFACE_ANY, \ + page, \ + HID_USAGE_ANY) +#define REGISTER_HID_DETECTOR_PU(name, func, vid, pid, page, usage) \ + static HIDDeviceDetector device_detector_obj_##vid##pid##__##page##_##usage(name, \ + func, \ + vid, \ + pid, \ + HID_INTERFACE_ANY, \ + page, \ + usage) +#define REGISTER_HID_WRAPPED_DETECTOR(name, func, vid, pid) \ + static HIDWrappedDeviceDetector device_detector_obj_##vid##pid(name, \ + func, \ + vid, \ + pid, \ + HID_INTERFACE_ANY, \ + HID_USAGE_PAGE_ANY, \ + HID_USAGE_ANY) +#define REGISTER_HID_WRAPPED_DETECTOR_I(name, func, vid, pid, interface) \ + static HIDWrappedDeviceDetector device_detector_obj_##vid##pid##_##interface( \ + name, func, vid, pid, interface, HID_USAGE_PAGE_ANY, HID_USAGE_ANY) +#define REGISTER_HID_WRAPPED_DETECTOR_IPU(name, func, vid, pid, interface, page, usage) \ + static HIDWrappedDeviceDetector \ + device_detector_obj_##vid##pid##_##interface##_##page##_##usage(name, \ + func, \ + vid, \ + pid, \ + interface, \ + page, \ + usage) +#define REGISTER_HID_WRAPPED_DETECTOR_PU(name, func, vid, pid, page, usage) \ + static HIDWrappedDeviceDetector device_detector_obj_##vid##pid##__##page##_##usage( \ + name, func, vid, pid, HID_INTERFACE_ANY, page, usage) +#define REGISTER_DYNAMIC_DETECTOR(name, func) \ + static DynamicDetector device_detector_obj_##func(name, func) +#define REGISTER_PRE_DETECTION_HOOK(func) static PreDetectionHook device_detector_obj_##func(func) -#define REGISTER_DYNAMIC_I2C_DETECTOR(name, func) I2CDeviceDetector device_detector_obj_##func(name, func) -#define REGISTER_DYNAMIC_I2C_DIMM_DETECTOR(name, func, jedec_id, dimm_type) I2CDIMMDeviceDetector device_detector_obj_##func(name, func, jedec_id, dimm_type) -#define REGISTER_DYNAMIC_I2C_PCI_DETECTOR(name, func, ven, dev, subven, subdev, addr) I2CPCIDeviceDetector device_detector_obj_##ven##dev##subven##subdev##addr##func(name, func, ven, dev, subven, subdev, addr) -#define REGISTER_DYNAMIC_I2C_BUS_DETECTOR(func) I2CBusDetector device_detector_obj_##func(func) -#define REGISTER_DYNAMIC_HID_DETECTOR(name, func, vid, pid) HIDDeviceDetector device_detector_obj_##vid##pid(name, func, vid, pid, HID_INTERFACE_ANY, HID_USAGE_PAGE_ANY, HID_USAGE_ANY) -#define REGISTER_DYNAMIC_HID_DETECTOR_I(name, func, vid, pid, interface) HIDDeviceDetector device_detector_obj_##vid##pid##_##interface(name, func, vid, pid, interface, HID_USAGE_PAGE_ANY, HID_USAGE_ANY) -#define REGISTER_DYNAMIC_HID_DETECTOR_IP(name, func, vid, pid, interface, page) HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page(name, func, vid, pid, interface, page, HID_USAGE_ANY) -#define REGISTER_DYNAMIC_HID_DETECTOR_IPU(name, func, vid, pid, interface, page, usage) HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page##_##usage(name, func, vid, pid, interface, page, usage) -#define REGISTER_DYNAMIC_HID_DETECTOR_P(name, func, vid, pid, page) HIDDeviceDetector device_detector_obj_##vid##pid##__##page(name, func, vid, pid, HID_INTERFACE_ANY, page, HID_USAGE_ANY) -#define REGISTER_DYNAMIC_HID_DETECTOR_PU(name, func, vid, pid, page, usage) HIDDeviceDetector device_detector_obj_##vid##pid##__##page##_##usage(name, func, vid, pid, HID_INTERFACE_ANY, page, usage) +#define REGISTER_DYNAMIC_I2C_DETECTOR(name, func) \ + I2CDeviceDetector device_detector_obj_##func(name, func) +#define REGISTER_DYNAMIC_I2C_DIMM_DETECTOR(name, func, jedec_id, dimm_type) \ + I2CDIMMDeviceDetector device_detector_obj_##func(name, func, jedec_id, dimm_type) +#define REGISTER_DYNAMIC_I2C_PCI_DETECTOR(name, func, ven, dev, subven, subdev, addr) \ + I2CPCIDeviceDetector device_detector_obj_##ven##dev##subven##subdev##addr##func(name, \ + func, \ + ven, \ + dev, \ + subven, \ + subdev, \ + addr) +#define REGISTER_DYNAMIC_I2C_BUS_DETECTOR(func) I2CBusDetector device_detector_obj_##func(func) +#define REGISTER_DYNAMIC_HID_DETECTOR(name, func, vid, pid) \ + HIDDeviceDetector device_detector_obj_##vid##pid(name, \ + func, \ + vid, \ + pid, \ + HID_INTERFACE_ANY, \ + HID_USAGE_PAGE_ANY, \ + HID_USAGE_ANY) +#define REGISTER_DYNAMIC_HID_DETECTOR_I(name, func, vid, pid, interface) \ + HIDDeviceDetector device_detector_obj_##vid##pid##_##interface(name, \ + func, \ + vid, \ + pid, \ + interface, \ + HID_USAGE_PAGE_ANY, \ + HID_USAGE_ANY) +#define REGISTER_DYNAMIC_HID_DETECTOR_IP(name, func, vid, pid, interface, page) \ + HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page(name, \ + func, \ + vid, \ + pid, \ + interface, \ + page, \ + HID_USAGE_ANY) +#define REGISTER_DYNAMIC_HID_DETECTOR_IPU(name, func, vid, pid, interface, page, usage) \ + HIDDeviceDetector device_detector_obj_##vid##pid##_##interface##_##page##_##usage(name, \ + func, \ + vid, \ + pid, \ + interface, \ + page, \ + usage) +#define REGISTER_DYNAMIC_HID_DETECTOR_P(name, func, vid, pid, page) \ + HIDDeviceDetector device_detector_obj_##vid##pid##__##page(name, \ + func, \ + vid, \ + pid, \ + HID_INTERFACE_ANY, \ + page, \ + HID_USAGE_ANY) +#define REGISTER_DYNAMIC_HID_DETECTOR_PU(name, func, vid, pid, page, usage) \ + HIDDeviceDetector device_detector_obj_##vid##pid##__##page##_##usage(name, \ + func, \ + vid, \ + pid, \ + HID_INTERFACE_ANY, \ + page, \ + usage) diff --git a/DeviceDetector.h b/DeviceDetector.h index 66d3bdac9..445c83bb5 100644 --- a/DeviceDetector.h +++ b/DeviceDetector.h @@ -19,35 +19,50 @@ class DeviceDetector { public: DeviceDetector(std::string name, DeviceDetectorFunction detector) - { + { ResourceManager::get()->RegisterDeviceDetector(name, detector); - } + } }; class I2CDeviceDetector { public: I2CDeviceDetector(std::string name, I2CDeviceDetectorFunction detector) - { + { ResourceManager::get()->RegisterI2CDeviceDetector(name, detector); - } + } }; class I2CDIMMDeviceDetector { public: - I2CDIMMDeviceDetector(std::string name, I2CDIMMDeviceDetectorFunction detector, uint16_t jedec_id, uint8_t dimm_type) - { + I2CDIMMDeviceDetector(std::string name, + I2CDIMMDeviceDetectorFunction detector, + uint16_t jedec_id, + uint8_t dimm_type) + { ResourceManager::get()->RegisterI2CDIMMDeviceDetector(name, detector, jedec_id, dimm_type); - } + } }; class I2CPCIDeviceDetector { public: - I2CPCIDeviceDetector(std::string name, I2CPCIDeviceDetectorFunction detector, uint16_t ven_id, uint16_t dev_id, uint16_t subven_id, uint16_t subdev_id, uint8_t i2c_addr) + I2CPCIDeviceDetector(std::string name, + I2CPCIDeviceDetectorFunction detector, + uint16_t ven_id, + uint16_t dev_id, + uint16_t subven_id, + uint16_t subdev_id, + uint8_t i2c_addr) { - ResourceManager::get()->RegisterI2CPCIDeviceDetector(name, detector, ven_id, dev_id, subven_id, subdev_id, i2c_addr); + ResourceManager::get()->RegisterI2CPCIDeviceDetector(name, + detector, + ven_id, + dev_id, + subven_id, + subdev_id, + i2c_addr); } }; @@ -63,18 +78,37 @@ public: class HIDDeviceDetector { public: - HIDDeviceDetector(std::string name, HIDDeviceDetectorFunction detector, uint16_t vid, uint16_t pid, int interface, int usage_page, int usage) + HIDDeviceDetector(std::string name, + HIDDeviceDetectorFunction detector, + uint16_t vid, + uint16_t pid, + int interface, + int usage_page, + int usage) { - ResourceManager::get()->RegisterHIDDeviceDetector(name, detector, vid, pid, interface, usage_page, usage); + ResourceManager::get() + ->RegisterHIDDeviceDetector(name, detector, vid, pid, interface, usage_page, usage); } }; class HIDWrappedDeviceDetector { public: - HIDWrappedDeviceDetector(std::string name, HIDWrappedDeviceDetectorFunction detector, uint16_t vid, uint16_t pid, int interface, int usage_page, int usage) + HIDWrappedDeviceDetector(std::string name, + HIDWrappedDeviceDetectorFunction detector, + uint16_t vid, + uint16_t pid, + int interface, + int usage_page, + int usage) { - ResourceManager::get()->RegisterHIDWrappedDeviceDetector(name, detector, vid, pid, interface, usage_page, usage); + ResourceManager::get()->RegisterHIDWrappedDeviceDetector(name, + detector, + vid, + pid, + interface, + usage_page, + usage); } }; diff --git a/LogManager.cpp b/LogManager.cpp index 220a0d9a3..908481bcc 100644 --- a/LogManager.cpp +++ b/LogManager.cpp @@ -17,10 +17,11 @@ #include "filesystem.h" -const char* LogManager::log_codes[] = {"FATAL:", "ERROR:", "Warning:", "Info:", "Verbose:", "Debug:", "Trace:", "Dialog:"}; +const char *LogManager::log_codes[] + = {"FATAL:", "ERROR:", "Warning:", "Info:", "Verbose:", "Debug:", "Trace:", "Dialog:"}; -const char* TimestampPattern = "%04d%02d%02d_%02d%02d%02d"; -const char* TimestampRegex = "[0-9]{8}_[0-9]{6}"; // relies on the structure of the template above +const char *TimestampPattern = "%04d%02d%02d_%02d%02d%02d"; +const char *TimestampRegex = "[0-9]{8}_[0-9]{6}"; // relies on the structure of the template above LogManager::LogManager() { @@ -29,44 +30,39 @@ LogManager::LogManager() log_file_enabled = true; } -LogManager* LogManager::get() +LogManager *LogManager::get() { - static LogManager* _instance = nullptr; + static LogManager *_instance = nullptr; static std::mutex instance_mutex; std::lock_guard grd(instance_mutex); /*-------------------------------------------------*\ | Create a new instance if one does not exist | \*-------------------------------------------------*/ - if(!_instance) - { + if (!_instance) { _instance = new LogManager(); } - + return _instance; } unsigned int LogManager::getLoglevel() { - if(log_console_enabled) - { - return(LL_TRACE); - } - else - { - return(loglevel); + if (log_console_enabled) { + return (LL_TRACE); + } else { + return (loglevel); } } -void LogManager::configure(json config, const filesystem::path& defaultDir) +void LogManager::configure(json config, const filesystem::path &defaultDir) { std::lock_guard grd(entry_mutex); /*-------------------------------------------------*\ | If the log is not open, create a new log file | \*-------------------------------------------------*/ - if(!log_stream.is_open()) - { + if (!log_stream.is_open()) { /*----------------------------------------------------*\ | If a limit is declared in the config for the maximum | | number of log files, respect the limit | @@ -77,13 +73,11 @@ void LogManager::configure(json config, const filesystem::path& defaultDir) | 0 or less equals no limit (default) | \*----------------------------------------------------*/ int loglimit = 0; - if(config.contains("file_count_limit") && config["file_count_limit"].is_number_integer()) - { + if (config.contains("file_count_limit") && config["file_count_limit"].is_number_integer()) { loglimit = config["file_count_limit"]; } - if(config.contains("log_file")) - { + if (config.contains("log_file")) { log_file_enabled = config["log_file"]; } @@ -93,21 +87,16 @@ void LogManager::configure(json config, const filesystem::path& defaultDir) \*-----------------------------------------*/ std::string logtempl = "OpenRGB_#.log"; - if(log_file_enabled) - { - + if (log_file_enabled) { /*-------------------------------------------------*\ | If the logfile is defined in the configuration, | | use the configured name | \*-------------------------------------------------*/ - if(config.contains("logfile")) - { - const json& logfile_obj = config["logfile"]; - if(logfile_obj.is_string()) - { + if (config.contains("logfile")) { + const json &logfile_obj = config["logfile"]; + if (logfile_obj.is_string()) { std::string tmpname = config["logfile"]; - if(!tmpname.empty()) - { + if (!tmpname.empty()) { logtempl = tmpname; } } @@ -117,14 +106,21 @@ void LogManager::configure(json config, const filesystem::path& defaultDir) | replace it with a timestamp | \*-------------------------------------------------*/ time_t t = time(0); - struct tm* tmp = localtime(&t); + struct tm *tmp = localtime(&t); char time_string[64]; - snprintf(time_string, 64, TimestampPattern, 1900 + tmp->tm_year, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec); + snprintf(time_string, + 64, + TimestampPattern, + 1900 + tmp->tm_year, + tmp->tm_mon + 1, + tmp->tm_mday, + tmp->tm_hour, + tmp->tm_min, + tmp->tm_sec); std::string logname = logtempl; size_t oct = logname.find("#"); - if(oct != logname.npos) - { + if (oct != logname.npos) { logname.replace(oct, 1, time_string); } @@ -132,8 +128,7 @@ void LogManager::configure(json config, const filesystem::path& defaultDir) | If the path is relative, use logs dir | \*-------------------------------------------------*/ filesystem::path p = filesystem::u8path(logname); - if(p.is_relative()) - { + if (p.is_relative()) { p = defaultDir / "logs" / logname; } filesystem::create_directories(p.parent_path()); @@ -153,9 +148,12 @@ void LogManager::configure(json config, const filesystem::path& defaultDir) | Print Git Commit info, version, etc. | \*-------------------------------------------------*/ log_stream << " OpenRGB v" << VERSION_STRING << std::endl; - log_stream << " Commit: " << GIT_COMMIT_ID << " from " << GIT_COMMIT_DATE << std::endl; + log_stream << " Commit: " << GIT_COMMIT_ID << " from " << GIT_COMMIT_DATE + << std::endl; log_stream << " Launched: " << time_string << std::endl; - log_stream << "====================================================================================================" << std::endl; + log_stream << "========================================================================" + "============================" + << std::endl; log_stream << std::endl; } } @@ -163,15 +161,13 @@ void LogManager::configure(json config, const filesystem::path& defaultDir) /*-------------------------------------------------*\ | Check loglevel configuration | \*-------------------------------------------------*/ - if(config.contains("loglevel")) - { - const json& loglevel_obj = config["loglevel"]; + if (config.contains("loglevel")) { + const json &loglevel_obj = config["loglevel"]; /*-------------------------------------------------*\ | Set the log level if configured | \*-------------------------------------------------*/ - if(loglevel_obj.is_number_integer()) - { + if (loglevel_obj.is_number_integer()) { loglevel = loglevel_obj; } } @@ -179,8 +175,7 @@ void LogManager::configure(json config, const filesystem::path& defaultDir) /*-------------------------------------------------*\ | Check log console configuration | \*-------------------------------------------------*/ - if(config.contains("log_console")) - { + if (config.contains("log_console")) { log_console_enabled = config["log_console"]; } @@ -195,23 +190,22 @@ void LogManager::_flush() /*-------------------------------------------------*\ | If the log is open, write out buffered messages | \*-------------------------------------------------*/ - if(log_stream.is_open()) - { - for(size_t msg = 0; msg < temp_messages.size(); ++msg) - { - if(temp_messages[msg]->level <= loglevel || temp_messages[msg]->level == LL_DIALOG) - { + if (log_stream.is_open()) { + for (size_t msg = 0; msg < temp_messages.size(); ++msg) { + if (temp_messages[msg]->level <= loglevel || temp_messages[msg]->level == LL_DIALOG) { // Put the timestamp here - std::chrono::milliseconds counter = std::chrono::duration_cast(temp_messages[msg]->counted_second); - log_stream << std::left << std::setw(6) << counter.count() << "|"; + std::chrono::milliseconds counter + = std::chrono::duration_cast( + temp_messages[msg]->counted_second); + log_stream << std::left << std::setw(6) << counter.count() << "|"; log_stream << std::left << std::setw(9) << log_codes[temp_messages[msg]->level]; log_stream << temp_messages[msg]->buffer; - - if(print_source) - { - log_stream << " [" << temp_messages[msg]->filename << ":" << temp_messages[msg]->line << "]"; + + if (print_source) { + log_stream << " [" << temp_messages[msg]->filename << ":" + << temp_messages[msg]->line << "]"; } - + log_stream << std::endl; } } @@ -234,14 +228,14 @@ void LogManager::flush() _flush(); } -void LogManager::_append(const char* filename, int line, unsigned int level, const char* fmt, va_list va) +void LogManager::_append( + const char *filename, int line, unsigned int level, const char *fmt, va_list va) { /*-------------------------------------------------*\ | If a critical message occurs, enable source | | printing and set loglevel and verbosity to highest| \*-------------------------------------------------*/ - if(level == LL_FATAL) - { + if (level == LL_FATAL) { print_source = true; loglevel = LL_DEBUG; verbosity = LL_DEBUG; @@ -265,19 +259,17 @@ void LogManager::_append(const char* filename, int line, unsigned int level, con /*-------------------------------------------------*\ | Fill in message information | \*-------------------------------------------------*/ - mes->level = level; - mes->filename = filename; - mes->line = line; + mes->level = level; + mes->filename = filename; + mes->line = line; mes->counted_second = std::chrono::steady_clock::now() - base_clock; /*-------------------------------------------------*\ | If this is a dialog message, call the dialog show | | callback | \*-------------------------------------------------*/ - if(level == LL_DIALOG) - { - for(size_t idx = 0; idx < dialog_show_callbacks.size(); idx++) - { + if (level == LL_DIALOG) { + for (size_t idx = 0; idx < dialog_show_callbacks.size(); idx++) { dialog_show_callbacks[idx](dialog_show_callback_args[idx], mes); } } @@ -287,11 +279,9 @@ void LogManager::_append(const char* filename, int line, unsigned int level, con | print it on the screen | | TODO: Put the timestamp here | \*-------------------------------------------------*/ - if(level <= verbosity || level == LL_DIALOG) - { + if (level <= verbosity || level == LL_DIALOG) { std::cout << mes->buffer; - if(print_source) - { + if (print_source) { std::cout << " [" << mes->filename << ":" << mes->line << "]"; } std::cout << std::endl; @@ -302,8 +292,7 @@ void LogManager::_append(const char* filename, int line, unsigned int level, con \*-------------------------------------------------*/ temp_messages.push_back(mes); - if(log_console_enabled) - { + if (log_console_enabled) { all_messages.push_back(mes); } @@ -323,7 +312,7 @@ void LogManager::clearMessages() all_messages.clear(); } -void LogManager::append(const char* filename, int line, unsigned int level, const char* fmt, ...) +void LogManager::append(const char *filename, int line, unsigned int level, const char *fmt, ...) { va_list va; va_start(va, fmt); @@ -340,8 +329,7 @@ void LogManager::setLoglevel(unsigned int level) | Check that the new log level is valid, otherwise | | set it within the valid range | \*-------------------------------------------------*/ - if(level > LL_TRACE) - { + if (level > LL_TRACE) { level = LL_TRACE; } @@ -360,8 +348,7 @@ void LogManager::setVerbosity(unsigned int level) | set it within the valid range | \*-------------------------------------------------*/ - if(level > LL_TRACE) - { + if (level > LL_TRACE) { level = LL_TRACE; } @@ -379,29 +366,28 @@ void LogManager::setPrintSource(bool v) print_source = v; } -void LogManager::RegisterDialogShowCallback(LogDialogShowCallback callback, void* receiver) +void LogManager::RegisterDialogShowCallback(LogDialogShowCallback callback, void *receiver) { LOG_DEBUG("[LogManager] dialog show callback registered"); dialog_show_callbacks.push_back(callback); dialog_show_callback_args.push_back(receiver); } -void LogManager::UnregisterDialogShowCallback(LogDialogShowCallback callback, void* receiver) +void LogManager::UnregisterDialogShowCallback(LogDialogShowCallback callback, void *receiver) { - for(size_t idx = 0; idx < dialog_show_callbacks.size(); idx++) - { - if(dialog_show_callbacks[idx] == callback && dialog_show_callback_args[idx] == receiver) - { + for (size_t idx = 0; idx < dialog_show_callbacks.size(); idx++) { + if (dialog_show_callbacks[idx] == callback && dialog_show_callback_args[idx] == receiver) { dialog_show_callbacks.erase(dialog_show_callbacks.begin() + idx); dialog_show_callback_args.erase(dialog_show_callback_args.begin() + idx); } } } -void LogManager::rotate_logs(const filesystem::path& folder, const filesystem::path& templ, int max_count) +void LogManager::rotate_logs(const filesystem::path &folder, + const filesystem::path &templ, + int max_count) { - if(max_count < 1) - { + if (max_count < 1) { return; } @@ -411,10 +397,8 @@ void LogManager::rotate_logs(const filesystem::path& folder, const filesystem::p // The # symbol is replaced with a timestamp regex // Any regex-unfriendly symbols are escaped with a backslash std::string regex_templ = "^"; - for(size_t i = 0; i < templ2.size(); ++i) - { - switch(templ2[i]) - { + for (size_t i = 0; i < templ2.size(); ++i) { + switch (templ2[i]) { // Symbols that have special meanings in regex'es need backslash escaping case '.': case '^': @@ -449,35 +433,35 @@ void LogManager::rotate_logs(const filesystem::path& folder, const filesystem::p std::vector valid_paths; std::filesystem::directory_iterator it(folder); - for(; it != filesystem::end(it); ++it) - { - if(it->is_regular_file()) - { + for (; it != filesystem::end(it); ++it) { + if (it->is_regular_file()) { std::string fname = it->path().filename().u8string(); - if(std::regex_match(fname, r)) - { + if (std::regex_match(fname, r)) { valid_paths.push_back(it->path()); } } } std::sort(valid_paths.begin(), valid_paths.end()); - size_t remove_count = valid_paths.size() - max_count + 1; // NOTE: the "1" extra file to remove creates space for the one we're about to create - if(remove_count > valid_paths.size()) // for max_count <= 0 and to prevent any possible errors in the above logic + size_t remove_count + = valid_paths.size() - max_count + + 1; // NOTE: the "1" extra file to remove creates space for the one we're about to create + if (remove_count + > valid_paths + .size()) // for max_count <= 0 and to prevent any possible errors in the above logic { remove_count = valid_paths.size(); } - for(size_t i = 0; i < remove_count; ++i) - { + for (size_t i = 0; i < remove_count; ++i) { std::error_code ec; // Uses error code to force the `remove` call to be `noexcept` - if(filesystem::remove(valid_paths[i], ec)) - { - LOG_VERBOSE("[LogManager] Removed log file [%s] during rotation", valid_paths[i].u8string().c_str()); - } - else - { - LOG_WARNING("[LogManager] Failed to remove log file [%s] during rotation: %s", valid_paths[i].u8string().c_str(), ec.message().c_str()); + if (filesystem::remove(valid_paths[i], ec)) { + LOG_VERBOSE("[LogManager] Removed log file [%s] during rotation", + valid_paths[i].u8string().c_str()); + } else { + LOG_WARNING("[LogManager] Failed to remove log file [%s] during rotation: %s", + valid_paths[i].u8string().c_str(), + ec.message().c_str()); } } } diff --git a/LogManager.h b/LogManager.h index f099a6c58..a94b83325 100644 --- a/LogManager.h +++ b/LogManager.h @@ -22,50 +22,54 @@ | Common LOG strings | | This may need to be in it's own .h file | \*-------------------------------------------------*/ -#define SMBUS_CHECK_DEVICE_MESSAGE_EN "[%s] Bus %02d is a motherboard and the subvendor matches the one for %s, looking for a device at 0x%02X" -#define SMBUS_CHECK_DEVICE_FAILURE_EN "[%s] Bus %02d is not a motherboard or the subvendor does not match the one for %s, skipping detection" +#define SMBUS_CHECK_DEVICE_MESSAGE_EN \ + "[%s] Bus %02d is a motherboard and the subvendor matches the one for %s, looking for a " \ + "device at 0x%02X" +#define SMBUS_CHECK_DEVICE_FAILURE_EN \ + "[%s] Bus %02d is not a motherboard or the subvendor does not match the one for %s, skipping " \ + "detection" -#define GPU_DETECT_MESSAGE "[%s] Found a device match at Bus %02d for Device 0x%04X and SubDevice 0x%04X: %s" +#define GPU_DETECT_MESSAGE \ + "[%s] Found a device match at Bus %02d for Device 0x%04X and SubDevice 0x%04X: %s" using json = nlohmann::json; -enum -{ - LL_FATAL, // Critical unrecoverable errors that cause a generalized crash of a module or of the entire app - LL_ERROR, // Local errors that abort an operation - LL_WARNING, // Local errors that may cause an operation to have an undefined behavior or may have dangerous/unforeseen consequences - LL_INFO, // Initialization messages, significant actions and follow-up information - LL_VERBOSE, // Tracing of commands and performed actions, usually for debug purposes, comments on the higher priority messages - LL_DEBUG, // Deep tracing, "printf-style debugging" alternative, for debug purposes. Such messages should be put all over the code instead of comments +enum { + LL_FATAL, // Critical unrecoverable errors that cause a generalized crash of a module or of the entire app + LL_ERROR, // Local errors that abort an operation + LL_WARNING, // Local errors that may cause an operation to have an undefined behavior or may have dangerous/unforeseen consequences + LL_INFO, // Initialization messages, significant actions and follow-up information + LL_VERBOSE, // Tracing of commands and performed actions, usually for debug purposes, comments on the higher priority messages + LL_DEBUG, // Deep tracing, "printf-style debugging" alternative, for debug purposes. Such messages should be put all over the code instead of comments LL_TRACE, - LL_DIALOG // Log messages to be shown in a GUI dialog box + LL_DIALOG // Log messages to be shown in a GUI dialog box }; struct LogMessage { std::string buffer; unsigned int level; - const char* filename; + const char *filename; int line; std::chrono::duration counted_second; // int timestamp or float time_offset? TBD }; typedef std::shared_ptr PLogMessage; -typedef void(*LogDialogShowCallback)(void*, PLogMessage); +typedef void (*LogDialogShowCallback)(void *, PLogMessage); class LogManager { private: LogManager(); - LogManager(const LogManager&) = delete; - LogManager(LogManager&&) = delete; + LogManager(const LogManager &) = delete; + LogManager(LogManager &&) = delete; ~LogManager(); std::recursive_mutex entry_mutex; std::mutex section_mutex; std::ofstream log_stream; - std::vector dialog_show_callbacks; - std::vector dialog_show_callback_args; + std::vector dialog_show_callbacks; + std::vector dialog_show_callback_args; // A temporary log message storage to hold them until the stream opens std::vector temp_messages; @@ -86,41 +90,41 @@ private: std::chrono::time_point base_clock; // A non-guarded append() - void _append(const char* filename, int line, unsigned int level, const char* fmt, va_list va); + void _append(const char *filename, int line, unsigned int level, const char *fmt, va_list va); // A non-guarded flush() void _flush(); - void rotate_logs(const filesystem::path& folder, const filesystem::path& templ, int max_count); + void rotate_logs(const filesystem::path &folder, const filesystem::path &templ, int max_count); public: - static LogManager* get(); - void configure(json config, const filesystem::path & defaultDir); + static LogManager *get(); + void configure(json config, const filesystem::path &defaultDir); void flush(); - void append(const char* filename, int line, unsigned int level, const char* fmt, ...); + void append(const char *filename, int line, unsigned int level, const char *fmt, ...); void setLoglevel(unsigned int); void setVerbosity(unsigned int); void setPrintSource(bool); - void RegisterDialogShowCallback(LogDialogShowCallback callback, void* receiver); - void UnregisterDialogShowCallback(LogDialogShowCallback callback, void* receiver); + void RegisterDialogShowCallback(LogDialogShowCallback callback, void *receiver); + void UnregisterDialogShowCallback(LogDialogShowCallback callback, void *receiver); unsigned int getLoglevel(); - unsigned int getVerbosity() {return verbosity;} + unsigned int getVerbosity() { return verbosity; } void clearMessages(); std::vector messages(); bool log_console_enabled; bool log_file_enabled; - static const char* log_codes[]; + static const char *log_codes[]; }; -#define LogAppend(level, ...) LogManager::get()->append(__FILE__, __LINE__, level, __VA_ARGS__) -#define LOG_FATAL(...) LogAppend(LL_FATAL, __VA_ARGS__) -#define LOG_ERROR(...) LogAppend(LL_ERROR, __VA_ARGS__) -#define LOG_WARNING(...) LogAppend(LL_WARNING, __VA_ARGS__) -#define LOG_INFO(...) LogAppend(LL_INFO, __VA_ARGS__) -#define LOG_VERBOSE(...) LogAppend(LL_VERBOSE, __VA_ARGS__) -#define LOG_DEBUG(...) LogAppend(LL_DEBUG, __VA_ARGS__) -#define LOG_TRACE(...) LogAppend(LL_TRACE, __VA_ARGS__) -#define LOG_DIALOG(...) LogAppend(LL_DIALOG, __VA_ARGS__) +#define LogAppend(level, ...) LogManager::get()->append(__FILE__, __LINE__, level, __VA_ARGS__) +#define LOG_FATAL(...) LogAppend(LL_FATAL, __VA_ARGS__) +#define LOG_ERROR(...) LogAppend(LL_ERROR, __VA_ARGS__) +#define LOG_WARNING(...) LogAppend(LL_WARNING, __VA_ARGS__) +#define LOG_INFO(...) LogAppend(LL_INFO, __VA_ARGS__) +#define LOG_VERBOSE(...) LogAppend(LL_VERBOSE, __VA_ARGS__) +#define LOG_DEBUG(...) LogAppend(LL_DEBUG, __VA_ARGS__) +#define LOG_TRACE(...) LogAppend(LL_TRACE, __VA_ARGS__) +#define LOG_DIALOG(...) LogAppend(LL_DIALOG, __VA_ARGS__) #endif // LOGMANAGER_H diff --git a/NetworkClient.cpp b/NetworkClient.cpp index 9ea9a3b30..c0f46018b 100644 --- a/NetworkClient.cpp +++ b/NetworkClient.cpp @@ -29,17 +29,18 @@ using namespace std::chrono_literals; -NetworkClient::NetworkClient(std::vector& control) : controllers(control) +NetworkClient::NetworkClient(std::vector &control) + : controllers(control) { - port_ip = "127.0.0.1"; - port_num = OPENRGB_SDK_PORT; - client_sock = -1; - server_connected = false; + port_ip = "127.0.0.1"; + port_num = OPENRGB_SDK_PORT; + client_sock = -1; + server_connected = false; server_controller_count = 0; - change_in_progress = false; + change_in_progress = false; - ListenThread = NULL; - ConnectionThread = NULL; + ListenThread = NULL; + ConnectionThread = NULL; } NetworkClient::~NetworkClient() @@ -61,8 +62,8 @@ void NetworkClient::ClientInfoChanged() /*---------------------------------------------------------*\ | Client info has changed, call the callbacks | \*---------------------------------------------------------*/ - for(unsigned int callback_idx = 0; callback_idx < ClientInfoChangeCallbacks.size(); callback_idx++) - { + for (unsigned int callback_idx = 0; callback_idx < ClientInfoChangeCallbacks.size(); + callback_idx++) { ClientInfoChangeCallbacks[callback_idx](ClientInfoChangeCallbackArgs[callback_idx]); } @@ -84,29 +85,27 @@ unsigned int NetworkClient::GetProtocolVersion() { unsigned int protocol_version = 0; - if(server_protocol_version > OPENRGB_SDK_PROTOCOL_VERSION) - { + if (server_protocol_version > OPENRGB_SDK_PROTOCOL_VERSION) { protocol_version = OPENRGB_SDK_PROTOCOL_VERSION; - } - else - { + } else { protocol_version = server_protocol_version; } - return(protocol_version); + return (protocol_version); } bool NetworkClient::GetConnected() { - return(server_connected); + return (server_connected); } bool NetworkClient::GetOnline() { - return(server_connected && server_initialized); + return (server_connected && server_initialized); } -void NetworkClient::RegisterClientInfoChangeCallback(NetClientCallback new_callback, void * new_callback_arg) +void NetworkClient::RegisterClientInfoChangeCallback(NetClientCallback new_callback, + void *new_callback_arg) { ClientInfoChangeCallbacks.push_back(new_callback); ClientInfoChangeCallbackArgs.push_back(new_callback_arg); @@ -114,8 +113,7 @@ void NetworkClient::RegisterClientInfoChangeCallback(NetClientCallback new_callb void NetworkClient::SetIP(std::string new_ip) { - if(server_connected == false) - { + if (server_connected == false) { port_ip = new_ip; } } @@ -124,16 +122,14 @@ void NetworkClient::SetName(std::string new_name) { client_name = new_name; - if(server_connected == true) - { + if (server_connected == true) { SendData_ClientString(); } } void NetworkClient::SetPort(unsigned short new_port) { - if(server_connected == false) - { + if (server_connected == false) { port_num = new_port; } } @@ -167,25 +163,23 @@ void NetworkClient::StopClient() | Disconnect the server and set it as inactive | \*---------------------------------------------------------*/ server_connected = false; - client_active = false; + client_active = false; /*---------------------------------------------------------*\ | Shut down and close the client socket | \*---------------------------------------------------------*/ - if(server_connected) - { + if (server_connected) { shutdown(client_sock, SD_RECEIVE); closesocket(client_sock); } - client_active = false; + client_active = false; server_connected = false; /*---------------------------------------------------------*\ | Close the listen thread | \*---------------------------------------------------------*/ - if(ListenThread) - { + if (ListenThread) { ListenThread->join(); delete ListenThread; ListenThread = nullptr; @@ -194,8 +188,7 @@ void NetworkClient::StopClient() /*---------------------------------------------------------*\ | Close the connection thread | \*---------------------------------------------------------*/ - if(ConnectionThread) - { + if (ConnectionThread) { connection_cv.notify_all(); ConnectionThread->join(); delete ConnectionThread; @@ -217,10 +210,8 @@ void NetworkClient::ConnectionThreadFunction() /*---------------------------------------------------------*\ | This thread manages the connection to the server | \*---------------------------------------------------------*/ - while(client_active == true) - { - if(server_connected == false) - { + while (client_active == true) { + if (server_connected == false) { /*---------------------------------------------------------*\ | Connect to server and reconnect if the connection is lost | \*---------------------------------------------------------*/ @@ -229,10 +220,9 @@ void NetworkClient::ConnectionThreadFunction() /*---------------------------------------------------------*\ | Try to connect to server | \*---------------------------------------------------------*/ - if(port.tcp_client_connect() == true) - { + if (port.tcp_client_connect() == true) { client_sock = port.sock; - printf( "Connected to server\n" ); + printf("Connected to server\n"); /*---------------------------------------------------------*\ | Server is now connected | @@ -253,21 +243,18 @@ void NetworkClient::ConnectionThreadFunction() | Client info has changed, call the callbacks | \*---------------------------------------------------------*/ ClientInfoChanged(); - } - else - { - printf( "Connection attempt failed\n" ); + } else { + printf("Connection attempt failed\n"); } } /*-------------------------------------------------------------*\ | Double-check client_active as it could have changed | \*-------------------------------------------------------------*/ - if(client_active && server_initialized == false && server_connected == true) - { - unsigned int timeout_counter = 0; - requested_controllers = 0; - server_controller_count = 0; + if (client_active && server_initialized == false && server_connected == true) { + unsigned int timeout_counter = 0; + requested_controllers = 0; + server_controller_count = 0; server_controller_count_received = false; server_protocol_version_received = false; @@ -275,8 +262,7 @@ void NetworkClient::ConnectionThreadFunction() | Wait for server to connect | \*---------------------------------------------------------*/ connection_cv.wait_for(lock, 100ms); - if(!client_active) - { + if (!client_active) { break; } @@ -288,11 +274,9 @@ void NetworkClient::ConnectionThreadFunction() /*---------------------------------------------------------*\ | Wait up to 1s for protocol version reply | \*---------------------------------------------------------*/ - while(!server_protocol_version_received) - { + while (!server_protocol_version_received) { connection_cv.wait_for(lock, 5ms); - if(!client_active) - { + if (!client_active) { break; } @@ -303,9 +287,8 @@ void NetworkClient::ConnectionThreadFunction() | server doesn't support protocol versioning and use | | protocol version 0 | \*---------------------------------------------------------*/ - if(timeout_counter > 200) - { - server_protocol_version = 0; + if (timeout_counter > 200) { + server_protocol_version = 0; server_protocol_version_received = true; } } @@ -323,11 +306,9 @@ void NetworkClient::ConnectionThreadFunction() /*---------------------------------------------------------*\ | Wait for server controller count | \*---------------------------------------------------------*/ - while(!server_controller_count_received) - { + while (!server_controller_count_received) { connection_cv.wait_for(lock, 5ms); - if(!client_active) - { + if (!client_active) { break; } } @@ -337,8 +318,7 @@ void NetworkClient::ConnectionThreadFunction() /*---------------------------------------------------------*\ | Once count is received, request controllers | \*---------------------------------------------------------*/ - while(requested_controllers < server_controller_count) - { + while (requested_controllers < server_controller_count) { printf("Client: Requesting controller %d\r\n", requested_controllers); controller_data_received = false; @@ -347,11 +327,9 @@ void NetworkClient::ConnectionThreadFunction() /*---------------------------------------------------------*\ | Wait until controller is received | \*---------------------------------------------------------*/ - while(controller_data_received == false) - { + while (controller_data_received == false) { connection_cv.wait_for(lock, 5ms); - if(!client_active) - { + if (!client_active) { break; } } @@ -365,8 +343,8 @@ void NetworkClient::ConnectionThreadFunction() | All controllers received, add them to master list | \*---------------------------------------------------------*/ printf("Client: All controllers received, adding them to master list\r\n"); - for(std::size_t controller_idx = 0; controller_idx < server_controllers.size(); controller_idx++) - { + for (std::size_t controller_idx = 0; controller_idx < server_controllers.size(); + controller_idx++) { controllers.push_back(server_controllers[controller_idx]); } @@ -389,32 +367,25 @@ void NetworkClient::ConnectionThreadFunction() int NetworkClient::recv_select(SOCKET s, char *buf, int len, int flags) { - fd_set set; - struct timeval timeout; + fd_set set; + struct timeval timeout; - while(1) - { - timeout.tv_sec = 5; - timeout.tv_usec = 0; + while (1) { + timeout.tv_sec = 5; + timeout.tv_usec = 0; FD_ZERO(&set); FD_SET(s, &set); - int rv = select((int)s + 1, &set, NULL, NULL, &timeout); + int rv = select((int) s + 1, &set, NULL, NULL, &timeout); - if(rv == SOCKET_ERROR || server_connected == false) - { + if (rv == SOCKET_ERROR || server_connected == false) { return 0; - } - else if(rv == 0) - { + } else if (rv == 0) { continue; + } else { + return (recv(s, buf, len, flags)); } - else - { - return(recv(s, buf, len, flags)); - } - } } @@ -425,29 +396,25 @@ void NetworkClient::ListenThreadFunction() /*---------------------------------------------------------*\ | This thread handles messages received from the server | \*---------------------------------------------------------*/ - while(server_connected == true) - { + while (server_connected == true) { NetPacketHeader header; - int bytes_read = 0; - char * data = NULL; + int bytes_read = 0; + char *data = NULL; - for(unsigned int i = 0; i < 4; i++) - { + for (unsigned int i = 0; i < 4; i++) { /*---------------------------------------------------------*\ | Read byte of magic | \*---------------------------------------------------------*/ bytes_read = recv_select(client_sock, &header.pkt_magic[i], 1, 0); - if(bytes_read <= 0) - { + if (bytes_read <= 0) { goto listen_done; } /*---------------------------------------------------------*\ | Test characters of magic "ORGB" | \*---------------------------------------------------------*/ - if(header.pkt_magic[i] != openrgb_sdk_magic[i]) - { + if (header.pkt_magic[i] != openrgb_sdk_magic[i]) { continue; } } @@ -457,84 +424,82 @@ void NetworkClient::ListenThreadFunction() | rest of the header | \*---------------------------------------------------------*/ bytes_read = 0; - do - { + do { int tmp_bytes_read = 0; - tmp_bytes_read = recv_select(client_sock, (char *)&header.pkt_dev_idx + bytes_read, sizeof(header) - sizeof(header.pkt_magic) - bytes_read, 0); + tmp_bytes_read = recv_select(client_sock, + (char *) &header.pkt_dev_idx + bytes_read, + sizeof(header) - sizeof(header.pkt_magic) - bytes_read, + 0); bytes_read += tmp_bytes_read; - if(tmp_bytes_read <= 0) - { + if (tmp_bytes_read <= 0) { goto listen_done; } - } while(bytes_read != sizeof(header) - sizeof(header.pkt_magic)); + } while (bytes_read != sizeof(header) - sizeof(header.pkt_magic)); /*---------------------------------------------------------*\ | Header received, now receive the data | \*---------------------------------------------------------*/ - if(header.pkt_size > 0) - { + if (header.pkt_size > 0) { bytes_read = 0; data = new char[header.pkt_size]; - do - { + do { int tmp_bytes_read = 0; - tmp_bytes_read = recv_select(client_sock, &data[(unsigned int)bytes_read], header.pkt_size - bytes_read, 0); + tmp_bytes_read = recv_select(client_sock, + &data[(unsigned int) bytes_read], + header.pkt_size - bytes_read, + 0); - if(tmp_bytes_read <= 0) - { + if (tmp_bytes_read <= 0) { goto listen_done; } bytes_read += tmp_bytes_read; - } while ((unsigned int)bytes_read < header.pkt_size); + } while ((unsigned int) bytes_read < header.pkt_size); } /*---------------------------------------------------------*\ | Entire request received, select functionality based on | | request ID | \*---------------------------------------------------------*/ - switch(header.pkt_id) - { - case NET_PACKET_ID_REQUEST_CONTROLLER_COUNT: - ProcessReply_ControllerCount(header.pkt_size, data); - break; + switch (header.pkt_id) { + case NET_PACKET_ID_REQUEST_CONTROLLER_COUNT: + ProcessReply_ControllerCount(header.pkt_size, data); + break; - case NET_PACKET_ID_REQUEST_CONTROLLER_DATA: - ProcessReply_ControllerData(header.pkt_size, data, header.pkt_dev_idx); - break; + case NET_PACKET_ID_REQUEST_CONTROLLER_DATA: + ProcessReply_ControllerData(header.pkt_size, data, header.pkt_dev_idx); + break; - case NET_PACKET_ID_REQUEST_PROTOCOL_VERSION: - ProcessReply_ProtocolVersion(header.pkt_size, data); - break; + case NET_PACKET_ID_REQUEST_PROTOCOL_VERSION: + ProcessReply_ProtocolVersion(header.pkt_size, data); + break; - case NET_PACKET_ID_DEVICE_LIST_UPDATED: - ProcessRequest_DeviceListChanged(); - break; + case NET_PACKET_ID_DEVICE_LIST_UPDATED: + ProcessRequest_DeviceListChanged(); + break; } delete[] data; } listen_done: - printf( "Client socket has been closed"); + printf("Client socket has been closed"); server_initialized = false; server_connected = false; ControllerListMutex.lock(); - for(size_t server_controller_idx = 0; server_controller_idx < server_controllers.size(); server_controller_idx++) - { - for(size_t controller_idx = 0; controller_idx < controllers.size(); controller_idx++) - { - if(controllers[controller_idx] == server_controllers[server_controller_idx]) - { + for (size_t server_controller_idx = 0; server_controller_idx < server_controllers.size(); + server_controller_idx++) { + for (size_t controller_idx = 0; controller_idx < controllers.size(); controller_idx++) { + if (controllers[controller_idx] == server_controllers[server_controller_idx]) { controllers.erase(controllers.begin() + controller_idx); break; } @@ -545,8 +510,8 @@ listen_done: server_controllers.clear(); - for(size_t server_controller_idx = 0; server_controller_idx < server_controllers_copy.size(); server_controller_idx++) - { + for (size_t server_controller_idx = 0; server_controller_idx < server_controllers_copy.size(); + server_controller_idx++) { delete server_controllers_copy[server_controller_idx]; } @@ -560,10 +525,8 @@ listen_done: void NetworkClient::WaitOnControllerData() { - for(int i = 0; i < 1000; i++) - { - if(controller_data_received) - { + for (int i = 0; i < 1000; i++) { + if (controller_data_received) { break; } std::this_thread::sleep_for(1ms); @@ -572,26 +535,26 @@ void NetworkClient::WaitOnControllerData() return; } -void NetworkClient::ProcessReply_ControllerCount(unsigned int data_size, char * data) +void NetworkClient::ProcessReply_ControllerCount(unsigned int data_size, char *data) { - if(data_size == sizeof(unsigned int)) - { + if (data_size == sizeof(unsigned int)) { memcpy(&server_controller_count, data, sizeof(unsigned int)); server_controller_count_received = true; } } -void NetworkClient::ProcessReply_ControllerData(unsigned int data_size, char * data, unsigned int dev_idx) +void NetworkClient::ProcessReply_ControllerData(unsigned int data_size, + char *data, + unsigned int dev_idx) { /*---------------------------------------------------------*\ | Verify the controller description size (first 4 bytes of | | data) matches the packet size in the header | \*---------------------------------------------------------*/ - if(data_size == *((unsigned int*)data)) - { - RGBController_Network * new_controller = new RGBController_Network(this, dev_idx); + if (data_size == *((unsigned int *) data)) { + RGBController_Network *new_controller = new RGBController_Network(this, dev_idx); - new_controller->ReadDeviceDescription((unsigned char *)data, GetProtocolVersion()); + new_controller->ReadDeviceDescription((unsigned char *) data, GetProtocolVersion()); /*-----------------------------------------------------*\ | Mark this controller as remote owned | @@ -601,20 +564,17 @@ void NetworkClient::ProcessReply_ControllerData(unsigned int data_size, char * d ControllerListMutex.lock(); - if(dev_idx >= server_controllers.size()) - { + if (dev_idx >= server_controllers.size()) { server_controllers.push_back(new_controller); - } - else - { + } else { server_controllers[dev_idx]->active_mode = new_controller->active_mode; server_controllers[dev_idx]->leds.clear(); - server_controllers[dev_idx]->leds = new_controller->leds; + server_controllers[dev_idx]->leds = new_controller->leds; server_controllers[dev_idx]->colors.clear(); - server_controllers[dev_idx]->colors = new_controller->colors; - for(unsigned int i = 0; i < server_controllers[dev_idx]->zones.size(); i++) - { - server_controllers[dev_idx]->zones[i].leds_count = new_controller->zones[i].leds_count; + server_controllers[dev_idx]->colors = new_controller->colors; + for (unsigned int i = 0; i < server_controllers[dev_idx]->zones.size(); i++) { + server_controllers[dev_idx]->zones[i].leds_count = new_controller->zones[i] + .leds_count; server_controllers[dev_idx]->zones[i].segments.clear(); server_controllers[dev_idx]->zones[i].segments = new_controller->zones[i].segments; } @@ -629,10 +589,9 @@ void NetworkClient::ProcessReply_ControllerData(unsigned int data_size, char * d } } -void NetworkClient::ProcessReply_ProtocolVersion(unsigned int data_size, char * data) +void NetworkClient::ProcessReply_ProtocolVersion(unsigned int data_size, char *data) { - if(data_size == sizeof(unsigned int)) - { + if (data_size == sizeof(unsigned int)) { memcpy(&server_protocol_version, data, sizeof(unsigned int)); server_protocol_version_received = true; } @@ -644,12 +603,10 @@ void NetworkClient::ProcessRequest_DeviceListChanged() ControllerListMutex.lock(); - for(size_t server_controller_idx = 0; server_controller_idx < server_controllers.size(); server_controller_idx++) - { - for(size_t controller_idx = 0; controller_idx < controllers.size(); controller_idx++) - { - if(controllers[controller_idx] == server_controllers[server_controller_idx]) - { + for (size_t server_controller_idx = 0; server_controller_idx < server_controllers.size(); + server_controller_idx++) { + for (size_t controller_idx = 0; controller_idx < controllers.size(); controller_idx++) { + if (controllers[controller_idx] == server_controllers[server_controller_idx]) { controllers.erase(controllers.begin() + controller_idx); break; } @@ -660,8 +617,8 @@ void NetworkClient::ProcessRequest_DeviceListChanged() server_controllers.clear(); - for(size_t server_controller_idx = 0; server_controller_idx < server_controllers_copy.size(); server_controller_idx++) - { + for (size_t server_controller_idx = 0; server_controller_idx < server_controllers_copy.size(); + server_controller_idx++) { delete server_controllers_copy[server_controller_idx]; } @@ -684,11 +641,14 @@ void NetworkClient::SendData_ClientString() { NetPacketHeader reply_hdr; - InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_SET_CLIENT_NAME, (unsigned int)strlen(client_name.c_str()) + 1); + InitNetPacketHeader(&reply_hdr, + 0, + NET_PACKET_ID_SET_CLIENT_NAME, + (unsigned int) strlen(client_name.c_str()) + 1); send_in_progress.lock(); - send(client_sock, (char *)&reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)client_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); + send(client_sock, (char *) &reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) client_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); send_in_progress.unlock(); } @@ -699,50 +659,44 @@ void NetworkClient::SendRequest_ControllerCount() InitNetPacketHeader(&request_hdr, 0, NET_PACKET_ID_REQUEST_CONTROLLER_COUNT, 0); send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); send_in_progress.unlock(); } void NetworkClient::SendRequest_ControllerData(unsigned int dev_idx) { NetPacketHeader request_hdr; - unsigned int protocol_version; + unsigned int protocol_version; controller_data_received = false; memcpy(request_hdr.pkt_magic, openrgb_sdk_magic, sizeof(openrgb_sdk_magic)); - request_hdr.pkt_dev_idx = dev_idx; - request_hdr.pkt_id = NET_PACKET_ID_REQUEST_CONTROLLER_DATA; + request_hdr.pkt_dev_idx = dev_idx; + request_hdr.pkt_id = NET_PACKET_ID_REQUEST_CONTROLLER_DATA; - if(server_protocol_version == 0) - { - request_hdr.pkt_size = 0; + if (server_protocol_version == 0) { + request_hdr.pkt_size = 0; send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); send_in_progress.unlock(); - } - else - { - request_hdr.pkt_size = sizeof(unsigned int); + } else { + request_hdr.pkt_size = sizeof(unsigned int); /*-------------------------------------------------------------*\ | Limit the protocol version to the highest supported by both | | the client and the server. | \*-------------------------------------------------------------*/ - if(server_protocol_version > OPENRGB_SDK_PROTOCOL_VERSION) - { + if (server_protocol_version > OPENRGB_SDK_PROTOCOL_VERSION) { protocol_version = OPENRGB_SDK_PROTOCOL_VERSION; - } - else - { + } else { protocol_version = server_protocol_version; } send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)&protocol_version, sizeof(unsigned int), MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &protocol_version, sizeof(unsigned int), MSG_NOSIGNAL); send_in_progress.unlock(); } } @@ -750,40 +704,46 @@ void NetworkClient::SendRequest_ControllerData(unsigned int dev_idx) void NetworkClient::SendRequest_ProtocolVersion() { NetPacketHeader request_hdr; - unsigned int request_data; + unsigned int request_data; - InitNetPacketHeader(&request_hdr, 0, NET_PACKET_ID_REQUEST_PROTOCOL_VERSION, sizeof(unsigned int)); + InitNetPacketHeader(&request_hdr, + 0, + NET_PACKET_ID_REQUEST_PROTOCOL_VERSION, + sizeof(unsigned int)); - request_data = OPENRGB_SDK_PROTOCOL_VERSION; + request_data = OPENRGB_SDK_PROTOCOL_VERSION; send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)&request_data, sizeof(unsigned int), MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &request_data, sizeof(unsigned int), MSG_NOSIGNAL); send_in_progress.unlock(); } void NetworkClient::SendRequest_RGBController_ClearSegments(unsigned int dev_idx, int zone) { - if(change_in_progress) - { + if (change_in_progress) { return; } NetPacketHeader request_hdr; - int request_data[1]; + int request_data[1]; - InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_CLEARSEGMENTS, sizeof(request_data)); + InitNetPacketHeader(&request_hdr, + dev_idx, + NET_PACKET_ID_RGBCONTROLLER_CLEARSEGMENTS, + sizeof(request_data)); - request_data[0] = zone; + request_data[0] = zone; - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)&request_data, sizeof(request_data), MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &request_data, sizeof(request_data), MSG_NOSIGNAL); } -void NetworkClient::SendRequest_RGBController_AddSegment(unsigned int dev_idx, unsigned char * data, unsigned int size) +void NetworkClient::SendRequest_RGBController_AddSegment(unsigned int dev_idx, + unsigned char *data, + unsigned int size) { - if(change_in_progress) - { + if (change_in_progress) { return; } @@ -791,35 +751,40 @@ void NetworkClient::SendRequest_RGBController_AddSegment(unsigned int dev_idx, u InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_ADDSEGMENT, size); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)data, size, 0); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) data, size, 0); } -void NetworkClient::SendRequest_RGBController_ResizeZone(unsigned int dev_idx, int zone, int new_size) +void NetworkClient::SendRequest_RGBController_ResizeZone(unsigned int dev_idx, + int zone, + int new_size) { - if(change_in_progress) - { + if (change_in_progress) { return; } NetPacketHeader request_hdr; - int request_data[2]; + int request_data[2]; - InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE, sizeof(request_data)); + InitNetPacketHeader(&request_hdr, + dev_idx, + NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE, + sizeof(request_data)); - request_data[0] = zone; - request_data[1] = new_size; + request_data[0] = zone; + request_data[1] = new_size; send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)&request_data, sizeof(request_data), MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &request_data, sizeof(request_data), MSG_NOSIGNAL); send_in_progress.unlock(); } -void NetworkClient::SendRequest_RGBController_UpdateLEDs(unsigned int dev_idx, unsigned char * data, unsigned int size) +void NetworkClient::SendRequest_RGBController_UpdateLEDs(unsigned int dev_idx, + unsigned char *data, + unsigned int size) { - if(change_in_progress) - { + if (change_in_progress) { return; } @@ -828,15 +793,16 @@ void NetworkClient::SendRequest_RGBController_UpdateLEDs(unsigned int dev_idx, u InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_UPDATELEDS, size); send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)data, size, 0); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) data, size, 0); send_in_progress.unlock(); } -void NetworkClient::SendRequest_RGBController_UpdateZoneLEDs(unsigned int dev_idx, unsigned char * data, unsigned int size) +void NetworkClient::SendRequest_RGBController_UpdateZoneLEDs(unsigned int dev_idx, + unsigned char *data, + unsigned int size) { - if(change_in_progress) - { + if (change_in_progress) { return; } @@ -845,15 +811,16 @@ void NetworkClient::SendRequest_RGBController_UpdateZoneLEDs(unsigned int dev_id InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_UPDATEZONELEDS, size); send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)data, size, MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) data, size, MSG_NOSIGNAL); send_in_progress.unlock(); } -void NetworkClient::SendRequest_RGBController_UpdateSingleLED(unsigned int dev_idx, unsigned char * data, unsigned int size) +void NetworkClient::SendRequest_RGBController_UpdateSingleLED(unsigned int dev_idx, + unsigned char *data, + unsigned int size) { - if(change_in_progress) - { + if (change_in_progress) { return; } @@ -862,15 +829,14 @@ void NetworkClient::SendRequest_RGBController_UpdateSingleLED(unsigned int dev_i InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_UPDATESINGLELED, size); send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)data, size, MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) data, size, MSG_NOSIGNAL); send_in_progress.unlock(); } void NetworkClient::SendRequest_RGBController_SetCustomMode(unsigned int dev_idx) { - if(change_in_progress) - { + if (change_in_progress) { return; } @@ -879,14 +845,15 @@ void NetworkClient::SendRequest_RGBController_SetCustomMode(unsigned int dev_idx InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_SETCUSTOMMODE, 0); send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); send_in_progress.unlock(); } -void NetworkClient::SendRequest_RGBController_UpdateMode(unsigned int dev_idx, unsigned char * data, unsigned int size) +void NetworkClient::SendRequest_RGBController_UpdateMode(unsigned int dev_idx, + unsigned char *data, + unsigned int size) { - if(change_in_progress) - { + if (change_in_progress) { return; } @@ -895,15 +862,16 @@ void NetworkClient::SendRequest_RGBController_UpdateMode(unsigned int dev_idx, u InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_UPDATEMODE, size); send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)data, size, MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) data, size, MSG_NOSIGNAL); send_in_progress.unlock(); } -void NetworkClient::SendRequest_RGBController_SaveMode(unsigned int dev_idx, unsigned char * data, unsigned int size) +void NetworkClient::SendRequest_RGBController_SaveMode(unsigned int dev_idx, + unsigned char *data, + unsigned int size) { - if(change_in_progress) - { + if (change_in_progress) { return; } @@ -912,8 +880,8 @@ void NetworkClient::SendRequest_RGBController_SaveMode(unsigned int dev_idx, uns InitNetPacketHeader(&request_hdr, dev_idx, NET_PACKET_ID_RGBCONTROLLER_SAVEMODE, size); send_in_progress.lock(); - send(client_sock, (char *)&request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)data, size, MSG_NOSIGNAL); + send(client_sock, (char *) &request_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) data, size, MSG_NOSIGNAL); send_in_progress.unlock(); } @@ -921,11 +889,14 @@ void NetworkClient::SendRequest_LoadProfile(std::string profile_name) { NetPacketHeader reply_hdr; - InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_LOAD_PROFILE, (unsigned int)strlen(profile_name.c_str()) + 1); + InitNetPacketHeader(&reply_hdr, + 0, + NET_PACKET_ID_REQUEST_LOAD_PROFILE, + (unsigned int) strlen(profile_name.c_str()) + 1); send_in_progress.lock(); - send(client_sock, (char *)&reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)profile_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); + send(client_sock, (char *) &reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) profile_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); send_in_progress.unlock(); } @@ -933,11 +904,14 @@ void NetworkClient::SendRequest_SaveProfile(std::string profile_name) { NetPacketHeader reply_hdr; - InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_SAVE_PROFILE, (unsigned int)strlen(profile_name.c_str()) + 1); + InitNetPacketHeader(&reply_hdr, + 0, + NET_PACKET_ID_REQUEST_SAVE_PROFILE, + (unsigned int) strlen(profile_name.c_str()) + 1); send_in_progress.lock(); - send(client_sock, (char *)&reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)profile_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); + send(client_sock, (char *) &reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) profile_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); send_in_progress.unlock(); } @@ -945,11 +919,14 @@ void NetworkClient::SendRequest_DeleteProfile(std::string profile_name) { NetPacketHeader reply_hdr; - InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_DELETE_PROFILE, (unsigned int)strlen(profile_name.c_str()) + 1); + InitNetPacketHeader(&reply_hdr, + 0, + NET_PACKET_ID_REQUEST_DELETE_PROFILE, + (unsigned int) strlen(profile_name.c_str()) + 1); send_in_progress.lock(); - send(client_sock, (char *)&reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); - send(client_sock, (char *)profile_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); + send(client_sock, (char *) &reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) profile_name.c_str(), reply_hdr.pkt_size, MSG_NOSIGNAL); send_in_progress.unlock(); } @@ -960,16 +937,15 @@ void NetworkClient::SendRequest_GetProfileList() InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_PROFILE_LIST, 0); send_in_progress.lock(); - send(client_sock, (char *)&reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); + send(client_sock, (char *) &reply_hdr, sizeof(NetPacketHeader), MSG_NOSIGNAL); send_in_progress.unlock(); } -std::vector * NetworkClient::ProcessReply_ProfileList(unsigned int data_size, char * data) +std::vector *NetworkClient::ProcessReply_ProfileList(unsigned int data_size, char *data) { - std::vector * profile_list; + std::vector *profile_list; - if(data_size > 0) - { + if (data_size > 0) { profile_list = new std::vector(data_size); /*---------------------------------------------------------*\ @@ -981,8 +957,7 @@ std::vector * NetworkClient::ProcessReply_ProfileList(unsigned int memcpy(&num_profile, data, sizeof(unsigned short)); data_ptr += sizeof(unsigned short); - for(int i = 0; i < num_profile; i++) - { + for (int i = 0; i < num_profile; i++) { unsigned short name_len; memcpy(&name_len, data, sizeof(unsigned short)); @@ -995,9 +970,7 @@ std::vector * NetworkClient::ProcessReply_ProfileList(unsigned int } server_controller_count_received = true; - } - else - { + } else { profile_list = new std::vector(0); } diff --git a/NetworkClient.h b/NetworkClient.h index 77353f53e..96cb2c6cd 100644 --- a/NetworkClient.h +++ b/NetworkClient.h @@ -23,99 +23,109 @@ typedef void (*NetClientCallback)(void *); class NetworkClient { public: - NetworkClient(std::vector& control); + NetworkClient(std::vector &control); ~NetworkClient(); - void ClientInfoChanged(); + void ClientInfoChanged(); - bool GetConnected(); - std::string GetIP(); - unsigned short GetPort(); - unsigned int GetProtocolVersion(); - bool GetOnline(); + bool GetConnected(); + std::string GetIP(); + unsigned short GetPort(); + unsigned int GetProtocolVersion(); + bool GetOnline(); - void ClearCallbacks(); - void RegisterClientInfoChangeCallback(NetClientCallback new_callback, void * new_callback_arg); + void ClearCallbacks(); + void RegisterClientInfoChangeCallback(NetClientCallback new_callback, void *new_callback_arg); - void SetIP(std::string new_ip); - void SetName(std::string new_name); - void SetPort(unsigned short new_port); + void SetIP(std::string new_ip); + void SetName(std::string new_name); + void SetPort(unsigned short new_port); - void StartClient(); - void StopClient(); + void StartClient(); + void StopClient(); - void ConnectionThreadFunction(); - void ListenThreadFunction(); + void ConnectionThreadFunction(); + void ListenThreadFunction(); - void WaitOnControllerData(); + void WaitOnControllerData(); - void ProcessReply_ControllerCount(unsigned int data_size, char * data); - void ProcessReply_ControllerData(unsigned int data_size, char * data, unsigned int dev_idx); - void ProcessReply_ProtocolVersion(unsigned int data_size, char * data); + void ProcessReply_ControllerCount(unsigned int data_size, char *data); + void ProcessReply_ControllerData(unsigned int data_size, char *data, unsigned int dev_idx); + void ProcessReply_ProtocolVersion(unsigned int data_size, char *data); - void ProcessRequest_DeviceListChanged(); + void ProcessRequest_DeviceListChanged(); - void SendData_ClientString(); + void SendData_ClientString(); - void SendRequest_ControllerCount(); - void SendRequest_ControllerData(unsigned int dev_idx); - void SendRequest_ProtocolVersion(); + void SendRequest_ControllerCount(); + void SendRequest_ControllerData(unsigned int dev_idx); + void SendRequest_ProtocolVersion(); - void SendRequest_RGBController_ClearSegments(unsigned int dev_idx, int zone); - void SendRequest_RGBController_AddSegment(unsigned int dev_idx, unsigned char * data, unsigned int size); - void SendRequest_RGBController_ResizeZone(unsigned int dev_idx, int zone, int new_size); + void SendRequest_RGBController_ClearSegments(unsigned int dev_idx, int zone); + void SendRequest_RGBController_AddSegment(unsigned int dev_idx, + unsigned char *data, + unsigned int size); + void SendRequest_RGBController_ResizeZone(unsigned int dev_idx, int zone, int new_size); - void SendRequest_RGBController_UpdateLEDs(unsigned int dev_idx, unsigned char * data, unsigned int size); - void SendRequest_RGBController_UpdateZoneLEDs(unsigned int dev_idx, unsigned char * data, unsigned int size); - void SendRequest_RGBController_UpdateSingleLED(unsigned int dev_idx, unsigned char * data, unsigned int size); + void SendRequest_RGBController_UpdateLEDs(unsigned int dev_idx, + unsigned char *data, + unsigned int size); + void SendRequest_RGBController_UpdateZoneLEDs(unsigned int dev_idx, + unsigned char *data, + unsigned int size); + void SendRequest_RGBController_UpdateSingleLED(unsigned int dev_idx, + unsigned char *data, + unsigned int size); - void SendRequest_RGBController_SetCustomMode(unsigned int dev_idx); + void SendRequest_RGBController_SetCustomMode(unsigned int dev_idx); - void SendRequest_RGBController_UpdateMode(unsigned int dev_idx, unsigned char * data, unsigned int size); - void SendRequest_RGBController_SaveMode(unsigned int dev_idx, unsigned char * data, unsigned int size); + void SendRequest_RGBController_UpdateMode(unsigned int dev_idx, + unsigned char *data, + unsigned int size); + void SendRequest_RGBController_SaveMode(unsigned int dev_idx, + unsigned char *data, + unsigned int size); + std::vector *ProcessReply_ProfileList(unsigned int data_size, char *data); - std::vector * ProcessReply_ProfileList(unsigned int data_size, char * data); + void SendRequest_GetProfileList(); + void SendRequest_LoadProfile(std::string profile_name); + void SendRequest_SaveProfile(std::string profile_name); + void SendRequest_DeleteProfile(std::string profile_name); - void SendRequest_GetProfileList(); - void SendRequest_LoadProfile(std::string profile_name); - void SendRequest_SaveProfile(std::string profile_name); - void SendRequest_DeleteProfile(std::string profile_name); + std::vector server_controllers; - std::vector server_controllers; - - std::mutex ControllerListMutex; + std::mutex ControllerListMutex; protected: - std::vector& controllers; - + std::vector &controllers; private: - SOCKET client_sock; - std::string client_name; - net_port port; - std::string port_ip; - unsigned short port_num; + SOCKET client_sock; + std::string client_name; + net_port port; + std::string port_ip; + unsigned short port_num; std::atomic client_active; - bool controller_data_received; - bool server_connected; - bool server_initialized; - unsigned int server_controller_count; - bool server_controller_count_received; - unsigned int server_protocol_version; - bool server_protocol_version_received; - bool change_in_progress; - std::mutex send_in_progress; + bool controller_data_received; + bool server_connected; + bool server_initialized; + unsigned int server_controller_count; + bool server_controller_count_received; + unsigned int server_protocol_version; + bool server_protocol_version_received; + bool change_in_progress; + std::mutex send_in_progress; - std::mutex connection_mutex; + std::mutex connection_mutex; std::condition_variable connection_cv; - std::thread * ConnectionThread; - std::thread * ListenThread; + std::thread *ConnectionThread; + std::thread *ListenThread; - std::mutex ClientInfoChangeMutex; - std::vector ClientInfoChangeCallbacks; - std::vector ClientInfoChangeCallbackArgs; + std::mutex ClientInfoChangeMutex; + std::vector ClientInfoChangeCallbacks; + std::vector ClientInfoChangeCallbackArgs; int recv_select(SOCKET s, char *buf, int len, int flags); }; diff --git a/NetworkProtocol.cpp b/NetworkProtocol.cpp index 53e98a461..aa0f69b0a 100644 --- a/NetworkProtocol.cpp +++ b/NetworkProtocol.cpp @@ -15,19 +15,16 @@ /*-----------------------------------------------------*\ | OpenRGB SDK Magic Value "ORGB" | \*-----------------------------------------------------*/ -const char openrgb_sdk_magic[OPENRGB_SDK_MAGIC_SIZE] = { 'O', 'R', 'G', 'B' }; +const char openrgb_sdk_magic[OPENRGB_SDK_MAGIC_SIZE] = {'O', 'R', 'G', 'B'}; -void InitNetPacketHeader - ( - NetPacketHeader * pkt_hdr, - unsigned int pkt_dev_idx, - unsigned int pkt_id, - unsigned int pkt_size - ) +void InitNetPacketHeader(NetPacketHeader *pkt_hdr, + unsigned int pkt_dev_idx, + unsigned int pkt_id, + unsigned int pkt_size) { memcpy(pkt_hdr->pkt_magic, openrgb_sdk_magic, sizeof(openrgb_sdk_magic)); - pkt_hdr->pkt_dev_idx = pkt_dev_idx; - pkt_hdr->pkt_id = pkt_id; - pkt_hdr->pkt_size = pkt_size; + pkt_hdr->pkt_dev_idx = pkt_dev_idx; + pkt_hdr->pkt_id = pkt_id; + pkt_hdr->pkt_size = pkt_size; } diff --git a/NetworkProtocol.h b/NetworkProtocol.h index b89739548..abd8ecce3 100644 --- a/NetworkProtocol.h +++ b/NetworkProtocol.h @@ -22,7 +22,7 @@ | 5: Zone flags, controller flags, resizable effects-only zones | (Release 1.0) | \*---------------------------------------------------------------------*/ -#define OPENRGB_SDK_PROTOCOL_VERSION 5 +#define OPENRGB_SDK_PROTOCOL_VERSION 5 /*-----------------------------------------------------*\ | Default Interface to bind to. | @@ -43,54 +43,63 @@ extern const char openrgb_sdk_magic[OPENRGB_SDK_MAGIC_SIZE]; typedef struct NetPacketHeader { - char pkt_magic[4]; /* Magic value "ORGB" identifies beginning of packet */ - unsigned int pkt_dev_idx; /* Device index */ - unsigned int pkt_id; /* Packet ID */ - unsigned int pkt_size; /* Packet size */ + char pkt_magic[4]; /* Magic value "ORGB" identifies beginning of packet */ + unsigned int pkt_dev_idx; /* Device index */ + unsigned int pkt_id; /* Packet ID */ + unsigned int pkt_size; /* Packet size */ } NetPacketHeader; -enum -{ +enum { /*----------------------------------------------------------------------------------------------------------*\ | Network requests | \*----------------------------------------------------------------------------------------------------------*/ - NET_PACKET_ID_REQUEST_CONTROLLER_COUNT = 0, /* Request RGBController device count from server */ - NET_PACKET_ID_REQUEST_CONTROLLER_DATA = 1, /* Request RGBController data block */ + NET_PACKET_ID_REQUEST_CONTROLLER_COUNT + = 0, /* Request RGBController device count from server */ + NET_PACKET_ID_REQUEST_CONTROLLER_DATA + = 1, /* Request RGBController data block */ - NET_PACKET_ID_REQUEST_PROTOCOL_VERSION = 40, /* Request OpenRGB SDK protocol version from server */ + NET_PACKET_ID_REQUEST_PROTOCOL_VERSION + = 40, /* Request OpenRGB SDK protocol version from server */ - NET_PACKET_ID_SET_CLIENT_NAME = 50, /* Send client name string to server */ + NET_PACKET_ID_SET_CLIENT_NAME = 50, /* Send client name string to server */ - NET_PACKET_ID_DEVICE_LIST_UPDATED = 100, /* Indicate to clients that device list has updated */ + NET_PACKET_ID_DEVICE_LIST_UPDATED = 100, /* Indicate to clients that device list has updated */ - NET_PACKET_ID_REQUEST_PROFILE_LIST = 150, /* Request profile list */ - NET_PACKET_ID_REQUEST_SAVE_PROFILE = 151, /* Save current configuration in a new profile */ - NET_PACKET_ID_REQUEST_LOAD_PROFILE = 152, /* Load a given profile */ - NET_PACKET_ID_REQUEST_DELETE_PROFILE = 153, /* Delete a given profile */ + NET_PACKET_ID_REQUEST_PROFILE_LIST = 150, /* Request profile list */ + NET_PACKET_ID_REQUEST_SAVE_PROFILE = 151, /* Save current configuration in a new profile */ + NET_PACKET_ID_REQUEST_LOAD_PROFILE = 152, /* Load a given profile */ + NET_PACKET_ID_REQUEST_DELETE_PROFILE + = 153, /* Delete a given profile */ - NET_PACKET_ID_REQUEST_PLUGIN_LIST = 200, /* Request list of plugins */ - NET_PACKET_ID_PLUGIN_SPECIFIC = 201, /* Interact with a plugin */ + NET_PACKET_ID_REQUEST_PLUGIN_LIST = 200, /* Request list of plugins */ + NET_PACKET_ID_PLUGIN_SPECIFIC = 201, /* Interact with a plugin */ /*----------------------------------------------------------------------------------------------------------*\ | RGBController class functions | \*----------------------------------------------------------------------------------------------------------*/ - NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE = 1000, /* RGBController::ResizeZone() */ - NET_PACKET_ID_RGBCONTROLLER_CLEARSEGMENTS = 1001, /* RGBController::ClearSegments() */ - NET_PACKET_ID_RGBCONTROLLER_ADDSEGMENT = 1002, /* RGBController::AddSegment() */ + NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE + = 1000, /* RGBController::ResizeZone() */ + NET_PACKET_ID_RGBCONTROLLER_CLEARSEGMENTS + = 1001, /* RGBController::ClearSegments() */ + NET_PACKET_ID_RGBCONTROLLER_ADDSEGMENT + = 1002, /* RGBController::AddSegment() */ - NET_PACKET_ID_RGBCONTROLLER_UPDATELEDS = 1050, /* RGBController::UpdateLEDs() */ - NET_PACKET_ID_RGBCONTROLLER_UPDATEZONELEDS = 1051, /* RGBController::UpdateZoneLEDs() */ - NET_PACKET_ID_RGBCONTROLLER_UPDATESINGLELED = 1052, /* RGBController::UpdateSingleLED() */ + NET_PACKET_ID_RGBCONTROLLER_UPDATELEDS + = 1050, /* RGBController::UpdateLEDs() */ + NET_PACKET_ID_RGBCONTROLLER_UPDATEZONELEDS + = 1051, /* RGBController::UpdateZoneLEDs() */ + NET_PACKET_ID_RGBCONTROLLER_UPDATESINGLELED + = 1052, /* RGBController::UpdateSingleLED() */ - NET_PACKET_ID_RGBCONTROLLER_SETCUSTOMMODE = 1100, /* RGBController::SetCustomMode() */ - NET_PACKET_ID_RGBCONTROLLER_UPDATEMODE = 1101, /* RGBController::UpdateMode() */ - NET_PACKET_ID_RGBCONTROLLER_SAVEMODE = 1102, /* RGBController::SaveMode() */ + NET_PACKET_ID_RGBCONTROLLER_SETCUSTOMMODE + = 1100, /* RGBController::SetCustomMode() */ + NET_PACKET_ID_RGBCONTROLLER_UPDATEMODE + = 1101, /* RGBController::UpdateMode() */ + NET_PACKET_ID_RGBCONTROLLER_SAVEMODE + = 1102, /* RGBController::SaveMode() */ }; -void InitNetPacketHeader - ( - NetPacketHeader * pkt_hdr, - unsigned int pkt_dev_idx, - unsigned int pkt_id, - unsigned int pkt_size - ); +void InitNetPacketHeader(NetPacketHeader *pkt_hdr, + unsigned int pkt_dev_idx, + unsigned int pkt_id, + unsigned int pkt_size); diff --git a/NetworkServer.cpp b/NetworkServer.cpp index bac944007..5032484f8 100644 --- a/NetworkServer.cpp +++ b/NetworkServer.cpp @@ -38,17 +38,16 @@ using namespace std::chrono_literals; NetworkClientInfo::NetworkClientInfo() { - client_string = "Client"; - client_ip = OPENRGB_SDK_HOST; - client_sock = INVALID_SOCKET; - client_listen_thread = nullptr; + client_string = "Client"; + client_ip = OPENRGB_SDK_HOST; + client_sock = INVALID_SOCKET; + client_listen_thread = nullptr; client_protocol_version = 0; } NetworkClientInfo::~NetworkClientInfo() { - if(client_sock != INVALID_SOCKET) - { + if (client_sock != INVALID_SOCKET) { LOG_INFO("[NetworkServer] Closing server connection: %s", client_ip.c_str()); delete client_listen_thread; shutdown(client_sock, SD_RECEIVE); @@ -56,20 +55,20 @@ NetworkClientInfo::~NetworkClientInfo() } } -NetworkServer::NetworkServer(std::vector& control) : controllers(control) +NetworkServer::NetworkServer(std::vector &control) + : controllers(control) { - host = OPENRGB_SDK_HOST; - port_num = OPENRGB_SDK_PORT; - server_online = false; - server_listening = false; - legacy_workaround_enabled = false; + host = OPENRGB_SDK_HOST; + port_num = OPENRGB_SDK_PORT; + server_online = false; + server_listening = false; + legacy_workaround_enabled = false; - for(int i = 0; i < MAXSOCK; i++) - { + for (int i = 0; i < MAXSOCK; i++) { ConnectionThread[i] = nullptr; } - profile_manager = nullptr; + profile_manager = nullptr; } NetworkServer::~NetworkServer() @@ -84,8 +83,8 @@ void NetworkServer::ClientInfoChanged() /*---------------------------------------------------------*\ | Client info has changed, call the callbacks | \*---------------------------------------------------------*/ - for(unsigned int callback_idx = 0; callback_idx < ClientInfoChangeCallbacks.size(); callback_idx++) - { + for (unsigned int callback_idx = 0; callback_idx < ClientInfoChangeCallbacks.size(); + callback_idx++) { ClientInfoChangeCallbacks[callback_idx](ClientInfoChangeCallbackArgs[callback_idx]); } @@ -98,8 +97,7 @@ void NetworkServer::DeviceListChanged() | Indicate to the clients that the controller list has | | changed | \*---------------------------------------------------------*/ - for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++) - { + for (unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++) { SendRequest_DeviceListChanged(ServerClients[client_idx]->client_sock); } } @@ -111,9 +109,10 @@ void NetworkServer::ServerListeningChanged() /*---------------------------------------------------------*\ | Server state has changed, call the callbacks | \*---------------------------------------------------------*/ - for(unsigned int callback_idx = 0; callback_idx < ServerListeningChangeCallbacks.size(); callback_idx++) - { - ServerListeningChangeCallbacks[callback_idx](ServerListeningChangeCallbackArgs[callback_idx]); + for (unsigned int callback_idx = 0; callback_idx < ServerListeningChangeCallbacks.size(); + callback_idx++) { + ServerListeningChangeCallbacks[callback_idx]( + ServerListeningChangeCallbackArgs[callback_idx]); } ServerListeningChangeMutex.unlock(); @@ -141,21 +140,18 @@ bool NetworkServer::GetListening() unsigned int NetworkServer::GetNumClients() { - return (unsigned int)ServerClients.size(); + return (unsigned int) ServerClients.size(); } -const char * NetworkServer::GetClientString(unsigned int client_num) +const char *NetworkServer::GetClientString(unsigned int client_num) { - const char * result; + const char *result; ServerClientsMutex.lock(); - if(client_num < ServerClients.size()) - { + if (client_num < ServerClients.size()) { result = ServerClients[client_num]->client_string.c_str(); - } - else - { + } else { result = ""; } @@ -164,18 +160,15 @@ const char * NetworkServer::GetClientString(unsigned int client_num) return result; } -const char * NetworkServer::GetClientIP(unsigned int client_num) +const char *NetworkServer::GetClientIP(unsigned int client_num) { - const char * result; + const char *result; ServerClientsMutex.lock(); - if(client_num < ServerClients.size()) - { + if (client_num < ServerClients.size()) { result = ServerClients[client_num]->client_ip.c_str(); - } - else - { + } else { result = ""; } @@ -190,12 +183,9 @@ unsigned int NetworkServer::GetClientProtocolVersion(unsigned int client_num) ServerClientsMutex.lock(); - if(client_num < ServerClients.size()) - { + if (client_num < ServerClients.size()) { result = ServerClients[client_num]->client_protocol_version; - } - else - { + } else { result = 0; } @@ -204,13 +194,15 @@ unsigned int NetworkServer::GetClientProtocolVersion(unsigned int client_num) return result; } -void NetworkServer::RegisterClientInfoChangeCallback(NetServerCallback new_callback, void * new_callback_arg) +void NetworkServer::RegisterClientInfoChangeCallback(NetServerCallback new_callback, + void *new_callback_arg) { ClientInfoChangeCallbacks.push_back(new_callback); ClientInfoChangeCallbackArgs.push_back(new_callback_arg); } -void NetworkServer::RegisterServerListeningChangeCallback(NetServerCallback new_callback, void * new_callback_arg) +void NetworkServer::RegisterServerListeningChangeCallback(NetServerCallback new_callback, + void *new_callback_arg) { ServerListeningChangeCallbacks.push_back(new_callback); ServerListeningChangeCallbackArgs.push_back(new_callback_arg); @@ -218,8 +210,7 @@ void NetworkServer::RegisterServerListeningChangeCallback(NetServerCallback new_ void NetworkServer::SetHost(std::string new_host) { - if(server_online == false) - { + if (server_online == false) { host = new_host; } } @@ -231,8 +222,7 @@ void NetworkServer::SetLegacyWorkaroundEnable(bool enable) void NetworkServer::SetPort(unsigned short new_port) { - if(server_online == false) - { + if (server_online == false) { port_num = new_port; } } @@ -254,8 +244,7 @@ void NetworkServer::StartServer() | Windows requires WSAStartup before using sockets | \*---------------------------------------------------------*/ #ifdef WIN32 - if(WSAStartup(MAKEWORD(2, 2), &wsa) != NO_ERROR) - { + if (WSAStartup(MAKEWORD(2, 2), &wsa) != NO_ERROR) { WSACleanup(); return; } @@ -267,8 +256,7 @@ void NetworkServer::StartServer() hints.ai_flags = AI_PASSIVE; err = getaddrinfo(host.c_str(), port_str, &hints, &result); - if(err) - { + if (err) { LOG_ERROR("[NetworkServer] Unable to get address."); WSACleanup(); return; @@ -277,12 +265,10 @@ void NetworkServer::StartServer() /*---------------------------------------------------------*\ | Create a server socket for each address returned. | \*---------------------------------------------------------*/ - for(res = result; res && socket_count < MAXSOCK; res = res->ai_next) - { + for (res = result; res && socket_count < MAXSOCK; res = res->ai_next) { server_sock[socket_count] = socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if(server_sock[socket_count] == INVALID_SOCKET) - { + if (server_sock[socket_count] == INVALID_SOCKET) { LOG_ERROR("[NetworkServer] Network socket could not be created."); WSACleanup(); return; @@ -291,30 +277,25 @@ void NetworkServer::StartServer() /*---------------------------------------------------------*\ | Bind the server socket | \*---------------------------------------------------------*/ - if(bind(server_sock[socket_count], res->ai_addr, res->ai_addrlen) == SOCKET_ERROR) - { - if(errno == EADDRINUSE) - { - LOG_ERROR("[NetworkServer] Could not bind network socket. Is port %hu already being used?", GetPort()); - } - else if(errno == EACCES) - { - LOG_ERROR("[NetworkServer] Could not bind network socket. Access to socket was denied."); - } - else if(errno == EBADF) - { - LOG_ERROR("[NetworkServer] Could not bind network socket. sockfd is not a valid file descriptor."); - } - else if(errno == EINVAL) - { - LOG_ERROR("[NetworkServer] Could not bind network socket. The socket is already bound to an address, or addrlen is wrong, or addr is not a valid address for this socket's domain."); - } - else if(errno == ENOTSOCK) - { - LOG_ERROR("[NetworkServer] Could not bind network socket. The file descriptor sockfd does not refer to a socket."); - } - else - { + if (bind(server_sock[socket_count], res->ai_addr, res->ai_addrlen) == SOCKET_ERROR) { + if (errno == EADDRINUSE) { + LOG_ERROR("[NetworkServer] Could not bind network socket. Is port %hu already " + "being used?", + GetPort()); + } else if (errno == EACCES) { + LOG_ERROR( + "[NetworkServer] Could not bind network socket. Access to socket was denied."); + } else if (errno == EBADF) { + LOG_ERROR("[NetworkServer] Could not bind network socket. sockfd is not a valid " + "file descriptor."); + } else if (errno == EINVAL) { + LOG_ERROR("[NetworkServer] Could not bind network socket. The socket is already " + "bound to an address, or addrlen is wrong, or addr is not a valid " + "address for this socket's domain."); + } else if (errno == ENOTSOCK) { + LOG_ERROR("[NetworkServer] Could not bind network socket. The file descriptor " + "sockfd does not refer to a socket."); + } else { /*---------------------------------------------------------*\ | errno could be a Linux specific error, see: | | https://man7.org/linux/man-pages/man2/bind.2.html | @@ -340,9 +321,10 @@ void NetworkServer::StartServer() /*---------------------------------------------------------*\ | Start the connection thread | \*---------------------------------------------------------*/ - for(int curr_socket = 0; curr_socket < socket_count; curr_socket++) - { - ConnectionThread[curr_socket] = new std::thread(&NetworkServer::ConnectionThreadFunction, this, curr_socket); + for (int curr_socket = 0; curr_socket < socket_count; curr_socket++) { + ConnectionThread[curr_socket] = new std::thread(&NetworkServer::ConnectionThreadFunction, + this, + curr_socket); ConnectionThread[curr_socket]->detach(); } } @@ -354,25 +336,21 @@ void NetworkServer::StopServer() ServerClientsMutex.lock(); - for(unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++) - { + for (unsigned int client_idx = 0; client_idx < ServerClients.size(); client_idx++) { delete ServerClients[client_idx]; } ServerClients.clear(); - for(curr_socket = 0; curr_socket < socket_count; curr_socket++) - { + for (curr_socket = 0; curr_socket < socket_count; curr_socket++) { shutdown(server_sock[curr_socket], SD_RECEIVE); closesocket(server_sock[curr_socket]); } ServerClientsMutex.unlock(); - for(curr_socket = 0; curr_socket < socket_count; curr_socket++) - { - if(ConnectionThread[curr_socket]) - { + for (curr_socket = 0; curr_socket < socket_count; curr_socket++) { + if (ConnectionThread[curr_socket]) { delete ConnectionThread[curr_socket]; ConnectionThread[curr_socket] = nullptr; } @@ -393,20 +371,18 @@ void NetworkServer::ConnectionThreadFunction(int socket_idx) \*---------------------------------------------------------*/ LOG_INFO("[NetworkServer] Network connection thread started on port %hu", GetPort()); - while(server_online == true) - { + while (server_online == true) { /*---------------------------------------------------------*\ | Create new socket for client connection | \*---------------------------------------------------------*/ - NetworkClientInfo * client_info = new NetworkClientInfo(); + NetworkClientInfo *client_info = new NetworkClientInfo(); /*---------------------------------------------------------*\ | Listen for incoming client connection on the server | | socket. This call blocks until a connection is | | established | \*---------------------------------------------------------*/ - if(listen(server_sock[socket_idx], 10) < 0) - { + if (listen(server_sock[socket_idx], 10) < 0) { LOG_INFO("[NetworkServer] Connection thread closed"); server_online = false; @@ -419,10 +395,9 @@ void NetworkServer::ConnectionThreadFunction(int socket_idx) /*---------------------------------------------------------*\ | Accept the client connection | \*---------------------------------------------------------*/ - client_info->client_sock = accept_select((int)server_sock[socket_idx]); + client_info->client_sock = accept_select((int) server_sock[socket_idx]); - if(client_info->client_sock < 0) - { + if (client_info->client_sock < 0) { LOG_INFO("[NetworkServer] Connection thread closed"); server_online = false; @@ -447,17 +422,14 @@ void NetworkServer::ConnectionThreadFunction(int socket_idx) char ipstr[INET6_ADDRSTRLEN]; socklen_t len; len = sizeof(tmp_addr); - getpeername(client_info->client_sock, (struct sockaddr*)&tmp_addr, &len); + getpeername(client_info->client_sock, (struct sockaddr *) &tmp_addr, &len); - if(tmp_addr.ss_family == AF_INET) - { - struct sockaddr_in *s_4 = (struct sockaddr_in *)&tmp_addr; + if (tmp_addr.ss_family == AF_INET) { + struct sockaddr_in *s_4 = (struct sockaddr_in *) &tmp_addr; inet_ntop(AF_INET, &s_4->sin_addr, ipstr, sizeof(ipstr)); client_info->client_ip = ipstr; - } - else - { - struct sockaddr_in6 *s_6 = (struct sockaddr_in6 *)&tmp_addr; + } else { + struct sockaddr_in6 *s_6 = (struct sockaddr_in6 *) &tmp_addr; inet_ntop(AF_INET6, &s_6->sin6_addr, ipstr, sizeof(ipstr)); client_info->client_ip = ipstr; } @@ -470,7 +442,9 @@ void NetworkServer::ConnectionThreadFunction(int socket_idx) /*---------------------------------------------------------*\ | Start a listener thread for the new client socket | \*---------------------------------------------------------*/ - client_info->client_listen_thread = new std::thread(&NetworkServer::ListenThreadFunction, this, client_info); + client_info->client_listen_thread = new std::thread(&NetworkServer::ListenThreadFunction, + this, + client_info); client_info->client_listen_thread->detach(); ServerClients.push_back(client_info); @@ -490,65 +464,53 @@ void NetworkServer::ConnectionThreadFunction(int socket_idx) int NetworkServer::accept_select(int sockfd) { - fd_set set; - struct timeval timeout; + fd_set set; + struct timeval timeout; - while(1) - { - timeout.tv_sec = TCP_TIMEOUT_SECONDS; - timeout.tv_usec = 0; + while (1) { + timeout.tv_sec = TCP_TIMEOUT_SECONDS; + timeout.tv_usec = 0; FD_ZERO(&set); FD_SET(sockfd, &set); int rv = select(sockfd + 1, &set, NULL, NULL, &timeout); - if(rv == SOCKET_ERROR || server_online == false) - { + if (rv == SOCKET_ERROR || server_online == false) { return -1; - } - else if(rv == 0) - { + } else if (rv == 0) { continue; - } - else - { - return(accept((int)sockfd, NULL, NULL)); + } else { + return (accept((int) sockfd, NULL, NULL)); } } } int NetworkServer::recv_select(SOCKET s, char *buf, int len, int flags) { - fd_set set; - struct timeval timeout; + fd_set set; + struct timeval timeout; - while(1) - { - timeout.tv_sec = TCP_TIMEOUT_SECONDS; - timeout.tv_usec = 0; + while (1) { + timeout.tv_sec = TCP_TIMEOUT_SECONDS; + timeout.tv_usec = 0; FD_ZERO(&set); FD_SET(s, &set); - int rv = select((int)s + 1, &set, NULL, NULL, &timeout); + int rv = select((int) s + 1, &set, NULL, NULL, &timeout); - if(rv == SOCKET_ERROR || server_online == false) - { + if (rv == SOCKET_ERROR || server_online == false) { return 0; - } - else if(rv == 0) - { + } else if (rv == 0) { continue; - } - else - { - return(recv(s, buf, len, flags)); + } else { + return (recv(s, buf, len, flags)); } } } -void NetworkServer::ListenThreadFunction(NetworkClientInfo * client_info) +void NetworkServer::ListenThreadFunction(NetworkClientInfo *client_info) { SOCKET client_sock = client_info->client_sock; @@ -557,21 +519,18 @@ void NetworkServer::ListenThreadFunction(NetworkClientInfo * client_info) /*---------------------------------------------------------*\ | This thread handles messages received from clients | \*---------------------------------------------------------*/ - while(server_online == true) - { + while (server_online == true) { NetPacketHeader header; - int bytes_read = 0; - char * data = NULL; + int bytes_read = 0; + char *data = NULL; - for(unsigned int i = 0; i < 4; i++) - { + for (unsigned int i = 0; i < 4; i++) { /*---------------------------------------------------------*\ | Read byte of magic | \*---------------------------------------------------------*/ bytes_read = recv_select(client_sock, &header.pkt_magic[i], 1, 0); - if(bytes_read <= 0) - { + if (bytes_read <= 0) { LOG_ERROR("[NetworkServer] recv_select failed receiving magic, closing listener"); goto listen_done; } @@ -579,8 +538,7 @@ void NetworkServer::ListenThreadFunction(NetworkClientInfo * client_info) /*---------------------------------------------------------*\ | Test characters of magic "ORGB" | \*---------------------------------------------------------*/ - if(header.pkt_magic[i] != openrgb_sdk_magic[i]) - { + if (header.pkt_magic[i] != openrgb_sdk_magic[i]) { LOG_ERROR("[NetworkServer] Invalid magic received"); continue; } @@ -591,215 +549,202 @@ void NetworkServer::ListenThreadFunction(NetworkClientInfo * client_info) | rest of the header | \*---------------------------------------------------------*/ bytes_read = 0; - do - { + do { int tmp_bytes_read = 0; - tmp_bytes_read = recv_select(client_sock, (char *)&header.pkt_dev_idx + bytes_read, sizeof(header) - sizeof(header.pkt_magic) - bytes_read, 0); + tmp_bytes_read = recv_select(client_sock, + (char *) &header.pkt_dev_idx + bytes_read, + sizeof(header) - sizeof(header.pkt_magic) - bytes_read, + 0); bytes_read += tmp_bytes_read; - if(tmp_bytes_read <= 0) - { + if (tmp_bytes_read <= 0) { LOG_ERROR("[NetworkServer] recv_select failed receiving header, closing listener"); goto listen_done; } - } while(bytes_read != sizeof(header) - sizeof(header.pkt_magic)); + } while (bytes_read != sizeof(header) - sizeof(header.pkt_magic)); /*---------------------------------------------------------*\ | Header received, now receive the data | \*---------------------------------------------------------*/ bytes_read = 0; - if(header.pkt_size > 0) - { + if (header.pkt_size > 0) { data = new char[header.pkt_size]; - do - { + do { int tmp_bytes_read = 0; - tmp_bytes_read = recv_select(client_sock, &data[(unsigned int)bytes_read], header.pkt_size - bytes_read, 0); + tmp_bytes_read = recv_select(client_sock, + &data[(unsigned int) bytes_read], + header.pkt_size - bytes_read, + 0); - if(tmp_bytes_read <= 0) - { - LOG_ERROR("[NetworkServer] recv_select failed receiving data, closing listener"); + if (tmp_bytes_read <= 0) { + LOG_ERROR( + "[NetworkServer] recv_select failed receiving data, closing listener"); goto listen_done; } bytes_read += tmp_bytes_read; - } while ((unsigned int)bytes_read < header.pkt_size); + } while ((unsigned int) bytes_read < header.pkt_size); } /*---------------------------------------------------------*\ | Entire request received, select functionality based on | | request ID | \*---------------------------------------------------------*/ - switch(header.pkt_id) - { - case NET_PACKET_ID_REQUEST_CONTROLLER_COUNT: - SendReply_ControllerCount(client_sock); + switch (header.pkt_id) { + case NET_PACKET_ID_REQUEST_CONTROLLER_COUNT: + SendReply_ControllerCount(client_sock); + break; + + case NET_PACKET_ID_REQUEST_CONTROLLER_DATA: { + unsigned int protocol_version = 0; + + if (header.pkt_size == sizeof(unsigned int)) { + memcpy(&protocol_version, data, sizeof(unsigned int)); + } + + SendReply_ControllerData(client_sock, header.pkt_dev_idx, protocol_version); + } break; + + case NET_PACKET_ID_REQUEST_PROTOCOL_VERSION: + SendReply_ProtocolVersion(client_sock); + ProcessRequest_ClientProtocolVersion(client_sock, header.pkt_size, data); + break; + + case NET_PACKET_ID_SET_CLIENT_NAME: + if (data == NULL) { break; + } - case NET_PACKET_ID_REQUEST_CONTROLLER_DATA: - { - unsigned int protocol_version = 0; + ProcessRequest_ClientString(client_sock, header.pkt_size, data); + break; - if(header.pkt_size == sizeof(unsigned int)) - { - memcpy(&protocol_version, data, sizeof(unsigned int)); - } + case NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE: + if (data == NULL) { + break; + } - SendReply_ControllerData(client_sock, header.pkt_dev_idx, protocol_version); + if ((header.pkt_dev_idx < controllers.size()) + && (header.pkt_size == (2 * sizeof(int)))) { + int zone; + int new_size; + + memcpy(&zone, data, sizeof(int)); + memcpy(&new_size, data + sizeof(int), sizeof(int)); + + controllers[header.pkt_dev_idx]->ResizeZone(zone, new_size); + profile_manager->SaveProfile("sizes", true); + } + break; + + case NET_PACKET_ID_RGBCONTROLLER_UPDATELEDS: + if (data == NULL) { + break; + } + + /*---------------------------------------------------------*\ + | Verify the color description size (first 4 bytes of data) | + | matches the packet size in the header | + | | + | If protocol version is 4 or below and the legacy SDK | + | compatibility workaround is enabled, ignore this check. | + | This allows backwards compatibility with old versions of | + | SDK applications that didn't properly implement the size | + | field. | + \*---------------------------------------------------------*/ + if ((header.pkt_size == *((unsigned int *) data)) + || ((client_info->client_protocol_version <= 4) && (legacy_workaround_enabled))) { + if (header.pkt_dev_idx < controllers.size()) { + controllers[header.pkt_dev_idx]->SetColorDescription((unsigned char *) data); + controllers[header.pkt_dev_idx]->UpdateLEDs(); } + } else { + LOG_ERROR("[NetworkServer] UpdateLEDs packet has invalid size. Packet size: %d, " + "Data size: %d", + header.pkt_size, + *((unsigned int *) data)); + goto listen_done; + } + break; + + case NET_PACKET_ID_RGBCONTROLLER_UPDATEZONELEDS: + if (data == NULL) { break; + } - case NET_PACKET_ID_REQUEST_PROTOCOL_VERSION: - SendReply_ProtocolVersion(client_sock); - ProcessRequest_ClientProtocolVersion(client_sock, header.pkt_size, data); - break; - - case NET_PACKET_ID_SET_CLIENT_NAME: - if(data == NULL) - { - break; - } - - ProcessRequest_ClientString(client_sock, header.pkt_size, data); - break; - - case NET_PACKET_ID_RGBCONTROLLER_RESIZEZONE: - if(data == NULL) - { - break; - } - - if((header.pkt_dev_idx < controllers.size()) && (header.pkt_size == (2 * sizeof(int)))) - { + /*---------------------------------------------------------*\ + | Verify the color description size (first 4 bytes of data) | + | matches the packet size in the header | + | | + | If protocol version is 4 or below and the legacy SDK | + | compatibility workaround is enabled, ignore this check. | + | This allows backwards compatibility with old versions of | + | SDK applications that didn't properly implement the size | + | field. | + \*---------------------------------------------------------*/ + if ((header.pkt_size == *((unsigned int *) data)) + || ((client_info->client_protocol_version <= 4) && (legacy_workaround_enabled))) { + if (header.pkt_dev_idx < controllers.size()) { int zone; - int new_size; - memcpy(&zone, data, sizeof(int)); - memcpy(&new_size, data + sizeof(int), sizeof(int)); + memcpy(&zone, &data[sizeof(unsigned int)], sizeof(int)); - controllers[header.pkt_dev_idx]->ResizeZone(zone, new_size); - profile_manager->SaveProfile("sizes", true); + controllers[header.pkt_dev_idx]->SetZoneColorDescription((unsigned char *) data); + controllers[header.pkt_dev_idx]->UpdateZoneLEDs(zone); } + } else { + LOG_ERROR("[NetworkServer] UpdateZoneLEDs packet has invalid size. Packet size: " + "%d, Data size: %d", + header.pkt_size, + *((unsigned int *) data)); + goto listen_done; + } + break; + + case NET_PACKET_ID_RGBCONTROLLER_UPDATESINGLELED: + if (data == NULL) { break; + } - case NET_PACKET_ID_RGBCONTROLLER_UPDATELEDS: - if(data == NULL) - { - break; - } - - /*---------------------------------------------------------*\ - | Verify the color description size (first 4 bytes of data) | - | matches the packet size in the header | - | | - | If protocol version is 4 or below and the legacy SDK | - | compatibility workaround is enabled, ignore this check. | - | This allows backwards compatibility with old versions of | - | SDK applications that didn't properly implement the size | - | field. | - \*---------------------------------------------------------*/ - if((header.pkt_size == *((unsigned int*)data)) - || ((client_info->client_protocol_version <= 4) - && (legacy_workaround_enabled))) - { - if(header.pkt_dev_idx < controllers.size()) - { - controllers[header.pkt_dev_idx]->SetColorDescription((unsigned char *)data); - controllers[header.pkt_dev_idx]->UpdateLEDs(); - } - } - else - { - LOG_ERROR("[NetworkServer] UpdateLEDs packet has invalid size. Packet size: %d, Data size: %d", header.pkt_size, *((unsigned int*)data)); - goto listen_done; - } - break; - - case NET_PACKET_ID_RGBCONTROLLER_UPDATEZONELEDS: - if(data == NULL) - { - break; - } - - /*---------------------------------------------------------*\ - | Verify the color description size (first 4 bytes of data) | - | matches the packet size in the header | - | | - | If protocol version is 4 or below and the legacy SDK | - | compatibility workaround is enabled, ignore this check. | - | This allows backwards compatibility with old versions of | - | SDK applications that didn't properly implement the size | - | field. | - \*---------------------------------------------------------*/ - if((header.pkt_size == *((unsigned int*)data)) - || ((client_info->client_protocol_version <= 4) - && (legacy_workaround_enabled))) - { - if(header.pkt_dev_idx < controllers.size()) - { - int zone; - - memcpy(&zone, &data[sizeof(unsigned int)], sizeof(int)); - - controllers[header.pkt_dev_idx]->SetZoneColorDescription((unsigned char *)data); - controllers[header.pkt_dev_idx]->UpdateZoneLEDs(zone); - } - } - else - { - LOG_ERROR("[NetworkServer] UpdateZoneLEDs packet has invalid size. Packet size: %d, Data size: %d", header.pkt_size, *((unsigned int*)data)); - goto listen_done; - } - break; - - case NET_PACKET_ID_RGBCONTROLLER_UPDATESINGLELED: - if(data == NULL) - { - break; - } - - /*---------------------------------------------------------*\ + /*---------------------------------------------------------*\ | Verify the single LED color description size (8 bytes) | | matches the packet size in the header | \*---------------------------------------------------------*/ - if(header.pkt_size == (sizeof(int) + sizeof(RGBColor))) - { - if(header.pkt_dev_idx < controllers.size()) - { - int led; + if (header.pkt_size == (sizeof(int) + sizeof(RGBColor))) { + if (header.pkt_dev_idx < controllers.size()) { + int led; - memcpy(&led, data, sizeof(int)); + memcpy(&led, data, sizeof(int)); - controllers[header.pkt_dev_idx]->SetSingleLEDColorDescription((unsigned char *)data); - controllers[header.pkt_dev_idx]->UpdateSingleLED(led); - } - } - else - { - LOG_ERROR("[NetworkServer] UpdateSingleLED packet has invalid size. Packet size: %d, Data size: %d", header.pkt_size, (sizeof(int) + sizeof(RGBColor))); - goto listen_done; + controllers[header.pkt_dev_idx]->SetSingleLEDColorDescription( + (unsigned char *) data); + controllers[header.pkt_dev_idx]->UpdateSingleLED(led); } + } else { + LOG_ERROR("[NetworkServer] UpdateSingleLED packet has invalid size. Packet size: " + "%d, Data size: %d", + header.pkt_size, + (sizeof(int) + sizeof(RGBColor))); + goto listen_done; + } + break; + + case NET_PACKET_ID_RGBCONTROLLER_SETCUSTOMMODE: + if (header.pkt_dev_idx < controllers.size()) { + controllers[header.pkt_dev_idx]->SetCustomMode(); + } + break; + + case NET_PACKET_ID_RGBCONTROLLER_UPDATEMODE: + if (data == NULL) { break; + } - case NET_PACKET_ID_RGBCONTROLLER_SETCUSTOMMODE: - if(header.pkt_dev_idx < controllers.size()) - { - controllers[header.pkt_dev_idx]->SetCustomMode(); - } - break; - - case NET_PACKET_ID_RGBCONTROLLER_UPDATEMODE: - if(data == NULL) - { - break; - } - - /*---------------------------------------------------------*\ + /*---------------------------------------------------------*\ | Verify the mode description size (first 4 bytes of data) | | matches the packet size in the header | | | @@ -809,30 +754,29 @@ void NetworkServer::ListenThreadFunction(NetworkClientInfo * client_info) | SDK applications that didn't properly implement the size | | field. | \*---------------------------------------------------------*/ - if((header.pkt_size == *((unsigned int*)data)) - || ((client_info->client_protocol_version <= 4) - && (legacy_workaround_enabled))) - { - if(header.pkt_dev_idx < controllers.size()) - { - controllers[header.pkt_dev_idx]->SetModeDescription((unsigned char *)data, client_info->client_protocol_version); - controllers[header.pkt_dev_idx]->UpdateMode(); - } - } - else - { - LOG_ERROR("[NetworkServer] UpdateMode packet has invalid size. Packet size: %d, Data size: %d", header.pkt_size, *((unsigned int*)data)); - goto listen_done; + if ((header.pkt_size == *((unsigned int *) data)) + || ((client_info->client_protocol_version <= 4) && (legacy_workaround_enabled))) { + if (header.pkt_dev_idx < controllers.size()) { + controllers[header.pkt_dev_idx] + ->SetModeDescription((unsigned char *) data, + client_info->client_protocol_version); + controllers[header.pkt_dev_idx]->UpdateMode(); } + } else { + LOG_ERROR("[NetworkServer] UpdateMode packet has invalid size. Packet size: %d, " + "Data size: %d", + header.pkt_size, + *((unsigned int *) data)); + goto listen_done; + } + break; + + case NET_PACKET_ID_RGBCONTROLLER_SAVEMODE: + if (data == NULL) { break; + } - case NET_PACKET_ID_RGBCONTROLLER_SAVEMODE: - if(data == NULL) - { - break; - } - - /*---------------------------------------------------------*\ + /*---------------------------------------------------------*\ | Verify the mode description size (first 4 bytes of data) | | matches the packet size in the header | | | @@ -842,131 +786,116 @@ void NetworkServer::ListenThreadFunction(NetworkClientInfo * client_info) | SDK applications that didn't properly implement the size | | field. | \*---------------------------------------------------------*/ - if((header.pkt_size == *((unsigned int*)data)) - || ((client_info->client_protocol_version <= 4) - && (legacy_workaround_enabled))) - { - if(header.pkt_dev_idx < controllers.size()) - { - controllers[header.pkt_dev_idx]->SetModeDescription((unsigned char *)data, client_info->client_protocol_version); - controllers[header.pkt_dev_idx]->SaveMode(); - } + if ((header.pkt_size == *((unsigned int *) data)) + || ((client_info->client_protocol_version <= 4) && (legacy_workaround_enabled))) { + if (header.pkt_dev_idx < controllers.size()) { + controllers[header.pkt_dev_idx] + ->SetModeDescription((unsigned char *) data, + client_info->client_protocol_version); + controllers[header.pkt_dev_idx]->SaveMode(); } + } + break; + + case NET_PACKET_ID_REQUEST_PROFILE_LIST: + SendReply_ProfileList(client_sock); + break; + + case NET_PACKET_ID_REQUEST_SAVE_PROFILE: + if (data == NULL) { break; + } - case NET_PACKET_ID_REQUEST_PROFILE_LIST: - SendReply_ProfileList(client_sock); + if (profile_manager) { + std::string profile_name; + profile_name.assign(data, header.pkt_size); + + profile_manager->SaveProfile(profile_name); + } + + break; + + case NET_PACKET_ID_REQUEST_LOAD_PROFILE: + if (data == NULL) { break; + } - case NET_PACKET_ID_REQUEST_SAVE_PROFILE: - if(data == NULL) - { - break; - } + if (profile_manager) { + std::string profile_name; + profile_name.assign(data, header.pkt_size); - if(profile_manager) - { - std::string profile_name; - profile_name.assign(data, header.pkt_size); + profile_manager->LoadProfile(profile_name); + } - profile_manager->SaveProfile(profile_name); - } + for (RGBController *controller : controllers) { + controller->UpdateLEDs(); + } + break; + + case NET_PACKET_ID_REQUEST_DELETE_PROFILE: + if (data == NULL) { break; + } - case NET_PACKET_ID_REQUEST_LOAD_PROFILE: - if(data == NULL) - { - break; - } - - if(profile_manager) - { - std::string profile_name; - profile_name.assign(data, header.pkt_size); - - profile_manager->LoadProfile(profile_name); - } - - for(RGBController* controller : controllers) - { - controller->UpdateLEDs(); + if (profile_manager) { + std::string profile_name; + profile_name.assign(data, header.pkt_size); + + profile_manager->DeleteProfile(profile_name); + } + + break; + + case NET_PACKET_ID_REQUEST_PLUGIN_LIST: + SendReply_PluginList(client_sock); + break; + + case NET_PACKET_ID_PLUGIN_SPECIFIC: { + unsigned int plugin_pkt_type = *((unsigned int *) (data)); + unsigned int plugin_pkt_size = header.pkt_size - (sizeof(unsigned int)); + unsigned char *plugin_data = (unsigned char *) (data + sizeof(unsigned int)); + + if (header.pkt_dev_idx < plugins.size()) { + NetworkPlugin plugin = plugins[header.pkt_dev_idx]; + unsigned char *output = plugin.callback(plugin.callback_arg, + plugin_pkt_type, + plugin_data, + &plugin_pkt_size); + if (output != nullptr) { + SendReply_PluginSpecific(client_sock, plugin_pkt_type, output, plugin_pkt_size); } + } + break; + } break; + case NET_PACKET_ID_RGBCONTROLLER_CLEARSEGMENTS: + if (data == NULL) { break; + } - case NET_PACKET_ID_REQUEST_DELETE_PROFILE: - if(data == NULL) - { - break; - } + if ((header.pkt_dev_idx < controllers.size()) && (header.pkt_size == sizeof(int))) { + int zone; - if(profile_manager) - { - std::string profile_name; - profile_name.assign(data, header.pkt_size); + memcpy(&zone, data, sizeof(int)); - profile_manager->DeleteProfile(profile_name); - } + controllers[header.pkt_dev_idx]->ClearSegments(zone); + profile_manager->SaveProfile("sizes", true); + } + break; - break; - - case NET_PACKET_ID_REQUEST_PLUGIN_LIST: - SendReply_PluginList(client_sock); - break; - - case NET_PACKET_ID_PLUGIN_SPECIFIC: - { - unsigned int plugin_pkt_type = *((unsigned int*)(data)); - unsigned int plugin_pkt_size = header.pkt_size - (sizeof(unsigned int)); - unsigned char* plugin_data = (unsigned char*)(data + sizeof(unsigned int)); - - if(header.pkt_dev_idx < plugins.size()) - { - NetworkPlugin plugin = plugins[header.pkt_dev_idx]; - unsigned char* output = plugin.callback(plugin.callback_arg, plugin_pkt_type, plugin_data, &plugin_pkt_size); - if(output != nullptr) - { - SendReply_PluginSpecific(client_sock, plugin_pkt_type, output, plugin_pkt_size); - } - } - break; - } - break; - - case NET_PACKET_ID_RGBCONTROLLER_CLEARSEGMENTS: - if(data == NULL) - { - break; - } - - if((header.pkt_dev_idx < controllers.size()) && (header.pkt_size == sizeof(int))) - { - int zone; - - memcpy(&zone, data, sizeof(int)); - - controllers[header.pkt_dev_idx]->ClearSegments(zone); - profile_manager->SaveProfile("sizes", true); - } - break; - - case NET_PACKET_ID_RGBCONTROLLER_ADDSEGMENT: - { - /*---------------------------------------------------------*\ + case NET_PACKET_ID_RGBCONTROLLER_ADDSEGMENT: { + /*---------------------------------------------------------*\ | Verify the segment description size (first 4 bytes of | | data) matches the packet size in the header | \*---------------------------------------------------------*/ - if(header.pkt_size == *((unsigned int*)data)) - { - if(header.pkt_dev_idx < controllers.size()) - { - controllers[header.pkt_dev_idx]->SetSegmentDescription((unsigned char *)data); - profile_manager->SaveProfile("sizes", true); - } - } + if (header.pkt_size == *((unsigned int *) data)) { + if (header.pkt_dev_idx < controllers.size()) { + controllers[header.pkt_dev_idx]->SetSegmentDescription((unsigned char *) data); + profile_manager->SaveProfile("sizes", true); } - break; + } + } break; } delete[] data; @@ -976,10 +905,8 @@ listen_done: ServerClientsMutex.lock(); - for(unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++) - { - if(ServerClients[this_idx] == client_info) - { + for (unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++) { + if (ServerClients[this_idx] == client_info) { delete client_info; ServerClients.erase(ServerClients.begin() + this_idx); break; @@ -996,25 +923,23 @@ listen_done: ClientInfoChanged(); } -void NetworkServer::ProcessRequest_ClientProtocolVersion(SOCKET client_sock, unsigned int data_size, char * data) +void NetworkServer::ProcessRequest_ClientProtocolVersion(SOCKET client_sock, + unsigned int data_size, + char *data) { unsigned int protocol_version = 0; - if(data_size == sizeof(unsigned int) && (data != NULL)) - { + if (data_size == sizeof(unsigned int) && (data != NULL)) { memcpy(&protocol_version, data, sizeof(unsigned int)); } - if(protocol_version > OPENRGB_SDK_PROTOCOL_VERSION) - { + if (protocol_version > OPENRGB_SDK_PROTOCOL_VERSION) { protocol_version = OPENRGB_SDK_PROTOCOL_VERSION; } ServerClientsMutex.lock(); - for(unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++) - { - if(ServerClients[this_idx]->client_sock == client_sock) - { + for (unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++) { + if (ServerClients[this_idx]->client_sock == client_sock) { ServerClients[this_idx]->client_protocol_version = protocol_version; break; } @@ -1027,13 +952,13 @@ void NetworkServer::ProcessRequest_ClientProtocolVersion(SOCKET client_sock, uns ClientInfoChanged(); } -void NetworkServer::ProcessRequest_ClientString(SOCKET client_sock, unsigned int data_size, char * data) +void NetworkServer::ProcessRequest_ClientString(SOCKET client_sock, + unsigned int data_size, + char *data) { ServerClientsMutex.lock(); - for(unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++) - { - if(ServerClients[this_idx]->client_sock == client_sock) - { + for (unsigned int this_idx = 0; this_idx < ServerClients.size(); this_idx++) { + if (ServerClients[this_idx]->client_sock == client_sock) { ServerClients[this_idx]->client_string.assign(data, data_size); break; } @@ -1049,30 +974,31 @@ void NetworkServer::ProcessRequest_ClientString(SOCKET client_sock, unsigned int void NetworkServer::SendReply_ControllerCount(SOCKET client_sock) { NetPacketHeader reply_hdr; - unsigned int reply_data; + unsigned int reply_data; InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_CONTROLLER_COUNT, sizeof(unsigned int)); - reply_data = (unsigned int)controllers.size(); + reply_data = (unsigned int) controllers.size(); - send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0); - send(client_sock, (const char *)&reply_data, sizeof(unsigned int), 0); + send(client_sock, (const char *) &reply_hdr, sizeof(NetPacketHeader), 0); + send(client_sock, (const char *) &reply_data, sizeof(unsigned int), 0); } -void NetworkServer::SendReply_ControllerData(SOCKET client_sock, unsigned int dev_idx, unsigned int protocol_version) +void NetworkServer::SendReply_ControllerData(SOCKET client_sock, + unsigned int dev_idx, + unsigned int protocol_version) { - if(dev_idx < controllers.size()) - { + if (dev_idx < controllers.size()) { NetPacketHeader reply_hdr; unsigned char *reply_data = controllers[dev_idx]->GetDeviceDescription(protocol_version); - unsigned int reply_size; + unsigned int reply_size; memcpy(&reply_size, reply_data, sizeof(reply_size)); InitNetPacketHeader(&reply_hdr, dev_idx, NET_PACKET_ID_REQUEST_CONTROLLER_DATA, reply_size); - send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0); - send(client_sock, (const char *)reply_data, reply_size, 0); + send(client_sock, (const char *) &reply_hdr, sizeof(NetPacketHeader), 0); + send(client_sock, (const char *) reply_data, reply_size, 0); delete[] reply_data; } @@ -1081,14 +1007,14 @@ void NetworkServer::SendReply_ControllerData(SOCKET client_sock, unsigned int de void NetworkServer::SendReply_ProtocolVersion(SOCKET client_sock) { NetPacketHeader reply_hdr; - unsigned int reply_data; + unsigned int reply_data; InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_PROTOCOL_VERSION, sizeof(unsigned int)); reply_data = OPENRGB_SDK_PROTOCOL_VERSION; - send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0); - send(client_sock, (const char *)&reply_data, sizeof(unsigned int), 0); + send(client_sock, (const char *) &reply_hdr, sizeof(NetPacketHeader), 0); + send(client_sock, (const char *) &reply_data, sizeof(unsigned int), 0); } void NetworkServer::SendRequest_DeviceListChanged(SOCKET client_sock) @@ -1097,13 +1023,12 @@ void NetworkServer::SendRequest_DeviceListChanged(SOCKET client_sock) InitNetPacketHeader(&pkt_hdr, 0, NET_PACKET_ID_DEVICE_LIST_UPDATED, 0); - send(client_sock, (char *)&pkt_hdr, sizeof(NetPacketHeader), 0); + send(client_sock, (char *) &pkt_hdr, sizeof(NetPacketHeader), 0); } void NetworkServer::SendReply_ProfileList(SOCKET client_sock) { - if(!profile_manager) - { + if (!profile_manager) { return; } @@ -1115,8 +1040,8 @@ void NetworkServer::SendReply_ProfileList(SOCKET client_sock) InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_PROFILE_LIST, reply_size); - send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0); - send(client_sock, (const char *)reply_data, reply_size, 0); + send(client_sock, (const char *) &reply_hdr, sizeof(NetPacketHeader), 0); + send(client_sock, (const char *) reply_data, reply_size, 0); } void NetworkServer::SendReply_PluginList(SOCKET client_sock) @@ -1127,17 +1052,16 @@ void NetworkServer::SendReply_PluginList(SOCKET client_sock) /*---------------------------------------------------------*\ | Calculate data size | \*---------------------------------------------------------*/ - unsigned short num_plugins = (unsigned short)plugins.size(); + unsigned short num_plugins = (unsigned short) plugins.size(); data_size += sizeof(data_size); data_size += sizeof(num_plugins); - for(unsigned int i = 0; i < num_plugins; i++) - { + for (unsigned int i = 0; i < num_plugins; i++) { data_size += sizeof(unsigned short) * 3; - data_size += (unsigned int)strlen(plugins[i].name.c_str()) + 1; - data_size += (unsigned int)strlen(plugins[i].description.c_str()) + 1; - data_size += (unsigned int)strlen(plugins[i].version.c_str()) + 1; + data_size += (unsigned int) strlen(plugins[i].name.c_str()) + 1; + data_size += (unsigned int) strlen(plugins[i].description.c_str()) + 1; + data_size += (unsigned int) strlen(plugins[i].version.c_str()) + 1; data_size += sizeof(unsigned int) * 2; } @@ -1158,39 +1082,38 @@ void NetworkServer::SendReply_PluginList(SOCKET client_sock) memcpy(&data_buf[data_ptr], &num_plugins, sizeof(num_plugins)); data_ptr += sizeof(num_plugins); - for(unsigned int i = 0; i < num_plugins; i++) - { + for (unsigned int i = 0; i < num_plugins; i++) { /*---------------------------------------------------------*\ | Copy in plugin name (size+data) | \*---------------------------------------------------------*/ - unsigned short str_len = (unsigned short)strlen(plugins[i].name.c_str()) + 1; + unsigned short str_len = (unsigned short) strlen(plugins[i].name.c_str()) + 1; memcpy(&data_buf[data_ptr], &str_len, sizeof(unsigned short)); data_ptr += sizeof(unsigned short); - strcpy((char *)&data_buf[data_ptr], plugins[i].name.c_str()); + strcpy((char *) &data_buf[data_ptr], plugins[i].name.c_str()); data_ptr += str_len; /*---------------------------------------------------------*\ | Copy in plugin description (size+data) | \*---------------------------------------------------------*/ - str_len = (unsigned short)strlen(plugins[i].description.c_str()) + 1; + str_len = (unsigned short) strlen(plugins[i].description.c_str()) + 1; memcpy(&data_buf[data_ptr], &str_len, sizeof(unsigned short)); data_ptr += sizeof(unsigned short); - strcpy((char *)&data_buf[data_ptr], plugins[i].description.c_str()); + strcpy((char *) &data_buf[data_ptr], plugins[i].description.c_str()); data_ptr += str_len; /*---------------------------------------------------------*\ | Copy in plugin version (size+data) | \*---------------------------------------------------------*/ - str_len = (unsigned short)strlen(plugins[i].version.c_str()) + 1; + str_len = (unsigned short) strlen(plugins[i].version.c_str()) + 1; memcpy(&data_buf[data_ptr], &str_len, sizeof(unsigned short)); data_ptr += sizeof(unsigned short); - strcpy((char *)&data_buf[data_ptr], plugins[i].version.c_str()); + strcpy((char *) &data_buf[data_ptr], plugins[i].version.c_str()); data_ptr += str_len; /*---------------------------------------------------------*\ @@ -1213,25 +1136,28 @@ void NetworkServer::SendReply_PluginList(SOCKET client_sock) InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_REQUEST_PLUGIN_LIST, reply_size); - send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0); - send(client_sock, (const char *)data_buf, reply_size, 0); + send(client_sock, (const char *) &reply_hdr, sizeof(NetPacketHeader), 0); + send(client_sock, (const char *) data_buf, reply_size, 0); - delete [] data_buf; + delete[] data_buf; } -void NetworkServer::SendReply_PluginSpecific(SOCKET client_sock, unsigned int pkt_type, unsigned char* data, unsigned int data_size) +void NetworkServer::SendReply_PluginSpecific(SOCKET client_sock, + unsigned int pkt_type, + unsigned char *data, + unsigned int data_size) { NetPacketHeader reply_hdr; InitNetPacketHeader(&reply_hdr, 0, NET_PACKET_ID_PLUGIN_SPECIFIC, data_size + sizeof(pkt_type)); - send(client_sock, (const char *)&reply_hdr, sizeof(NetPacketHeader), 0); - send(client_sock, (const char *)&pkt_type, sizeof(pkt_type), 0); - send(client_sock, (const char *)data, data_size, 0); - delete [] data; + send(client_sock, (const char *) &reply_hdr, sizeof(NetPacketHeader), 0); + send(client_sock, (const char *) &pkt_type, sizeof(pkt_type), 0); + send(client_sock, (const char *) data, data_size, 0); + delete[] data; } -void NetworkServer::SetProfileManager(ProfileManagerInterface* profile_manager_pointer) +void NetworkServer::SetProfileManager(ProfileManagerInterface *profile_manager_pointer) { profile_manager = profile_manager_pointer; } @@ -1243,10 +1169,8 @@ void NetworkServer::RegisterPlugin(NetworkPlugin plugin) void NetworkServer::UnregisterPlugin(std::string plugin_name) { - for(std::vector::iterator it = plugins.begin(); it != plugins.end(); it++) - { - if(it->name == plugin_name) - { + for (std::vector::iterator it = plugins.begin(); it != plugins.end(); it++) { + if (it->name == plugin_name) { plugins.erase(it); break; } diff --git a/NetworkServer.h b/NetworkServer.h index 8d9f91062..07544bcd3 100644 --- a/NetworkServer.h +++ b/NetworkServer.h @@ -23,7 +23,7 @@ #define TCP_TIMEOUT_SECONDS 5 typedef void (*NetServerCallback)(void *); -typedef unsigned char* (*NetPluginCallback)(void *, unsigned int, unsigned char*, unsigned int*); +typedef unsigned char *(*NetPluginCallback)(void *, unsigned int, unsigned char *, unsigned int *); struct NetworkPlugin { @@ -31,7 +31,7 @@ struct NetworkPlugin std::string description; std::string version; NetPluginCallback callback; - void* callback_arg; + void *callback_arg; unsigned int protocol_version; }; @@ -41,95 +41,102 @@ public: NetworkClientInfo(); ~NetworkClientInfo(); - SOCKET client_sock; - std::thread * client_listen_thread; - std::string client_string; - unsigned int client_protocol_version; - std::string client_ip; + SOCKET client_sock; + std::thread *client_listen_thread; + std::string client_string; + unsigned int client_protocol_version; + std::string client_ip; }; class NetworkServer { public: - NetworkServer(std::vector& control); + NetworkServer(std::vector &control); ~NetworkServer(); - std::string GetHost(); - unsigned short GetPort(); - bool GetOnline(); - bool GetListening(); - unsigned int GetNumClients(); - const char * GetClientString(unsigned int client_num); - const char * GetClientIP(unsigned int client_num); - unsigned int GetClientProtocolVersion(unsigned int client_num); + std::string GetHost(); + unsigned short GetPort(); + bool GetOnline(); + bool GetListening(); + unsigned int GetNumClients(); + const char *GetClientString(unsigned int client_num); + const char *GetClientIP(unsigned int client_num); + unsigned int GetClientProtocolVersion(unsigned int client_num); - void ClientInfoChanged(); - void DeviceListChanged(); - void RegisterClientInfoChangeCallback(NetServerCallback, void * new_callback_arg); + void ClientInfoChanged(); + void DeviceListChanged(); + void RegisterClientInfoChangeCallback(NetServerCallback, void *new_callback_arg); - void ServerListeningChanged(); - void RegisterServerListeningChangeCallback(NetServerCallback, void * new_callback_arg); + void ServerListeningChanged(); + void RegisterServerListeningChangeCallback(NetServerCallback, void *new_callback_arg); - void SetHost(std::string host); - void SetLegacyWorkaroundEnable(bool enable); - void SetPort(unsigned short new_port); + void SetHost(std::string host); + void SetLegacyWorkaroundEnable(bool enable); + void SetPort(unsigned short new_port); - void StartServer(); - void StopServer(); + void StartServer(); + void StopServer(); - void ConnectionThreadFunction(int socket_idx); - void ListenThreadFunction(NetworkClientInfo * client_sock); + void ConnectionThreadFunction(int socket_idx); + void ListenThreadFunction(NetworkClientInfo *client_sock); - void ProcessRequest_ClientProtocolVersion(SOCKET client_sock, unsigned int data_size, char * data); - void ProcessRequest_ClientString(SOCKET client_sock, unsigned int data_size, char * data); + void ProcessRequest_ClientProtocolVersion(SOCKET client_sock, + unsigned int data_size, + char *data); + void ProcessRequest_ClientString(SOCKET client_sock, unsigned int data_size, char *data); - void SendReply_ControllerCount(SOCKET client_sock); - void SendReply_ControllerData(SOCKET client_sock, unsigned int dev_idx, unsigned int protocol_version); - void SendReply_ProtocolVersion(SOCKET client_sock); + void SendReply_ControllerCount(SOCKET client_sock); + void SendReply_ControllerData(SOCKET client_sock, + unsigned int dev_idx, + unsigned int protocol_version); + void SendReply_ProtocolVersion(SOCKET client_sock); - void SendRequest_DeviceListChanged(SOCKET client_sock); - void SendReply_ProfileList(SOCKET client_sock); - void SendReply_PluginList(SOCKET client_sock); - void SendReply_PluginSpecific(SOCKET client_sock, unsigned int pkt_type, unsigned char* data, unsigned int data_size); + void SendRequest_DeviceListChanged(SOCKET client_sock); + void SendReply_ProfileList(SOCKET client_sock); + void SendReply_PluginList(SOCKET client_sock); + void SendReply_PluginSpecific(SOCKET client_sock, + unsigned int pkt_type, + unsigned char *data, + unsigned int data_size); - void SetProfileManager(ProfileManagerInterface* profile_manager_pointer); + void SetProfileManager(ProfileManagerInterface *profile_manager_pointer); - void RegisterPlugin(NetworkPlugin plugin); - void UnregisterPlugin(std::string plugin_name); + void RegisterPlugin(NetworkPlugin plugin); + void UnregisterPlugin(std::string plugin_name); protected: - std::string host; - unsigned short port_num; - std::atomic server_online; - std::atomic server_listening; + std::string host; + unsigned short port_num; + std::atomic server_online; + std::atomic server_listening; - std::vector& controllers; + std::vector &controllers; - std::mutex ServerClientsMutex; - std::vector ServerClients; - std::thread * ConnectionThread[MAXSOCK]; + std::mutex ServerClientsMutex; + std::vector ServerClients; + std::thread *ConnectionThread[MAXSOCK]; - std::mutex ClientInfoChangeMutex; - std::vector ClientInfoChangeCallbacks; - std::vector ClientInfoChangeCallbackArgs; + std::mutex ClientInfoChangeMutex; + std::vector ClientInfoChangeCallbacks; + std::vector ClientInfoChangeCallbackArgs; - std::mutex ServerListeningChangeMutex; - std::vector ServerListeningChangeCallbacks; - std::vector ServerListeningChangeCallbackArgs; + std::mutex ServerListeningChangeMutex; + std::vector ServerListeningChangeCallbacks; + std::vector ServerListeningChangeCallbackArgs; - ProfileManagerInterface* profile_manager; + ProfileManagerInterface *profile_manager; - std::vector plugins; + std::vector plugins; private: #ifdef WIN32 - WSADATA wsa; + WSADATA wsa; #endif - bool legacy_workaround_enabled; - int socket_count; - SOCKET server_sock[MAXSOCK]; + bool legacy_workaround_enabled; + int socket_count; + SOCKET server_sock[MAXSOCK]; - int accept_select(int sockfd); - int recv_select(SOCKET s, char *buf, int len, int flags); + int accept_select(int sockfd); + int recv_select(SOCKET s, char *buf, int len, int flags); }; diff --git a/OpenRGB.pro b/OpenRGB.pro index 0f235a258..1d01239eb 100644 --- a/OpenRGB.pro +++ b/OpenRGB.pro @@ -170,6 +170,8 @@ HEADERS += $$GUI_H \ $$CONTROLLER_H \ Colors.h \ + Controllers/MachenikeG5ProController/MachenikeG5ProController.h \ + Controllers/MachenikeG5ProController/RGBController_MachenikeG5Pro.h \ dependencies/ColorWheel/ColorWheel.h \ dependencies/json/nlohmann/json.hpp \ LogManager.h \ @@ -210,6 +212,9 @@ HEADERS += SOURCES += \ $$GUI_CPP \ $$CONTROLLER_CPP \ + Controllers/MachenikeG5ProController/MachenikeG5ProController.cpp \ + Controllers/MachenikeG5ProController/MachenikeG5ProControllerDetect.cpp \ + Controllers/MachenikeG5ProController/RGBController_MachenikeG5Pro.cpp \ dependencies/ColorWheel/ColorWheel.cpp \ dependencies/hueplusplus-1.2.0/src/Action.cpp \ dependencies/hueplusplus-1.2.0/src/APICache.cpp \ diff --git a/OpenRGBPluginInterface.h b/OpenRGBPluginInterface.h index 13d72d465..199f9e807 100644 --- a/OpenRGBPluginInterface.h +++ b/OpenRGBPluginInterface.h @@ -17,7 +17,7 @@ #include #include "ResourceManagerInterface.h" -#define OpenRGBPluginInterface_IID "com.OpenRGBPluginInterface" +#define OpenRGBPluginInterface_IID "com.OpenRGBPluginInterface" /*-----------------------------------------------------------------------------------------------------*\ | OpenRGB Plugin API Versions | @@ -27,17 +27,16 @@ | 3: OpenRGB 0.9 Use filesystem::path for paths, Added segments | | 4: OpenRGB 1.0 Resizable effects-only zones, zone flags | \*-----------------------------------------------------------------------------------------------------*/ -#define OPENRGB_PLUGIN_API_VERSION 4 +#define OPENRGB_PLUGIN_API_VERSION 4 /*-----------------------------------------------------------------------------------------------------*\ | Plugin Tab Location Values | \*-----------------------------------------------------------------------------------------------------*/ -enum -{ - OPENRGB_PLUGIN_LOCATION_TOP = 0, /* Top-level tab (no icon) */ - OPENRGB_PLUGIN_LOCATION_DEVICES = 1, /* Devices tab */ - OPENRGB_PLUGIN_LOCATION_INFORMATION = 2, /* Information tab */ - OPENRGB_PLUGIN_LOCATION_SETTINGS = 3, /* Settings tab */ +enum { + OPENRGB_PLUGIN_LOCATION_TOP = 0, /* Top-level tab (no icon) */ + OPENRGB_PLUGIN_LOCATION_DEVICES = 1, /* Devices tab */ + OPENRGB_PLUGIN_LOCATION_INFORMATION = 2, /* Information tab */ + OPENRGB_PLUGIN_LOCATION_SETTINGS = 3, /* Settings tab */ }; struct OpenRGBPluginInfo @@ -45,42 +44,42 @@ struct OpenRGBPluginInfo /*-------------------------------------------------------------------------------------------------*\ | Plugin Details | \*-------------------------------------------------------------------------------------------------*/ - std::string Name; /* Plugin name string */ - std::string Description; /* Plugin description string */ - std::string Version; /* Plugin version string */ - std::string Commit; /* Plugin commit (git or otherwise) string */ - std::string URL; /* Plugin project URL string */ - QImage Icon; /* Icon image (displayed 64x64) */ + std::string Name; /* Plugin name string */ + std::string Description; /* Plugin description string */ + std::string Version; /* Plugin version string */ + std::string Commit; /* Plugin commit (git or otherwise) string */ + std::string URL; /* Plugin project URL string */ + QImage Icon; /* Icon image (displayed 64x64) */ /*-------------------------------------------------------------------------------------------------*\ | Plugin Tab Configuration | \*-------------------------------------------------------------------------------------------------*/ - unsigned int Location; /* Plugin tab location from Plugin Tab Location enum */ - /* This field is mandatory, an invalid value will */ - /* prevent plugin tab from being displayed */ - std::string Label; /* Plugin tab label string */ - std::string TabIconString; /* Plugin tab icon string, leave empty to use custom */ - QImage TabIcon; /* Custom tab icon image (displayed 16x16) */ + unsigned int Location; /* Plugin tab location from Plugin Tab Location enum */ + /* This field is mandatory, an invalid value will */ + /* prevent plugin tab from being displayed */ + std::string Label; /* Plugin tab label string */ + std::string TabIconString; /* Plugin tab icon string, leave empty to use custom */ + QImage TabIcon; /* Custom tab icon image (displayed 16x16) */ }; class OpenRGBPluginInterface { public: - virtual ~OpenRGBPluginInterface() {} + virtual ~OpenRGBPluginInterface() {} /*-------------------------------------------------------------------------------------------------*\ | Plugin Information | \*-------------------------------------------------------------------------------------------------*/ - virtual OpenRGBPluginInfo GetPluginInfo() = 0; - virtual unsigned int GetPluginAPIVersion() = 0; + virtual OpenRGBPluginInfo GetPluginInfo() = 0; + virtual unsigned int GetPluginAPIVersion() = 0; /*-------------------------------------------------------------------------------------------------*\ | Plugin Functionality | \*-------------------------------------------------------------------------------------------------*/ - virtual void Load(ResourceManagerInterface* resource_manager_ptr) = 0; - virtual QWidget* GetWidget() = 0; - virtual QMenu* GetTrayMenu() = 0; - virtual void Unload() = 0; + virtual void Load(ResourceManagerInterface *resource_manager_ptr) = 0; + virtual QWidget *GetWidget() = 0; + virtual QMenu *GetTrayMenu() = 0; + virtual void Unload() = 0; }; Q_DECLARE_INTERFACE(OpenRGBPluginInterface, OpenRGBPluginInterface_IID) diff --git a/PluginManager.cpp b/PluginManager.cpp index 157b6cd5a..e612e956e 100644 --- a/PluginManager.cpp +++ b/PluginManager.cpp @@ -23,26 +23,28 @@ PluginManager::PluginManager() /*---------------------------------------------------------*\ | Initialize plugin manager class variables | \*---------------------------------------------------------*/ - AddPluginCallbackVal = nullptr; - AddPluginCallbackArg = nullptr; + AddPluginCallbackVal = nullptr; + AddPluginCallbackArg = nullptr; RemovePluginCallbackVal = nullptr; RemovePluginCallbackArg = nullptr; /*-------------------------------------------------------------------------*\ | Create OpenRGB plugins directory | \*-------------------------------------------------------------------------*/ - filesystem::path plugins_dir = ResourceManager::get()->GetConfigurationDirectory() / plugins_path; + filesystem::path plugins_dir = ResourceManager::get()->GetConfigurationDirectory() + / plugins_path; filesystem::create_directories(plugins_dir); } -void PluginManager::RegisterAddPluginCallback(AddPluginCallback new_callback, void * new_callback_arg) +void PluginManager::RegisterAddPluginCallback(AddPluginCallback new_callback, void *new_callback_arg) { - AddPluginCallbackVal = new_callback; - AddPluginCallbackArg = new_callback_arg; + AddPluginCallbackVal = new_callback; + AddPluginCallbackArg = new_callback_arg; } -void PluginManager::RegisterRemovePluginCallback(RemovePluginCallback new_callback, void * new_callback_arg) +void PluginManager::RegisterRemovePluginCallback(RemovePluginCallback new_callback, + void *new_callback_arg) { RemovePluginCallbackVal = new_callback; RemovePluginCallbackArg = new_callback_arg; @@ -56,7 +58,8 @@ void PluginManager::ScanAndLoadPlugins() | The user plugins directory is a directory named "plugins" | | in the configuration directory | \*---------------------------------------------------------*/ - filesystem::path plugins_dir = ResourceManager::get()->GetConfigurationDirectory() / plugins_path; + filesystem::path plugins_dir = ResourceManager::get()->GetConfigurationDirectory() + / plugins_path; ScanAndLoadPluginsFrom(plugins_dir, false); #ifdef OPENRGB_SYSTEM_PLUGIN_DIRECTORY @@ -89,19 +92,17 @@ void PluginManager::ScanAndLoadPlugins() #endif } -void PluginManager::ScanAndLoadPluginsFrom(const filesystem::path & plugins_dir, bool is_system) +void PluginManager::ScanAndLoadPluginsFrom(const filesystem::path &plugins_dir, bool is_system) { - if(is_system) - { - LOG_TRACE("[PluginManager] Scanning system plugin directory: %s", plugins_dir.generic_u8string().c_str()); - } - else - { - LOG_TRACE("[PluginManager] Scanning user plugin directory: %s", plugins_dir.generic_u8string().c_str()); + if (is_system) { + LOG_TRACE("[PluginManager] Scanning system plugin directory: %s", + plugins_dir.generic_u8string().c_str()); + } else { + LOG_TRACE("[PluginManager] Scanning user plugin directory: %s", + plugins_dir.generic_u8string().c_str()); } - if(!filesystem::is_directory(plugins_dir)) - { + if (!filesystem::is_directory(plugins_dir)) { return; } @@ -109,22 +110,21 @@ void PluginManager::ScanAndLoadPluginsFrom(const filesystem::path & plugins_dir, | Get a list of all files in the plugins directory | \*---------------------------------------------------------*/ - for(const filesystem::directory_entry& entry: filesystem::directory_iterator(plugins_dir)) - { - if(filesystem::is_directory(entry.path())) - { + for (const filesystem::directory_entry &entry : filesystem::directory_iterator(plugins_dir)) { + if (filesystem::is_directory(entry.path())) { continue; } filesystem::path plugin_path = entry.path(); - LOG_TRACE("[PluginManager] Found plugin file %s", plugin_path.filename().generic_u8string().c_str()); + LOG_TRACE("[PluginManager] Found plugin file %s", + plugin_path.filename().generic_u8string().c_str()); AddPlugin(plugin_path, is_system); } } -void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) +void PluginManager::AddPlugin(const filesystem::path &path, bool is_system) { - OpenRGBPluginInterface* plugin = nullptr; + OpenRGBPluginInterface *plugin = nullptr; unsigned int plugin_idx; @@ -136,14 +136,15 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) /*---------------------------------------------------------------------*\ | Check if this plugin is on the remove list | \*---------------------------------------------------------------------*/ - if(plugin_settings.contains("plugins_remove")) - { - for(unsigned int plugin_remove_idx = 0; plugin_remove_idx < plugin_settings["plugins_remove"].size(); plugin_remove_idx++) - { - LOG_WARNING("[PluginManager] Checking remove %d, %s", plugin_remove_idx, to_string(plugin_settings["plugins_remove"][plugin_remove_idx]).c_str()); + if (plugin_settings.contains("plugins_remove")) { + for (unsigned int plugin_remove_idx = 0; + plugin_remove_idx < plugin_settings["plugins_remove"].size(); + plugin_remove_idx++) { + LOG_WARNING("[PluginManager] Checking remove %d, %s", + plugin_remove_idx, + to_string(plugin_settings["plugins_remove"][plugin_remove_idx]).c_str()); - if(plugin_settings["plugins_remove"][plugin_remove_idx] == path.generic_u8string()) - { + if (plugin_settings["plugins_remove"][plugin_remove_idx] == path.generic_u8string()) { /*---------------------------------------------------------*\ | Delete the plugin file | \*---------------------------------------------------------*/ @@ -163,10 +164,8 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) /*---------------------------------------------------------------------*\ | Search active plugins to see if this path already exists | \*---------------------------------------------------------------------*/ - for(plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) - { - if(path == ActivePlugins[plugin_idx].path) - { + for (plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) { + if (path == ActivePlugins[plugin_idx].path) { break; } } @@ -174,32 +173,30 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) /*---------------------------------------------------------------------*\ | If the path does not match an existing entry, create a new entry | \*---------------------------------------------------------------------*/ - if(plugin_idx == ActivePlugins.size()) - { + if (plugin_idx == ActivePlugins.size()) { /*-----------------------------------------------------------------*\ | Create a QPluginLoader and load the plugin | \*-----------------------------------------------------------------*/ - std::string path_string = path.generic_u8string(); - QPluginLoader* loader = new QPluginLoader(QString::fromStdString(path_string)); - QObject* instance = loader->instance(); + std::string path_string = path.generic_u8string(); + QPluginLoader *loader = new QPluginLoader(QString::fromStdString(path_string)); + QObject *instance = loader->instance(); - if(!loader->isLoaded()) - { - LOG_WARNING("[PluginManager] Plugin %s cannot be loaded: %s", path.c_str(), loader->errorString().toStdString().c_str()); + if (!loader->isLoaded()) { + LOG_WARNING("[PluginManager] Plugin %s cannot be loaded: %s", + path.c_str(), + loader->errorString().toStdString().c_str()); } /*-----------------------------------------------------------------*\ | Check that the plugin is valid, then check the API version | \*-----------------------------------------------------------------*/ - if(instance) - { - plugin = qobject_cast(instance); + if (instance) { + plugin = qobject_cast(instance); - if(plugin) - { - if(plugin->GetPluginAPIVersion() == OPENRGB_PLUGIN_API_VERSION) - { - LOG_TRACE("[PluginManager] Plugin %s has a compatible API version", path.c_str()); + if (plugin) { + if (plugin->GetPluginAPIVersion() == OPENRGB_PLUGIN_API_VERSION) { + LOG_TRACE("[PluginManager] Plugin %s has a compatible API version", + path.c_str()); /*-----------------------------------------------------*\ | Get the plugin information | @@ -209,36 +206,35 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) /*-----------------------------------------------------*\ | Search the settings to see if it is enabled | \*-----------------------------------------------------*/ - std::string name = ""; - std::string description = ""; - bool enabled = true; - bool found = false; - unsigned int plugin_ct = 0; + std::string name = ""; + std::string description = ""; + bool enabled = true; + bool found = false; + unsigned int plugin_ct = 0; - if(plugin_settings.contains("plugins")) - { - plugin_ct = (unsigned int)plugin_settings["plugins"].size(); + if (plugin_settings.contains("plugins")) { + plugin_ct = (unsigned int) plugin_settings["plugins"].size(); - for(unsigned int plugin_settings_idx = 0; plugin_settings_idx < plugin_settings["plugins"].size(); plugin_settings_idx++) - { - if(plugin_settings["plugins"][plugin_settings_idx].contains("name")) - { - name = plugin_settings["plugins"][plugin_settings_idx]["name"]; + for (unsigned int plugin_settings_idx = 0; + plugin_settings_idx < plugin_settings["plugins"].size(); + plugin_settings_idx++) { + if (plugin_settings["plugins"][plugin_settings_idx].contains("name")) { + name = plugin_settings["plugins"][plugin_settings_idx]["name"]; } - if(plugin_settings["plugins"][plugin_settings_idx].contains("description")) - { - description = plugin_settings["plugins"][plugin_settings_idx]["description"]; + if (plugin_settings["plugins"][plugin_settings_idx].contains( + "description")) { + description = plugin_settings["plugins"][plugin_settings_idx] + ["description"]; } - if(plugin_settings["plugins"][plugin_settings_idx].contains("enabled")) - { - enabled = plugin_settings["plugins"][plugin_settings_idx]["enabled"]; + if (plugin_settings["plugins"][plugin_settings_idx].contains( + "enabled")) { + enabled + = plugin_settings["plugins"][plugin_settings_idx]["enabled"]; } - if((info.Name == name) - &&(info.Description == description)) - { + if ((info.Name == name) && (info.Description == description)) { found = true; break; } @@ -249,13 +245,13 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) | If the plugin was not in the list, add it to the list | | and default it to enabled, then save the settings | \*-----------------------------------------------------*/ - if(!found) - { - plugin_settings["plugins"][plugin_ct]["name"] = info.Name; - plugin_settings["plugins"][plugin_ct]["description"] = info.Description; - plugin_settings["plugins"][plugin_ct]["enabled"] = enabled; + if (!found) { + plugin_settings["plugins"][plugin_ct]["name"] = info.Name; + plugin_settings["plugins"][plugin_ct]["description"] = info.Description; + plugin_settings["plugins"][plugin_ct]["enabled"] = enabled; - ResourceManager::get()->GetSettingsManager()->SetSettings("Plugins", plugin_settings); + ResourceManager::get()->GetSettingsManager()->SetSettings("Plugins", + plugin_settings); ResourceManager::get()->GetSettingsManager()->SaveSettings(); } @@ -266,35 +262,33 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) \*-----------------------------------------------------*/ OpenRGBPluginEntry entry; - entry.info = info; - entry.plugin = plugin; - entry.loader = loader; - entry.path = path_string; - entry.enabled = enabled; - entry.widget = nullptr; - entry.incompatible = false; - entry.api_version = plugin->GetPluginAPIVersion(); - entry.is_system = is_system; + entry.info = info; + entry.plugin = plugin; + entry.loader = loader; + entry.path = path_string; + entry.enabled = enabled; + entry.widget = nullptr; + entry.incompatible = false; + entry.api_version = plugin->GetPluginAPIVersion(); + entry.is_system = is_system; loader->unload(); ActivePlugins.push_back(entry); - if(entry.enabled) - { + if (entry.enabled) { LoadPlugin(&ActivePlugins.back()); } - } - else - { + } else { /*-----------------------------------------------------*\ | Fill in a plugin information object with text showing | | the plugin is incompatible | \*-----------------------------------------------------*/ OpenRGBPluginInfo info; - info.Name = "Incompatible Plugin"; - info.Description = "This plugin is not compatible with this version of OpenRGB."; + info.Name = "Incompatible Plugin"; + info.Description + = "This plugin is not compatible with this version of OpenRGB."; /*-----------------------------------------------------*\ | Add the plugin to the PluginManager active plugins | @@ -302,15 +296,15 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) \*-----------------------------------------------------*/ OpenRGBPluginEntry entry; - entry.info = info; - entry.plugin = plugin; - entry.loader = loader; - entry.path = path_string; - entry.enabled = false; - entry.widget = nullptr; - entry.incompatible = true; - entry.api_version = plugin->GetPluginAPIVersion(); - entry.is_system = is_system; + entry.info = info; + entry.plugin = plugin; + entry.loader = loader; + entry.path = path_string; + entry.enabled = false; + entry.widget = nullptr; + entry.incompatible = true; + entry.api_version = plugin->GetPluginAPIVersion(); + entry.is_system = is_system; loader->unload(); @@ -318,27 +312,24 @@ void PluginManager::AddPlugin(const filesystem::path& path, bool is_system) bool unloaded = loader->unload(); - LOG_WARNING("[PluginManager] Plugin %s has an incompatible API version", path.c_str()); + LOG_WARNING("[PluginManager] Plugin %s has an incompatible API version", + path.c_str()); - if(!unloaded) - { + if (!unloaded) { LOG_WARNING("[PluginManager] Plugin %s cannot be unloaded", path.c_str()); } } + } else { + LOG_WARNING("[PluginManager] Plugin %s cannot be casted to OpenRGBPluginInterface", + path.c_str()); } - else - { - LOG_WARNING("[PluginManager] Plugin %s cannot be casted to OpenRGBPluginInterface", path.c_str()); - } - } - else - { + } else { LOG_WARNING("[PluginManager] Plugin %s cannot be instantiated.", path.c_str()); } } } -void PluginManager::RemovePlugin(const filesystem::path& path) +void PluginManager::RemovePlugin(const filesystem::path &path) { unsigned int plugin_idx; @@ -347,10 +338,8 @@ void PluginManager::RemovePlugin(const filesystem::path& path) /*---------------------------------------------------------------------*\ | Search active plugins to see if this path already exists | \*---------------------------------------------------------------------*/ - for(plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) - { - if(path == ActivePlugins[plugin_idx].path) - { + for (plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) { + if (path == ActivePlugins[plugin_idx].path) { break; } } @@ -358,8 +347,7 @@ void PluginManager::RemovePlugin(const filesystem::path& path) /*---------------------------------------------------------------------*\ | If the plugin path does not exist in the active plugins list, return | \*---------------------------------------------------------------------*/ - if(plugin_idx == ActivePlugins.size()) - { + if (plugin_idx == ActivePlugins.size()) { LOG_TRACE("[PluginManager] Plugin %s not active", path.c_str()); return; } @@ -367,8 +355,7 @@ void PluginManager::RemovePlugin(const filesystem::path& path) /*---------------------------------------------------------------------*\ | If the selected plugin is in the list and loaded, unload it | \*---------------------------------------------------------------------*/ - if(ActivePlugins[plugin_idx].loader->isLoaded()) - { + if (ActivePlugins[plugin_idx].loader->isLoaded()) { LOG_TRACE("[PluginManager] Plugin %s is active, unloading", path.c_str()); UnloadPlugin(&ActivePlugins[plugin_idx]); } @@ -379,17 +366,15 @@ void PluginManager::RemovePlugin(const filesystem::path& path) ActivePlugins.erase(ActivePlugins.begin() + plugin_idx); } -void PluginManager::EnablePlugin(const filesystem::path& path) +void PluginManager::EnablePlugin(const filesystem::path &path) { unsigned int plugin_idx; /*---------------------------------------------------------------------*\ | Search active plugins to see if this path already exists | \*---------------------------------------------------------------------*/ - for(plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) - { - if(path == ActivePlugins[plugin_idx].path) - { + for (plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) { + if (path == ActivePlugins[plugin_idx].path) { break; } } @@ -397,8 +382,7 @@ void PluginManager::EnablePlugin(const filesystem::path& path) /*---------------------------------------------------------------------*\ | If the plugin path does not exist in the active plugins list, return | \*---------------------------------------------------------------------*/ - if(plugin_idx == ActivePlugins.size()) - { + if (plugin_idx == ActivePlugins.size()) { return; } @@ -406,33 +390,28 @@ void PluginManager::EnablePlugin(const filesystem::path& path) LoadPlugin(&ActivePlugins[plugin_idx]); } -void PluginManager::LoadPlugin(OpenRGBPluginEntry* plugin_entry) +void PluginManager::LoadPlugin(OpenRGBPluginEntry *plugin_entry) { /*---------------------------------------------------------------------*\ | If the plugin is in the list but is incompatible, return | \*---------------------------------------------------------------------*/ - if(plugin_entry->incompatible) - { + if (plugin_entry->incompatible) { return; } /*---------------------------------------------------------------------*\ | If the selected plugin is in the list but not loaded, load it | \*---------------------------------------------------------------------*/ - if(!plugin_entry->loader->isLoaded()) - { + if (!plugin_entry->loader->isLoaded()) { plugin_entry->loader->load(); - QObject* instance = plugin_entry->loader->instance(); + QObject *instance = plugin_entry->loader->instance(); - if(instance) - { - OpenRGBPluginInterface* plugin = qobject_cast(instance); + if (instance) { + OpenRGBPluginInterface *plugin = qobject_cast(instance); - if(plugin) - { - if(plugin->GetPluginAPIVersion() == OPENRGB_PLUGIN_API_VERSION) - { + if (plugin) { + if (plugin->GetPluginAPIVersion() == OPENRGB_PLUGIN_API_VERSION) { plugin_entry->plugin = plugin; plugin->Load(ResourceManager::get()); @@ -440,8 +419,7 @@ void PluginManager::LoadPlugin(OpenRGBPluginEntry* plugin_entry) /*-------------------------------------------------*\ | Call the Add Plugin callback | \*-------------------------------------------------*/ - if(AddPluginCallbackArg != nullptr) - { + if (AddPluginCallbackArg != nullptr) { AddPluginCallbackVal(AddPluginCallbackArg, plugin_entry); } } @@ -450,17 +428,15 @@ void PluginManager::LoadPlugin(OpenRGBPluginEntry* plugin_entry) } } -void PluginManager::DisablePlugin(const filesystem::path& path) +void PluginManager::DisablePlugin(const filesystem::path &path) { unsigned int plugin_idx; /*---------------------------------------------------------------------*\ | Search active plugins to see if this path already exists | \*---------------------------------------------------------------------*/ - for(plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) - { - if(path == ActivePlugins[plugin_idx].path) - { + for (plugin_idx = 0; plugin_idx < ActivePlugins.size(); plugin_idx++) { + if (path == ActivePlugins[plugin_idx].path) { break; } } @@ -468,8 +444,7 @@ void PluginManager::DisablePlugin(const filesystem::path& path) /*---------------------------------------------------------------------*\ | If the plugin path does not exist in the active plugins list, return | \*---------------------------------------------------------------------*/ - if(plugin_idx == ActivePlugins.size()) - { + if (plugin_idx == ActivePlugins.size()) { return; } @@ -477,13 +452,12 @@ void PluginManager::DisablePlugin(const filesystem::path& path) UnloadPlugin(&ActivePlugins[plugin_idx]); } -void PluginManager::UnloadPlugin(OpenRGBPluginEntry* plugin_entry) +void PluginManager::UnloadPlugin(OpenRGBPluginEntry *plugin_entry) { /*---------------------------------------------------------------------*\ | If the selected plugin is in the list and loaded, unload it | \*---------------------------------------------------------------------*/ - if(plugin_entry->loader->isLoaded()) - { + if (plugin_entry->loader->isLoaded()) { /*-------------------------------------------------*\ | Call plugin's Unload function before GUI removal | \*-------------------------------------------------*/ @@ -492,34 +466,26 @@ void PluginManager::UnloadPlugin(OpenRGBPluginEntry* plugin_entry) /*-------------------------------------------------*\ | Call the Remove Plugin callback | \*-------------------------------------------------*/ - if(RemovePluginCallbackVal != nullptr) - { + if (RemovePluginCallbackVal != nullptr) { RemovePluginCallbackVal(RemovePluginCallbackArg, plugin_entry); } bool unloaded = plugin_entry->loader->unload(); - if(!unloaded) - { + if (!unloaded) { LOG_WARNING("[PluginManager] Plugin %s cannot be unloaded", plugin_entry->path.c_str()); - } - else - { + } else { LOG_TRACE("[PluginManager] Plugin %s successfully unloaded", plugin_entry->path.c_str()); } - } - else - { + } else { LOG_TRACE("[PluginManager] Plugin %s was already unloaded", plugin_entry->path.c_str()); } } void PluginManager::LoadPlugins() { - for(OpenRGBPluginEntry& plugin_entry: ActivePlugins) - { - if(plugin_entry.enabled) - { + for (OpenRGBPluginEntry &plugin_entry : ActivePlugins) { + if (plugin_entry.enabled) { LoadPlugin(&plugin_entry); } } @@ -527,8 +493,7 @@ void PluginManager::LoadPlugins() void PluginManager::UnloadPlugins() { - for(OpenRGBPluginEntry& plugin_entry: ActivePlugins) - { + for (OpenRGBPluginEntry &plugin_entry : ActivePlugins) { UnloadPlugin(&plugin_entry); } } diff --git a/PluginManager.h b/PluginManager.h index 389e5fd10..f085dab46 100644 --- a/PluginManager.h +++ b/PluginManager.h @@ -19,36 +19,36 @@ typedef struct { - OpenRGBPluginInfo info; - OpenRGBPluginInterface* plugin; - QPluginLoader* loader; - QWidget* widget; - QMenu* traymenu; - std::string path; - bool enabled; - bool incompatible; - bool is_system; - int api_version; + OpenRGBPluginInfo info; + OpenRGBPluginInterface *plugin; + QPluginLoader *loader; + QWidget *widget; + QMenu *traymenu; + std::string path; + bool enabled; + bool incompatible; + bool is_system; + int api_version; } OpenRGBPluginEntry; -typedef void (*AddPluginCallback)(void *, OpenRGBPluginEntry* plugin); -typedef void (*RemovePluginCallback)(void *, OpenRGBPluginEntry* plugin); +typedef void (*AddPluginCallback)(void *, OpenRGBPluginEntry *plugin); +typedef void (*RemovePluginCallback)(void *, OpenRGBPluginEntry *plugin); class PluginManager { public: PluginManager(); - void RegisterAddPluginCallback(AddPluginCallback new_callback, void * new_callback_arg); - void RegisterRemovePluginCallback(RemovePluginCallback new_callback, void * new_callback_arg); + void RegisterAddPluginCallback(AddPluginCallback new_callback, void *new_callback_arg); + void RegisterRemovePluginCallback(RemovePluginCallback new_callback, void *new_callback_arg); void ScanAndLoadPlugins(); - void AddPlugin(const filesystem::path& path, bool is_system); - void RemovePlugin(const filesystem::path& path); + void AddPlugin(const filesystem::path &path, bool is_system); + void RemovePlugin(const filesystem::path &path); - void EnablePlugin(const filesystem::path& path); - void DisablePlugin(const filesystem::path& path); + void EnablePlugin(const filesystem::path &path); + void DisablePlugin(const filesystem::path &path); void LoadPlugins(); void UnloadPlugins(); @@ -56,16 +56,16 @@ public: std::vector ActivePlugins; private: - void LoadPlugin(OpenRGBPluginEntry* plugin_entry); - void UnloadPlugin(OpenRGBPluginEntry* plugin_entry); + void LoadPlugin(OpenRGBPluginEntry *plugin_entry); + void UnloadPlugin(OpenRGBPluginEntry *plugin_entry); - void ScanAndLoadPluginsFrom(const filesystem::path & plugins_dir, bool is_system); + void ScanAndLoadPluginsFrom(const filesystem::path &plugins_dir, bool is_system); - AddPluginCallback AddPluginCallbackVal; - void * AddPluginCallbackArg; + AddPluginCallback AddPluginCallbackVal; + void *AddPluginCallbackArg; - RemovePluginCallback RemovePluginCallbackVal; - void * RemovePluginCallbackArg; + RemovePluginCallback RemovePluginCallbackVal; + void *RemovePluginCallbackArg; - const char * plugins_path = "plugins/"; + const char *plugins_path = "plugins/"; }; diff --git a/ProfileManager.cpp b/ProfileManager.cpp index a6262f332..de8d15717 100644 --- a/ProfileManager.cpp +++ b/ProfileManager.cpp @@ -18,19 +18,16 @@ #include "filesystem.h" #include "StringUtils.h" -#define OPENRGB_PROFILE_HEADER "OPENRGB_PROFILE" +#define OPENRGB_PROFILE_HEADER "OPENRGB_PROFILE" #define OPENRGB_PROFILE_VERSION OPENRGB_SDK_PROTOCOL_VERSION -ProfileManager::ProfileManager(const filesystem::path& config_dir) +ProfileManager::ProfileManager(const filesystem::path &config_dir) { configuration_directory = config_dir; UpdateProfileList(); } -ProfileManager::~ProfileManager() -{ - -} +ProfileManager::~ProfileManager() {} bool ProfileManager::SaveProfile(std::string profile_name, bool sizes) { @@ -44,8 +41,7 @@ bool ProfileManager::SaveProfile(std::string profile_name, bool sizes) /*---------------------------------------------------------*\ | If a name was entered, save the profile file | \*---------------------------------------------------------*/ - if(profile_name != "") - { + if (profile_name != "") { /*---------------------------------------------------------*\ | Extension .orp - OpenRgb Profile | \*---------------------------------------------------------*/ @@ -54,12 +50,9 @@ bool ProfileManager::SaveProfile(std::string profile_name, bool sizes) /*---------------------------------------------------------*\ | Determine file extension | \*---------------------------------------------------------*/ - if(sizes) - { + if (sizes) { filename += ".ors"; - } - else - { + } else { filename += ".orp"; } @@ -67,7 +60,8 @@ bool ProfileManager::SaveProfile(std::string profile_name, bool sizes) | Open an output file in binary mode | \*---------------------------------------------------------*/ filesystem::path profile_path = configuration_directory / filesystem::u8path(filename); - std::ofstream controller_file(profile_path, std::ios::out | std::ios::binary | std::ios::trunc); + std::ofstream controller_file(profile_path, + std::ios::out | std::ios::binary | std::ios::trunc); /*---------------------------------------------------------*\ | Write header | @@ -76,29 +70,30 @@ bool ProfileManager::SaveProfile(std::string profile_name, bool sizes) \*---------------------------------------------------------*/ unsigned int profile_version = OPENRGB_PROFILE_VERSION; controller_file.write(OPENRGB_PROFILE_HEADER, 16); - controller_file.write((char *)&profile_version, sizeof(unsigned int)); + controller_file.write((char *) &profile_version, sizeof(unsigned int)); /*---------------------------------------------------------*\ | Write controller data for each controller | \*---------------------------------------------------------*/ - for(std::size_t controller_index = 0; controller_index < controllers.size(); controller_index++) - { + for (std::size_t controller_index = 0; controller_index < controllers.size(); + controller_index++) { /*-----------------------------------------------------*\ | Ignore remote and virtual controllers when saving | | sizes | \*-----------------------------------------------------*/ - if(sizes && (controllers[controller_index]->flags & CONTROLLER_FLAG_REMOTE - || controllers[controller_index]->flags & CONTROLLER_FLAG_VIRTUAL)) - { + if (sizes + && (controllers[controller_index]->flags & CONTROLLER_FLAG_REMOTE + || controllers[controller_index]->flags & CONTROLLER_FLAG_VIRTUAL)) { break; } - unsigned char *controller_data = controllers[controller_index]->GetDeviceDescription(profile_version); + unsigned char *controller_data = controllers[controller_index]->GetDeviceDescription( + profile_version); unsigned int controller_size; memcpy(&controller_size, controller_data, sizeof(controller_size)); - controller_file.write((const char *)controller_data, controller_size); + controller_file.write((const char *) controller_data, controller_size); delete[] controller_data; } @@ -113,15 +108,13 @@ bool ProfileManager::SaveProfile(std::string profile_name, bool sizes) \*---------------------------------------------------------*/ UpdateProfileList(); - return(true); - } - else - { - return(false); + return (true); + } else { + return (false); } } -void ProfileManager::SetConfigurationDirectory(const filesystem::path& directory) +void ProfileManager::SetConfigurationDirectory(const filesystem::path &directory) { configuration_directory = directory; UpdateProfileList(); @@ -130,38 +123,30 @@ void ProfileManager::SetConfigurationDirectory(const filesystem::path& directory bool ProfileManager::LoadProfile(std::string profile_name) { profile_name = StringUtils::remove_null_terminating_chars(profile_name); - return(LoadProfileWithOptions(profile_name, false, true)); + return (LoadProfileWithOptions(profile_name, false, true)); } bool ProfileManager::LoadSizeFromProfile(std::string profile_name) { profile_name = StringUtils::remove_null_terminating_chars(profile_name); - return(LoadProfileWithOptions(profile_name, true, false)); + return (LoadProfileWithOptions(profile_name, true, false)); } -std::vector ProfileManager::LoadProfileToList - ( - std::string profile_name, - bool sizes - ) +std::vector ProfileManager::LoadProfileToList(std::string profile_name, bool sizes) { - std::vector temp_controllers; - unsigned int controller_size; - unsigned int controller_offset = 0; + std::vector temp_controllers; + unsigned int controller_size; + unsigned int controller_offset = 0; filesystem::path filename = configuration_directory / filesystem::u8path(profile_name); /*---------------------------------------------------------*\ | Determine file extension | \*---------------------------------------------------------*/ - if(sizes) - { + if (sizes) { filename.concat(".ors"); - } - else - { - if(filename.extension() != ".orp") - { + } else { + if (filename.extension() != ".orp") { filename.concat(".orp"); } } @@ -174,41 +159,37 @@ std::vector ProfileManager::LoadProfileToList /*---------------------------------------------------------*\ | Read and verify file header | \*---------------------------------------------------------*/ - char profile_string[16] = ""; - unsigned int profile_version = 0; + char profile_string[16] = ""; + unsigned int profile_version = 0; controller_file.read(profile_string, 16); - controller_file.read((char *)&profile_version, sizeof(unsigned int)); + controller_file.read((char *) &profile_version, sizeof(unsigned int)); /*---------------------------------------------------------*\ | Profile version started at 1 and protocol version started | | at 0. Version 1 profiles should use protocol 0, but 2 or | | greater should be synchronized | \*---------------------------------------------------------*/ - if(profile_version == 1) - { + if (profile_version == 1) { profile_version = 0; } controller_offset += 16 + sizeof(unsigned int); controller_file.seekg(controller_offset); - if(strcmp(profile_string, OPENRGB_PROFILE_HEADER) == 0) - { - if(profile_version <= OPENRGB_PROFILE_VERSION) - { + if (strcmp(profile_string, OPENRGB_PROFILE_HEADER) == 0) { + if (profile_version <= OPENRGB_PROFILE_VERSION) { /*---------------------------------------------------------*\ | Read controller data from file until EOF | \*---------------------------------------------------------*/ - while(!(controller_file.peek() == EOF)) - { - controller_file.read((char *)&controller_size, sizeof(controller_size)); + while (!(controller_file.peek() == EOF)) { + controller_file.read((char *) &controller_size, sizeof(controller_size)); unsigned char *controller_data = new unsigned char[controller_size]; controller_file.seekg(controller_offset); - controller_file.read((char *)controller_data, controller_size); + controller_file.read((char *) controller_data, controller_size); RGBController_Dummy *temp_controller = new RGBController_Dummy(); @@ -224,20 +205,16 @@ std::vector ProfileManager::LoadProfileToList } } - return(temp_controllers); + return (temp_controllers); } -bool ProfileManager::LoadDeviceFromListWithOptions - ( - std::vector& temp_controllers, - std::vector& temp_controller_used, - RGBController* load_controller, - bool load_size, - bool load_settings - ) +bool ProfileManager::LoadDeviceFromListWithOptions(std::vector &temp_controllers, + std::vector &temp_controller_used, + RGBController *load_controller, + bool load_size, + bool load_settings) { - for(std::size_t temp_index = 0; temp_index < temp_controllers.size(); temp_index++) - { + for (std::size_t temp_index = 0; temp_index < temp_controllers.size(); temp_index++) { RGBController *temp_controller = temp_controllers[temp_index]; /*---------------------------------------------------------*\ @@ -249,39 +226,29 @@ bool ProfileManager::LoadDeviceFromListWithOptions \*---------------------------------------------------------*/ bool location_check; - if(load_controller->location.find("HID: ") == 0) - { + if (load_controller->location.find("HID: ") == 0) { location_check = true; - } - else if(load_controller->location.find("I2C: ") == 0) - { + } else if (load_controller->location.find("I2C: ") == 0) { std::size_t loc = load_controller->location.rfind(", "); - if(loc == std::string::npos) - { + if (loc == std::string::npos) { location_check = false; - } - else - { + } else { std::string i2c_address = load_controller->location.substr(loc + 2); location_check = temp_controller->location.find(i2c_address) != std::string::npos; } - } - else - { + } else { location_check = temp_controller->location == load_controller->location; } /*---------------------------------------------------------*\ | Test if saved controller data matches this controller | \*---------------------------------------------------------*/ - if((temp_controller_used[temp_index] == false ) - &&(temp_controller->type == load_controller->type ) - &&(temp_controller->name == load_controller->name ) - &&(temp_controller->description == load_controller->description) - &&(temp_controller->version == load_controller->version ) - &&(temp_controller->serial == load_controller->serial ) - &&(location_check == true )) - { + if ((temp_controller_used[temp_index] == false) + && (temp_controller->type == load_controller->type) + && (temp_controller->name == load_controller->name) + && (temp_controller->description == load_controller->description) + && (temp_controller->version == load_controller->version) + && (temp_controller->serial == load_controller->serial) && (location_check == true)) { /*---------------------------------------------------------*\ | Set used flag for this temp device | \*---------------------------------------------------------*/ @@ -290,29 +257,34 @@ bool ProfileManager::LoadDeviceFromListWithOptions /*---------------------------------------------------------*\ | Update zone sizes if requested | \*---------------------------------------------------------*/ - if(load_size) - { - if(temp_controller->zones.size() == load_controller->zones.size()) - { - for(std::size_t zone_idx = 0; zone_idx < temp_controller->zones.size(); zone_idx++) - { - if((temp_controller->zones[zone_idx].name == load_controller->zones[zone_idx].name ) - &&(temp_controller->zones[zone_idx].type == load_controller->zones[zone_idx].type ) - &&(temp_controller->zones[zone_idx].leds_min == load_controller->zones[zone_idx].leds_min ) - &&(temp_controller->zones[zone_idx].leds_max == load_controller->zones[zone_idx].leds_max )) - { - if(temp_controller->zones[zone_idx].leds_count != load_controller->zones[zone_idx].leds_count) - { - load_controller->ResizeZone((int)zone_idx, temp_controller->zones[zone_idx].leds_count); + if (load_size) { + if (temp_controller->zones.size() == load_controller->zones.size()) { + for (std::size_t zone_idx = 0; zone_idx < temp_controller->zones.size(); + zone_idx++) { + if ((temp_controller->zones[zone_idx].name + == load_controller->zones[zone_idx].name) + && (temp_controller->zones[zone_idx].type + == load_controller->zones[zone_idx].type) + && (temp_controller->zones[zone_idx].leds_min + == load_controller->zones[zone_idx].leds_min) + && (temp_controller->zones[zone_idx].leds_max + == load_controller->zones[zone_idx].leds_max)) { + if (temp_controller->zones[zone_idx].leds_count + != load_controller->zones[zone_idx].leds_count) { + load_controller + ->ResizeZone((int) zone_idx, + temp_controller->zones[zone_idx].leds_count); } - if(temp_controller->zones[zone_idx].segments.size() != load_controller->zones[zone_idx].segments.size()) - { + if (temp_controller->zones[zone_idx].segments.size() + != load_controller->zones[zone_idx].segments.size()) { load_controller->zones[zone_idx].segments.clear(); - for(std::size_t segment_idx = 0; segment_idx < temp_controller->zones[zone_idx].segments.size(); segment_idx++) - { - load_controller->zones[zone_idx].segments.push_back(temp_controller->zones[zone_idx].segments[segment_idx]); + for (std::size_t segment_idx = 0; + segment_idx < temp_controller->zones[zone_idx].segments.size(); + segment_idx++) { + load_controller->zones[zone_idx].segments.push_back( + temp_controller->zones[zone_idx].segments[segment_idx]); } } } @@ -323,38 +295,48 @@ bool ProfileManager::LoadDeviceFromListWithOptions /*---------------------------------------------------------*\ | Update settings if requested | \*---------------------------------------------------------*/ - if(load_settings) - { + if (load_settings) { /*---------------------------------------------------------*\ | Update all modes | \*---------------------------------------------------------*/ - if(temp_controller->modes.size() == load_controller->modes.size()) - { - for(std::size_t mode_index = 0; mode_index < temp_controller->modes.size(); mode_index++) - { - if((temp_controller->modes[mode_index].name == load_controller->modes[mode_index].name ) - &&(temp_controller->modes[mode_index].value == load_controller->modes[mode_index].value ) - &&(temp_controller->modes[mode_index].flags == load_controller->modes[mode_index].flags ) - &&(temp_controller->modes[mode_index].speed_min == load_controller->modes[mode_index].speed_min ) - &&(temp_controller->modes[mode_index].speed_max == load_controller->modes[mode_index].speed_max ) - //&&(temp_controller->modes[mode_index].brightness_min == load_controller->modes[mode_index].brightness_min) - //&&(temp_controller->modes[mode_index].brightness_max == load_controller->modes[mode_index].brightness_max) - &&(temp_controller->modes[mode_index].colors_min == load_controller->modes[mode_index].colors_min ) - &&(temp_controller->modes[mode_index].colors_max == load_controller->modes[mode_index].colors_max )) - { - load_controller->modes[mode_index].speed = temp_controller->modes[mode_index].speed; - load_controller->modes[mode_index].brightness = temp_controller->modes[mode_index].brightness; - load_controller->modes[mode_index].direction = temp_controller->modes[mode_index].direction; - load_controller->modes[mode_index].color_mode = temp_controller->modes[mode_index].color_mode; + if (temp_controller->modes.size() == load_controller->modes.size()) { + for (std::size_t mode_index = 0; mode_index < temp_controller->modes.size(); + mode_index++) { + if ((temp_controller->modes[mode_index].name + == load_controller->modes[mode_index].name) + && (temp_controller->modes[mode_index].value + == load_controller->modes[mode_index].value) + && (temp_controller->modes[mode_index].flags + == load_controller->modes[mode_index].flags) + && (temp_controller->modes[mode_index].speed_min + == load_controller->modes[mode_index].speed_min) + && (temp_controller->modes[mode_index].speed_max + == load_controller->modes[mode_index].speed_max) + //&&(temp_controller->modes[mode_index].brightness_min == load_controller->modes[mode_index].brightness_min) + //&&(temp_controller->modes[mode_index].brightness_max == load_controller->modes[mode_index].brightness_max) + && (temp_controller->modes[mode_index].colors_min + == load_controller->modes[mode_index].colors_min) + && (temp_controller->modes[mode_index].colors_max + == load_controller->modes[mode_index].colors_max)) { + load_controller->modes[mode_index].speed + = temp_controller->modes[mode_index].speed; + load_controller->modes[mode_index].brightness + = temp_controller->modes[mode_index].brightness; + load_controller->modes[mode_index].direction + = temp_controller->modes[mode_index].direction; + load_controller->modes[mode_index].color_mode + = temp_controller->modes[mode_index].color_mode; - load_controller->modes[mode_index].colors.resize(temp_controller->modes[mode_index].colors.size()); + load_controller->modes[mode_index].colors.resize( + temp_controller->modes[mode_index].colors.size()); - for(std::size_t mode_color_index = 0; mode_color_index < temp_controller->modes[mode_index].colors.size(); mode_color_index++) - { - load_controller->modes[mode_index].colors[mode_color_index] = temp_controller->modes[mode_index].colors[mode_color_index]; + for (std::size_t mode_color_index = 0; + mode_color_index < temp_controller->modes[mode_index].colors.size(); + mode_color_index++) { + load_controller->modes[mode_index].colors[mode_color_index] + = temp_controller->modes[mode_index].colors[mode_color_index]; } } - } load_controller->active_mode = temp_controller->active_mode; @@ -363,32 +345,28 @@ bool ProfileManager::LoadDeviceFromListWithOptions /*---------------------------------------------------------*\ | Update all colors | \*---------------------------------------------------------*/ - if(temp_controller->colors.size() == load_controller->colors.size()) - { - for(std::size_t color_index = 0; color_index < temp_controller->colors.size(); color_index++) - { + if (temp_controller->colors.size() == load_controller->colors.size()) { + for (std::size_t color_index = 0; color_index < temp_controller->colors.size(); + color_index++) { load_controller->colors[color_index] = temp_controller->colors[color_index]; } } } - return(true); + return (true); } } - return(false); + return (false); } -bool ProfileManager::LoadProfileWithOptions - ( - std::string profile_name, - bool load_size, - bool load_settings - ) +bool ProfileManager::LoadProfileWithOptions(std::string profile_name, + bool load_size, + bool load_settings) { - std::vector temp_controllers; - std::vector temp_controller_used; - bool ret_val = false; + std::vector temp_controllers; + std::vector temp_controller_used; + bool ret_val = false; /*---------------------------------------------------------*\ | Get the list of controllers from the resource manager | @@ -405,8 +383,8 @@ bool ProfileManager::LoadProfileWithOptions \*---------------------------------------------------------*/ temp_controller_used.resize(temp_controllers.size()); - for(unsigned int controller_idx = 0; controller_idx < temp_controller_used.size(); controller_idx++) - { + for (unsigned int controller_idx = 0; controller_idx < temp_controller_used.size(); + controller_idx++) { temp_controller_used[controller_idx] = false; } @@ -414,23 +392,30 @@ bool ProfileManager::LoadProfileWithOptions | Loop through all controllers. For each controller, search| | all saved controllers until a match is found | \*---------------------------------------------------------*/ - for(std::size_t controller_index = 0; controller_index < controllers.size(); controller_index++) - { - bool temp_ret_val = LoadDeviceFromListWithOptions(temp_controllers, temp_controller_used, controllers[controller_index], load_size, load_settings); - std::string current_name = controllers[controller_index]->name + " @ " + controllers[controller_index]->location; - LOG_INFO("[ProfileManager] Profile loading: %s for %s", ( temp_ret_val ? "Succeeded" : "FAILED!" ), current_name.c_str()); + for (std::size_t controller_index = 0; controller_index < controllers.size(); + controller_index++) { + bool temp_ret_val = LoadDeviceFromListWithOptions(temp_controllers, + temp_controller_used, + controllers[controller_index], + load_size, + load_settings); + std::string current_name = controllers[controller_index]->name + " @ " + + controllers[controller_index]->location; + LOG_INFO("[ProfileManager] Profile loading: %s for %s", + (temp_ret_val ? "Succeeded" : "FAILED!"), + current_name.c_str()); ret_val |= temp_ret_val; } /*---------------------------------------------------------*\ | Delete all temporary controllers | \*---------------------------------------------------------*/ - for(unsigned int controller_idx = 0; controller_idx < temp_controllers.size(); controller_idx++) - { + for (unsigned int controller_idx = 0; controller_idx < temp_controllers.size(); + controller_idx++) { delete temp_controllers[controller_idx]; } - return(ret_val); + return (ret_val); } void ProfileManager::DeleteProfile(std::string profile_name) @@ -452,13 +437,12 @@ void ProfileManager::UpdateProfileList() /*---------------------------------------------------------*\ | Load profiles by looking for .orp files in current dir | \*---------------------------------------------------------*/ - for(const auto & entry : filesystem::directory_iterator(configuration_directory)) - { + for (const auto &entry : filesystem::directory_iterator(configuration_directory)) { std::string filename = entry.path().filename().string(); - if(filename.find(".orp") != std::string::npos) - { - LOG_INFO("[ProfileManager] Found file: %s attempting to validate header", filename.c_str()); + if (filename.find(".orp") != std::string::npos) { + LOG_INFO("[ProfileManager] Found file: %s attempting to validate header", + filename.c_str()); /*---------------------------------------------------------*\ | Open input file in binary mode | @@ -470,32 +454,33 @@ void ProfileManager::UpdateProfileList() /*---------------------------------------------------------*\ | Read and verify file header | \*---------------------------------------------------------*/ - char profile_string[16]; - unsigned int profile_version; + char profile_string[16]; + unsigned int profile_version; profile_file.read(profile_string, 16); - profile_file.read((char *)&profile_version, sizeof(unsigned int)); + profile_file.read((char *) &profile_version, sizeof(unsigned int)); - if(strcmp(profile_string, OPENRGB_PROFILE_HEADER) == 0) - { - if(profile_version <= OPENRGB_PROFILE_VERSION) - { + if (strcmp(profile_string, OPENRGB_PROFILE_HEADER) == 0) { + if (profile_version <= OPENRGB_PROFILE_VERSION) { /*---------------------------------------------------------*\ | Add this profile to the list | \*---------------------------------------------------------*/ filename.erase(filename.length() - 4); profile_list.push_back(filename); - LOG_INFO("[ProfileManager] Valid v%i profile found for %s", profile_version, filename.c_str()); + LOG_INFO("[ProfileManager] Valid v%i profile found for %s", + profile_version, + filename.c_str()); + } else { + LOG_WARNING("[ProfileManager] Profile %s isn't valid for current version (v%i, " + "expected v%i at most)", + filename.c_str(), + profile_version, + OPENRGB_PROFILE_VERSION); } - else - { - LOG_WARNING("[ProfileManager] Profile %s isn't valid for current version (v%i, expected v%i at most)", filename.c_str(), profile_version, OPENRGB_PROFILE_VERSION); - } - } - else - { - LOG_WARNING("[ProfileManager] Profile %s isn't valid: header is missing", filename.c_str()); + } else { + LOG_WARNING("[ProfileManager] Profile %s isn't valid: header is missing", + filename.c_str()); } profile_file.close(); @@ -503,7 +488,7 @@ void ProfileManager::UpdateProfileList() } } -unsigned char * ProfileManager::GetProfileListDescription() +unsigned char *ProfileManager::GetProfileListDescription() { unsigned int data_ptr = 0; unsigned int data_size = 0; @@ -511,15 +496,14 @@ unsigned char * ProfileManager::GetProfileListDescription() /*---------------------------------------------------------*\ | Calculate data size | \*---------------------------------------------------------*/ - unsigned short num_profiles = (unsigned short)profile_list.size(); + unsigned short num_profiles = (unsigned short) profile_list.size(); - data_size += sizeof(data_size); - data_size += sizeof(num_profiles); + data_size += sizeof(data_size); + data_size += sizeof(num_profiles); - for(unsigned int i = 0; i < num_profiles; i++) - { - data_size += sizeof (unsigned short); - data_size += (unsigned int)strlen(profile_list[i].c_str()) + 1; + for (unsigned int i = 0; i < num_profiles; i++) { + data_size += sizeof(unsigned short); + data_size += (unsigned int) strlen(profile_list[i].c_str()) + 1; } /*---------------------------------------------------------*\ @@ -542,16 +526,15 @@ unsigned char * ProfileManager::GetProfileListDescription() /*---------------------------------------------------------*\ | Copy in profile names (size+data) | \*---------------------------------------------------------*/ - for(unsigned int i = 0; i < num_profiles; i++) - { - unsigned short name_len = (unsigned short)strlen(profile_list[i].c_str()) + 1; + for (unsigned int i = 0; i < num_profiles; i++) { + unsigned short name_len = (unsigned short) strlen(profile_list[i].c_str()) + 1; memcpy(&data_buf[data_ptr], &name_len, sizeof(name_len)); data_ptr += sizeof(name_len); - strcpy((char *)&data_buf[data_ptr], profile_list[i].c_str()); + strcpy((char *) &data_buf[data_ptr], profile_list[i].c_str()); data_ptr += name_len; } - return(data_buf); + return (data_buf); } diff --git a/ProfileManager.h b/ProfileManager.h index 082d05661..eea963d1e 100644 --- a/ProfileManager.h +++ b/ProfileManager.h @@ -15,81 +15,58 @@ class ProfileManagerInterface { public: - virtual bool SaveProfile - ( - std::string profile_name, - bool sizes = false - ) = 0; - virtual bool LoadProfile(std::string profile_name) = 0; - virtual bool LoadSizeFromProfile(std::string profile_name) = 0; - virtual void DeleteProfile(std::string profile_name) = 0; - virtual unsigned char * GetProfileListDescription() = 0; + virtual bool SaveProfile(std::string profile_name, bool sizes = false) = 0; + virtual bool LoadProfile(std::string profile_name) = 0; + virtual bool LoadSizeFromProfile(std::string profile_name) = 0; + virtual void DeleteProfile(std::string profile_name) = 0; + virtual unsigned char *GetProfileListDescription() = 0; std::vector profile_list; - virtual bool LoadDeviceFromListWithOptions - ( - std::vector& temp_controllers, - std::vector& temp_controller_used, - RGBController* load_controller, - bool load_size, - bool load_settings - ) = 0; + virtual bool LoadDeviceFromListWithOptions(std::vector &temp_controllers, + std::vector &temp_controller_used, + RGBController *load_controller, + bool load_size, + bool load_settings) + = 0; - virtual std::vector LoadProfileToList - ( - std::string profile_name, - bool sizes = false - ) = 0; + virtual std::vector LoadProfileToList(std::string profile_name, + bool sizes = false) + = 0; + + virtual void SetConfigurationDirectory(const filesystem::path &directory) = 0; - virtual void SetConfigurationDirectory(const filesystem::path& directory) = 0; protected: virtual ~ProfileManagerInterface() {}; }; -class ProfileManager: public ProfileManagerInterface +class ProfileManager : public ProfileManagerInterface { public: - ProfileManager(const filesystem::path& config_dir); + ProfileManager(const filesystem::path &config_dir); ~ProfileManager(); - bool SaveProfile - ( - std::string profile_name, - bool sizes = false - ); + bool SaveProfile(std::string profile_name, bool sizes = false); bool LoadProfile(std::string profile_name); bool LoadSizeFromProfile(std::string profile_name); void DeleteProfile(std::string profile_name); - unsigned char * GetProfileListDescription(); + unsigned char *GetProfileListDescription(); std::vector profile_list; - bool LoadDeviceFromListWithOptions - ( - std::vector& temp_controllers, - std::vector& temp_controller_used, - RGBController* load_controller, - bool load_size, - bool load_settings - ); + bool LoadDeviceFromListWithOptions(std::vector &temp_controllers, + std::vector &temp_controller_used, + RGBController *load_controller, + bool load_size, + bool load_settings); - std::vector LoadProfileToList - ( - std::string profile_name, - bool sizes = false - ); + std::vector LoadProfileToList(std::string profile_name, bool sizes = false); - void SetConfigurationDirectory(const filesystem::path& directory); + void SetConfigurationDirectory(const filesystem::path &directory); private: filesystem::path configuration_directory; void UpdateProfileList(); - bool LoadProfileWithOptions - ( - std::string profile_name, - bool load_size, - bool load_settings - ); + bool LoadProfileWithOptions(std::string profile_name, bool load_size, bool load_settings); }; diff --git a/ResourceManager.cpp b/ResourceManager.cpp index d06c47391..6b23086e2 100644 --- a/ResourceManager.cpp +++ b/ResourceManager.cpp @@ -33,78 +33,82 @@ /*-------------------------------------------------------------------------*\ | Translation Strings | \*-------------------------------------------------------------------------*/ -const char* I2C_ERR_WIN = QT_TRANSLATE_NOOP("ResourceManager", - "

Some internal devices may not be detected:

" - "

One or more I2C or SMBus interfaces failed to initialize.

" - "

RGB DRAM modules, some motherboards' onboard RGB lighting, and RGB Graphics Cards, will not be available in OpenRGB without I2C or SMBus.

" - "

How to fix this:

" - "

On Windows, this is usually caused by a failure to load the WinRing0 driver.

" - "

You must run OpenRGB as administrator at least once to allow WinRing0 to set up.

" - "

See help.openrgb.org for additional troubleshooting steps if you keep seeing this message.

" - "

If you are not using internal RGB on a desktop this message is not important to you.

"); -const char* I2C_ERR_LINUX = QT_TRANSLATE_NOOP("ResourceManager", - "

Some internal devices may not be detected:

" - "

One or more I2C or SMBus interfaces failed to initialize.

" - "

RGB DRAM modules, some motherboards' onboard RGB lighting, and RGB Graphics Cards, will not be available in OpenRGB without I2C or SMBus.

" - "

How to fix this:

" - "

On Linux, this is usually because the i2c-dev module is not loaded.

" - "

You must load the i2c-dev module along with the correct i2c driver for your motherboard. " - "This is usually i2c-piix4 for AMD systems and i2c-i801 for Intel systems.

" - "

See help.openrgb.org for additional troubleshooting steps if you keep seeing this message.

" - "

If you are not using internal RGB on a desktop this message is not important to you.

"); +const char *I2C_ERR_WIN = QT_TRANSLATE_NOOP( + "ResourceManager", + "

Some internal devices may not be detected:

" + "

One or more I2C or SMBus interfaces failed to initialize.

" + "

RGB DRAM modules, some motherboards' onboard RGB lighting, and RGB Graphics Cards, will " + "not be available in OpenRGB without I2C or SMBus.

" + "

How to fix this:

" + "

On Windows, this is usually caused by a failure to load the WinRing0 driver.

" + "

You must run OpenRGB as administrator at least once to allow WinRing0 to set up.

" + "

See help.openrgb.org for additional " + "troubleshooting steps if you keep seeing this message.

" + "

If you are not using internal RGB on a desktop this message is not important to " + "you.

"); +const char *I2C_ERR_LINUX = QT_TRANSLATE_NOOP( + "ResourceManager", + "

Some internal devices may not be detected:

" + "

One or more I2C or SMBus interfaces failed to initialize.

" + "

RGB DRAM modules, some motherboards' onboard RGB lighting, and RGB Graphics Cards, will " + "not be available in OpenRGB without I2C or SMBus.

" + "

How to fix this:

" + "

On Linux, this is usually because the i2c-dev module is not loaded.

" + "

You must load the i2c-dev module along with the correct i2c driver for your motherboard. " + "This is usually i2c-piix4 for AMD systems and i2c-i801 for Intel systems.

" + "

See help.openrgb.org for additional " + "troubleshooting steps if you keep seeing this message.

" + "

If you are not using internal RGB on a desktop this message is not important to " + "you.

"); -const char* UDEV_MISSING = QT_TRANSLATE_NOOP("ResourceManager", - "

WARNING:

" - "

The OpenRGB udev rules are not installed.

" - "

Most devices will not be available unless running OpenRGB as root.

" - "

If using AppImage, Flatpak, or self-compiled versions of OpenRGB you must install the udev rules manually

" - "

See https://openrgb.org/udev to install the udev rules manually

"); -const char* UDEV_MUTLI = QT_TRANSLATE_NOOP("ResourceManager", - "

WARNING:

" - "

Multiple OpenRGB udev rules are installed.

" - "

The udev rules file 60-openrgb.rules is installed in both /etc/udev/rules.d and /usr/lib/udev/rules.d.

" - "

Multiple udev rules files can conflict, it is recommended to remove one of them.

"); +const char *UDEV_MISSING + = QT_TRANSLATE_NOOP("ResourceManager", + "

WARNING:

" + "

The OpenRGB udev rules are not installed.

" + "

Most devices will not be available unless running OpenRGB as root.

" + "

If using AppImage, Flatpak, or self-compiled versions of OpenRGB you " + "must install the udev rules manually

" + "

See https://openrgb.org/udev to " + "install the udev rules manually

"); +const char *UDEV_MUTLI = QT_TRANSLATE_NOOP( + "ResourceManager", + "

WARNING:

" + "

Multiple OpenRGB udev rules are installed.

" + "

The udev rules file 60-openrgb.rules is installed in both /etc/udev/rules.d and " + "/usr/lib/udev/rules.d.

" + "

Multiple udev rules files can conflict, it is recommended to remove one of them.

"); +const hidapi_wrapper default_wrapper + = {NULL, + (hidapi_wrapper_send_feature_report) hid_send_feature_report, + (hidapi_wrapper_get_feature_report) hid_get_feature_report, + (hidapi_wrapper_get_serial_number_string) hid_get_serial_number_string, + (hidapi_wrapper_open_path) hid_open_path, + (hidapi_wrapper_enumerate) hid_enumerate, + (hidapi_wrapper_free_enumeration) hid_free_enumeration, + (hidapi_wrapper_close) hid_close, + (hidapi_wrapper_error) hid_error}; -const hidapi_wrapper default_wrapper = +bool BasicHIDBlock::compare(hid_device_info *info) { - NULL, - (hidapi_wrapper_send_feature_report) hid_send_feature_report, - (hidapi_wrapper_get_feature_report) hid_get_feature_report, - (hidapi_wrapper_get_serial_number_string) hid_get_serial_number_string, - (hidapi_wrapper_open_path) hid_open_path, - (hidapi_wrapper_enumerate) hid_enumerate, - (hidapi_wrapper_free_enumeration) hid_free_enumeration, - (hidapi_wrapper_close) hid_close, - (hidapi_wrapper_error) hid_error -}; - -bool BasicHIDBlock::compare(hid_device_info* info) -{ - return ( (vid == info->vendor_id) - && (pid == info->product_id) + return ((vid == info->vendor_id) && (pid == info->product_id) #ifdef USE_HID_USAGE - && ( (usage_page == HID_USAGE_PAGE_ANY) - || (usage_page == info->usage_page) ) - && ( (usage == HID_USAGE_ANY) - || (usage == info->usage) ) - && ( (interface == HID_INTERFACE_ANY) - || (interface == info->interface_number ) ) + && ((usage_page == HID_USAGE_PAGE_ANY) || (usage_page == info->usage_page)) + && ((usage == HID_USAGE_ANY) || (usage == info->usage)) + && ((interface == HID_INTERFACE_ANY) || (interface == info->interface_number)) #else - && ( (interface == HID_INTERFACE_ANY) - || (interface == info->interface_number ) ) + && ((interface == HID_INTERFACE_ANY) || (interface == info->interface_number)) #endif - ); + ); } -ResourceManager* ResourceManager::instance; +ResourceManager *ResourceManager::instance; using namespace std::chrono_literals; ResourceManager *ResourceManager::get() { - if(!instance) - { + if (!instance) { instance = new ResourceManager(); } @@ -116,86 +120,80 @@ ResourceManager::ResourceManager() /*-------------------------------------------------------------------------*\ | Initialize Detection Variables | \*-------------------------------------------------------------------------*/ - detection_enabled = true; - detection_percent = 100; - detection_string = ""; - detection_is_required = false; + detection_enabled = true; + detection_percent = 100; + detection_string = ""; + detection_is_required = false; dynamic_detectors_processed = false; - init_finished = false; - background_thread_running = true; + init_finished = false; + background_thread_running = true; /*-------------------------------------------------------------------------*\ | Start the background detection thread in advance; it will be suspended | | until necessary | \*-------------------------------------------------------------------------*/ - DetectDevicesThread = new std::thread(&ResourceManager::BackgroundThreadFunction, this); + DetectDevicesThread = new std::thread(&ResourceManager::BackgroundThreadFunction, this); SetupConfigurationDirectory(); /*-------------------------------------------------------------------------*\ | Load settings from file | \*-------------------------------------------------------------------------*/ - settings_manager = new SettingsManager(); + settings_manager = new SettingsManager(); settings_manager->LoadSettings(GetConfigurationDirectory() / "OpenRGB.json"); /*-------------------------------------------------------------------------*\ | Configure the log manager | \*-------------------------------------------------------------------------*/ - LogManager::get()->configure(settings_manager->GetSettings("LogManager"), GetConfigurationDirectory()); + LogManager::get()->configure(settings_manager->GetSettings("LogManager"), + GetConfigurationDirectory()); /*-------------------------------------------------------------------------*\ | Initialize Server Instance | | If configured, pass through full controller list including clients | | Otherwise, pass only local hardware controllers | \*-------------------------------------------------------------------------*/ - json server_settings = settings_manager->GetSettings("Server"); - bool all_controllers = false; - bool legacy_workaround = false; + json server_settings = settings_manager->GetSettings("Server"); + bool all_controllers = false; + bool legacy_workaround = false; - if(server_settings.contains("all_controllers")) - { - all_controllers = server_settings["all_controllers"]; + if (server_settings.contains("all_controllers")) { + all_controllers = server_settings["all_controllers"]; } - if(all_controllers) - { - server = new NetworkServer(rgb_controllers); - } - else - { - server = new NetworkServer(rgb_controllers_hw); + if (all_controllers) { + server = new NetworkServer(rgb_controllers); + } else { + server = new NetworkServer(rgb_controllers_hw); } /*-------------------------------------------------------------------------*\ | Enable legacy SDK workaround in server if configured | \*-------------------------------------------------------------------------*/ - if(server_settings.contains("legacy_workaround")) - { - legacy_workaround = server_settings["legacy_workaround"]; + if (server_settings.contains("legacy_workaround")) { + legacy_workaround = server_settings["legacy_workaround"]; } - if(legacy_workaround) - { + if (legacy_workaround) { server->SetLegacyWorkaroundEnable(true); } /*-------------------------------------------------------------------------*\ | Initialize Saved Client Connections | \*-------------------------------------------------------------------------*/ - json client_settings = settings_manager->GetSettings("Client"); + json client_settings = settings_manager->GetSettings("Client"); - if(client_settings.contains("clients")) - { - for(unsigned int client_idx = 0; client_idx < client_settings["clients"].size(); client_idx++) - { - NetworkClient * client = new NetworkClient(rgb_controllers); + if (client_settings.contains("clients")) { + for (unsigned int client_idx = 0; client_idx < client_settings["clients"].size(); + client_idx++) { + NetworkClient *client = new NetworkClient(rgb_controllers); std::string titleString = "OpenRGB "; titleString.append(VERSION_STRING); - std::string client_ip = client_settings["clients"][client_idx]["ip"]; - unsigned short client_port = client_settings["clients"][client_idx]["port"]; + std::string client_ip = client_settings["clients"][client_idx]["ip"]; + unsigned short client_port = client_settings["clients"][client_idx]["port"]; client->SetIP(client_ip.c_str()); client->SetName(titleString.c_str()); @@ -203,10 +201,8 @@ ResourceManager::ResourceManager() client->StartClient(); - for(int timeout = 0; timeout < 100; timeout++) - { - if(client->GetConnected()) - { + for (int timeout = 0; timeout < 100; timeout++) { + if (client->GetConnected()) { break; } std::this_thread::sleep_for(10ms); @@ -219,9 +215,9 @@ ResourceManager::ResourceManager() /*-------------------------------------------------------------------------*\ | Load sizes list from file | \*-------------------------------------------------------------------------*/ - profile_manager = new ProfileManager(GetConfigurationDirectory()); + profile_manager = new ProfileManager(GetConfigurationDirectory()); server->SetProfileManager(profile_manager); - rgb_controllers_sizes = profile_manager->LoadProfileToList("sizes", true); + rgb_controllers_sizes = profile_manager->LoadProfileToList("sizes", true); } ResourceManager::~ResourceManager() @@ -234,8 +230,7 @@ ResourceManager::~ResourceManager() BackgroundFunctionStartTrigger.notify_one(); // Stop the background thread - if(DetectDevicesThread) - { + if (DetectDevicesThread) { DetectDevicesThread->join(); delete DetectDevicesThread; DetectDevicesThread = nullptr; @@ -244,11 +239,17 @@ ResourceManager::~ResourceManager() void ResourceManager::RegisterI2CBus(i2c_smbus_interface *bus) { - LOG_INFO("[ResourceManager] Registering I2C interface: %s Device %04X:%04X Subsystem: %04X:%04X", bus->device_name, bus->pci_vendor, bus->pci_device,bus->pci_subsystem_vendor,bus->pci_subsystem_device); + LOG_INFO( + "[ResourceManager] Registering I2C interface: %s Device %04X:%04X Subsystem: %04X:%04X", + bus->device_name, + bus->pci_vendor, + bus->pci_device, + bus->pci_subsystem_vendor, + bus->pci_subsystem_device); busses.push_back(bus); } -std::vector & ResourceManager::GetI2CBusses() +std::vector &ResourceManager::GetI2CBusses() { return busses; } @@ -273,25 +274,29 @@ void ResourceManager::RegisterRGBController(RGBController *rgb_controller) | size can be removed and profile can be loaded per | | controller before adding to list | \*-------------------------------------------------*/ - if(rgb_controllers_hw.size() != detection_prev_size) - { + if (rgb_controllers_hw.size() != detection_prev_size) { /*-------------------------------------------------*\ | First, load sizes for the new controllers | \*-------------------------------------------------*/ - for(unsigned int controller_size_idx = detection_prev_size; controller_size_idx < rgb_controllers_hw.size(); controller_size_idx++) - { - profile_manager->LoadDeviceFromListWithOptions(rgb_controllers_sizes, detection_size_entry_used, rgb_controllers_hw[controller_size_idx], true, false); + for (unsigned int controller_size_idx = detection_prev_size; + controller_size_idx < rgb_controllers_hw.size(); + controller_size_idx++) { + profile_manager->LoadDeviceFromListWithOptions(rgb_controllers_sizes, + detection_size_entry_used, + rgb_controllers_hw[controller_size_idx], + true, + false); } UpdateDeviceList(); } - detection_prev_size = (unsigned int)rgb_controllers_hw.size(); + detection_prev_size = (unsigned int) rgb_controllers_hw.size(); UpdateDeviceList(); } -void ResourceManager::UnregisterRGBController(RGBController* rgb_controller) +void ResourceManager::UnregisterRGBController(RGBController *rgb_controller) { LOG_INFO("[%s] Unregistering RGB controller", rgb_controller->name.c_str()); @@ -303,27 +308,29 @@ void ResourceManager::UnregisterRGBController(RGBController* rgb_controller) /*-------------------------------------------------------------------------*\ | Find the controller to remove and remove it from the hardware list | \*-------------------------------------------------------------------------*/ - std::vector::iterator hw_it = std::find(rgb_controllers_hw.begin(), rgb_controllers_hw.end(), rgb_controller); + std::vector::iterator hw_it = std::find(rgb_controllers_hw.begin(), + rgb_controllers_hw.end(), + rgb_controller); - if (hw_it != rgb_controllers_hw.end()) - { + if (hw_it != rgb_controllers_hw.end()) { rgb_controllers_hw.erase(hw_it); } /*-------------------------------------------------------------------------*\ | Find the controller to remove and remove it from the master list | \*-------------------------------------------------------------------------*/ - std::vector::iterator rgb_it = std::find(rgb_controllers.begin(), rgb_controllers.end(), rgb_controller); + std::vector::iterator rgb_it = std::find(rgb_controllers.begin(), + rgb_controllers.end(), + rgb_controller); - if (rgb_it != rgb_controllers.end()) - { + if (rgb_it != rgb_controllers.end()) { rgb_controllers.erase(rgb_it); } UpdateDeviceList(); } -std::vector & ResourceManager::GetRGBControllers() +std::vector &ResourceManager::GetRGBControllers() { return rgb_controllers; } @@ -339,29 +346,38 @@ void ResourceManager::RegisterI2CDeviceDetector(std::string name, I2CDeviceDetec i2c_device_detectors.push_back(detector); } -void ResourceManager::RegisterI2CDIMMDeviceDetector(std::string name, I2CDIMMDeviceDetectorFunction detector, uint16_t jedec_id, uint8_t dimm_type) +void ResourceManager::RegisterI2CDIMMDeviceDetector(std::string name, + I2CDIMMDeviceDetectorFunction detector, + uint16_t jedec_id, + uint8_t dimm_type) { I2CDIMMDeviceDetectorBlock block; - block.name = name; - block.function = detector; - block.jedec_id = jedec_id; - block.dimm_type = dimm_type; + block.name = name; + block.function = detector; + block.jedec_id = jedec_id; + block.dimm_type = dimm_type; i2c_dimm_device_detectors.push_back(block); } -void ResourceManager::RegisterI2CPCIDeviceDetector(std::string name, I2CPCIDeviceDetectorFunction detector, uint16_t ven_id, uint16_t dev_id, uint16_t subven_id, uint16_t subdev_id, uint8_t i2c_addr) +void ResourceManager::RegisterI2CPCIDeviceDetector(std::string name, + I2CPCIDeviceDetectorFunction detector, + uint16_t ven_id, + uint16_t dev_id, + uint16_t subven_id, + uint16_t subdev_id, + uint8_t i2c_addr) { I2CPCIDeviceDetectorBlock block; - block.name = name; - block.function = detector; - block.ven_id = ven_id; - block.dev_id = dev_id; - block.subven_id = subven_id; - block.subdev_id = subdev_id; - block.i2c_addr = i2c_addr; + block.name = name; + block.function = detector; + block.ven_id = ven_id; + block.dev_id = dev_id; + block.subven_id = subven_id; + block.subdev_id = subdev_id; + block.i2c_addr = i2c_addr; i2c_pci_device_detectors.push_back(block); } @@ -373,28 +389,28 @@ void ResourceManager::RegisterDeviceDetector(std::string name, DeviceDetectorFun } void ResourceManager::RegisterHIDDeviceDetector(std::string name, - HIDDeviceDetectorFunction detector, - uint16_t vid, - uint16_t pid, - int interface, - int usage_page, - int usage) + HIDDeviceDetectorFunction detector, + uint16_t vid, + uint16_t pid, + int interface, + int usage_page, + int usage) { HIDDeviceDetectorBlock block; - block.name = name; - block.vid = vid; - block.pid = pid; - block.function = detector; - block.interface = interface; - block.usage_page = usage_page; - block.usage = usage; + block.name = name; + block.vid = vid; + block.pid = pid; + block.function = detector; + block.interface = interface; + block.usage_page = usage_page; + block.usage = usage; hid_device_detectors.push_back(block); } void ResourceManager::RegisterHIDWrappedDeviceDetector(std::string name, - HIDWrappedDeviceDetectorFunction detector, + HIDWrappedDeviceDetectorFunction detector, uint16_t vid, uint16_t pid, int interface, @@ -403,13 +419,13 @@ void ResourceManager::RegisterHIDWrappedDeviceDetector(std::string name, { HIDWrappedDeviceDetectorBlock block; - block.name = name; - block.vid = vid; - block.pid = pid; - block.function = detector; - block.interface = interface; - block.usage_page = usage_page; - block.usage = usage; + block.name = name; + block.vid = vid; + block.pid = pid; + block.function = detector; + block.interface = interface; + block.usage_page = usage_page; + block.usage = usage; hid_wrapped_device_detectors.push_back(block); } @@ -425,98 +441,111 @@ void ResourceManager::RegisterPreDetectionHook(PreDetectionHookFunction hook) pre_detection_hooks.push_back(hook); } -void ResourceManager::RegisterDeviceListChangeCallback(DeviceListChangeCallback new_callback, void * new_callback_arg) +void ResourceManager::RegisterDeviceListChangeCallback(DeviceListChangeCallback new_callback, + void *new_callback_arg) { DeviceListChangeCallbacks.push_back(new_callback); DeviceListChangeCallbackArgs.push_back(new_callback_arg); - LOG_TRACE("[ResourceManager] Registered device list change callback. Total callbacks registered: %d", DeviceListChangeCallbacks.size()); + LOG_TRACE( + "[ResourceManager] Registered device list change callback. Total callbacks registered: %d", + DeviceListChangeCallbacks.size()); } -void ResourceManager::UnregisterDeviceListChangeCallback(DeviceListChangeCallback callback, void * callback_arg) +void ResourceManager::UnregisterDeviceListChangeCallback(DeviceListChangeCallback callback, + void *callback_arg) { - for(size_t idx = 0; idx < DeviceListChangeCallbacks.size(); idx++) - { - if(DeviceListChangeCallbacks[idx] == callback && DeviceListChangeCallbackArgs[idx] == callback_arg) - { + for (size_t idx = 0; idx < DeviceListChangeCallbacks.size(); idx++) { + if (DeviceListChangeCallbacks[idx] == callback + && DeviceListChangeCallbackArgs[idx] == callback_arg) { DeviceListChangeCallbacks.erase(DeviceListChangeCallbacks.begin() + idx); DeviceListChangeCallbackArgs.erase(DeviceListChangeCallbackArgs.begin() + idx); } } - LOG_TRACE("[ResourceManager] Unregistered device list change callback. Total callbacks registered: %d", DeviceListChangeCallbacks.size()); + LOG_TRACE("[ResourceManager] Unregistered device list change callback. Total callbacks " + "registered: %d", + DeviceListChangeCallbacks.size()); } -void ResourceManager::RegisterI2CBusListChangeCallback(I2CBusListChangeCallback new_callback, void * new_callback_arg) +void ResourceManager::RegisterI2CBusListChangeCallback(I2CBusListChangeCallback new_callback, + void *new_callback_arg) { I2CBusListChangeCallbacks.push_back(new_callback); I2CBusListChangeCallbackArgs.push_back(new_callback_arg); } -void ResourceManager::UnregisterI2CBusListChangeCallback(I2CBusListChangeCallback callback, void * callback_arg) +void ResourceManager::UnregisterI2CBusListChangeCallback(I2CBusListChangeCallback callback, + void *callback_arg) { - for(size_t idx = 0; idx < I2CBusListChangeCallbacks.size(); idx++) - { - if(I2CBusListChangeCallbacks[idx] == callback && I2CBusListChangeCallbackArgs[idx] == callback_arg) - { + for (size_t idx = 0; idx < I2CBusListChangeCallbacks.size(); idx++) { + if (I2CBusListChangeCallbacks[idx] == callback + && I2CBusListChangeCallbackArgs[idx] == callback_arg) { I2CBusListChangeCallbacks.erase(I2CBusListChangeCallbacks.begin() + idx); I2CBusListChangeCallbackArgs.erase(I2CBusListChangeCallbackArgs.begin() + idx); } } } -void ResourceManager::RegisterDetectionProgressCallback(DetectionProgressCallback new_callback, void *new_callback_arg) +void ResourceManager::RegisterDetectionProgressCallback(DetectionProgressCallback new_callback, + void *new_callback_arg) { DetectionProgressCallbacks.push_back(new_callback); DetectionProgressCallbackArgs.push_back(new_callback_arg); - LOG_TRACE("[ResourceManager] Registered detection progress callback. Total callbacks registered: %d", DetectionProgressCallbacks.size()); + LOG_TRACE( + "[ResourceManager] Registered detection progress callback. Total callbacks registered: %d", + DetectionProgressCallbacks.size()); } -void ResourceManager::UnregisterDetectionProgressCallback(DetectionProgressCallback callback, void *callback_arg) +void ResourceManager::UnregisterDetectionProgressCallback(DetectionProgressCallback callback, + void *callback_arg) { - for(size_t idx = 0; idx < DetectionProgressCallbacks.size(); idx++) - { - if(DetectionProgressCallbacks[idx] == callback && DetectionProgressCallbackArgs[idx] == callback_arg) - { + for (size_t idx = 0; idx < DetectionProgressCallbacks.size(); idx++) { + if (DetectionProgressCallbacks[idx] == callback + && DetectionProgressCallbackArgs[idx] == callback_arg) { DetectionProgressCallbacks.erase(DetectionProgressCallbacks.begin() + idx); DetectionProgressCallbackArgs.erase(DetectionProgressCallbackArgs.begin() + idx); } } - LOG_TRACE("[ResourceManager] Unregistered detection progress callback. Total callbacks registered: %d", DetectionProgressCallbacks.size()); + LOG_TRACE("[ResourceManager] Unregistered detection progress callback. Total callbacks " + "registered: %d", + DetectionProgressCallbacks.size()); } -void ResourceManager::RegisterDetectionStartCallback(DetectionStartCallback new_callback, void *new_callback_arg) +void ResourceManager::RegisterDetectionStartCallback(DetectionStartCallback new_callback, + void *new_callback_arg) { DetectionStartCallbacks.push_back(new_callback); DetectionStartCallbackArgs.push_back(new_callback_arg); } -void ResourceManager::UnregisterDetectionStartCallback(DetectionStartCallback callback, void *callback_arg) +void ResourceManager::UnregisterDetectionStartCallback(DetectionStartCallback callback, + void *callback_arg) { - for(size_t idx = 0; idx < DetectionStartCallbacks.size(); idx++) - { - if(DetectionStartCallbacks[idx] == callback && DetectionStartCallbackArgs[idx] == callback_arg) - { + for (size_t idx = 0; idx < DetectionStartCallbacks.size(); idx++) { + if (DetectionStartCallbacks[idx] == callback + && DetectionStartCallbackArgs[idx] == callback_arg) { DetectionStartCallbacks.erase(DetectionStartCallbacks.begin() + idx); DetectionStartCallbackArgs.erase(DetectionStartCallbackArgs.begin() + idx); } } } -void ResourceManager::RegisterDetectionEndCallback(DetectionEndCallback new_callback, void *new_callback_arg) +void ResourceManager::RegisterDetectionEndCallback(DetectionEndCallback new_callback, + void *new_callback_arg) { DetectionEndCallbacks.push_back(new_callback); DetectionEndCallbackArgs.push_back(new_callback_arg); } -void ResourceManager::UnregisterDetectionEndCallback(DetectionEndCallback callback, void *callback_arg) +void ResourceManager::UnregisterDetectionEndCallback(DetectionEndCallback callback, + void *callback_arg) { - for(size_t idx = 0; idx < DetectionEndCallbacks.size(); idx++) - { - if(DetectionEndCallbacks[idx] == callback && DetectionEndCallbackArgs[idx] == callback_arg) - { + for (size_t idx = 0; idx < DetectionEndCallbacks.size(); idx++) { + if (DetectionEndCallbacks[idx] == callback + && DetectionEndCallbackArgs[idx] == callback_arg) { DetectionEndCallbacks.erase(DetectionEndCallbacks.begin() + idx); DetectionEndCallbackArgs.erase(DetectionEndCallbackArgs.begin() + idx); } @@ -530,16 +559,14 @@ void ResourceManager::UpdateDeviceList() /*-------------------------------------------------*\ | Insert hardware controllers into controller list | \*-------------------------------------------------*/ - for(unsigned int hw_controller_idx = 0; hw_controller_idx < rgb_controllers_hw.size(); hw_controller_idx++) - { + for (unsigned int hw_controller_idx = 0; hw_controller_idx < rgb_controllers_hw.size(); + hw_controller_idx++) { /*-------------------------------------------------*\ | Check if the controller is already in the list | | at the correct index | \*-------------------------------------------------*/ - if(hw_controller_idx < rgb_controllers.size()) - { - if(rgb_controllers[hw_controller_idx] == rgb_controllers_hw[hw_controller_idx]) - { + if (hw_controller_idx < rgb_controllers.size()) { + if (rgb_controllers[hw_controller_idx] == rgb_controllers_hw[hw_controller_idx]) { continue; } } @@ -548,12 +575,12 @@ void ResourceManager::UpdateDeviceList() | If not, check if the controller is already in the | | list at a different index | \*-------------------------------------------------*/ - for(unsigned int controller_idx = 0; controller_idx < rgb_controllers.size(); controller_idx++) - { - if(rgb_controllers[controller_idx] == rgb_controllers_hw[hw_controller_idx]) - { + for (unsigned int controller_idx = 0; controller_idx < rgb_controllers.size(); + controller_idx++) { + if (rgb_controllers[controller_idx] == rgb_controllers_hw[hw_controller_idx]) { rgb_controllers.erase(rgb_controllers.begin() + controller_idx); - rgb_controllers.insert(rgb_controllers.begin() + hw_controller_idx, rgb_controllers_hw[hw_controller_idx]); + rgb_controllers.insert(rgb_controllers.begin() + hw_controller_idx, + rgb_controllers_hw[hw_controller_idx]); break; } } @@ -561,7 +588,8 @@ void ResourceManager::UpdateDeviceList() /*-------------------------------------------------*\ | If it still hasn't been found, add it to the list | \*-------------------------------------------------*/ - rgb_controllers.insert(rgb_controllers.begin() + hw_controller_idx, rgb_controllers_hw[hw_controller_idx]); + rgb_controllers.insert(rgb_controllers.begin() + hw_controller_idx, + rgb_controllers_hw[hw_controller_idx]); } /*-------------------------------------------------*\ @@ -585,9 +613,11 @@ void ResourceManager::DeviceListChanged() \*-------------------------------------------------*/ LOG_TRACE("[ResourceManager] Calling device list change callbacks."); - for(std::size_t callback_idx = 0; callback_idx < (unsigned int)DeviceListChangeCallbacks.size(); callback_idx++) - { - ResourceManager::DeviceListChangeCallbacks[callback_idx](DeviceListChangeCallbackArgs[callback_idx]); + for (std::size_t callback_idx = 0; + callback_idx < (unsigned int) DeviceListChangeCallbacks.size(); + callback_idx++) { + ResourceManager::DeviceListChangeCallbacks[callback_idx]( + DeviceListChangeCallbackArgs[callback_idx]); } } @@ -600,8 +630,9 @@ void ResourceManager::DetectionProgressChanged() \*-------------------------------------------------*/ LOG_TRACE("[ResourceManager] Calling detection progress callbacks."); - for(std::size_t callback_idx = 0; callback_idx < (unsigned int)DetectionProgressCallbacks.size(); callback_idx++) - { + for (std::size_t callback_idx = 0; + callback_idx < (unsigned int) DetectionProgressCallbacks.size(); + callback_idx++) { DetectionProgressCallbacks[callback_idx](DetectionProgressCallbackArgs[callback_idx]); } @@ -615,8 +646,9 @@ void ResourceManager::I2CBusListChanged() /*-------------------------------------------------*\ | Detection progress has changed, call the callbacks| \*-------------------------------------------------*/ - for(std::size_t callback_idx = 0; callback_idx < (unsigned int)I2CBusListChangeCallbacks.size(); callback_idx++) - { + for (std::size_t callback_idx = 0; + callback_idx < (unsigned int) I2CBusListChangeCallbacks.size(); + callback_idx++) { I2CBusListChangeCallbacks[callback_idx](I2CBusListChangeCallbackArgs[callback_idx]); } @@ -627,51 +659,43 @@ void ResourceManager::SetupConfigurationDirectory() { config_dir.clear(); #ifdef _WIN32 - const wchar_t* appdata = _wgetenv(L"APPDATA"); - if(appdata != NULL) - { + const wchar_t *appdata = _wgetenv(L"APPDATA"); + if (appdata != NULL) { config_dir = appdata; } #else - const char* xdg_config_home = getenv("XDG_CONFIG_HOME"); - const char* home = getenv("HOME"); + const char *xdg_config_home = getenv("XDG_CONFIG_HOME"); + const char *home = getenv("HOME"); /*-----------------------------------------------------*\ | Check both XDG_CONFIG_HOME and APPDATA environment | | variables. If neither exist, use current directory | \*-----------------------------------------------------*/ - if(xdg_config_home != NULL) - { + if (xdg_config_home != NULL) { config_dir = xdg_config_home; - } - else if(home != NULL) - { + } else if (home != NULL) { config_dir = home; config_dir /= ".config"; } #endif - /*-----------------------------------------------------*\ | If a configuration directory was found, append OpenRGB| \*-----------------------------------------------------*/ - if(config_dir != "") - { + if (config_dir != "") { config_dir.append("OpenRGB"); /*-------------------------------------------------------------------------*\ | Create OpenRGB configuration directory if it doesn't exist | \*-------------------------------------------------------------------------*/ filesystem::create_directories(config_dir); - } - else - { + } else { config_dir = "./"; } } filesystem::path ResourceManager::GetConfigurationDirectory() { - return(config_dir); + return (config_dir); } void ResourceManager::SetConfigurationDirectory(const filesystem::path &directory) @@ -681,29 +705,29 @@ void ResourceManager::SetConfigurationDirectory(const filesystem::path &director profile_manager->SetConfigurationDirectory(directory); rgb_controllers_sizes.clear(); - rgb_controllers_sizes = profile_manager->LoadProfileToList("sizes", true); + rgb_controllers_sizes = profile_manager->LoadProfileToList("sizes", true); } -NetworkServer* ResourceManager::GetServer() +NetworkServer *ResourceManager::GetServer() { - return(server); + return (server); } -static void NetworkClientInfoChangeCallback(void* this_ptr) +static void NetworkClientInfoChangeCallback(void *this_ptr) { - ResourceManager* this_obj = (ResourceManager*)this_ptr; + ResourceManager *this_obj = (ResourceManager *) this_ptr; this_obj->DeviceListChanged(); } -void ResourceManager::RegisterNetworkClient(NetworkClient* new_client) +void ResourceManager::RegisterNetworkClient(NetworkClient *new_client) { new_client->RegisterClientInfoChangeCallback(NetworkClientInfoChangeCallback, this); clients.push_back(new_client); } -void ResourceManager::UnregisterNetworkClient(NetworkClient* network_client) +void ResourceManager::UnregisterNetworkClient(NetworkClient *network_client) { /*-------------------------------------------------------------------------*\ | Stop the disconnecting client | @@ -718,10 +742,11 @@ void ResourceManager::UnregisterNetworkClient(NetworkClient* network_client) /*-------------------------------------------------------------------------*\ | Find the client to remove and remove it from the clients list | \*-------------------------------------------------------------------------*/ - std::vector::iterator client_it = std::find(clients.begin(), clients.end(), network_client); + std::vector::iterator client_it = std::find(clients.begin(), + clients.end(), + network_client); - if(client_it != clients.end()) - { + if (client_it != clients.end()) { clients.erase(client_it); } @@ -733,7 +758,6 @@ void ResourceManager::UnregisterNetworkClient(NetworkClient* network_client) UpdateDeviceList(); } - /******************************************************************************************\ * * * AttemptLocalConnection * @@ -745,14 +769,14 @@ void ResourceManager::UnregisterNetworkClient(NetworkClient* network_client) bool ResourceManager::AttemptLocalConnection() { detection_percent = 0; - detection_string = "Attempting local server connection..."; + detection_string = "Attempting local server connection..."; DetectionProgressChanged(); LOG_DEBUG("[ResourceManager] Attempting server connection..."); bool success = false; - NetworkClient * client = new NetworkClient(ResourceManager::get()->GetRGBControllers()); + NetworkClient *client = new NetworkClient(ResourceManager::get()->GetRGBControllers()); std::string titleString = "OpenRGB "; titleString.append(VERSION_STRING); @@ -760,17 +784,14 @@ bool ResourceManager::AttemptLocalConnection() client->SetName(titleString.c_str()); client->StartClient(); - for(int timeout = 0; timeout < 10; timeout++) - { - if(client->GetConnected()) - { + for (int timeout = 0; timeout < 10; timeout++) { + if (client->GetConnected()) { break; } std::this_thread::sleep_for(5ms); } - if(!client->GetConnected()) - { + if (!client->GetConnected()) { LOG_TRACE("[ResourceManager] Client failed to connect"); client->StopClient(); LOG_TRACE("[ResourceManager] Client stopped"); @@ -778,9 +799,7 @@ bool ResourceManager::AttemptLocalConnection() delete client; client = NULL; - } - else - { + } else { ResourceManager::get()->RegisterNetworkClient(client); LOG_TRACE("[ResourceManager] Registered network client"); @@ -790,10 +809,8 @@ bool ResourceManager::AttemptLocalConnection() | Wait up to 5 seconds for the client connection to | | retrieve all controllers | \*-----------------------------------------------------*/ - for(int timeout = 0; timeout < 1000; timeout++) - { - if(client->GetOnline()) - { + for (int timeout = 0; timeout < 1000; timeout++) { + if (client->GetOnline()) { break; } std::this_thread::sleep_for(5ms); @@ -803,24 +820,24 @@ bool ResourceManager::AttemptLocalConnection() return success; } -std::vector& ResourceManager::GetClients() +std::vector &ResourceManager::GetClients() { - return(clients); + return (clients); } -ProfileManager* ResourceManager::GetProfileManager() +ProfileManager *ResourceManager::GetProfileManager() { - return(profile_manager); + return (profile_manager); } -SettingsManager* ResourceManager::GetSettingsManager() +SettingsManager *ResourceManager::GetSettingsManager() { - return(settings_manager); + return (settings_manager); } bool ResourceManager::GetDetectionEnabled() { - return(detection_enabled); + return (detection_enabled); } unsigned int ResourceManager::GetDetectionPercent() @@ -839,12 +856,11 @@ void ResourceManager::Cleanup() std::vector rgb_controllers_hw_copy = rgb_controllers_hw; - for(std::size_t hw_controller_idx = 0; hw_controller_idx < rgb_controllers_hw.size(); hw_controller_idx++) - { - for(std::size_t controller_idx = 0; controller_idx < rgb_controllers.size(); controller_idx++) - { - if(rgb_controllers[controller_idx] == rgb_controllers_hw[hw_controller_idx]) - { + for (std::size_t hw_controller_idx = 0; hw_controller_idx < rgb_controllers_hw.size(); + hw_controller_idx++) { + for (std::size_t controller_idx = 0; controller_idx < rgb_controllers.size(); + controller_idx++) { + if (rgb_controllers[controller_idx] == rgb_controllers_hw[hw_controller_idx]) { rgb_controllers.erase(rgb_controllers.begin() + controller_idx); break; } @@ -858,8 +874,7 @@ void ResourceManager::Cleanup() rgb_controllers_hw.clear(); detection_prev_size = 0; - for(RGBController* rgb_controller : rgb_controllers_hw_copy) - { + for (RGBController *rgb_controller : rgb_controllers_hw_copy) { delete rgb_controller; } @@ -867,8 +882,7 @@ void ResourceManager::Cleanup() busses.clear(); - for(i2c_smbus_interface* bus : busses_copy) - { + for (i2c_smbus_interface *bus : busses_copy) { delete bus; } @@ -877,16 +891,14 @@ void ResourceManager::Cleanup() void ResourceManager::ProcessPreDetectionHooks() { - for(std::size_t hook_idx = 0; hook_idx < pre_detection_hooks.size(); hook_idx++) - { + for (std::size_t hook_idx = 0; hook_idx < pre_detection_hooks.size(); hook_idx++) { pre_detection_hooks[hook_idx](); } } void ResourceManager::ProcessDynamicDetectors() { - for(std::size_t detector_idx = 0; detector_idx < dynamic_detectors.size(); detector_idx++) - { + for (std::size_t detector_idx = 0; detector_idx < dynamic_detectors.size(); detector_idx++) { dynamic_detectors[detector_idx](); } @@ -908,8 +920,7 @@ bool ResourceManager::ProcessPreDetection() /*-----------------------------------------------------*\ | Process Dynamic Detectors | \*-----------------------------------------------------*/ - if(!dynamic_detectors_processed) - { + if (!dynamic_detectors_processed) { ProcessDynamicDetectors(); } @@ -918,8 +929,8 @@ bool ResourceManager::ProcessPreDetection() \*-----------------------------------------------------*/ LOG_TRACE("[ResourceManager] Calling detection start callbacks."); - for(std::size_t callback_idx = 0; callback_idx < DetectionStartCallbacks.size(); callback_idx++) - { + for (std::size_t callback_idx = 0; callback_idx < DetectionStartCallbacks.size(); + callback_idx++) { DetectionStartCallbacks[callback_idx](DetectionStartCallbackArgs[callback_idx]); } @@ -927,13 +938,11 @@ bool ResourceManager::ProcessPreDetection() | Update the detector settings | \*-----------------------------------------------------*/ UpdateDetectorSettings(); - if(detection_enabled) - { + if (detection_enabled) { /*-------------------------------------------------*\ | Do nothing is it is already detecting devices | \*-------------------------------------------------*/ - if(detection_is_required.load()) - { + if (detection_is_required.load()) { return false; } @@ -942,7 +951,7 @@ bool ResourceManager::ProcessPreDetection() | we shall remove it first | \*-------------------------------------------------*/ detection_percent = 0; - detection_string = ""; + detection_string = ""; DetectionProgressChanged(); @@ -955,7 +964,8 @@ bool ResourceManager::ProcessPreDetection() \*-------------------------------------------------*/ int hid_status = hid_init(); - LOG_INFO("[ResourceManager] Initializing HID interfaces: %s", ((hid_status == 0) ? "Success" : "Failed")); + LOG_INFO("[ResourceManager] Initializing HID interfaces: %s", + ((hid_status == 0) ? "Success" : "Failed")); /*-------------------------------------------------*\ | Mark the detection as ongoing | @@ -970,14 +980,12 @@ bool ResourceManager::ProcessPreDetection() void ResourceManager::DetectDevices() { - if(ProcessPreDetection()) - { + if (ProcessPreDetection()) { // Run the detection coroutine RunInBackgroundThread(std::bind(&ResourceManager::DetectDevicesCoroutine, this)); } - if(!detection_enabled) - { + if (!detection_enabled) { ProcessPostDetection(); } } @@ -987,15 +995,14 @@ void ResourceManager::ProcessPostDetection() /*-------------------------------------------------*\ | Signal that detection is complete | \*-------------------------------------------------*/ - detection_percent = 100; + detection_percent = 100; DetectionProgressChanged(); LOG_INFO("[ResourceManager] Calling Post-detection callbacks"); /*-----------------------------------------------------*\ | Call detection end callbacks | \*-----------------------------------------------------*/ - for(std::size_t callback_idx = 0; callback_idx < DetectionEndCallbacks.size(); callback_idx++) - { + for (std::size_t callback_idx = 0; callback_idx < DetectionEndCallbacks.size(); callback_idx++) { DetectionEndCallbacks[callback_idx](DetectionEndCallbackArgs[callback_idx]); } @@ -1015,13 +1022,13 @@ void ResourceManager::DetectDevicesCoroutine() { DetectDeviceMutex.lock(); - hid_device_info* current_hid_device; - float percent = 0.0f; - float percent_denominator = 0.0f; - json detector_settings; - unsigned int hid_device_count = 0; - hid_device_info* hid_devices = NULL; - bool hid_safe_mode = false; + hid_device_info *current_hid_device; + float percent = 0.0f; + float percent_denominator = 0.0f; + json detector_settings; + unsigned int hid_device_count = 0; + hid_device_info *hid_devices = NULL; + bool hid_safe_mode = false; LOG_INFO("------------------------------------------------------"); LOG_INFO("| Start device detection |"); @@ -1032,8 +1039,8 @@ void ResourceManager::DetectDevicesCoroutine() \*-------------------------------------------------*/ detection_size_entry_used.resize(rgb_controllers_sizes.size()); - for(std::size_t size_idx = 0; size_idx < (unsigned int)detection_size_entry_used.size(); size_idx++) - { + for (std::size_t size_idx = 0; size_idx < (unsigned int) detection_size_entry_used.size(); + size_idx++) { detection_size_entry_used[size_idx] = false; } @@ -1046,8 +1053,7 @@ void ResourceManager::DetectDevicesCoroutine() /*-------------------------------------------------*\ | Check HID safe mode setting | \*-------------------------------------------------*/ - if(detector_settings.contains("hid_safe_mode")) - { + if (detector_settings.contains("hid_safe_mode")) { hid_safe_mode = detector_settings["hid_safe_mode"]; } @@ -1059,21 +1065,21 @@ void ResourceManager::DetectDevicesCoroutine() | Start by iterating through all HID devices in | | list to get a total count | \*-------------------------------------------------*/ - if(!hid_safe_mode) - { + if (!hid_safe_mode) { hid_devices = hid_enumerate(0, 0); } current_hid_device = hid_devices; - while(current_hid_device) - { + while (current_hid_device) { hid_device_count++; current_hid_device = current_hid_device->next; } - percent_denominator = (float)(i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + i2c_pci_device_detectors.size() + device_detectors.size()) + (float)hid_device_count; + percent_denominator = (float) (i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + + i2c_pci_device_detectors.size() + device_detectors.size()) + + (float) hid_device_count; /*-------------------------------------------------*\ | Start at 0% detection progress | @@ -1084,21 +1090,16 @@ void ResourceManager::DetectDevicesCoroutine() /*-------------------------------------------------*\ | Check if the udev rules exist | \*-------------------------------------------------*/ - bool udev_not_exist = false; - bool udev_multiple = false; + bool udev_not_exist = false; + bool udev_multiple = false; - if(access("/etc/udev/rules.d/60-openrgb.rules", F_OK) != 0) - { - if(access("/usr/lib/udev/rules.d/60-openrgb.rules", F_OK) != 0) - { - udev_not_exist = true; + if (access("/etc/udev/rules.d/60-openrgb.rules", F_OK) != 0) { + if (access("/usr/lib/udev/rules.d/60-openrgb.rules", F_OK) != 0) { + udev_not_exist = true; } - } - else - { - if(access("/usr/lib/udev/rules.d/60-openrgb.rules", F_OK) == 0) - { - udev_multiple = true; + } else { + if (access("/usr/lib/udev/rules.d/60-openrgb.rules", F_OK) == 0) { + udev_multiple = true; } } #endif @@ -1112,10 +1113,11 @@ void ResourceManager::DetectDevicesCoroutine() bool i2c_interface_fail = false; - for(unsigned int i2c_bus_detector_idx = 0; i2c_bus_detector_idx < (unsigned int)i2c_bus_detectors.size() && detection_is_required.load(); i2c_bus_detector_idx++) - { - if(i2c_bus_detectors[i2c_bus_detector_idx]() == false) - { + for (unsigned int i2c_bus_detector_idx = 0; + i2c_bus_detector_idx < (unsigned int) i2c_bus_detectors.size() + && detection_is_required.load(); + i2c_bus_detector_idx++) { + if (i2c_bus_detectors[i2c_bus_detector_idx]() == false) { i2c_interface_fail = true; } @@ -1128,8 +1130,10 @@ void ResourceManager::DetectDevicesCoroutine() LOG_INFO("------------------------------------------------------"); LOG_INFO("| Detecting I2C devices |"); LOG_INFO("------------------------------------------------------"); - for(unsigned int i2c_detector_idx = 0; i2c_detector_idx < (unsigned int)i2c_device_detectors.size() && detection_is_required.load(); i2c_detector_idx++) - { + for (unsigned int i2c_detector_idx = 0; + i2c_detector_idx < (unsigned int) i2c_device_detectors.size() + && detection_is_required.load(); + i2c_detector_idx++) { std::size_t controller_size = rgb_controllers_hw.size(); detection_string = i2c_device_detector_strings[i2c_detector_idx].c_str(); @@ -1137,14 +1141,15 @@ void ResourceManager::DetectDevicesCoroutine() | Check if this detector is enabled | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); + if (this_device_enabled) { DetectionProgressChanged(); i2c_device_detectors[i2c_detector_idx](busses); @@ -1154,8 +1159,7 @@ void ResourceManager::DetectDevicesCoroutine() | If the device list size has changed, call the | | device list changed callbacks | \*-------------------------------------------------*/ - if(rgb_controllers_hw.size() == controller_size) - { + if (rgb_controllers_hw.size() == controller_size) { LOG_DEBUG("[%s] no devices found", detection_string); } @@ -1164,9 +1168,9 @@ void ResourceManager::DetectDevicesCoroutine() /*-------------------------------------------------*\ | Update detection percent | \*-------------------------------------------------*/ - percent = ((float)i2c_detector_idx + 1.0f) / percent_denominator; + percent = ((float) i2c_detector_idx + 1.0f) / percent_denominator; - detection_percent = (unsigned int)(percent * 100.0f); + detection_percent = (unsigned int) (percent * 100.0f); } /*-------------------------------------------------*\ @@ -1175,49 +1179,55 @@ void ResourceManager::DetectDevicesCoroutine() LOG_INFO("------------------------------------------------------"); LOG_INFO("| Detecting I2C DIMM modules |"); LOG_INFO("------------------------------------------------------"); - for(unsigned int bus = 0; bus < busses.size() && IsAnyDimmDetectorEnabled(detector_settings); bus++) - { + for (unsigned int bus = 0; bus < busses.size() && IsAnyDimmDetectorEnabled(detector_settings); + bus++) { IF_DRAM_SMBUS(busses[bus]->pci_vendor, busses[bus]->pci_device) { std::vector slots; SPDMemoryType dimm_type = SPD_RESERVED; - for(uint8_t spd_addr = 0x50; spd_addr < 0x58; spd_addr++) - { + for (uint8_t spd_addr = 0x50; spd_addr < 0x58; spd_addr++) { SPDDetector spd(busses[bus], spd_addr, dimm_type); - if(spd.is_valid()) - { + if (spd.is_valid()) { SPDWrapper accessor(spd); dimm_type = spd.memory_type(); - LOG_INFO("[ResourceManager] Detected occupied slot %d, bus %d, type %s", spd_addr - 0x50 + 1, bus, spd_memory_type_name[dimm_type]); + LOG_INFO("[ResourceManager] Detected occupied slot %d, bus %d, type %s", + spd_addr - 0x50 + 1, + bus, + spd_memory_type_name[dimm_type]); LOG_DEBUG("[ResourceManager] Jedec ID: 0x%04x", accessor.jedec_id()); slots.push_back(accessor); } } - for(unsigned int i2c_detector_idx = 0; i2c_detector_idx < i2c_dimm_device_detectors.size() && detection_is_required.load(); i2c_detector_idx++) - { - if(i2c_dimm_device_detectors[i2c_detector_idx].dimm_type == dimm_type && - is_jedec_in_slots(slots, i2c_dimm_device_detectors[i2c_detector_idx].jedec_id)) - { + for (unsigned int i2c_detector_idx = 0; + i2c_detector_idx < i2c_dimm_device_detectors.size() && detection_is_required.load(); + i2c_detector_idx++) { + if (i2c_dimm_device_detectors[i2c_detector_idx].dimm_type == dimm_type + && is_jedec_in_slots(slots, + i2c_dimm_device_detectors[i2c_detector_idx].jedec_id)) { detection_string = i2c_dimm_device_detectors[i2c_detector_idx].name.c_str(); /*-------------------------------------------------*\ | Check if this detector is enabled | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); + if (this_device_enabled) { DetectionProgressChanged(); - std::vector matching_slots = slots_with_jedec(slots, i2c_dimm_device_detectors[i2c_detector_idx].jedec_id); - i2c_dimm_device_detectors[i2c_detector_idx].function(busses[bus], matching_slots); + std::vector matching_slots + = slots_with_jedec(slots, + i2c_dimm_device_detectors[i2c_detector_idx].jedec_id); + i2c_dimm_device_detectors[i2c_detector_idx].function(busses[bus], + matching_slots); } LOG_TRACE("[%s] detection end", detection_string); @@ -1226,9 +1236,10 @@ void ResourceManager::DetectDevicesCoroutine() /*-------------------------------------------------*\ | Update detection percent | \*-------------------------------------------------*/ - percent = (i2c_device_detectors.size() + i2c_detector_idx + 1.0f) / percent_denominator; + percent = (i2c_device_detectors.size() + i2c_detector_idx + 1.0f) + / percent_denominator; - detection_percent = (unsigned int)(percent * 100.0f); + detection_percent = (unsigned int) (percent * 100.0f); } } } @@ -1239,32 +1250,38 @@ void ResourceManager::DetectDevicesCoroutine() LOG_INFO("------------------------------------------------------"); LOG_INFO("| Detecting I2C PCI devices |"); LOG_INFO("------------------------------------------------------"); - for(unsigned int i2c_detector_idx = 0; i2c_detector_idx < (unsigned int)i2c_pci_device_detectors.size() && detection_is_required.load(); i2c_detector_idx++) - { + for (unsigned int i2c_detector_idx = 0; + i2c_detector_idx < (unsigned int) i2c_pci_device_detectors.size() + && detection_is_required.load(); + i2c_detector_idx++) { detection_string = i2c_pci_device_detectors[i2c_detector_idx].name.c_str(); /*-------------------------------------------------*\ | Check if this detector is enabled | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); + if (this_device_enabled) { DetectionProgressChanged(); - for(unsigned int bus = 0; bus < busses.size(); bus++) - { - if(busses[bus]->pci_vendor == i2c_pci_device_detectors[i2c_detector_idx].ven_id && - busses[bus]->pci_device == i2c_pci_device_detectors[i2c_detector_idx].dev_id && - busses[bus]->pci_subsystem_vendor == i2c_pci_device_detectors[i2c_detector_idx].subven_id && - busses[bus]->pci_subsystem_device == i2c_pci_device_detectors[i2c_detector_idx].subdev_id) - { - i2c_pci_device_detectors[i2c_detector_idx].function(busses[bus], i2c_pci_device_detectors[i2c_detector_idx].i2c_addr, i2c_pci_device_detectors[i2c_detector_idx].name); + for (unsigned int bus = 0; bus < busses.size(); bus++) { + if (busses[bus]->pci_vendor == i2c_pci_device_detectors[i2c_detector_idx].ven_id + && busses[bus]->pci_device == i2c_pci_device_detectors[i2c_detector_idx].dev_id + && busses[bus]->pci_subsystem_vendor + == i2c_pci_device_detectors[i2c_detector_idx].subven_id + && busses[bus]->pci_subsystem_device + == i2c_pci_device_detectors[i2c_detector_idx].subdev_id) { + i2c_pci_device_detectors[i2c_detector_idx] + .function(busses[bus], + i2c_pci_device_detectors[i2c_detector_idx].i2c_addr, + i2c_pci_device_detectors[i2c_detector_idx].name); } } } @@ -1274,9 +1291,11 @@ void ResourceManager::DetectDevicesCoroutine() /*-------------------------------------------------*\ | Update detection percent | \*-------------------------------------------------*/ - percent = (i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + i2c_detector_idx + 1.0f) / percent_denominator; + percent = (i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + i2c_detector_idx + + 1.0f) + / percent_denominator; - detection_percent = (unsigned int)(percent * 100.0f); + detection_percent = (unsigned int) (percent * 100.0f); } /*-------------------------------------------------*\ @@ -1287,30 +1306,31 @@ void ResourceManager::DetectDevicesCoroutine() LOG_INFO("------------------------------------------------------"); LOG_INFO("| Detecting HID devices |"); if (hid_safe_mode) - LOG_INFO("| with safe mode |"); + LOG_INFO("| with safe mode |"); LOG_INFO("------------------------------------------------------"); current_hid_device = hid_devices; - if(hid_safe_mode) - { + if (hid_safe_mode) { /*-----------------------------------------------------------------------------*\ | Loop through all available detectors. If all required information matches, | | run the detector | \*-----------------------------------------------------------------------------*/ - for(unsigned int hid_detector_idx = 0; hid_detector_idx < (unsigned int)hid_device_detectors.size() && detection_is_required.load(); hid_detector_idx++) - { - HIDDeviceDetectorBlock & detector = hid_device_detectors[hid_detector_idx]; + for (unsigned int hid_detector_idx = 0; + hid_detector_idx < (unsigned int) hid_device_detectors.size() + && detection_is_required.load(); + hid_detector_idx++) { + HIDDeviceDetectorBlock &detector = hid_device_detectors[hid_detector_idx]; hid_devices = hid_enumerate(detector.vid, detector.pid); - LOG_VERBOSE("[ResourceManager] Trying to run detector for [%s] (for %04x:%04x)", detector.name.c_str(), detector.vid, detector.pid); + LOG_VERBOSE("[ResourceManager] Trying to run detector for [%s] (for %04x:%04x)", + detector.name.c_str(), + detector.vid, + detector.pid); current_hid_device = hid_devices; - while(current_hid_device) - { - - if(detector.compare(current_hid_device)) - { + while (current_hid_device) { + if (detector.compare(current_hid_device)) { detection_string = detector.name.c_str(); /*-------------------------------------------------*\ @@ -1318,18 +1338,20 @@ void ResourceManager::DetectDevicesCoroutine() | added to the settings list | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + if (this_device_enabled) { DetectionProgressChanged(); - detector.function(current_hid_device, hid_device_detectors[hid_detector_idx].name); + detector.function(current_hid_device, + hid_device_detectors[hid_detector_idx].name); LOG_TRACE("[%s] detection end", detection_string); } @@ -1340,22 +1362,27 @@ void ResourceManager::DetectDevicesCoroutine() hid_free_enumeration(hid_devices); } - } - else - { + } else { /*-------------------------------------------------*\ | Iterate through all devices in list and run | | detectors | \*-------------------------------------------------*/ hid_device_count = 0; - while(current_hid_device) - { - if(LogManager::get()->getLoglevel() >= LL_DEBUG) - { - const char* manu_name = StringUtils::wchar_to_char(current_hid_device->manufacturer_string); - const char* prod_name = StringUtils::wchar_to_char(current_hid_device->product_string); - LOG_DEBUG("[%04X:%04X U=%04X P=0x%04X I=%d] %-25s - %s", current_hid_device->vendor_id, current_hid_device->product_id, current_hid_device->usage, current_hid_device->usage_page, current_hid_device->interface_number, manu_name, prod_name); + while (current_hid_device) { + if (LogManager::get()->getLoglevel() >= LL_DEBUG) { + const char *manu_name = StringUtils::wchar_to_char( + current_hid_device->manufacturer_string); + const char *prod_name = StringUtils::wchar_to_char( + current_hid_device->product_string); + LOG_DEBUG("[%04X:%04X U=%04X P=0x%04X I=%d] %-25s - %s", + current_hid_device->vendor_id, + current_hid_device->product_id, + current_hid_device->usage, + current_hid_device->usage_page, + current_hid_device->interface_number, + manu_name, + prod_name); } detection_string = ""; DetectionProgressChanged(); @@ -1364,11 +1391,12 @@ void ResourceManager::DetectDevicesCoroutine() | Loop through all available detectors. If all required information matches, | | run the detector | \*-----------------------------------------------------------------------------*/ - for(unsigned int hid_detector_idx = 0; hid_detector_idx < (unsigned int)hid_device_detectors.size() && detection_is_required.load(); hid_detector_idx++) - { - HIDDeviceDetectorBlock & detector = hid_device_detectors[hid_detector_idx]; - if(detector.compare(current_hid_device)) - { + for (unsigned int hid_detector_idx = 0; + hid_detector_idx < (unsigned int) hid_device_detectors.size() + && detection_is_required.load(); + hid_detector_idx++) { + HIDDeviceDetectorBlock &detector = hid_device_detectors[hid_detector_idx]; + if (detector.compare(current_hid_device)) { detection_string = detector.name.c_str(); /*-------------------------------------------------*\ @@ -1376,18 +1404,20 @@ void ResourceManager::DetectDevicesCoroutine() | added to the settings list | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + if (this_device_enabled) { DetectionProgressChanged(); - detector.function(current_hid_device, hid_device_detectors[hid_detector_idx].name); + detector.function(current_hid_device, + hid_device_detectors[hid_detector_idx].name); } } } @@ -1396,11 +1426,13 @@ void ResourceManager::DetectDevicesCoroutine() | Loop through all available wrapped HID detectors. If all required | | information matches, run the detector | \*-----------------------------------------------------------------------------*/ - for(unsigned int hid_detector_idx = 0; hid_detector_idx < (unsigned int)hid_wrapped_device_detectors.size() && detection_is_required.load(); hid_detector_idx++) - { - HIDWrappedDeviceDetectorBlock & detector = hid_wrapped_device_detectors[hid_detector_idx]; - if(detector.compare(current_hid_device)) - { + for (unsigned int hid_detector_idx = 0; + hid_detector_idx < (unsigned int) hid_wrapped_device_detectors.size() + && detection_is_required.load(); + hid_detector_idx++) { + HIDWrappedDeviceDetectorBlock &detector + = hid_wrapped_device_detectors[hid_detector_idx]; + if (detector.compare(current_hid_device)) { detection_string = detector.name.c_str(); /*-------------------------------------------------*\ @@ -1408,18 +1440,21 @@ void ResourceManager::DetectDevicesCoroutine() | added to the settings list | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + if (this_device_enabled) { DetectionProgressChanged(); - detector.function(default_wrapper, current_hid_device, hid_wrapped_device_detectors[hid_detector_idx].name); + detector.function(default_wrapper, + current_hid_device, + hid_wrapped_device_detectors[hid_detector_idx].name); } } } @@ -1429,9 +1464,11 @@ void ResourceManager::DetectDevicesCoroutine() \*-------------------------------------------------*/ hid_device_count++; - percent = (i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + i2c_pci_device_detectors.size() + hid_device_count) / percent_denominator; + percent = (i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + + i2c_pci_device_detectors.size() + hid_device_count) + / percent_denominator; - detection_percent = (unsigned int)(percent * 100.0f); + detection_percent = (unsigned int) (percent * 100.0f); /*-------------------------------------------------*\ | Move on to the next HID device | @@ -1456,33 +1493,34 @@ void ResourceManager::DetectDevicesCoroutine() LOG_INFO("| Detecting libusb HID devices |"); LOG_INFO("------------------------------------------------------"); - void * dyn_handle = NULL; + void *dyn_handle = NULL; hidapi_wrapper wrapper; /*-------------------------------------------------*\ | Load the libhidapi-libusb library | \*-------------------------------------------------*/ #ifdef __GLIBC__ - if((dyn_handle = dlopen("libhidapi-libusb.so", RTLD_NOW | RTLD_NODELETE | RTLD_DEEPBIND))) + if ((dyn_handle = dlopen("libhidapi-libusb.so", RTLD_NOW | RTLD_NODELETE | RTLD_DEEPBIND))) #else - if(dyn_handle = dlopen("libhidapi-libusb.so", RTLD_NOW | RTLD_NODELETE )) + if (dyn_handle = dlopen("libhidapi-libusb.so", RTLD_NOW | RTLD_NODELETE)) #endif { /*-------------------------------------------------*\ | Create a wrapper with the libusb functions | \*-------------------------------------------------*/ - wrapper = - { - .dyn_handle = dyn_handle, - .hid_send_feature_report = (hidapi_wrapper_send_feature_report) dlsym(dyn_handle,"hid_send_feature_report"), - .hid_get_feature_report = (hidapi_wrapper_get_feature_report) dlsym(dyn_handle,"hid_get_feature_report"), - .hid_get_serial_number_string = (hidapi_wrapper_get_serial_number_string) dlsym(dyn_handle,"hid_get_serial_number_string"), - .hid_open_path = (hidapi_wrapper_open_path) dlsym(dyn_handle,"hid_open_path"), - .hid_enumerate = (hidapi_wrapper_enumerate) dlsym(dyn_handle,"hid_enumerate"), - .hid_free_enumeration = (hidapi_wrapper_free_enumeration) dlsym(dyn_handle,"hid_free_enumeration"), - .hid_close = (hidapi_wrapper_close) dlsym(dyn_handle,"hid_close"), - .hid_error = (hidapi_wrapper_error) dlsym(dyn_handle,"hid_free_enumeration") - }; + wrapper = {.dyn_handle = dyn_handle, + .hid_send_feature_report = (hidapi_wrapper_send_feature_report) + dlsym(dyn_handle, "hid_send_feature_report"), + .hid_get_feature_report = (hidapi_wrapper_get_feature_report) + dlsym(dyn_handle, "hid_get_feature_report"), + .hid_get_serial_number_string = (hidapi_wrapper_get_serial_number_string) + dlsym(dyn_handle, "hid_get_serial_number_string"), + .hid_open_path = (hidapi_wrapper_open_path) dlsym(dyn_handle, "hid_open_path"), + .hid_enumerate = (hidapi_wrapper_enumerate) dlsym(dyn_handle, "hid_enumerate"), + .hid_free_enumeration = (hidapi_wrapper_free_enumeration) + dlsym(dyn_handle, "hid_free_enumeration"), + .hid_close = (hidapi_wrapper_close) dlsym(dyn_handle, "hid_close"), + .hid_error = (hidapi_wrapper_error) dlsym(dyn_handle, "hid_free_enumeration")}; hid_devices = wrapper.hid_enumerate(0, 0); @@ -1494,13 +1532,20 @@ void ResourceManager::DetectDevicesCoroutine() \*-------------------------------------------------*/ hid_device_count = 0; - while(current_hid_device) - { - if(LogManager::get()->getLoglevel() >= LL_DEBUG) - { - const char* manu_name = StringUtils::wchar_to_char(current_hid_device->manufacturer_string); - const char* prod_name = StringUtils::wchar_to_char(current_hid_device->product_string); - LOG_DEBUG("[%04X:%04X U=%04X P=0x%04X I=%d] %-25s - %s", current_hid_device->vendor_id, current_hid_device->product_id, current_hid_device->usage, current_hid_device->usage_page, current_hid_device->interface_number, manu_name, prod_name); + while (current_hid_device) { + if (LogManager::get()->getLoglevel() >= LL_DEBUG) { + const char *manu_name = StringUtils::wchar_to_char( + current_hid_device->manufacturer_string); + const char *prod_name = StringUtils::wchar_to_char( + current_hid_device->product_string); + LOG_DEBUG("[%04X:%04X U=%04X P=0x%04X I=%d] %-25s - %s", + current_hid_device->vendor_id, + current_hid_device->product_id, + current_hid_device->usage, + current_hid_device->usage_page, + current_hid_device->interface_number, + manu_name, + prod_name); } detection_string = ""; DetectionProgressChanged(); @@ -1509,11 +1554,13 @@ void ResourceManager::DetectDevicesCoroutine() | Loop through all available wrapped HID detectors. If all required | | information matches, run the detector | \*-----------------------------------------------------------------------------*/ - for(unsigned int hid_detector_idx = 0; hid_detector_idx < (unsigned int)hid_wrapped_device_detectors.size() && detection_is_required.load(); hid_detector_idx++) - { - HIDWrappedDeviceDetectorBlock & detector = hid_wrapped_device_detectors[hid_detector_idx]; - if(detector.compare(current_hid_device)) - { + for (unsigned int hid_detector_idx = 0; + hid_detector_idx < (unsigned int) hid_wrapped_device_detectors.size() + && detection_is_required.load(); + hid_detector_idx++) { + HIDWrappedDeviceDetectorBlock &detector + = hid_wrapped_device_detectors[hid_detector_idx]; + if (detector.compare(current_hid_device)) { detection_string = detector.name.c_str(); /*-------------------------------------------------*\ @@ -1521,15 +1568,16 @@ void ResourceManager::DetectDevicesCoroutine() | added to the settings list | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + if (this_device_enabled) { DetectionProgressChanged(); detector.function(wrapper, current_hid_device, detector.name); @@ -1542,7 +1590,9 @@ void ResourceManager::DetectDevicesCoroutine() \*-------------------------------------------------*/ hid_device_count++; - percent = (i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + i2c_pci_device_detectors.size() + hid_device_count) / percent_denominator; + percent = (i2c_device_detectors.size() + i2c_dimm_device_detectors.size() + + i2c_pci_device_detectors.size() + hid_device_count) + / percent_denominator; detection_percent = percent * 100.0f; @@ -1567,23 +1617,25 @@ void ResourceManager::DetectDevicesCoroutine() LOG_INFO("| Detecting other devices |"); LOG_INFO("------------------------------------------------------"); - for(unsigned int detector_idx = 0; detector_idx < (unsigned int)device_detectors.size() && detection_is_required.load(); detector_idx++) - { + for (unsigned int detector_idx = 0; + detector_idx < (unsigned int) device_detectors.size() && detection_is_required.load(); + detector_idx++) { detection_string = device_detector_strings[detector_idx].c_str(); /*-------------------------------------------------*\ | Check if this detector is enabled | \*-------------------------------------------------*/ bool this_device_enabled = true; - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string)) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string)) { this_device_enabled = detector_settings["detectors"][detection_string]; } - LOG_DEBUG("[%s] is %s", detection_string, ((this_device_enabled == true) ? "enabled" : "disabled")); + LOG_DEBUG("[%s] is %s", + detection_string, + ((this_device_enabled == true) ? "enabled" : "disabled")); - if(this_device_enabled) - { + if (this_device_enabled) { DetectionProgressChanged(); device_detectors[detector_idx](); @@ -1594,9 +1646,10 @@ void ResourceManager::DetectDevicesCoroutine() /*-------------------------------------------------*\ | Update detection percent | \*-------------------------------------------------*/ - percent = (i2c_device_detectors.size() + hid_device_count + detector_idx + 1.0f) / percent_denominator; + percent = (i2c_device_detectors.size() + hid_device_count + detector_idx + 1.0f) + / percent_denominator; - detection_percent = (unsigned int)(percent * 100.0f); + detection_percent = (unsigned int) (percent * 100.0f); } /*-------------------------------------------------*\ @@ -1612,23 +1665,21 @@ void ResourceManager::DetectDevicesCoroutine() | If the udev rules file is not installed, show a | | dialog | \*-------------------------------------------------*/ - if(udev_not_exist) - { + if (udev_not_exist) { LOG_DIALOG("%s", UDEV_MISSING); - udev_multiple = false; - i2c_interface_fail = false; + udev_multiple = false; + i2c_interface_fail = false; } /*-------------------------------------------------*\ | If multiple udev rules files are installed, show | | a dialog | \*-------------------------------------------------*/ - if(udev_multiple) - { + if (udev_multiple) { LOG_DIALOG("%s", UDEV_MUTLI); - i2c_interface_fail = false; + i2c_interface_fail = false; } #endif @@ -1637,8 +1688,7 @@ void ResourceManager::DetectDevicesCoroutine() | If any i2c interfaces failed to detect due to an | | error condition, show a dialog | \*-------------------------------------------------*/ - if(i2c_interface_fail) - { + if (i2c_interface_fail) { #ifdef _WIN32 LOG_DIALOG("%s", I2C_ERR_WIN); #endif @@ -1656,13 +1706,16 @@ void ResourceManager::StopDeviceDetection() detection_string = "Stopping"; } -void ResourceManager::Initialize(bool tryConnect, bool detectDevices, bool startServer, bool applyPostOptions) +void ResourceManager::Initialize(bool tryConnect, + bool detectDevices, + bool startServer, + bool applyPostOptions) { // Cache the parameters // TODO: Possibly cache them in the CLI file somewhere - tryAutoConnect = tryConnect; - detection_enabled = detectDevices; - start_server = startServer; + tryAutoConnect = tryConnect; + detection_enabled = detectDevices; + start_server = startServer; apply_post_options = applyPostOptions; RunInBackgroundThread(std::bind(&ResourceManager::InitCoroutine, this)); @@ -1670,19 +1723,15 @@ void ResourceManager::Initialize(bool tryConnect, bool detectDevices, bool start void ResourceManager::InitCoroutine() { - if(tryAutoConnect) - { + if (tryAutoConnect) { detection_percent = 0; - detection_string = "Attempting server connection..."; + detection_string = "Attempting server connection..."; DetectionProgressChanged(); // Disable detection if a local server was found - if(AttemptLocalConnection()) - { + if (AttemptLocalConnection()) { DisableDetection(); - } - else - { + } else { LOG_DEBUG("[ResourceManager] Local OpenRGB server connected, running in client mode"); } tryAutoConnect = false; @@ -1693,29 +1742,23 @@ void ResourceManager::InitCoroutine() | Done in the same thread (InitThread), as we need to wait | | for completion anyway | \*---------------------------------------------------------*/ - if(detection_enabled) - { + if (detection_enabled) { LOG_DEBUG("[ResourceManager] Running standalone"); - if(ProcessPreDetection()) - { + if (ProcessPreDetection()) { // We are currently in a coroutine, so run detection directly with no scheduling DetectDevicesCoroutine(); } - } - else - { + } else { ProcessPostDetection(); } - if(start_server) - { + if (start_server) { detection_percent = 100; detection_string = "Starting server"; DetectionProgressChanged(); GetServer()->StartServer(); - if(!GetServer()->GetOnline()) - { + if (!GetServer()->GetOnline()) { LOG_DEBUG("[ResourceManager] Server failed to start"); } } @@ -1724,8 +1767,7 @@ void ResourceManager::InitCoroutine() | Process command line arguments after detection only if the| | pre-detection parsing indicated it should be run | \*---------------------------------------------------------*/ - if(apply_post_options) - { + if (apply_post_options) { cli_post_detection(); } @@ -1740,22 +1782,20 @@ void ResourceManager::HidExitCoroutine() \*-------------------------------------------------*/ int hid_status = hid_exit(); - LOG_DEBUG("[ResourceManager] Closing HID interfaces: %s", ((hid_status == 0) ? "Success" : "Failed")); + LOG_DEBUG("[ResourceManager] Closing HID interfaces: %s", + ((hid_status == 0) ? "Success" : "Failed")); } void ResourceManager::RunInBackgroundThread(std::function coroutine) { - if(std::this_thread::get_id() == DetectDevicesThread->get_id()) - { + if (std::this_thread::get_id() == DetectDevicesThread->get_id()) { // We are already in the background thread - don't schedule the call, run it immediately coroutine(); - } - else - { + } else { BackgroundThreadStateMutex.lock(); - if(ScheduledBackgroundFunction != nullptr) - { - LOG_WARNING("[ResourceManager] Detection coroutine: assigned a new coroutine when one was already scheduled - probably two rescan events sent at once"); + if (ScheduledBackgroundFunction != nullptr) { + LOG_WARNING("[ResourceManager] Detection coroutine: assigned a new coroutine when one " + "was already scheduled - probably two rescan events sent at once"); } ScheduledBackgroundFunction = coroutine; BackgroundThreadStateMutex.unlock(); @@ -1775,22 +1815,16 @@ void ResourceManager::BackgroundThreadFunction() // However, it seems to be necessary to be separate from the DeviceDetectionMutex, even though their states are nearly identical std::unique_lock lock(BackgroundThreadStateMutex); - while(background_thread_running) - { - if(ScheduledBackgroundFunction) - { + while (background_thread_running) { + if (ScheduledBackgroundFunction) { std::function coroutine = nullptr; std::swap(ScheduledBackgroundFunction, coroutine); - try - { + try { coroutine(); - } - catch(std::exception& e) - { - LOG_ERROR("[ResourceManager] Unhandled exception in coroutine; e.what(): %s", e.what()); - } - catch(...) - { + } catch (std::exception &e) { + LOG_ERROR("[ResourceManager] Unhandled exception in coroutine; e.what(): %s", + e.what()); + } catch (...) { LOG_ERROR("[ResourceManager] Unhandled exception in coroutine"); } } @@ -1802,8 +1836,8 @@ void ResourceManager::BackgroundThreadFunction() void ResourceManager::UpdateDetectorSettings() { - json detector_settings; - bool save_settings = false; + json detector_settings; + bool save_settings = false; /*-------------------------------------------------*\ | Open device disable list and read in disabled | @@ -1815,12 +1849,13 @@ void ResourceManager::UpdateDetectorSettings() | Loop through all I2C detectors and see if any | | need to be saved to the settings | \*-------------------------------------------------*/ - for(unsigned int i2c_detector_idx = 0; i2c_detector_idx < (unsigned int)i2c_device_detectors.size(); i2c_detector_idx++) - { + for (unsigned int i2c_detector_idx = 0; + i2c_detector_idx < (unsigned int) i2c_device_detectors.size(); + i2c_detector_idx++) { detection_string = i2c_device_detector_strings[i2c_detector_idx].c_str(); - if(!(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string))) - { + if (!(detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string))) { detector_settings["detectors"][detection_string] = true; save_settings = true; } @@ -1830,12 +1865,13 @@ void ResourceManager::UpdateDetectorSettings() | Loop through all I2C DIMM detectors and see | | if any need to be saved to the settings | \*-------------------------------------------------*/ - for(unsigned int i2c_detector_idx = 0; i2c_detector_idx < (unsigned int)i2c_dimm_device_detectors.size(); i2c_detector_idx++) - { + for (unsigned int i2c_detector_idx = 0; + i2c_detector_idx < (unsigned int) i2c_dimm_device_detectors.size(); + i2c_detector_idx++) { detection_string = i2c_dimm_device_detectors[i2c_detector_idx].name.c_str(); - if(!(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string))) - { + if (!(detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string))) { detector_settings["detectors"][detection_string] = true; save_settings = true; } @@ -1845,12 +1881,13 @@ void ResourceManager::UpdateDetectorSettings() | Loop through all I2C PCI detectors and see if any | | need to be saved to the settings | \*-------------------------------------------------*/ - for(unsigned int i2c_pci_detector_idx = 0; i2c_pci_detector_idx < (unsigned int)i2c_pci_device_detectors.size(); i2c_pci_detector_idx++) - { + for (unsigned int i2c_pci_detector_idx = 0; + i2c_pci_detector_idx < (unsigned int) i2c_pci_device_detectors.size(); + i2c_pci_detector_idx++) { detection_string = i2c_pci_device_detectors[i2c_pci_detector_idx].name.c_str(); - if(!(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string))) - { + if (!(detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string))) { detector_settings["detectors"][detection_string] = true; save_settings = true; } @@ -1860,12 +1897,13 @@ void ResourceManager::UpdateDetectorSettings() | Loop through all HID detectors and see if any | | need to be saved to the settings | \*-------------------------------------------------*/ - for(unsigned int hid_detector_idx = 0; hid_detector_idx < (unsigned int)hid_device_detectors.size(); hid_detector_idx++) - { + for (unsigned int hid_detector_idx = 0; + hid_detector_idx < (unsigned int) hid_device_detectors.size(); + hid_detector_idx++) { detection_string = hid_device_detectors[hid_detector_idx].name.c_str(); - if(!(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string))) - { + if (!(detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string))) { detector_settings["detectors"][detection_string] = true; save_settings = true; } @@ -1875,12 +1913,13 @@ void ResourceManager::UpdateDetectorSettings() | Loop through all HID wrapped detectors and see if | | any need to be saved to the settings | \*-------------------------------------------------*/ - for(unsigned int hid_wrapped_detector_idx = 0; hid_wrapped_detector_idx < (unsigned int)hid_wrapped_device_detectors.size(); hid_wrapped_detector_idx++) - { + for (unsigned int hid_wrapped_detector_idx = 0; + hid_wrapped_detector_idx < (unsigned int) hid_wrapped_device_detectors.size(); + hid_wrapped_detector_idx++) { detection_string = hid_wrapped_device_detectors[hid_wrapped_detector_idx].name.c_str(); - if(!(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string))) - { + if (!(detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string))) { detector_settings["detectors"][detection_string] = true; save_settings = true; } @@ -1890,12 +1929,12 @@ void ResourceManager::UpdateDetectorSettings() | Loop through remaining detectors and see if any | | need to be saved to the settings | \*-------------------------------------------------*/ - for(unsigned int detector_idx = 0; detector_idx < (unsigned int)device_detectors.size(); detector_idx++) - { + for (unsigned int detector_idx = 0; detector_idx < (unsigned int) device_detectors.size(); + detector_idx++) { detection_string = device_detector_strings[detector_idx].c_str(); - if(!(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string))) - { + if (!(detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string))) { detector_settings["detectors"][detection_string] = true; save_settings = true; } @@ -1906,8 +1945,7 @@ void ResourceManager::UpdateDetectorSettings() | saved, set the settings in the settings manager | | and save them. | \*-------------------------------------------------*/ - if(save_settings) - { + if (save_settings) { LOG_INFO("[ResourceManager] Saving detector settings"); settings_manager->SetSettings("Detectors", detector_settings); @@ -1923,8 +1961,7 @@ void ResourceManager::WaitForInitialization() | impossible without the use of a `barrier` | | implementation, which is only introduced in C++20 | \*-------------------------------------------------*/ - while (!init_finished) - { + while (!init_finished) { std::this_thread::sleep_for(1ms); }; } @@ -1937,15 +1974,16 @@ void ResourceManager::WaitForDeviceDetection() bool ResourceManager::IsAnyDimmDetectorEnabled(json &detector_settings) { - for(unsigned int i2c_detector_idx = 0; i2c_detector_idx < i2c_dimm_device_detectors.size() && detection_is_required.load(); i2c_detector_idx++) - { + for (unsigned int i2c_detector_idx = 0; + i2c_detector_idx < i2c_dimm_device_detectors.size() && detection_is_required.load(); + i2c_detector_idx++) { detection_string = i2c_dimm_device_detectors[i2c_detector_idx].name.c_str(); /*-------------------------------------------------*\ | Check if this detector is enabled | \*-------------------------------------------------*/ - if(detector_settings.contains("detectors") && detector_settings["detectors"].contains(detection_string) && - detector_settings["detectors"][detection_string] == true) - { + if (detector_settings.contains("detectors") + && detector_settings["detectors"].contains(detection_string) + && detector_settings["detectors"][detection_string] == true) { return true; } } diff --git a/ResourceManager.h b/ResourceManager.h index 32f6a566b..5e1f4017e 100644 --- a/ResourceManager.h +++ b/ResourceManager.h @@ -28,9 +28,9 @@ using json = nlohmann::json; -#define HID_INTERFACE_ANY -1 -#define HID_USAGE_ANY -1 -#define HID_USAGE_PAGE_ANY -1L +#define HID_INTERFACE_ANY -1 +#define HID_USAGE_ANY -1 +#define HID_USAGE_PAGE_ANY -1L #define CONTROLLER_LIST_HID 0 @@ -41,58 +41,61 @@ class ProfileManager; class RGBController; class SettingsManager; -typedef std::function I2CBusDetectorFunction; -typedef std::function DeviceDetectorFunction; -typedef std::function&)> I2CDeviceDetectorFunction; -typedef std::function&)> I2CDIMMDeviceDetectorFunction; -typedef std::function I2CPCIDeviceDetectorFunction; -typedef std::function HIDDeviceDetectorFunction; -typedef std::function HIDWrappedDeviceDetectorFunction; -typedef std::function DynamicDetectorFunction; -typedef std::function PreDetectionHookFunction; +typedef std::function I2CBusDetectorFunction; +typedef std::function DeviceDetectorFunction; +typedef std::function &)> I2CDeviceDetectorFunction; +typedef std::function &)> + I2CDIMMDeviceDetectorFunction; +typedef std::function + I2CPCIDeviceDetectorFunction; +typedef std::function HIDDeviceDetectorFunction; +typedef std::function + HIDWrappedDeviceDetectorFunction; +typedef std::function DynamicDetectorFunction; +typedef std::function PreDetectionHookFunction; class BasicHIDBlock { public: - std::string name; - uint16_t vid; - uint16_t pid; - int interface; - int usage_page; - int usage; + std::string name; + uint16_t vid; + uint16_t pid; + int interface; + int usage_page; + int usage; - bool compare(hid_device_info* info); + bool compare(hid_device_info *info); }; class HIDDeviceDetectorBlock : public BasicHIDBlock { public: - HIDDeviceDetectorFunction function; + HIDDeviceDetectorFunction function; }; class HIDWrappedDeviceDetectorBlock : public BasicHIDBlock { public: - HIDWrappedDeviceDetectorFunction function; + HIDWrappedDeviceDetectorFunction function; }; typedef struct { - std::string name; - I2CPCIDeviceDetectorFunction function; - uint16_t ven_id; - uint16_t dev_id; - uint16_t subven_id; - uint16_t subdev_id; - uint8_t i2c_addr; + std::string name; + I2CPCIDeviceDetectorFunction function; + uint16_t ven_id; + uint16_t dev_id; + uint16_t subven_id; + uint16_t subdev_id; + uint8_t i2c_addr; } I2CPCIDeviceDetectorBlock; typedef struct { - std::string name; - I2CDIMMDeviceDetectorFunction function; - uint16_t jedec_id; - uint8_t dimm_type; + std::string name; + I2CDIMMDeviceDetectorFunction function; + uint16_t jedec_id; + uint8_t dimm_type; } I2CDIMMDeviceDetectorBlock; /*-------------------------------------------------------------------------*\ @@ -100,12 +103,12 @@ typedef struct \*-------------------------------------------------------------------------*/ #define QT_TRANSLATE_NOOP(scope, x) x -extern const char* I2C_ERR_WIN; -extern const char* I2C_ERR_LINUX; -extern const char* UDEV_MISSING; -extern const char* UDEV_MULTI; +extern const char *I2C_ERR_WIN; +extern const char *I2C_ERR_LINUX; +extern const char *UDEV_MISSING; +extern const char *UDEV_MULTI; -class ResourceManager: public ResourceManagerInterface +class ResourceManager : public ResourceManagerInterface { public: static ResourceManager *get(); @@ -114,63 +117,75 @@ public: ~ResourceManager(); void RegisterI2CBus(i2c_smbus_interface *); - std::vector & GetI2CBusses(); + std::vector &GetI2CBusses(); void RegisterRGBController(RGBController *rgb_controller); void UnregisterRGBController(RGBController *rgb_controller); - std::vector & GetRGBControllers(); + std::vector &GetRGBControllers(); - void RegisterI2CBusDetector (I2CBusDetectorFunction detector); - void RegisterDeviceDetector (std::string name, DeviceDetectorFunction detector); - void RegisterI2CDeviceDetector (std::string name, I2CDeviceDetectorFunction detector); - void RegisterI2CDIMMDeviceDetector (std::string name, I2CDIMMDeviceDetectorFunction detector, uint16_t jedec_id, uint8_t dimm_type); - void RegisterI2CPCIDeviceDetector (std::string name, I2CPCIDeviceDetectorFunction detector, uint16_t ven_id, uint16_t dev_id, uint16_t subven_id, uint16_t subdev_id, uint8_t i2c_addr); - void RegisterHIDDeviceDetector (std::string name, - HIDDeviceDetectorFunction detector, - uint16_t vid, - uint16_t pid, - int interface = HID_INTERFACE_ANY, - int usage_page = HID_USAGE_PAGE_ANY, - int usage = HID_USAGE_ANY); - void RegisterHIDWrappedDeviceDetector (std::string name, - HIDWrappedDeviceDetectorFunction detector, - uint16_t vid, - uint16_t pid, - int interface = HID_INTERFACE_ANY, - int usage_page = HID_USAGE_PAGE_ANY, - int usage = HID_USAGE_ANY); - void RegisterDynamicDetector (std::string name, DynamicDetectorFunction detector); - void RegisterPreDetectionHook (PreDetectionHookFunction hook); + void RegisterI2CBusDetector(I2CBusDetectorFunction detector); + void RegisterDeviceDetector(std::string name, DeviceDetectorFunction detector); + void RegisterI2CDeviceDetector(std::string name, I2CDeviceDetectorFunction detector); + void RegisterI2CDIMMDeviceDetector(std::string name, + I2CDIMMDeviceDetectorFunction detector, + uint16_t jedec_id, + uint8_t dimm_type); + void RegisterI2CPCIDeviceDetector(std::string name, + I2CPCIDeviceDetectorFunction detector, + uint16_t ven_id, + uint16_t dev_id, + uint16_t subven_id, + uint16_t subdev_id, + uint8_t i2c_addr); + void RegisterHIDDeviceDetector(std::string name, + HIDDeviceDetectorFunction detector, + uint16_t vid, + uint16_t pid, + int interface = HID_INTERFACE_ANY, + int usage_page = HID_USAGE_PAGE_ANY, + int usage = HID_USAGE_ANY); + void RegisterHIDWrappedDeviceDetector(std::string name, + HIDWrappedDeviceDetectorFunction detector, + uint16_t vid, + uint16_t pid, + int interface = HID_INTERFACE_ANY, + int usage_page = HID_USAGE_PAGE_ANY, + int usage = HID_USAGE_ANY); + void RegisterDynamicDetector(std::string name, DynamicDetectorFunction detector); + void RegisterPreDetectionHook(PreDetectionHookFunction hook); - void RegisterDeviceListChangeCallback(DeviceListChangeCallback new_callback, void * new_callback_arg); - void RegisterDetectionProgressCallback(DetectionProgressCallback new_callback, void * new_callback_arg); - void RegisterDetectionStartCallback(DetectionStartCallback new_callback, void * new_callback_arg); - void RegisterDetectionEndCallback(DetectionEndCallback new_callback, void * new_callback_arg); - void RegisterI2CBusListChangeCallback(I2CBusListChangeCallback new_callback, void * new_callback_arg); + void RegisterDeviceListChangeCallback(DeviceListChangeCallback new_callback, + void *new_callback_arg); + void RegisterDetectionProgressCallback(DetectionProgressCallback new_callback, + void *new_callback_arg); + void RegisterDetectionStartCallback(DetectionStartCallback new_callback, void *new_callback_arg); + void RegisterDetectionEndCallback(DetectionEndCallback new_callback, void *new_callback_arg); + void RegisterI2CBusListChangeCallback(I2CBusListChangeCallback new_callback, + void *new_callback_arg); - void UnregisterDeviceListChangeCallback(DeviceListChangeCallback callback, void * callback_arg); + void UnregisterDeviceListChangeCallback(DeviceListChangeCallback callback, void *callback_arg); void UnregisterDetectionProgressCallback(DetectionProgressCallback callback, void *callback_arg); void UnregisterDetectionStartCallback(DetectionStartCallback callback, void *callback_arg); void UnregisterDetectionEndCallback(DetectionEndCallback callback, void *callback_arg); - void UnregisterI2CBusListChangeCallback(I2CBusListChangeCallback callback, void * callback_arg); + void UnregisterI2CBusListChangeCallback(I2CBusListChangeCallback callback, void *callback_arg); - bool GetDetectionEnabled(); + bool GetDetectionEnabled(); unsigned int GetDetectionPercent(); - const char* GetDetectionString(); + const char *GetDetectionString(); - filesystem::path GetConfigurationDirectory(); + filesystem::path GetConfigurationDirectory(); - void RegisterNetworkClient(NetworkClient* new_client); - void UnregisterNetworkClient(NetworkClient* network_client); + void RegisterNetworkClient(NetworkClient *new_client); + void UnregisterNetworkClient(NetworkClient *network_client); - std::vector& GetClients(); - NetworkServer* GetServer(); + std::vector &GetClients(); + NetworkServer *GetServer(); - ProfileManager* GetProfileManager(); - SettingsManager* GetSettingsManager(); + ProfileManager *GetProfileManager(); + SettingsManager *GetSettingsManager(); - void SetConfigurationDirectory(const filesystem::path &directory); + void SetConfigurationDirectory(const filesystem::path &directory); void ProcessPreDetectionHooks(); // Consider making private void ProcessDynamicDetectors(); // Consider making private @@ -213,125 +228,125 @@ private: /*-------------------------------------------------------------------------------------*\ | Static pointer to shared instance of ResourceManager | \*-------------------------------------------------------------------------------------*/ - static ResourceManager* instance; + static ResourceManager *instance; /*-------------------------------------------------------------------------------------*\ | Auto connection permitting flag | \*-------------------------------------------------------------------------------------*/ - bool tryAutoConnect; + bool tryAutoConnect; /*-------------------------------------------------------------------------------------*\ | Detection enabled flag | \*-------------------------------------------------------------------------------------*/ - bool detection_enabled; + bool detection_enabled; /*-------------------------------------------------------------------------------------*\ | Auto connection permitting flag | \*-------------------------------------------------------------------------------------*/ - bool start_server; + bool start_server; /*-------------------------------------------------------------------------------------*\ | Auto connection permitting flag | \*-------------------------------------------------------------------------------------*/ - bool apply_post_options; + bool apply_post_options; /*-------------------------------------------------------------------------------------*\ | Initialization completion flag | \*-------------------------------------------------------------------------------------*/ - std::atomic init_finished; + std::atomic init_finished; /*-------------------------------------------------------------------------------------*\ | Profile Manager | \*-------------------------------------------------------------------------------------*/ - ProfileManager* profile_manager; + ProfileManager *profile_manager; /*-------------------------------------------------------------------------------------*\ | Settings Manager | \*-------------------------------------------------------------------------------------*/ - SettingsManager* settings_manager; + SettingsManager *settings_manager; /*-------------------------------------------------------------------------------------*\ | I2C/SMBus Interfaces | \*-------------------------------------------------------------------------------------*/ - std::vector busses; + std::vector busses; /*-------------------------------------------------------------------------------------*\ | RGBControllers | \*-------------------------------------------------------------------------------------*/ - std::vector rgb_controllers_sizes; - std::vector rgb_controllers_hw; - std::vector rgb_controllers; + std::vector rgb_controllers_sizes; + std::vector rgb_controllers_hw; + std::vector rgb_controllers; /*-------------------------------------------------------------------------------------*\ | Network Server | \*-------------------------------------------------------------------------------------*/ - NetworkServer* server; + NetworkServer *server; /*-------------------------------------------------------------------------------------*\ | Network Clients | \*-------------------------------------------------------------------------------------*/ - std::vector clients; + std::vector clients; /*-------------------------------------------------------------------------------------*\ | Detectors | \*-------------------------------------------------------------------------------------*/ - std::vector device_detectors; - std::vector device_detector_strings; - std::vector i2c_bus_detectors; - std::vector i2c_device_detectors; - std::vector i2c_device_detector_strings; - std::vector i2c_dimm_device_detectors; - std::vector i2c_pci_device_detectors; - std::vector hid_device_detectors; - std::vector hid_wrapped_device_detectors; - std::vector dynamic_detectors; - std::vector dynamic_detector_strings; - std::vector pre_detection_hooks; + std::vector device_detectors; + std::vector device_detector_strings; + std::vector i2c_bus_detectors; + std::vector i2c_device_detectors; + std::vector i2c_device_detector_strings; + std::vector i2c_dimm_device_detectors; + std::vector i2c_pci_device_detectors; + std::vector hid_device_detectors; + std::vector hid_wrapped_device_detectors; + std::vector dynamic_detectors; + std::vector dynamic_detector_strings; + std::vector pre_detection_hooks; - bool dynamic_detectors_processed; + bool dynamic_detectors_processed; /*-------------------------------------------------------------------------------------*\ | Detection Thread and Detection State | \*-------------------------------------------------------------------------------------*/ - std::thread * DetectDevicesThread; - std::mutex DetectDeviceMutex; - std::function ScheduledBackgroundFunction; - std::mutex BackgroundThreadStateMutex; - std::condition_variable BackgroundFunctionStartTrigger; // NOTE: wakes up the background detection thread - - std::atomic background_thread_running; - std::atomic detection_is_required; - std::atomic detection_percent; - std::atomic detection_prev_size; - std::vector detection_size_entry_used; - const char* detection_string; + std::thread *DetectDevicesThread; + std::mutex DetectDeviceMutex; + std::function ScheduledBackgroundFunction; + std::mutex BackgroundThreadStateMutex; + std::condition_variable + BackgroundFunctionStartTrigger; // NOTE: wakes up the background detection thread + std::atomic background_thread_running; + std::atomic detection_is_required; + std::atomic detection_percent; + std::atomic detection_prev_size; + std::vector detection_size_entry_used; + const char *detection_string; /*-------------------------------------------------------------------------------------*\ | Device List Changed Callback | \*-------------------------------------------------------------------------------------*/ - std::mutex DeviceListChangeMutex; - std::vector DeviceListChangeCallbacks; - std::vector DeviceListChangeCallbackArgs; + std::mutex DeviceListChangeMutex; + std::vector DeviceListChangeCallbacks; + std::vector DeviceListChangeCallbackArgs; /*-------------------------------------------------------------------------------------*\ | Detection Progress, Start, and End Callbacks | \*-------------------------------------------------------------------------------------*/ - std::mutex DetectionProgressMutex; - std::vector DetectionProgressCallbacks; - std::vector DetectionProgressCallbackArgs; + std::mutex DetectionProgressMutex; + std::vector DetectionProgressCallbacks; + std::vector DetectionProgressCallbackArgs; - std::vector DetectionStartCallbacks; - std::vector DetectionStartCallbackArgs; + std::vector DetectionStartCallbacks; + std::vector DetectionStartCallbackArgs; - std::vector DetectionEndCallbacks; - std::vector DetectionEndCallbackArgs; + std::vector DetectionEndCallbacks; + std::vector DetectionEndCallbackArgs; /*-------------------------------------------------------------------------------------*\ | I2C/SMBus Adapter List Changed Callback | \*-------------------------------------------------------------------------------------*/ - std::mutex I2CBusListChangeMutex; - std::vector I2CBusListChangeCallbacks; - std::vector I2CBusListChangeCallbackArgs; + std::mutex I2CBusListChangeMutex; + std::vector I2CBusListChangeCallbacks; + std::vector I2CBusListChangeCallbackArgs; filesystem::path config_dir; }; diff --git a/ResourceManagerInterface.h b/ResourceManagerInterface.h index 92bc5ee37..dfa22e0f4 100644 --- a/ResourceManagerInterface.h +++ b/ResourceManagerInterface.h @@ -1,8 +1,8 @@ #pragma once -#include -#include "i2c_smbus.h" #include "filesystem.h" +#include "i2c_smbus.h" +#include class NetworkClient; class NetworkServer; @@ -19,38 +19,57 @@ typedef void (*I2CBusListChangeCallback)(void *); class ResourceManagerInterface { public: - virtual std::vector & GetI2CBusses() = 0; + virtual std::vector &GetI2CBusses() = 0; - virtual void RegisterRGBController(RGBController *rgb_controller) = 0; - virtual void UnregisterRGBController(RGBController *rgb_controller) = 0; + virtual void RegisterRGBController(RGBController *rgb_controller) = 0; + virtual void UnregisterRGBController(RGBController *rgb_controller) = 0; - virtual void RegisterDeviceListChangeCallback(DeviceListChangeCallback new_callback, void * new_callback_arg) = 0; - virtual void RegisterDetectionProgressCallback(DetectionProgressCallback new_callback, void * new_callback_arg) = 0; - virtual void RegisterDetectionStartCallback(DetectionStartCallback new_callback, void * new_callback_arg) = 0; - virtual void RegisterDetectionEndCallback(DetectionEndCallback new_callback, void * new_callback_arg) = 0; - virtual void RegisterI2CBusListChangeCallback(I2CBusListChangeCallback new_callback, void * new_callback_arg) = 0; + virtual void RegisterDeviceListChangeCallback(DeviceListChangeCallback new_callback, + void *new_callback_arg) + = 0; + virtual void RegisterDetectionProgressCallback(DetectionProgressCallback new_callback, + void *new_callback_arg) + = 0; + virtual void RegisterDetectionStartCallback(DetectionStartCallback new_callback, + void *new_callback_arg) + = 0; + virtual void RegisterDetectionEndCallback(DetectionEndCallback new_callback, + void *new_callback_arg) + = 0; + virtual void RegisterI2CBusListChangeCallback(I2CBusListChangeCallback new_callback, + void *new_callback_arg) + = 0; - virtual void UnregisterDeviceListChangeCallback(DeviceListChangeCallback callback, void * callback_arg) = 0; - virtual void UnregisterDetectionProgressCallback(DetectionProgressCallback callback, void *callback_arg) = 0; - virtual void UnregisterDetectionStartCallback(DetectionStartCallback callback, void *callback_arg) = 0; - virtual void UnregisterDetectionEndCallback(DetectionEndCallback callback, void *callback_arg) = 0; - virtual void UnregisterI2CBusListChangeCallback(I2CBusListChangeCallback callback, void * callback_arg) = 0; + virtual void UnregisterDeviceListChangeCallback(DeviceListChangeCallback callback, + void *callback_arg) + = 0; + virtual void UnregisterDetectionProgressCallback(DetectionProgressCallback callback, + void *callback_arg) + = 0; + virtual void UnregisterDetectionStartCallback(DetectionStartCallback callback, + void *callback_arg) + = 0; + virtual void UnregisterDetectionEndCallback(DetectionEndCallback callback, void *callback_arg) + = 0; + virtual void UnregisterI2CBusListChangeCallback(I2CBusListChangeCallback callback, + void *callback_arg) + = 0; - virtual std::vector & GetRGBControllers() = 0; + virtual std::vector &GetRGBControllers() = 0; - virtual unsigned int GetDetectionPercent() = 0; + virtual unsigned int GetDetectionPercent() = 0; - virtual filesystem::path GetConfigurationDirectory() = 0; + virtual filesystem::path GetConfigurationDirectory() = 0; - virtual std::vector& GetClients() = 0; - virtual NetworkServer* GetServer() = 0; + virtual std::vector &GetClients() = 0; + virtual NetworkServer *GetServer() = 0; - virtual ProfileManager* GetProfileManager() = 0; - virtual SettingsManager* GetSettingsManager() = 0; + virtual ProfileManager *GetProfileManager() = 0; + virtual SettingsManager *GetSettingsManager() = 0; - virtual void UpdateDeviceList() = 0; - virtual void WaitForDeviceDetection() = 0; + virtual void UpdateDeviceList() = 0; + virtual void WaitForDeviceDetection() = 0; protected: - virtual ~ResourceManagerInterface() {}; + virtual ~ResourceManagerInterface() {}; }; diff --git a/SettingsManager.cpp b/SettingsManager.cpp index fde61b13b..2962841c1 100644 --- a/SettingsManager.cpp +++ b/SettingsManager.cpp @@ -21,10 +21,7 @@ SettingsManager::SettingsManager() config_found = false; } -SettingsManager::~SettingsManager() -{ - -} +SettingsManager::~SettingsManager() {} json SettingsManager::GetSettings(std::string settings_key) { @@ -37,8 +34,7 @@ json SettingsManager::GetSettings(std::string settings_key) json result; mutex.lock(); - if(settings_data.contains(settings_key)) - { + if (settings_data.contains(settings_key)) { result = settings_data[settings_key]; } @@ -54,7 +50,7 @@ void SettingsManager::SetSettings(std::string settings_key, json new_settings) mutex.unlock(); } -void SettingsManager::LoadSettings(const filesystem::path& filename) +void SettingsManager::LoadSettings(const filesystem::path &filename) { /*---------------------------------------------------------*\ | Clear any stored settings before loading | @@ -72,21 +68,16 @@ void SettingsManager::LoadSettings(const filesystem::path& filename) | Open input file in binary mode | \*---------------------------------------------------------*/ config_found = filesystem::exists(filename); - if(config_found) - { + if (config_found) { std::ifstream settings_file(settings_filename, std::ios::in | std::ios::binary); /*---------------------------------------------------------*\ | Read settings into JSON store | \*---------------------------------------------------------*/ - if(settings_file) - { - try - { + if (settings_file) { + try { settings_file >> settings_data; - } - catch(const std::exception& e) - { + } catch (const std::exception &e) { /*-------------------------------------------------*\ | If an exception was caught, that means the JSON | | parsing failed. Clear out any data in the store | @@ -110,14 +101,10 @@ void SettingsManager::SaveSettings() mutex.lock(); std::ofstream settings_file(settings_filename, std::ios::out | std::ios::binary); - if(settings_file) - { - try - { + if (settings_file) { + try { settings_file << settings_data.dump(4); - } - catch(const std::exception& e) - { + } catch (const std::exception &e) { LOG_ERROR("[SettingsManager] Cannot write to file: %s", e.what()); } diff --git a/SettingsManager.h b/SettingsManager.h index 2251fadcb..797906a18 100644 --- a/SettingsManager.h +++ b/SettingsManager.h @@ -22,17 +22,17 @@ using json = nlohmann::json; class SettingsManagerInterface { public: - virtual json GetSettings(std::string settings_key) = 0; - virtual void SetSettings(std::string settings_key, json new_settings) = 0; + virtual json GetSettings(std::string settings_key) = 0; + virtual void SetSettings(std::string settings_key, json new_settings) = 0; - virtual void LoadSettings(const filesystem::path& filename) = 0; - virtual void SaveSettings() = 0; + virtual void LoadSettings(const filesystem::path &filename) = 0; + virtual void SaveSettings() = 0; protected: virtual ~SettingsManagerInterface() {}; }; -class SettingsManager: public SettingsManagerInterface +class SettingsManager : public SettingsManagerInterface { public: SettingsManager(); @@ -41,13 +41,13 @@ public: json GetSettings(std::string settings_key) override; void SetSettings(std::string settings_key, json new_settings) override; - void LoadSettings(const filesystem::path& filename) override; + void LoadSettings(const filesystem::path &filename) override; void SaveSettings() override; private: - json settings_data; - json settings_prototype; + json settings_data; + json settings_prototype; filesystem::path settings_filename; - std::mutex mutex; - bool config_found; + std::mutex mutex; + bool config_found; }; diff --git a/StringUtils.cpp b/StringUtils.cpp index c1805cbbb..efb328b47 100644 --- a/StringUtils.cpp +++ b/StringUtils.cpp @@ -12,36 +12,32 @@ #include #include "StringUtils.h" -const char* StringUtils::wchar_to_char(const wchar_t* pwchar) +const char *StringUtils::wchar_to_char(const wchar_t *pwchar) { - if (pwchar == nullptr) - { + if (pwchar == nullptr) { return ""; } // get the number of characters in the string. int currentCharIndex = 0; - char currentChar = (char)pwchar[currentCharIndex]; + char currentChar = (char) pwchar[currentCharIndex]; - while (currentChar != '\0') - { + while (currentChar != '\0') { currentCharIndex++; - currentChar = (char)pwchar[currentCharIndex]; + currentChar = (char) pwchar[currentCharIndex]; } const int charCount = currentCharIndex + 1; // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes) - char* filePathC = (char*)malloc(sizeof(char) * charCount); + char *filePathC = (char *) malloc(sizeof(char) * charCount); - for (int i = 0; i < charCount; i++) - { + for (int i = 0; i < charCount; i++) { // convert to char (1 byte) - char character = (char)pwchar[i]; + char character = (char) pwchar[i]; *filePathC = character; filePathC += sizeof(char); - } filePathC += '\0'; @@ -54,23 +50,21 @@ std::string StringUtils::wstring_to_string(const std::wstring wstring) { std::wstring_convert, wchar_t> converter; - return(converter.to_bytes(wstring)); + return (converter.to_bytes(wstring)); } std::string StringUtils::u16string_to_string(const std::u16string wstring) { - std::wstring_convert,char16_t> converter; + std::wstring_convert, char16_t> converter; - return(converter.to_bytes(wstring)); + return (converter.to_bytes(wstring)); } const std::string StringUtils::remove_null_terminating_chars(std::string input) { - while (!input.empty() && input.back() == 0) - { + while (!input.empty() && input.back() == 0) { input.pop_back(); } return input; } - diff --git a/StringUtils.h b/StringUtils.h index f69bb65de..5445d702e 100644 --- a/StringUtils.h +++ b/StringUtils.h @@ -14,7 +14,7 @@ class StringUtils { public: - static const char* wchar_to_char(const wchar_t* pwchar); + static const char *wchar_to_char(const wchar_t *pwchar); static std::string wstring_to_string(const std::wstring wstring); static std::string u16string_to_string(const std::u16string wstring); static const std::string remove_null_terminating_chars(std::string input); diff --git a/cli.cpp b/cli.cpp index 9ecd37f3d..1c5f5c223 100644 --- a/cli.cpp +++ b/cli.cpp @@ -29,226 +29,225 @@ \*-------------------------------------------------------------*/ #ifdef _WIN32 #include - #define strcasecmp _strcmpi +#define strcasecmp _strcmpi #endif using namespace std::chrono_literals; -static std::string profile_save_filename = ""; -const unsigned int brightness_percentage = 100; -const unsigned int speed_percentage = 100; +static std::string profile_save_filename = ""; +const unsigned int brightness_percentage = 100; +const unsigned int speed_percentage = 100; static int preserve_argc = 0; -static char** preserve_argv = nullptr; +static char **preserve_argv = nullptr; -enum -{ - RET_FLAG_PRINT_HELP = 1, - RET_FLAG_START_GUI = 2, - RET_FLAG_I2C_TOOLS = 4, - RET_FLAG_START_MINIMIZED = 8, - RET_FLAG_NO_DETECT = 16, +enum { + RET_FLAG_PRINT_HELP = 1, + RET_FLAG_START_GUI = 2, + RET_FLAG_I2C_TOOLS = 4, + RET_FLAG_START_MINIMIZED = 8, + RET_FLAG_NO_DETECT = 16, RET_FLAG_CLI_POST_DETECTION = 32, - RET_FLAG_START_SERVER = 64, - RET_FLAG_NO_AUTO_CONNECT = 128, + RET_FLAG_START_SERVER = 64, + RET_FLAG_NO_AUTO_CONNECT = 128, }; struct DeviceOptions { - int device; - int zone = -1; + int device; + int zone = -1; std::vector> colors; - std::string mode; - unsigned int speed = 100; - unsigned int brightness = 100; - unsigned int size; - bool random_colors = false; - bool hasSize = false; - bool hasOption = false; + std::string mode; + unsigned int speed = 100; + unsigned int brightness = 100; + unsigned int size; + bool random_colors = false; + bool hasSize = false; + bool hasOption = false; }; struct ServerOptions { bool start = false; - unsigned short port = OPENRGB_SDK_PORT; + unsigned short port = OPENRGB_SDK_PORT; }; struct Options { - std::vector devices; + std::vector devices; /*---------------------------------------------------------*\ | If hasDevice is false, devices above is empty and | | allDeviceOptions shall be applied to all available devices| | except in the case that a profile was loaded. | \*---------------------------------------------------------*/ - bool hasDevice = false; - bool profile_loaded = false; - DeviceOptions allDeviceOptions; - ServerOptions servOpts; + bool hasDevice = false; + bool profile_loaded = false; + DeviceOptions allDeviceOptions; + ServerOptions servOpts; }; /*---------------------------------------------------------------------------------------------------------*\ | Support a common subset of human colors; for easier typing: https://www.w3.org/TR/css-color-3/#svg-color | \*---------------------------------------------------------------------------------------------------------*/ -struct HumanColors { uint32_t rgb; const char* keyword; } static const human_colors[] = +struct HumanColors { - { COLOR_BLACK, "black" }, - { COLOR_NAVY, "navy" }, - { COLOR_DARKBLUE, "darkblue" }, - { COLOR_MEDIUMBLUE, "mediumblue" }, - { COLOR_BLUE, "blue" }, - { COLOR_DARKGREEN, "darkgreen" }, - { COLOR_GREEN, "green" }, - { COLOR_TEAL, "teal" }, - { COLOR_DARKCYAN, "darkcyan" }, - { COLOR_DEEPSKYBLUE, "deepskyblue" }, - { COLOR_DARKTURQUOISE, "darkturquoise" }, - { COLOR_MEDIUMSPRINGGREEN, "mediumspringgreen" }, - { COLOR_LIME, "lime" }, - { COLOR_SPRINGGREEN, "springgreen" }, - { COLOR_AQUA, "aqua" }, - { COLOR_CYAN, "cyan" }, - { COLOR_MIDNIGHTBLUE, "midnightblue" }, - { COLOR_DODGERBLUE, "dodgerblue" }, - { COLOR_LIGHTSEAGREEN, "lightseagreen" }, - { COLOR_FORESTGREEN, "forestgreen" }, - { COLOR_SEAGREEN, "seagreen" }, - { COLOR_DARKSLATEGRAY, "darkslategray" }, - { COLOR_DARKSLATEGREY, "darkslategrey" }, - { COLOR_LIMEGREEN, "limegreen" }, - { COLOR_MEDIUMSEAGREEN, "mediumseagreen" }, - { COLOR_TURQUOISE, "turquoise" }, - { COLOR_ROYALBLUE, "royalblue" }, - { COLOR_STEELBLUE, "steelblue" }, - { COLOR_DARKSLATEBLUE, "darkslateblue" }, - { COLOR_MEDIUMTURQUOISE, "mediumturquoise" }, - { COLOR_INDIGO, "indigo" }, - { COLOR_DARKOLIVEGREEN, "darkolivegreen" }, - { COLOR_CADETBLUE, "cadetblue" }, - { COLOR_CORNFLOWERBLUE, "cornflowerblue" }, - { COLOR_MEDIUMAQUAMARINE, "mediumaquamarine" }, - { COLOR_DIMGRAY, "dimgray" }, - { COLOR_DIMGREY, "dimgrey" }, - { COLOR_SLATEBLUE, "slateblue" }, - { COLOR_OLIVEDRAB, "olivedrab" }, - { COLOR_SLATEGRAY, "slategray" }, - { COLOR_SLATEGREY, "slategrey" }, - { COLOR_LIGHTSLATEGRAY, "lightslategray" }, - { COLOR_LIGHTSLATEGREY, "lightslategrey" }, - { COLOR_MEDIUMSLATEBLUE, "mediumslateblue" }, - { COLOR_LAWNGREEN, "lawngreen" }, - { COLOR_CHARTREUSE, "chartreuse" }, - { COLOR_AQUAMARINE, "aquamarine" }, - { COLOR_MAROON, "maroon" }, - { COLOR_PURPLE, "purple" }, - { COLOR_ELECTRIC_ULTRAMARINE, "electricultramarine" }, - { COLOR_OLIVE, "olive" }, - { COLOR_GRAY, "gray" }, - { COLOR_GREY, "grey" }, - { COLOR_SKYBLUE, "skyblue" }, - { COLOR_LIGHTSKYBLUE, "lightskyblue" }, - { COLOR_BLUEVIOLET, "blueviolet" }, - { COLOR_DARKRED, "darkred" }, - { COLOR_DARKMAGENTA, "darkmagenta" }, - { COLOR_SADDLEBROWN, "saddlebrown" }, - { COLOR_DARKSEAGREEN, "darkseagreen" }, - { COLOR_LIGHTGREEN, "lightgreen" }, - { COLOR_MEDIUMPURPLE, "mediumpurple" }, - { COLOR_DARKVIOLET, "darkviolet" }, - { COLOR_PALEGREEN, "palegreen" }, - { COLOR_DARKORCHID, "darkorchid" }, - { COLOR_YELLOWGREEN, "yellowgreen" }, - { COLOR_SIENNA, "sienna" }, - { COLOR_BROWN, "brown" }, - { COLOR_DARKGRAY, "darkgray" }, - { COLOR_DARKGREY, "darkgrey" }, - { COLOR_LIGHTBLUE, "lightblue" }, - { COLOR_GREENYELLOW, "greenyellow" }, - { COLOR_PALETURQUOISE, "paleturquoise" }, - { COLOR_LIGHTSTEELBLUE, "lightsteelblue" }, - { COLOR_POWDERBLUE, "powderblue" }, - { COLOR_FIREBRICK, "firebrick" }, - { COLOR_DARKGOLDENROD, "darkgoldenrod" }, - { COLOR_MEDIUMORCHID, "mediumorchid" }, - { COLOR_ROSYBROWN, "rosybrown" }, - { COLOR_DARKKHAKI, "darkkhaki" }, - { COLOR_SILVER, "silver" }, - { COLOR_MEDIUMVIOLETRED, "mediumvioletred" }, - { COLOR_INDIANRED, "indianred" }, - { COLOR_PERU, "peru" }, - { COLOR_CHOCOLATE, "chocolate" }, - { COLOR_TAN, "tan" }, - { COLOR_LIGHTGRAY, "lightgray" }, - { COLOR_LIGHTGREY, "lightgrey" }, - { COLOR_THISTLE, "thistle" }, - { COLOR_ORCHID, "orchid" }, - { COLOR_GOLDENROD, "goldenrod" }, - { COLOR_PALEVIOLETRED, "palevioletred" }, - { COLOR_CRIMSON, "crimson" }, - { COLOR_GAINSBORO, "gainsboro" }, - { COLOR_PLUM, "plum" }, - { COLOR_BURLYWOOD, "burlywood" }, - { COLOR_LIGHTCYAN, "lightcyan" }, - { COLOR_LAVENDER, "lavender" }, - { COLOR_DARKSALMON, "darksalmon" }, - { COLOR_VIOLET, "violet" }, - { COLOR_PALEGOLDENROD, "palegoldenrod" }, - { COLOR_LIGHTCORAL, "lightcoral" }, - { COLOR_KHAKI, "khaki" }, - { COLOR_ALICEBLUE, "aliceblue" }, - { COLOR_HONEYDEW, "honeydew" }, - { COLOR_AZURE, "azure" }, - { COLOR_SANDYBROWN, "sandybrown" }, - { COLOR_WHEAT, "wheat" }, - { COLOR_BEIGE, "beige" }, - { COLOR_WHITESMOKE, "whitesmoke" }, - { COLOR_MINTCREAM, "mintcream" }, - { COLOR_GHOSTWHITE, "ghostwhite" }, - { COLOR_SALMON, "salmon" }, - { COLOR_ANTIQUEWHITE, "antiquewhite" }, - { COLOR_LINEN, "linen" }, - { COLOR_LIGHTGOLDENRODYELLOW, "lightgoldenrodyellow" }, - { COLOR_OLDLACE, "oldlace" }, - { COLOR_RED, "red" }, - { COLOR_FUCHSIA, "fuchsia" }, - { COLOR_MAGENTA, "magenta" }, - { COLOR_DEEPPINK, "deeppink" }, - { COLOR_ORANGERED, "orangered" }, - { COLOR_TOMATO, "tomato" }, - { COLOR_HOTPINK, "hotpink" }, - { COLOR_CORAL, "coral" }, - { COLOR_DARKORANGE, "darkorange" }, - { COLOR_LIGHTSALMON, "lightsalmon" }, - { COLOR_ORANGE, "orange" }, - { COLOR_LIGHTPINK, "lightpink" }, - { COLOR_PINK, "pink" }, - { COLOR_GOLD, "gold" }, - { COLOR_PEACHPUFF, "peachpuff" }, - { COLOR_NAVAJOWHITE, "navajowhite" }, - { COLOR_MOCCASIN, "moccasin" }, - { COLOR_BISQUE, "bisque" }, - { COLOR_MISTYROSE, "mistyrose" }, - { COLOR_BLANCHEDALMOND, "blanchedalmond" }, - { COLOR_PAPAYAWHIP, "papayawhip" }, - { COLOR_LAVENDERBLUSH, "lavenderblush" }, - { COLOR_SEASHELL, "seashell" }, - { COLOR_CORNSILK, "cornsilk" }, - { COLOR_LEMONCHIFFON, "lemonchiffon" }, - { COLOR_FLORALWHITE, "floralwhite" }, - { COLOR_SNOW, "snow" }, - { COLOR_YELLOW, "yellow" }, - { COLOR_LIGHTYELLOW, "lightyellow" }, - { COLOR_IVORY, "ivory" }, - { COLOR_WHITE, "white" }, - { 0, NULL } -}; + uint32_t rgb; + const char *keyword; +} static const human_colors[] = {{COLOR_BLACK, "black"}, + {COLOR_NAVY, "navy"}, + {COLOR_DARKBLUE, "darkblue"}, + {COLOR_MEDIUMBLUE, "mediumblue"}, + {COLOR_BLUE, "blue"}, + {COLOR_DARKGREEN, "darkgreen"}, + {COLOR_GREEN, "green"}, + {COLOR_TEAL, "teal"}, + {COLOR_DARKCYAN, "darkcyan"}, + {COLOR_DEEPSKYBLUE, "deepskyblue"}, + {COLOR_DARKTURQUOISE, "darkturquoise"}, + {COLOR_MEDIUMSPRINGGREEN, "mediumspringgreen"}, + {COLOR_LIME, "lime"}, + {COLOR_SPRINGGREEN, "springgreen"}, + {COLOR_AQUA, "aqua"}, + {COLOR_CYAN, "cyan"}, + {COLOR_MIDNIGHTBLUE, "midnightblue"}, + {COLOR_DODGERBLUE, "dodgerblue"}, + {COLOR_LIGHTSEAGREEN, "lightseagreen"}, + {COLOR_FORESTGREEN, "forestgreen"}, + {COLOR_SEAGREEN, "seagreen"}, + {COLOR_DARKSLATEGRAY, "darkslategray"}, + {COLOR_DARKSLATEGREY, "darkslategrey"}, + {COLOR_LIMEGREEN, "limegreen"}, + {COLOR_MEDIUMSEAGREEN, "mediumseagreen"}, + {COLOR_TURQUOISE, "turquoise"}, + {COLOR_ROYALBLUE, "royalblue"}, + {COLOR_STEELBLUE, "steelblue"}, + {COLOR_DARKSLATEBLUE, "darkslateblue"}, + {COLOR_MEDIUMTURQUOISE, "mediumturquoise"}, + {COLOR_INDIGO, "indigo"}, + {COLOR_DARKOLIVEGREEN, "darkolivegreen"}, + {COLOR_CADETBLUE, "cadetblue"}, + {COLOR_CORNFLOWERBLUE, "cornflowerblue"}, + {COLOR_MEDIUMAQUAMARINE, "mediumaquamarine"}, + {COLOR_DIMGRAY, "dimgray"}, + {COLOR_DIMGREY, "dimgrey"}, + {COLOR_SLATEBLUE, "slateblue"}, + {COLOR_OLIVEDRAB, "olivedrab"}, + {COLOR_SLATEGRAY, "slategray"}, + {COLOR_SLATEGREY, "slategrey"}, + {COLOR_LIGHTSLATEGRAY, "lightslategray"}, + {COLOR_LIGHTSLATEGREY, "lightslategrey"}, + {COLOR_MEDIUMSLATEBLUE, "mediumslateblue"}, + {COLOR_LAWNGREEN, "lawngreen"}, + {COLOR_CHARTREUSE, "chartreuse"}, + {COLOR_AQUAMARINE, "aquamarine"}, + {COLOR_MAROON, "maroon"}, + {COLOR_PURPLE, "purple"}, + {COLOR_ELECTRIC_ULTRAMARINE, "electricultramarine"}, + {COLOR_OLIVE, "olive"}, + {COLOR_GRAY, "gray"}, + {COLOR_GREY, "grey"}, + {COLOR_SKYBLUE, "skyblue"}, + {COLOR_LIGHTSKYBLUE, "lightskyblue"}, + {COLOR_BLUEVIOLET, "blueviolet"}, + {COLOR_DARKRED, "darkred"}, + {COLOR_DARKMAGENTA, "darkmagenta"}, + {COLOR_SADDLEBROWN, "saddlebrown"}, + {COLOR_DARKSEAGREEN, "darkseagreen"}, + {COLOR_LIGHTGREEN, "lightgreen"}, + {COLOR_MEDIUMPURPLE, "mediumpurple"}, + {COLOR_DARKVIOLET, "darkviolet"}, + {COLOR_PALEGREEN, "palegreen"}, + {COLOR_DARKORCHID, "darkorchid"}, + {COLOR_YELLOWGREEN, "yellowgreen"}, + {COLOR_SIENNA, "sienna"}, + {COLOR_BROWN, "brown"}, + {COLOR_DARKGRAY, "darkgray"}, + {COLOR_DARKGREY, "darkgrey"}, + {COLOR_LIGHTBLUE, "lightblue"}, + {COLOR_GREENYELLOW, "greenyellow"}, + {COLOR_PALETURQUOISE, "paleturquoise"}, + {COLOR_LIGHTSTEELBLUE, "lightsteelblue"}, + {COLOR_POWDERBLUE, "powderblue"}, + {COLOR_FIREBRICK, "firebrick"}, + {COLOR_DARKGOLDENROD, "darkgoldenrod"}, + {COLOR_MEDIUMORCHID, "mediumorchid"}, + {COLOR_ROSYBROWN, "rosybrown"}, + {COLOR_DARKKHAKI, "darkkhaki"}, + {COLOR_SILVER, "silver"}, + {COLOR_MEDIUMVIOLETRED, "mediumvioletred"}, + {COLOR_INDIANRED, "indianred"}, + {COLOR_PERU, "peru"}, + {COLOR_CHOCOLATE, "chocolate"}, + {COLOR_TAN, "tan"}, + {COLOR_LIGHTGRAY, "lightgray"}, + {COLOR_LIGHTGREY, "lightgrey"}, + {COLOR_THISTLE, "thistle"}, + {COLOR_ORCHID, "orchid"}, + {COLOR_GOLDENROD, "goldenrod"}, + {COLOR_PALEVIOLETRED, "palevioletred"}, + {COLOR_CRIMSON, "crimson"}, + {COLOR_GAINSBORO, "gainsboro"}, + {COLOR_PLUM, "plum"}, + {COLOR_BURLYWOOD, "burlywood"}, + {COLOR_LIGHTCYAN, "lightcyan"}, + {COLOR_LAVENDER, "lavender"}, + {COLOR_DARKSALMON, "darksalmon"}, + {COLOR_VIOLET, "violet"}, + {COLOR_PALEGOLDENROD, "palegoldenrod"}, + {COLOR_LIGHTCORAL, "lightcoral"}, + {COLOR_KHAKI, "khaki"}, + {COLOR_ALICEBLUE, "aliceblue"}, + {COLOR_HONEYDEW, "honeydew"}, + {COLOR_AZURE, "azure"}, + {COLOR_SANDYBROWN, "sandybrown"}, + {COLOR_WHEAT, "wheat"}, + {COLOR_BEIGE, "beige"}, + {COLOR_WHITESMOKE, "whitesmoke"}, + {COLOR_MINTCREAM, "mintcream"}, + {COLOR_GHOSTWHITE, "ghostwhite"}, + {COLOR_SALMON, "salmon"}, + {COLOR_ANTIQUEWHITE, "antiquewhite"}, + {COLOR_LINEN, "linen"}, + {COLOR_LIGHTGOLDENRODYELLOW, "lightgoldenrodyellow"}, + {COLOR_OLDLACE, "oldlace"}, + {COLOR_RED, "red"}, + {COLOR_FUCHSIA, "fuchsia"}, + {COLOR_MAGENTA, "magenta"}, + {COLOR_DEEPPINK, "deeppink"}, + {COLOR_ORANGERED, "orangered"}, + {COLOR_TOMATO, "tomato"}, + {COLOR_HOTPINK, "hotpink"}, + {COLOR_CORAL, "coral"}, + {COLOR_DARKORANGE, "darkorange"}, + {COLOR_LIGHTSALMON, "lightsalmon"}, + {COLOR_ORANGE, "orange"}, + {COLOR_LIGHTPINK, "lightpink"}, + {COLOR_PINK, "pink"}, + {COLOR_GOLD, "gold"}, + {COLOR_PEACHPUFF, "peachpuff"}, + {COLOR_NAVAJOWHITE, "navajowhite"}, + {COLOR_MOCCASIN, "moccasin"}, + {COLOR_BISQUE, "bisque"}, + {COLOR_MISTYROSE, "mistyrose"}, + {COLOR_BLANCHEDALMOND, "blanchedalmond"}, + {COLOR_PAPAYAWHIP, "papayawhip"}, + {COLOR_LAVENDERBLUSH, "lavenderblush"}, + {COLOR_SEASHELL, "seashell"}, + {COLOR_CORNSILK, "cornsilk"}, + {COLOR_LEMONCHIFFON, "lemonchiffon"}, + {COLOR_FLORALWHITE, "floralwhite"}, + {COLOR_SNOW, "snow"}, + {COLOR_YELLOW, "yellow"}, + {COLOR_LIGHTYELLOW, "lightyellow"}, + {COLOR_IVORY, "ivory"}, + {COLOR_WHITE, "white"}, + {0, NULL}}; bool ParseColors(std::string colors_string, DeviceOptions *options) { - while (colors_string.length() > 0) - { - size_t rgb_end = colors_string.find_first_of(','); + while (colors_string.length() > 0) { + size_t rgb_end = colors_string.find_first_of(','); std::string color = colors_string.substr(0, rgb_end); int32_t rgb = 0; @@ -262,34 +261,31 @@ bool ParseColors(std::string colors_string, DeviceOptions *options) | MODE_COLORS_RANDOM else generate a random colour from the | | human_colors list above | \*-----------------------------------------------------------------*/ - if (color == "random") - { + if (color == "random") { options->random_colors = true; - srand((unsigned int)time(NULL)); - int index = rand() % (sizeof(human_colors) / sizeof(human_colors[0])) + 1; //Anything other than black + srand((unsigned int) time(NULL)); + int index = rand() % (sizeof(human_colors) / sizeof(human_colors[0])) + + 1; //Anything other than black rgb = human_colors[index].rgb; parsed = true; - } - else - { + } else { /* swy: (A) try interpreting it as text; as human keywords, otherwise strtoul() will pick up 'darkgreen' as 0xDA */ - for (const struct HumanColors *hc = human_colors; hc->keyword != NULL; hc++) - { + for (const struct HumanColors *hc = human_colors; hc->keyword != NULL; hc++) { if (strcasecmp(hc->keyword, color.c_str()) != 0) continue; - rgb = hc->rgb; parsed = true; + rgb = hc->rgb; + parsed = true; break; } } /* swy: (B) no luck, try interpreting it as an hexadecimal number instead */ - if (!parsed) - { - if (color.length() == 6) - { - const char *colorptr = color.c_str(); char *endptr = NULL; + if (!parsed) { + if (color.length() == 6) { + const char *colorptr = color.c_str(); + char *endptr = NULL; rgb = strtoul(colorptr, &endptr, 16); @@ -301,16 +297,12 @@ bool ParseColors(std::string colors_string, DeviceOptions *options) } /* swy: we got it, save the 32-bit integer as a tuple of three RGB bytes */ - if (parsed) - { - options->colors.push_back(std::make_tuple( - (rgb >> (8 * 2)) & 0xFF, /* RR.... */ - (rgb >> (8 * 1)) & 0xFF, /* ..GG.. */ - (rgb >> (8 * 0)) & 0xFF /* ....BB */ - )); - } - else - { + if (parsed) { + options->colors.push_back(std::make_tuple((rgb >> (8 * 2)) & 0xFF, /* RR.... */ + (rgb >> (8 * 1)) & 0xFF, /* ..GG.. */ + (rgb >> (8 * 0)) & 0xFF /* ....BB */ + )); + } else { std::cout << "Error: Unknown color: '" + color + "', skipping." << std::endl; } @@ -325,11 +317,10 @@ bool ParseColors(std::string colors_string, DeviceOptions *options) return options->colors.size() > 0; } -unsigned int ParseMode(DeviceOptions& options, std::vector &rgb_controllers) +unsigned int ParseMode(DeviceOptions &options, std::vector &rgb_controllers) { // no need to check if --mode wasn't passed - if (options.mode.size() == 0) - { + if (options.mode.size() == 0) { return rgb_controllers[options.device]->active_mode; } @@ -337,46 +328,44 @@ unsigned int ParseMode(DeviceOptions& options, std::vector &rgb | Search through all of the device modes and see if there is| | a match. If no match is found, print an error message. | \*---------------------------------------------------------*/ - for(unsigned int mode_idx = 0; mode_idx < rgb_controllers[options.device]->modes.size(); mode_idx++) - { - if (strcasecmp(rgb_controllers[options.device]->modes[mode_idx].name.c_str(), options.mode.c_str()) == 0) - { + for (unsigned int mode_idx = 0; mode_idx < rgb_controllers[options.device]->modes.size(); + mode_idx++) { + if (strcasecmp(rgb_controllers[options.device]->modes[mode_idx].name.c_str(), + options.mode.c_str()) + == 0) { return mode_idx; } } - std::cout << "Error: Mode '" + options.mode + "' not available for device '" + rgb_controllers[options.device]->name + "'" << std::endl; + std::cout << "Error: Mode '" + options.mode + "' not available for device '" + + rgb_controllers[options.device]->name + "'" + << std::endl; return false; } -DeviceOptions* GetDeviceOptionsForDevID(Options *opts, int device) +DeviceOptions *GetDeviceOptionsForDevID(Options *opts, int device) { - if (device == -1) - { + if (device == -1) { return &opts->allDeviceOptions; } - for (unsigned int i = 0; i < opts->devices.size(); i++) - { - if (opts->devices[i].device == device) - { + for (unsigned int i = 0; i < opts->devices.size(); i++) { + if (opts->devices[i].device == device) { return &opts->devices[i]; } } // should never happen - std::cout << "Internal error: Tried setting an option on a device that wasn't specified" << std::endl; + std::cout << "Internal error: Tried setting an option on a device that wasn't specified" + << std::endl; abort(); } std::string QuoteIfNecessary(std::string str) { - if (str.find(' ') == std::string::npos) - { + if (str.find(' ') == std::string::npos) { return str; - } - else - { + } else { return "'" + str + "'"; } } @@ -394,43 +383,79 @@ void OptionHelp() help_text += "Usage: OpenRGB (--device [--mode] [--color])...\n"; help_text += "\n"; help_text += "Options:\n"; - help_text += "--gui Shows the GUI. GUI also appears when not passing any parameters\n"; - help_text += "--startminimized Starts the GUI minimized to tray. Implies --gui, even if not specified\n"; - help_text += "--client [IP]:[Port] Starts an SDK client on the given IP:Port (assumes port 6742 if not specified)\n"; + help_text += "--gui Shows the GUI. GUI also appears when " + "not passing any parameters\n"; + help_text += "--startminimized Starts the GUI minimized to tray. " + "Implies --gui, even if not specified\n"; + help_text += "--client [IP]:[Port] Starts an SDK client on the given " + "IP:Port (assumes port 6742 if not specified)\n"; help_text += "--server Starts the SDK's server\n"; - help_text += "--server-host Sets the SDK's server host. Default: 0.0.0.0 (all network interfaces)\n"; - help_text += "--server-port Sets the SDK's server port. Default: 6742 (1024-65535)\n"; - help_text += "-l, --list-devices Lists every compatible device with their number\n"; - help_text += "-d, --device [0-9 | \"name\"] Selects device to apply colors and/or effect to, or applies to all devices if omitted\n"; - help_text += " Basic string search is implemented 3 characters or more\n"; - help_text += " Can be specified multiple times with different modes and colors\n"; - help_text += "-z, --zone [0-9] Selects zone to apply colors and/or sizes to, or applies to all zones in device if omitted\n"; - help_text += " Must be specified after specifying a device\n"; - help_text += "-c, --color [random | FFFFF,00AAFF ...] Sets colors on each device directly if no effect is specified, and sets the effect color if an effect is specified\n"; - help_text += " If there are more LEDs than colors given, the last color will be applied to the remaining LEDs\n"; - help_text += "-m, --mode [breathing | static | ...] Sets the mode to be applied, check --list-devices to see which modes are supported on your device\n"; - help_text += "-b, --brightness [0-100] Sets the brightness as a percentage if the mode supports brightness\n"; - help_text += "-s, --speed [0-100] Sets the speed as a percentage if the mode supports speed\n"; - help_text += "-sz, --size [0-N] Sets the new size of the specified device zone.\n"; - help_text += " Must be specified after specifying a zone.\n"; - help_text += " If the specified size is out of range, or the zone does not offer resizing capability, the size will not be changed\n"; - help_text += "-V, --version Display version and software build information\n"; - help_text += "-p, --profile filename[.orp] Load the profile from filename/filename.orp\n"; - help_text += "-sp, --save-profile filename.orp Save the given settings to profile filename.orp\n"; - help_text += "--i2c-tools Shows the I2C/SMBus Tools page in the GUI. Implies --gui, even if not specified.\n"; - help_text += " USE I2C TOOLS AT YOUR OWN RISK! Don't use this option if you don't know what you're doing!\n"; - help_text += " There is a risk of bricking your motherboard, RGB controller, and RAM if you send invalid SMBus/I2C transactions.\n"; - help_text += "--localconfig Use the current working directory instead of the global configuration directory.\n"; - help_text += "--config path Use a custom path instead of the global configuration directory.\n"; - help_text += "--nodetect Do not try to detect hardware at startup.\n"; - help_text += "--noautoconnect Do not try to autoconnect to a local server at startup.\n"; - help_text += "--loglevel [0-6 | error | warning ...] Set the log level (0: fatal to 6: trace).\n"; - help_text += "--print-source Print the source code file and line number for each log entry.\n"; + help_text += "--server-host Sets the SDK's server host. Default: " + "0.0.0.0 (all network interfaces)\n"; + help_text += "--server-port Sets the SDK's server port. Default: " + "6742 (1024-65535)\n"; + help_text += "-l, --list-devices Lists every compatible device with " + "their number\n"; + help_text += "-d, --device [0-9 | \"name\"] Selects device to apply colors and/or " + "effect to, or applies to all devices if omitted\n"; + help_text += " Basic string search is implemented 3 " + "characters or more\n"; + help_text += " Can be specified multiple times with " + "different modes and colors\n"; + help_text += "-z, --zone [0-9] Selects zone to apply colors and/or " + "sizes to, or applies to all zones in device if omitted\n"; + help_text += " Must be specified after specifying a " + "device\n"; + help_text += "-c, --color [random | FFFFF,00AAFF ...] Sets colors on each device directly if " + "no effect is specified, and sets the effect color if an effect is specified\n"; + help_text += " If there are more LEDs than colors " + "given, the last color will be applied to the remaining LEDs\n"; + help_text += "-m, --mode [breathing | static | ...] Sets the mode to be applied, check " + "--list-devices to see which modes are supported on your device\n"; + help_text += "-b, --brightness [0-100] Sets the brightness as a percentage if " + "the mode supports brightness\n"; + help_text += "-s, --speed [0-100] Sets the speed as a percentage if the " + "mode supports speed\n"; + help_text += "-sz, --size [0-N] Sets the new size of the specified " + "device zone.\n"; + help_text += " Must be specified after specifying a " + "zone.\n"; + help_text + += " If the specified size is out of range, or " + "the zone does not offer resizing capability, the size will not be changed\n"; + help_text += "-V, --version Display version and software build " + "information\n"; + help_text + += "-p, --profile filename[.orp] Load the profile from filename/filename.orp\n"; + help_text += "-sp, --save-profile filename.orp Save the given settings to profile " + "filename.orp\n"; + help_text += "--i2c-tools Shows the I2C/SMBus Tools page in the " + "GUI. Implies --gui, even if not specified.\n"; + help_text += " USE I2C TOOLS AT YOUR OWN RISK! Don't " + "use this option if you don't know what you're doing!\n"; + help_text + += " There is a risk of bricking your " + "motherboard, RGB controller, and RAM if you send invalid SMBus/I2C transactions.\n"; + help_text += "--localconfig Use the current working directory " + "instead of the global configuration directory.\n"; + help_text += "--config path Use a custom path instead of the global " + "configuration directory.\n"; + help_text + += "--nodetect Do not try to detect hardware at startup.\n"; + help_text += "--noautoconnect Do not try to autoconnect to a local " + "server at startup.\n"; + help_text + += "--loglevel [0-6 | error | warning ...] Set the log level (0: fatal to 6: trace).\n"; + help_text += "--print-source Print the source code file and line " + "number for each log entry.\n"; help_text += "-v, --verbose Print log messages to stdout.\n"; - help_text += "-vv, --very-verbose Print debug messages and log messages to stdout.\n"; - help_text += "--autostart-check Check if OpenRGB starting at login is enabled.\n"; + help_text += "-vv, --very-verbose Print debug messages and log messages " + "to stdout.\n"; + help_text += "--autostart-check Check if OpenRGB starting at login is " + "enabled.\n"; help_text += "--autostart-disable Disable OpenRGB starting at login.\n"; - help_text += "--autostart-enable arguments Enable OpenRGB to start at login. Requires arguments to give to OpenRGB at login.\n"; + help_text += "--autostart-enable arguments Enable OpenRGB to start at login. " + "Requires arguments to give to OpenRGB at login.\n"; std::cout << help_text << std::endl; } @@ -456,12 +481,11 @@ void OptionVersion() std::cout << version_text << std::endl; } -void OptionListDevices(std::vector& rgb_controllers) +void OptionListDevices(std::vector &rgb_controllers) { ResourceManager::get()->WaitForDeviceDetection(); - for(std::size_t controller_idx = 0; controller_idx < rgb_controllers.size(); controller_idx++) - { + for (std::size_t controller_idx = 0; controller_idx < rgb_controllers.size(); controller_idx++) { RGBController *controller = rgb_controllers[controller_idx]; /*---------------------------------------------------------*\ @@ -472,54 +496,47 @@ void OptionListDevices(std::vector& rgb_controllers) /*---------------------------------------------------------*\ | Print device type | \*---------------------------------------------------------*/ - std::cout << " Type: " << device_type_to_str(controller->type) << std::endl; + std::cout << " Type: " << device_type_to_str(controller->type) << std::endl; /*---------------------------------------------------------*\ | Print device description | \*---------------------------------------------------------*/ - if(!controller->description.empty()) - { + if (!controller->description.empty()) { std::cout << " Description: " << controller->description << std::endl; } /*---------------------------------------------------------*\ | Print device version | \*---------------------------------------------------------*/ - if(!controller->version.empty()) - { + if (!controller->version.empty()) { std::cout << " Version: " << controller->version << std::endl; } /*---------------------------------------------------------*\ | Print device location | \*---------------------------------------------------------*/ - if(!controller->location.empty()) - { + if (!controller->location.empty()) { std::cout << " Location: " << controller->location << std::endl; } /*---------------------------------------------------------*\ | Print device serial | \*---------------------------------------------------------*/ - if(!controller->serial.empty()) - { + if (!controller->serial.empty()) { std::cout << " Serial: " << controller->serial << std::endl; } /*---------------------------------------------------------*\ | Print device modes | \*---------------------------------------------------------*/ - if(!controller->modes.empty()) - { + if (!controller->modes.empty()) { std::cout << " Modes:"; int current_mode = controller->GetMode(); - for(std::size_t mode_idx = 0; mode_idx < controller->modes.size(); mode_idx++) - { + for (std::size_t mode_idx = 0; mode_idx < controller->modes.size(); mode_idx++) { std::string modeStr = QuoteIfNecessary(controller->modes[mode_idx].name); - if(current_mode == (int)mode_idx) - { + if (current_mode == (int) mode_idx) { modeStr = "[" + modeStr + "]"; } std::cout << " " << modeStr; @@ -530,12 +547,10 @@ void OptionListDevices(std::vector& rgb_controllers) /*---------------------------------------------------------*\ | Print device zones | \*---------------------------------------------------------*/ - if(!controller->zones.empty()) - { + if (!controller->zones.empty()) { std::cout << " Zones:"; - for(std::size_t zone_idx = 0; zone_idx < controller->zones.size(); zone_idx++) - { + for (std::size_t zone_idx = 0; zone_idx < controller->zones.size(); zone_idx++) { std::cout << " " << QuoteIfNecessary(controller->zones[zone_idx].name); } std::cout << std::endl; @@ -544,12 +559,10 @@ void OptionListDevices(std::vector& rgb_controllers) /*---------------------------------------------------------*\ | Print device LEDs | \*---------------------------------------------------------*/ - if(!controller->leds.empty()) - { + if (!controller->leds.empty()) { std::cout << " LEDs:"; - for(std::size_t led_idx = 0; led_idx < controller->leds.size(); led_idx++) - { + for (std::size_t led_idx = 0; led_idx < controller->leds.size(); led_idx++) { std::cout << " " << QuoteIfNecessary(controller->leds[led_idx].name); } std::cout << std::endl; @@ -559,64 +572,56 @@ void OptionListDevices(std::vector& rgb_controllers) } } -bool OptionDevice(std::vector* current_devices, std::string argument, Options* options, std::vector& rgb_controllers) +bool OptionDevice(std::vector *current_devices, + std::string argument, + Options *options, + std::vector &rgb_controllers) { bool found = false; ResourceManager::get()->WaitForDeviceDetection(); - try - { + try { int current_device = std::stoi(argument); - if((current_device >= static_cast(rgb_controllers.size())) || (current_device < 0)) - { + if ((current_device >= static_cast(rgb_controllers.size())) || (current_device < 0)) { throw nullptr; } DeviceOptions newDev; newDev.device = current_device; - if(!options->hasDevice) - { + if (!options->hasDevice) { options->hasDevice = true; } current_devices->push_back(newDev); found = true; - } - catch(...) - { - if(argument.length() > 1) - { - for(unsigned int i = 0; i < rgb_controllers.size(); i++) - { + } catch (...) { + if (argument.length() > 1) { + for (unsigned int i = 0; i < rgb_controllers.size(); i++) { /*---------------------------------------------------------*\ | If the argument is not a number then check all the | | controllers names for a match | \*---------------------------------------------------------*/ - std::string name = rgb_controllers[i]->name; + std::string name = rgb_controllers[i]->name; std::transform(name.begin(), name.end(), name.begin(), ::tolower); std::transform(argument.begin(), argument.end(), argument.begin(), ::tolower); - if(name.find(argument) != std::string::npos) - { - found = true; + if (name.find(argument) != std::string::npos) { + found = true; DeviceOptions newDev; - newDev.device = i; + newDev.device = i; - if(!options->hasDevice) - { - options->hasDevice = true; + if (!options->hasDevice) { + options->hasDevice = true; } current_devices->push_back(newDev); } } - } - else - { + } else { std::cout << "Error: Invalid device ID: " + argument << std::endl; return false; } @@ -625,30 +630,29 @@ bool OptionDevice(std::vector* current_devices, std::string argum return found; } -bool OptionZone(std::vector* current_devices, std::string argument, Options* /*options*/, std::vector& rgb_controllers) +bool OptionZone(std::vector *current_devices, + std::string argument, + Options * /*options*/, + std::vector &rgb_controllers) { bool found = false; ResourceManager::get()->WaitForDeviceDetection(); - try - { + try { int current_zone = std::stoi(argument); - for(size_t i = 0; i < current_devices->size(); i++) - { + for (size_t i = 0; i < current_devices->size(); i++) { int current_device = current_devices->at(i).device; - if(current_zone >= static_cast(rgb_controllers[current_device]->zones.size()) || (current_zone < 0)) - { + if (current_zone >= static_cast(rgb_controllers[current_device]->zones.size()) + || (current_zone < 0)) { throw nullptr; } current_devices->at(i).zone = current_zone; found = true; } - } - catch(...) - { + } catch (...) { std::cout << "Error: Invalid zone ID: " + argument << std::endl; return false; } @@ -656,37 +660,30 @@ bool OptionZone(std::vector* current_devices, std::string argumen return found; } -bool CheckColor(std::string argument, DeviceOptions* currentDevOpts) +bool CheckColor(std::string argument, DeviceOptions *currentDevOpts) { - if(ParseColors(argument, currentDevOpts)) - { + if (ParseColors(argument, currentDevOpts)) { currentDevOpts->hasOption = true; return true; - } - else - { + } else { std::cout << "Error: Invalid color value: " + argument << std::endl; return false; } } -bool OptionColor(std::vector* current_devices, std::string argument, Options* options) +bool OptionColor(std::vector *current_devices, std::string argument, Options *options) { /*---------------------------------------------------------*\ | If a device is not selected i.e. size() == 0 | | then add color to allDeviceOptions | \*---------------------------------------------------------*/ - bool found = false; - DeviceOptions* currentDevOpts = &options->allDeviceOptions; + bool found = false; + DeviceOptions *currentDevOpts = &options->allDeviceOptions; - if(current_devices->size() == 0) - { + if (current_devices->size() == 0) { found = CheckColor(argument, currentDevOpts); - } - else - { - for(size_t i = 0; i < current_devices->size(); i++) - { + } else { + for (size_t i = 0; i < current_devices->size(); i++) { currentDevOpts = ¤t_devices->at(i); found = CheckColor(argument, currentDevOpts); @@ -696,10 +693,9 @@ bool OptionColor(std::vector* current_devices, std::string argume return found; } -bool OptionMode(std::vector* current_devices, std::string argument, Options* options) +bool OptionMode(std::vector *current_devices, std::string argument, Options *options) { - if(argument.size() == 0) - { + if (argument.size() == 0) { std::cout << "Error: --mode passed with no argument" << std::endl; return false; } @@ -708,19 +704,15 @@ bool OptionMode(std::vector* current_devices, std::string argumen | If a device is not selected i.e. size() == 0 | | then add mode to allDeviceOptions | \*---------------------------------------------------------*/ - bool found = false; - DeviceOptions* currentDevOpts = &options->allDeviceOptions; + bool found = false; + DeviceOptions *currentDevOpts = &options->allDeviceOptions; - if(current_devices->size() == 0) - { + if (current_devices->size() == 0) { currentDevOpts->mode = argument; currentDevOpts->hasOption = true; found = true; - } - else - { - for(size_t i = 0; i < current_devices->size(); i++) - { + } else { + for (size_t i = 0; i < current_devices->size(); i++) { currentDevOpts = ¤t_devices->at(i); currentDevOpts->mode = argument; @@ -732,10 +724,9 @@ bool OptionMode(std::vector* current_devices, std::string argumen return found; } -bool OptionSpeed(std::vector* current_devices, std::string argument, Options* options) +bool OptionSpeed(std::vector *current_devices, std::string argument, Options *options) { - if(argument.size() == 0) - { + if (argument.size() == 0) { std::cout << "Error: --speed passed with no argument" << std::endl; return false; } @@ -744,23 +735,20 @@ bool OptionSpeed(std::vector* current_devices, std::string argume | If a device is not selected i.e. size() == 0 | | then add speed to allDeviceOptions | \*---------------------------------------------------------*/ - bool found = false; - DeviceOptions* currentDevOpts = &options->allDeviceOptions; + bool found = false; + DeviceOptions *currentDevOpts = &options->allDeviceOptions; - if(current_devices->size() == 0) - { - currentDevOpts->speed = std::min(std::max(std::stoi(argument), 0),(int)speed_percentage); - currentDevOpts->hasOption = true; + if (current_devices->size() == 0) { + currentDevOpts->speed = std::min(std::max(std::stoi(argument), 0), (int) speed_percentage); + currentDevOpts->hasOption = true; found = true; - } - else - { - for(size_t i = 0; i < current_devices->size(); i++) - { - DeviceOptions* currentDevOpts = ¤t_devices->at(i); + } else { + for (size_t i = 0; i < current_devices->size(); i++) { + DeviceOptions *currentDevOpts = ¤t_devices->at(i); - currentDevOpts->speed = std::min(std::max(std::stoi(argument), 0),(int)speed_percentage); - currentDevOpts->hasOption = true; + currentDevOpts->speed = std::min(std::max(std::stoi(argument), 0), + (int) speed_percentage); + currentDevOpts->hasOption = true; found = true; } } @@ -768,10 +756,11 @@ bool OptionSpeed(std::vector* current_devices, std::string argume return found; } -bool OptionBrightness(std::vector* current_devices, std::string argument, Options* options) +bool OptionBrightness(std::vector *current_devices, + std::string argument, + Options *options) { - if(argument.size() == 0) - { + if (argument.size() == 0) { std::cout << "Error: --brightness passed with no argument" << std::endl; return false; } @@ -780,23 +769,21 @@ bool OptionBrightness(std::vector* current_devices, std::string a | If a device is not selected i.e. size() == 0 | | then add brightness to allDeviceOptions | \*---------------------------------------------------------*/ - bool found = false; - DeviceOptions* currentDevOpts = &options->allDeviceOptions; + bool found = false; + DeviceOptions *currentDevOpts = &options->allDeviceOptions; - if(current_devices->size() == 0) - { - currentDevOpts->brightness = std::min(std::max(std::stoi(argument), 0),(int)brightness_percentage); - currentDevOpts->hasOption = true; + if (current_devices->size() == 0) { + currentDevOpts->brightness = std::min(std::max(std::stoi(argument), 0), + (int) brightness_percentage); + currentDevOpts->hasOption = true; found = true; - } - else - { - for(size_t i = 0; i < current_devices->size(); i++) - { - DeviceOptions* currentDevOpts = ¤t_devices->at(i); + } else { + for (size_t i = 0; i < current_devices->size(); i++) { + DeviceOptions *currentDevOpts = ¤t_devices->at(i); - currentDevOpts->brightness = std::min(std::max(std::stoi(argument), 0),(int)brightness_percentage); - currentDevOpts->hasOption = true; + currentDevOpts->brightness = std::min(std::max(std::stoi(argument), 0), + (int) brightness_percentage); + currentDevOpts->hasOption = true; found = true; } } @@ -804,32 +791,31 @@ bool OptionBrightness(std::vector* current_devices, std::string a return found; } -bool OptionSize(std::vector* current_devices, std::string argument, Options* /*options*/, std::vector& rgb_controllers) +bool OptionSize(std::vector *current_devices, + std::string argument, + Options * /*options*/, + std::vector &rgb_controllers) { const unsigned int new_size = std::stoi(argument); ResourceManager::get()->WaitForDeviceDetection(); - for(size_t i = 0; i < current_devices->size(); i++) - { - int current_device = current_devices->at(i).device; - int current_zone = current_devices->at(i).zone; + for (size_t i = 0; i < current_devices->size(); i++) { + int current_device = current_devices->at(i).device; + int current_zone = current_devices->at(i).zone; /*---------------------------------------------------------*\ | Fail out if device, zone, or size are out of range | \*---------------------------------------------------------*/ - if((current_device >= static_cast(rgb_controllers.size())) || (current_device < 0)) - { + if ((current_device >= static_cast(rgb_controllers.size())) || (current_device < 0)) { std::cout << "Error: Device is out of range" << std::endl; return false; - } - else if((current_zone >= static_cast(rgb_controllers[current_device]->zones.size())) || (current_zone < 0)) - { + } else if ((current_zone >= static_cast(rgb_controllers[current_device]->zones.size())) + || (current_zone < 0)) { std::cout << "Error: Zone is out of range" << std::endl; return false; - } - else if((new_size < rgb_controllers[current_device]->zones[current_zone].leds_min) || (new_size > rgb_controllers[current_device]->zones[current_zone].leds_max)) - { + } else if ((new_size < rgb_controllers[current_device]->zones[current_zone].leds_min) + || (new_size > rgb_controllers[current_device]->zones[current_zone].leds_max)) { std::cout << "Error: New size is out of range" << std::endl; } @@ -847,27 +833,25 @@ bool OptionSize(std::vector* current_devices, std::string argumen return true; } -bool OptionProfile(std::string argument, std::vector& rgb_controllers) +bool OptionProfile(std::string argument, std::vector &rgb_controllers) { ResourceManager::get()->WaitForDeviceDetection(); /*---------------------------------------------------------*\ | Attempt to load profile | \*---------------------------------------------------------*/ - if(ResourceManager::get()->GetProfileManager()->LoadProfile(argument)) - { + if (ResourceManager::get()->GetProfileManager()->LoadProfile(argument)) { /*-----------------------------------------------------*\ | Change device mode if profile loading was successful | \*-----------------------------------------------------*/ - for(std::size_t controller_idx = 0; controller_idx < rgb_controllers.size(); controller_idx++) - { - RGBController* device = rgb_controllers[controller_idx]; + for (std::size_t controller_idx = 0; controller_idx < rgb_controllers.size(); + controller_idx++) { + RGBController *device = rgb_controllers[controller_idx]; device->DeviceUpdateMode(); LOG_DEBUG("[CLI] Updating mode for %s to %i", device->name.c_str(), device->active_mode); - if(device->modes[device->active_mode].color_mode == MODE_COLORS_PER_LED) - { + if (device->modes[device->active_mode].color_mode == MODE_COLORS_PER_LED) { device->DeviceUpdateLEDs(); LOG_DEBUG("[CLI] Mode uses per-LED color, also updating LEDs"); } @@ -875,9 +859,7 @@ bool OptionProfile(std::string argument, std::vector& rgb_contr std::cout << "Profile loaded successfully" << std::endl; return true; - } - else - { + } else { std::cout << "Profile failed to load" << std::endl; return false; } @@ -889,13 +871,13 @@ bool OptionSaveProfile(std::string argument) | Set save profile filename | \*---------------------------------------------------------*/ profile_save_filename = argument; - return(true); + return (true); } -int ProcessOptions(Options* options, std::vector& rgb_controllers) +int ProcessOptions(Options *options, std::vector &rgb_controllers) { - unsigned int ret_flags = 0; - int arg_index = 1; + unsigned int ret_flags = 0; + int arg_index = 1; std::vector current_devices; options->hasDevice = false; @@ -903,20 +885,18 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle #ifdef _WIN32 int fake_argc; - wchar_t** argvw = CommandLineToArgvW(GetCommandLineW(), &fake_argc); + wchar_t **argvw = CommandLineToArgvW(GetCommandLineW(), &fake_argc); #endif - while(arg_index < preserve_argc) - { - std::string option = preserve_argv[arg_index]; + while (arg_index < preserve_argc) { + std::string option = preserve_argv[arg_index]; std::string argument = ""; filesystem::path arg_path; /*---------------------------------------------------------*\ | Handle options that take an argument | \*---------------------------------------------------------*/ - if(arg_index + 1 < preserve_argc) - { + if (arg_index + 1 < preserve_argc) { argument = preserve_argv[arg_index + 1]; #ifdef _WIN32 arg_path = argvw[arg_index + 1]; @@ -928,8 +908,7 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -l / --list-devices (no arguments) | \*---------------------------------------------------------*/ - if(option == "--list-devices" || option == "-l") - { + if (option == "--list-devices" || option == "-l") { OptionListDevices(rgb_controllers); exit(0); } @@ -937,16 +916,13 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -d / --device | \*---------------------------------------------------------*/ - else if(option == "--device" || option == "-d") - { - while(!current_devices.empty()) - { + else if (option == "--device" || option == "-d") { + while (!current_devices.empty()) { options->devices.push_back(current_devices.back()); current_devices.pop_back(); } - if(!OptionDevice(¤t_devices, argument, options, rgb_controllers)) - { + if (!OptionDevice(¤t_devices, argument, options, rgb_controllers)) { return RET_FLAG_PRINT_HELP; } @@ -956,10 +932,8 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -z / --zone | \*---------------------------------------------------------*/ - else if(option == "--zone" || option == "-z") - { - if(!OptionZone(¤t_devices, argument, options, rgb_controllers)) - { + else if (option == "--zone" || option == "-z") { + if (!OptionZone(¤t_devices, argument, options, rgb_controllers)) { return RET_FLAG_PRINT_HELP; } @@ -969,10 +943,8 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -c / --color | \*---------------------------------------------------------*/ - else if(option == "--color" || option == "-c") - { - if(!OptionColor(¤t_devices, argument, options)) - { + else if (option == "--color" || option == "-c") { + if (!OptionColor(¤t_devices, argument, options)) { return RET_FLAG_PRINT_HELP; } @@ -982,10 +954,8 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -m / --mode | \*---------------------------------------------------------*/ - else if(option == "--mode" || option == "-m") - { - if(!OptionMode(¤t_devices, argument, options)) - { + else if (option == "--mode" || option == "-m") { + if (!OptionMode(¤t_devices, argument, options)) { return RET_FLAG_PRINT_HELP; } @@ -995,10 +965,8 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -b / --brightness | \*---------------------------------------------------------*/ - else if(option == "--brightness" || option == "-b") - { - if(!OptionBrightness(¤t_devices, argument, options)) - { + else if (option == "--brightness" || option == "-b") { + if (!OptionBrightness(¤t_devices, argument, options)) { return RET_FLAG_PRINT_HELP; } @@ -1008,10 +976,8 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -s / --speed | \*---------------------------------------------------------*/ - else if(option == "--speed" || option == "-s") - { - if(!OptionSpeed(¤t_devices, argument, options)) - { + else if (option == "--speed" || option == "-s") { + if (!OptionSpeed(¤t_devices, argument, options)) { return RET_FLAG_PRINT_HELP; } @@ -1021,10 +987,8 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -sz / --size | \*---------------------------------------------------------*/ - else if(option == "--size" || option == "-sz") - { - if(!OptionSize(¤t_devices, argument, options, rgb_controllers)) - { + else if (option == "--size" || option == "-sz") { + if (!OptionSize(¤t_devices, argument, options, rgb_controllers)) { return RET_FLAG_PRINT_HELP; } @@ -1034,8 +998,7 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -p / --profile | \*---------------------------------------------------------*/ - else if(option == "--profile" || option == "-p") - { + else if (option == "--profile" || option == "-p") { options->profile_loaded = OptionProfile(arg_path.generic_u8string(), rgb_controllers); arg_index++; @@ -1044,8 +1007,7 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | -sp / --save-profile | \*---------------------------------------------------------*/ - else if(option == "--save-profile" || option == "-sp") - { + else if (option == "--save-profile" || option == "-sp") { OptionSaveProfile(arg_path.generic_u8string()); arg_index++; @@ -1054,43 +1016,28 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle /*---------------------------------------------------------*\ | Invalid option | \*---------------------------------------------------------*/ - else - { - if((option == "--localconfig") - ||(option == "--nodetect") - ||(option == "--noautoconnect") - ||(option == "--server") - ||(option == "--gui") - ||(option == "--i2c-tools" || option == "--yolo") - ||(option == "--startminimized") - ||(option == "--print-source") - ||(option == "--verbose" || option == "-v") - ||(option == "--very-verbose" || option == "-vv") - ||(option == "--help" || option == "-h") - ||(option == "--version" || option == "-V") - ||(option == "--autostart-check") - ||(option == "--autostart-disable")) - { + else { + if ((option == "--localconfig") || (option == "--nodetect") + || (option == "--noautoconnect") || (option == "--server") || (option == "--gui") + || (option == "--i2c-tools" || option == "--yolo") || (option == "--startminimized") + || (option == "--print-source") || (option == "--verbose" || option == "-v") + || (option == "--very-verbose" || option == "-vv") + || (option == "--help" || option == "-h") + || (option == "--version" || option == "-V") || (option == "--autostart-check") + || (option == "--autostart-disable")) { /*-------------------------------------------------*\ | Do nothing, these are pre-detection arguments | | and this parser should ignore them | \*-------------------------------------------------*/ - } - else if((option == "--server-port") - ||(option == "--server-host") - ||(option == "--loglevel") - ||(option == "--config") - ||(option == "--client") - ||(option == "--autostart-enable")) - { + } else if ((option == "--server-port") || (option == "--server-host") + || (option == "--loglevel") || (option == "--config") + || (option == "--client") || (option == "--autostart-enable")) { /*-------------------------------------------------*\ | Increment index for pre-detection arguments with | | parameter | \*-------------------------------------------------*/ arg_index++; - } - else - { + } else { /*-------------------------------------------------*\ | If the argument is not a pre-detection argument, | | throw an error and print help | @@ -1107,33 +1054,29 @@ int ProcessOptions(Options* options, std::vector& rgb_controlle | If a device was specified, check to verify that a | | corresponding option was also specified | \*---------------------------------------------------------*/ - while(!current_devices.empty()) - { + while (!current_devices.empty()) { options->devices.push_back(current_devices.back()); current_devices.pop_back(); } - if(options->hasDevice) - { - for(std::size_t option_idx = 0; option_idx < options->devices.size(); option_idx++) - { - if(!options->devices[option_idx].hasOption) - { - std::cout << "Error: Device " + std::to_string(option_idx) + " specified, but neither mode nor color given" << std::endl; + if (options->hasDevice) { + for (std::size_t option_idx = 0; option_idx < options->devices.size(); option_idx++) { + if (!options->devices[option_idx].hasOption) { + std::cout << "Error: Device " + std::to_string(option_idx) + + " specified, but neither mode nor color given" + << std::endl; return RET_FLAG_PRINT_HELP; } } return 0; - } - else - { + } else { return ret_flags; } } -void ApplyOptions(DeviceOptions& options, std::vector& rgb_controllers) +void ApplyOptions(DeviceOptions &options, std::vector &rgb_controllers) { - RGBController* device = rgb_controllers[options.device]; + RGBController *device = rgb_controllers[options.device]; /*---------------------------------------------------------*\ | Set mode first, in case it's 'direct' (which affects | @@ -1146,8 +1089,7 @@ void ApplyOptions(DeviceOptions& options, std::vector& rgb_cont | supports that colour mode then swich to it before | | evaluating if a colour needs to be set | \*---------------------------------------------------------*/ - if(options.random_colors && (device->modes[mode].flags & MODE_FLAG_HAS_RANDOM_COLOR)) - { + if (options.random_colors && (device->modes[mode].flags & MODE_FLAG_HAS_RANDOM_COLOR)) { device->modes[mode].color_mode = MODE_COLORS_RANDOM; } @@ -1156,87 +1098,80 @@ void ApplyOptions(DeviceOptions& options, std::vector& rgb_cont | supports that colour mode then swich to it before | | evaluating if a colour needs to be set | \*---------------------------------------------------------*/ - if((device->modes[mode].flags & MODE_FLAG_HAS_BRIGHTNESS)) - { - unsigned int new_brightness = device->modes[mode].brightness_max - device->modes[mode].brightness_min; - new_brightness *= options.brightness; - new_brightness /= brightness_percentage; + if ((device->modes[mode].flags & MODE_FLAG_HAS_BRIGHTNESS)) { + unsigned int new_brightness = device->modes[mode].brightness_max + - device->modes[mode].brightness_min; + new_brightness *= options.brightness; + new_brightness /= brightness_percentage; - device->modes[mode].brightness = device->modes[mode].brightness_min + new_brightness; + device->modes[mode].brightness = device->modes[mode].brightness_min + new_brightness; } - if((device->modes[mode].flags & MODE_FLAG_HAS_SPEED)) - { - unsigned int new_speed = device->modes[mode].speed_max - device->modes[mode].speed_min; - new_speed *= options.speed; - new_speed /= speed_percentage; + if ((device->modes[mode].flags & MODE_FLAG_HAS_SPEED)) { + unsigned int new_speed = device->modes[mode].speed_max - device->modes[mode].speed_min; + new_speed *= options.speed; + new_speed /= speed_percentage; - device->modes[mode].speed = device->modes[mode].speed_min + new_speed; + device->modes[mode].speed = device->modes[mode].speed_min + new_speed; } /*---------------------------------------------------------*\ | Determine which color mode this mode uses and update | | colors accordingly | \*---------------------------------------------------------*/ - switch(device->modes[mode].color_mode) - { - case MODE_COLORS_NONE: - break; + switch (device->modes[mode].color_mode) { + case MODE_COLORS_NONE: + break; - case MODE_COLORS_RANDOM: - break; + case MODE_COLORS_RANDOM: + break; - case MODE_COLORS_PER_LED: - if(options.colors.size() != 0) - { - std::size_t last_set_color = 0; + case MODE_COLORS_PER_LED: + if (options.colors.size() != 0) { + std::size_t last_set_color = 0; - RGBColor* start_from; - unsigned int led_count; - if(options.zone < 0) - { - start_from = &device->colors[0]; - led_count = (unsigned int)device->leds.size(); - } - else - { - start_from = device->zones[options.zone].colors; - led_count = device->zones[options.zone].leds_count; - } - - for(std::size_t led_idx = 0; led_idx < led_count; led_idx++) - { - if(led_idx < options.colors.size()) - { - last_set_color = led_idx; - } - - start_from[led_idx] = ToRGBColor(std::get<0>(options.colors[last_set_color]), - std::get<1>(options.colors[last_set_color]), - std::get<2>(options.colors[last_set_color])); - } + RGBColor *start_from; + unsigned int led_count; + if (options.zone < 0) { + start_from = &device->colors[0]; + led_count = (unsigned int) device->leds.size(); + } else { + start_from = device->zones[options.zone].colors; + led_count = device->zones[options.zone].leds_count; } - break; - case MODE_COLORS_MODE_SPECIFIC: - if(options.colors.size() >= device->modes[mode].colors_min && options.colors.size() <= device->modes[mode].colors_max) - { - device->modes[mode].colors.resize(options.colors.size()); - - for(std::size_t color_idx = 0; color_idx < options.colors.size(); color_idx++) - { - device->modes[mode].colors[color_idx] = ToRGBColor(std::get<0>(options.colors[color_idx]), - std::get<1>(options.colors[color_idx]), - std::get<2>(options.colors[color_idx])); + for (std::size_t led_idx = 0; led_idx < led_count; led_idx++) { + if (led_idx < options.colors.size()) { + last_set_color = led_idx; } + + start_from[led_idx] = ToRGBColor(std::get<0>(options.colors[last_set_color]), + std::get<1>(options.colors[last_set_color]), + std::get<2>(options.colors[last_set_color])); } - else - { - std::cout << "Wrong number of colors specified for mode " + device->modes[mode].name << std::endl; - std::cout << "Please provide between " + std::to_string(device->modes[mode].colors_min) + " and " + std::to_string(device->modes[mode].colors_min) + " colors" << std::endl; - exit(0); + } + break; + + case MODE_COLORS_MODE_SPECIFIC: + if (options.colors.size() >= device->modes[mode].colors_min + && options.colors.size() <= device->modes[mode].colors_max) { + device->modes[mode].colors.resize(options.colors.size()); + + for (std::size_t color_idx = 0; color_idx < options.colors.size(); color_idx++) { + device->modes[mode].colors[color_idx] + = ToRGBColor(std::get<0>(options.colors[color_idx]), + std::get<1>(options.colors[color_idx]), + std::get<2>(options.colors[color_idx])); } - break; + } else { + std::cout << "Wrong number of colors specified for mode " + device->modes[mode].name + << std::endl; + std::cout << "Please provide between " + std::to_string(device->modes[mode].colors_min) + + " and " + std::to_string(device->modes[mode].colors_min) + " colors" + << std::endl; + exit(0); + } + break; } /*---------------------------------------------------------*\ @@ -1248,38 +1183,35 @@ void ApplyOptions(DeviceOptions& options, std::vector& rgb_cont /*---------------------------------------------------------*\ | Set device per-LED colors if necessary | \*---------------------------------------------------------*/ - if(device->modes[mode].color_mode == MODE_COLORS_PER_LED) - { + if (device->modes[mode].color_mode == MODE_COLORS_PER_LED) { device->DeviceUpdateLEDs(); } } - -unsigned int cli_pre_detection(int argc, char* argv[]) +unsigned int cli_pre_detection(int argc, char *argv[]) { /*---------------------------------------------------------*\ | Process only the arguments that should be performed prior | | to detecting devices and/or starting clients | \*---------------------------------------------------------*/ - int arg_index = 1; - unsigned int cfg_args = 0; - unsigned int ret_flags = 0; - std::string server_host = OPENRGB_SDK_HOST; - unsigned short server_port = OPENRGB_SDK_PORT; - bool server_start = false; - bool print_help = false; + int arg_index = 1; + unsigned int cfg_args = 0; + unsigned int ret_flags = 0; + std::string server_host = OPENRGB_SDK_HOST; + unsigned short server_port = OPENRGB_SDK_PORT; + bool server_start = false; + bool print_help = false; preserve_argc = argc; preserve_argv = argv; #ifdef _WIN32 int fake_argc; - wchar_t** argvw = CommandLineToArgvW(GetCommandLineW(), &fake_argc); + wchar_t **argvw = CommandLineToArgvW(GetCommandLineW(), &fake_argc); #endif - while(arg_index < argc) - { - std::string option = argv[arg_index]; + while (arg_index < argc) { + std::string option = argv[arg_index]; std::string argument = ""; LOG_DEBUG("[CLI] Parsing CLI option: %s", option.c_str()); @@ -1287,16 +1219,14 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | Handle options that take an argument | \*---------------------------------------------------------*/ - if(arg_index + 1 < argc) - { + if (arg_index + 1 < argc) { argument = argv[arg_index + 1]; } /*---------------------------------------------------------*\ | --localconfig | \*---------------------------------------------------------*/ - if(option == "--localconfig") - { + if (option == "--localconfig") { ResourceManager::get()->SetConfigurationDirectory("./"); cfg_args++; } @@ -1304,9 +1234,8 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --config | \*---------------------------------------------------------*/ - else if(option == "--config") - { - cfg_args+= 2; + else if (option == "--config") { + cfg_args += 2; arg_index++; #ifdef _WIN32 filesystem::path config_path(argvw[arg_index]); @@ -1314,14 +1243,13 @@ unsigned int cli_pre_detection(int argc, char* argv[]) filesystem::path config_path(argument); #endif - if(filesystem::is_directory(config_path)) - { + if (filesystem::is_directory(config_path)) { ResourceManager::get()->SetConfigurationDirectory(config_path); - LOG_INFO("[CLI] Setting config directory to %s",argument.c_str()); // TODO: Use config_path in logs somehow - } - else - { - LOG_ERROR("[CLI] '%s' is not a valid directory",argument.c_str()); // TODO: Use config_path in logs somehow + LOG_INFO("[CLI] Setting config directory to %s", + argument.c_str()); // TODO: Use config_path in logs somehow + } else { + LOG_ERROR("[CLI] '%s' is not a valid directory", + argument.c_str()); // TODO: Use config_path in logs somehow print_help = true; break; } @@ -1330,8 +1258,7 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --nodetect | \*---------------------------------------------------------*/ - else if(option == "--nodetect") - { + else if (option == "--nodetect") { ret_flags |= RET_FLAG_NO_DETECT; cfg_args++; } @@ -1339,8 +1266,7 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --noautoconnect | \*---------------------------------------------------------*/ - else if(option == "--noautoconnect") - { + else if (option == "--noautoconnect") { ret_flags |= RET_FLAG_NO_AUTO_CONNECT; cfg_args++; } @@ -1348,20 +1274,16 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --client | \*---------------------------------------------------------*/ - else if(option == "--client") - { - NetworkClient * client = new NetworkClient(ResourceManager::get()->GetRGBControllers()); + else if (option == "--client") { + NetworkClient *client = new NetworkClient(ResourceManager::get()->GetRGBControllers()); std::size_t pos = argument.find(":"); std::string ip = argument.substr(0, pos); unsigned short port_val; - if(pos == argument.npos) - { + if (pos == argument.npos) { port_val = OPENRGB_SDK_PORT; - } - else - { + } else { std::string port = argument.substr(argument.find(":") + 1); port_val = std::stoi(port); } @@ -1375,10 +1297,8 @@ unsigned int cli_pre_detection(int argc, char* argv[]) client->StartClient(); - for(int timeout = 0; timeout < 100; timeout++) - { - if(client->GetConnected()) - { + for (int timeout = 0; timeout < 100; timeout++) { + if (client->GetConnected()) { break; } std::this_thread::sleep_for(10ms); @@ -1393,42 +1313,34 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --server (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--server") - { + else if (option == "--server") { server_start = true; } /*---------------------------------------------------------*\ | --server-port | \*---------------------------------------------------------*/ - else if(option == "--server-port") - { - if (argument != "") - { - try - { + else if (option == "--server-port") { + if (argument != "") { + try { int port = std::stoi(argument); - if (port >= 1024 && port <= 65535) - { - server_port = port; + if (port >= 1024 && port <= 65535) { + server_port = port; server_start = true; - } - else - { - std::cout << "Error: Port out of range: " << port << " (1024-65535)" << std::endl; + } else { + std::cout << "Error: Port out of range: " << port << " (1024-65535)" + << std::endl; print_help = true; break; } - } - catch(std::invalid_argument& /*e*/) - { - std::cout << "Error: Invalid data in --server-port argument (expected a number in range 1024-65535)" << std::endl; + } catch (std::invalid_argument & /*e*/) { + std::cout << "Error: Invalid data in --server-port argument (expected a number " + "in range 1024-65535)" + << std::endl; print_help = true; break; } - } - else - { + } else { std::cout << "Error: Missing argument for --server-port" << std::endl; print_help = true; break; @@ -1439,17 +1351,13 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --server-host | \*---------------------------------------------------------*/ - else if(option == "--server-host") - { - if (argument != "") - { + else if (option == "--server-host") { + if (argument != "") { std::string host = argument; - server_host = host; + server_host = host; server_start = true; - } - else - { + } else { std::cout << "Error: Missing argument for --server-host" << std::endl; print_help = true; break; @@ -1461,85 +1369,56 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --loglevel | \*---------------------------------------------------------*/ - else if(option == "--loglevel") - { - if (argument != "") - { - try - { + else if (option == "--loglevel") { + if (argument != "") { + try { int level = std::stoi(argument); - if (level >= 0 && level <= LL_TRACE) - { + if (level >= 0 && level <= LL_TRACE) { LogManager::get()->setLoglevel(level); - } - else - { + } else { LOG_ERROR("[CLI] Loglevel out of range: %d (0-6)", level); print_help = true; break; } - } - catch(std::invalid_argument& /*e*/) - { - if(!strcasecmp(argument.c_str(), "fatal")) - { + } catch (std::invalid_argument & /*e*/) { + if (!strcasecmp(argument.c_str(), "fatal")) { LogManager::get()->setLoglevel(LL_FATAL); - } - else if(!strcasecmp(argument.c_str(), "error")) - { + } else if (!strcasecmp(argument.c_str(), "error")) { LogManager::get()->setLoglevel(LL_ERROR); - } - else if(!strcasecmp(argument.c_str(), "warning")) - { + } else if (!strcasecmp(argument.c_str(), "warning")) { LogManager::get()->setLoglevel(LL_WARNING); - } - else if(!strcasecmp(argument.c_str(), "info")) - { + } else if (!strcasecmp(argument.c_str(), "info")) { LogManager::get()->setLoglevel(LL_INFO); - } - else if(!strcasecmp(argument.c_str(), "verbose")) - { + } else if (!strcasecmp(argument.c_str(), "verbose")) { LogManager::get()->setLoglevel(LL_VERBOSE); - } - else if(!strcasecmp(argument.c_str(), "debug")) - { + } else if (!strcasecmp(argument.c_str(), "debug")) { LogManager::get()->setLoglevel(LL_DEBUG); - } - else if(!strcasecmp(argument.c_str(), "trace")) - { + } else if (!strcasecmp(argument.c_str(), "trace")) { LogManager::get()->setLoglevel(LL_TRACE); - } - else - { + } else { LOG_ERROR("[CLI] Invalid loglevel"); print_help = true; break; } } - } - else - { + } else { LOG_ERROR("[CLI] Missing argument for --loglevel"); print_help = true; break; } - cfg_args+= 2; + cfg_args += 2; arg_index++; } /*---------------------------------------------------------*\ | --autostart-check (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--autostart-check") - { + else if (option == "--autostart-check") { AutoStart auto_start("OpenRGB"); - if(auto_start.IsAutoStartEnabled()) - { + if (auto_start.IsAutoStartEnabled()) { std::cout << "Autostart is enabled." << std::endl; - } - else - { + } else { std::cout << "Autostart is disabled." << std::endl; } } @@ -1547,16 +1426,12 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --autostart-disable (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--autostart-disable") - { + else if (option == "--autostart-disable") { AutoStart auto_start("OpenRGB"); - if(auto_start.DisableAutoStart()) - { + if (auto_start.DisableAutoStart()) { std::cout << "Autostart disabled." << std::endl; - } - else - { + } else { std::cout << "Autostart failed to disable." << std::endl; } } @@ -1564,34 +1439,27 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --autostart-enable | \*---------------------------------------------------------*/ - else if(option == "--autostart-enable") - { - if (argument != "") - { + else if (option == "--autostart-enable") { + if (argument != "") { std::string desc = "OpenRGB "; desc += VERSION_STRING; desc += ", for controlling RGB lighting."; - AutoStart auto_start("OpenRGB"); - AutoStartInfo auto_start_interface; + AutoStart auto_start("OpenRGB"); + AutoStartInfo auto_start_interface; - auto_start_interface.args = argument; - auto_start_interface.category = "Utility;"; - auto_start_interface.desc = desc; - auto_start_interface.icon = "OpenRGB"; - auto_start_interface.path = auto_start.GetExePath(); + auto_start_interface.args = argument; + auto_start_interface.category = "Utility;"; + auto_start_interface.desc = desc; + auto_start_interface.icon = "OpenRGB"; + auto_start_interface.path = auto_start.GetExePath(); - if(auto_start.EnableAutoStart(auto_start_interface)) - { + if (auto_start.EnableAutoStart(auto_start_interface)) { std::cout << "Autostart enabled." << std::endl; - } - else - { + } else { std::cout << "Autostart failed to enable." << std::endl; } - } - else - { + } else { std::cout << "Error: Missing argument for --autostart-enable" << std::endl; print_help = true; break; @@ -1604,32 +1472,28 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --gui (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--gui") - { + else if (option == "--gui") { ret_flags |= RET_FLAG_START_GUI; } /*---------------------------------------------------------*\ | --i2c-tools / --yolo (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--i2c-tools" || option == "--yolo") - { + else if (option == "--i2c-tools" || option == "--yolo") { ret_flags |= RET_FLAG_START_GUI | RET_FLAG_I2C_TOOLS; } /*---------------------------------------------------------*\ | --startminimized (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--startminimized") - { + else if (option == "--startminimized") { ret_flags |= RET_FLAG_START_GUI | RET_FLAG_START_MINIMIZED; } /*---------------------------------------------------------*\ | -h / --help (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--help" || option == "-h") - { + else if (option == "--help" || option == "-h") { print_help = true; break; } @@ -1637,8 +1501,7 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | -V / --version (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--version" || option == "-V") - { + else if (option == "--version" || option == "-V") { OptionVersion(); exit(0); } @@ -1646,8 +1509,7 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | -v / --verbose (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--verbose" || option == "-v") - { + else if (option == "--verbose" || option == "-v") { LogManager::get()->setVerbosity(LL_VERBOSE); cfg_args++; } @@ -1655,8 +1517,7 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | -vv / --very-verbose (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--very-verbose" || option == "-vv") - { + else if (option == "--very-verbose" || option == "-vv") { LogManager::get()->setVerbosity(LL_TRACE); cfg_args++; } @@ -1664,8 +1525,7 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | --print-source (no arguments) | \*---------------------------------------------------------*/ - else if(option == "--print-source") - { + else if (option == "--print-source") { LogManager::get()->setPrintSource(true); cfg_args++; } @@ -1673,34 +1533,30 @@ unsigned int cli_pre_detection(int argc, char* argv[]) /*---------------------------------------------------------*\ | Any unrecognized arguments trigger the post-detection CLI | \*---------------------------------------------------------*/ - else - { + else { ret_flags |= RET_FLAG_CLI_POST_DETECTION; } arg_index++; } - if(print_help) - { + if (print_help) { OptionHelp(); exit(0); } - if(server_start) - { - NetworkServer * server = ResourceManager::get()->GetServer(); + if (server_start) { + NetworkServer *server = ResourceManager::get()->GetServer(); server->SetHost(server_host); server->SetPort(server_port); ret_flags |= RET_FLAG_START_SERVER; } - if((argc - cfg_args) <= 1) - { + if ((argc - cfg_args) <= 1) { ret_flags |= RET_FLAG_START_GUI; } - return(ret_flags); + return (ret_flags); } unsigned int cli_post_detection() @@ -1725,19 +1581,18 @@ unsigned int cli_post_detection() | If the return flags are set, exit CLI mode without | | processing device updates from CLI input. | \*---------------------------------------------------------*/ - switch(ret_flags) - { - case 0: - break; + switch (ret_flags) { + case 0: + break; - case RET_FLAG_PRINT_HELP: - OptionHelp(); - exit(-1); - break; + case RET_FLAG_PRINT_HELP: + OptionHelp(); + exit(-1); + break; - default: - return ret_flags; - break; + default: + return ret_flags; + break; } /*---------------------------------------------------------*\ @@ -1745,17 +1600,12 @@ unsigned int cli_post_detection() | through all of the specific devices and apply settings. | | Otherwise, apply settings to all devices. | \*---------------------------------------------------------*/ - if (options.hasDevice) - { - for(unsigned int device_idx = 0; device_idx < options.devices.size(); device_idx++) - { + if (options.hasDevice) { + for (unsigned int device_idx = 0; device_idx < options.devices.size(); device_idx++) { ApplyOptions(options.devices[device_idx], rgb_controllers); } - } - else if (!options.profile_loaded) - { - for (unsigned int device_idx = 0; device_idx < rgb_controllers.size(); device_idx++) - { + } else if (!options.profile_loaded) { + for (unsigned int device_idx = 0; device_idx < rgb_controllers.size(); device_idx++) { options.allDeviceOptions.device = device_idx; ApplyOptions(options.allDeviceOptions, rgb_controllers); } @@ -1764,14 +1614,10 @@ unsigned int cli_post_detection() /*---------------------------------------------------------*\ | If there is a save filename set, save the profile | \*---------------------------------------------------------*/ - if (profile_save_filename != "") - { - if(ResourceManager::get()->GetProfileManager()->SaveProfile(profile_save_filename)) - { + if (profile_save_filename != "") { + if (ResourceManager::get()->GetProfileManager()->SaveProfile(profile_save_filename)) { LOG_INFO("[CLI] Profile saved successfully"); - } - else - { + } else { LOG_ERROR("[CLI] Profile saving failed"); } } diff --git a/cli.h b/cli.h index 45e15b37c..f5e3902a2 100644 --- a/cli.h +++ b/cli.h @@ -1,19 +1,18 @@ #ifndef CLI_H #define CLI_H -unsigned int cli_pre_detection(int argc, char* argv[]); +unsigned int cli_pre_detection(int argc, char *argv[]); unsigned int cli_post_detection(); -enum -{ - RET_FLAG_PRINT_HELP = 1, - RET_FLAG_START_GUI = 2, - RET_FLAG_I2C_TOOLS = 4, - RET_FLAG_START_MINIMIZED = 8, - RET_FLAG_NO_DETECT = 16, +enum { + RET_FLAG_PRINT_HELP = 1, + RET_FLAG_START_GUI = 2, + RET_FLAG_I2C_TOOLS = 4, + RET_FLAG_START_MINIMIZED = 8, + RET_FLAG_NO_DETECT = 16, RET_FLAG_CLI_POST_DETECTION = 32, - RET_FLAG_START_SERVER = 64, - RET_FLAG_NO_AUTO_CONNECT = 128, + RET_FLAG_START_SERVER = 64, + RET_FLAG_NO_AUTO_CONNECT = 128, }; #endif diff --git a/filesystem.h b/filesystem.h index b56f28c8f..2a498f265 100644 --- a/filesystem.h +++ b/filesystem.h @@ -16,7 +16,7 @@ // Debian 10 provides the header, but does not enable the feature, so we additionally check for the feature test macro // MSVC below 2017 does not provide feature test macros, so we leave an exception for them -#if defined(__cpp_lib_filesystem) || defined (_MSC_VER) +#if defined(__cpp_lib_filesystem) || defined(_MSC_VER) namespace filesystem = std::filesystem; #define STD_FILESYSTEM_FOUND #endif diff --git a/main.cpp b/main.cpp index 32008e6b2..47889fad9 100644 --- a/main.cpp +++ b/main.cpp @@ -47,28 +47,33 @@ using namespace std::chrono_literals; void InitializeTimerResolution() { HMODULE ntdll = LoadLibrary("ntdll.dll"); - if(ntdll != NULL) - { - typedef LONG (*NTSETTIMERRESOLUTION)(ULONG DesiredResolution, BOOLEAN SetResolution, PULONG CurrentResolution); + if (ntdll != NULL) { + typedef LONG (*NTSETTIMERRESOLUTION)(ULONG DesiredResolution, + BOOLEAN SetResolution, + PULONG CurrentResolution); ULONG CurrentResolution; - NTSETTIMERRESOLUTION NtSetTimerResolution = (NTSETTIMERRESOLUTION)GetProcAddress(ntdll, "NtSetTimerResolution"); - if(NtSetTimerResolution != NULL) - { + NTSETTIMERRESOLUTION NtSetTimerResolution = (NTSETTIMERRESOLUTION) + GetProcAddress(ntdll, "NtSetTimerResolution"); + if (NtSetTimerResolution != NULL) { NtSetTimerResolution(1000, TRUE, &CurrentResolution); } } // PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION = 4, isn't defined in Win10 headers - PROCESS_POWER_THROTTLING_STATE PowerThrottlingState { PROCESS_POWER_THROTTLING_CURRENT_VERSION, 4, 0 }; + PROCESS_POWER_THROTTLING_STATE PowerThrottlingState{PROCESS_POWER_THROTTLING_CURRENT_VERSION, + 4, + 0}; // take care of the slowdown on Windows 11 - SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &PowerThrottlingState, sizeof(PowerThrottlingState)); + SetProcessInformation(GetCurrentProcess(), + ProcessPowerThrottling, + &PowerThrottlingState, + sizeof(PowerThrottlingState)); } #endif -void WaitWhileServerOnline(NetworkServer* srv) +void WaitWhileServerOnline(NetworkServer *srv) { - while (srv->GetOnline()) - { + while (srv->GetOnline()) { std::this_thread::sleep_for(1s); }; } @@ -81,65 +86,67 @@ void WaitWhileServerOnline(NetworkServer* srv) #ifdef _WIN32 void InstallWinRing0() { - TCHAR winring0_install_location[MAX_PATH]; // driver final location usually C:\windows\system32\drivers\WinRing0x64.sys + TCHAR winring0_install_location + [MAX_PATH]; // driver final location usually C:\windows\system32\drivers\WinRing0x64.sys uint system_path_length = GetSystemDirectory(winring0_install_location, MAX_PATH); std::string winring0_filename = "WinRing0.sys"; BOOL bIsWow64 = false; #if _WIN64 winring0_filename = "WinRing0x64.sys"; #else - BOOL (*fnIsWow64Process)(HANDLE, PBOOL) = (BOOL (__cdecl *)(HANDLE, PBOOL))GetProcAddress(GetModuleHandle(TEXT("kernel32")),"IsWow64Process"); - if (fnIsWow64Process) - { - fnIsWow64Process(GetCurrentProcess(),&bIsWow64); + BOOL (*fnIsWow64Process)(HANDLE, PBOOL) = (BOOL(__cdecl *)(HANDLE, PBOOL)) + GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); + if (fnIsWow64Process) { + fnIsWow64Process(GetCurrentProcess(), &bIsWow64); } - if(bIsWow64) - { + if (bIsWow64) { winring0_filename = "WinRing0x64.sys"; } #endif std::strncat(winring0_install_location, "\\drivers\\", MAX_PATH - system_path_length - 1); - std::strncat(winring0_install_location, winring0_filename.c_str(), MAX_PATH - system_path_length - 10); + std::strncat(winring0_install_location, + winring0_filename.c_str(), + MAX_PATH - system_path_length - 10); - std::string driver_name = winring0_filename.substr(0, winring0_filename.size() - 4); // driver name: WinRing0 or WinRing0x64 + std::string driver_name = winring0_filename + .substr(0, + winring0_filename.size() + - 4); // driver name: WinRing0 or WinRing0x64 SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (manager) - { + if (manager) { PVOID wow64_fsredirection_OldValue = NULL; - if(bIsWow64) - { + if (bIsWow64) { Wow64DisableWow64FsRedirection(&wow64_fsredirection_OldValue); } - if(INVALID_FILE_ATTRIBUTES == GetFileAttributes(winring0_install_location) && GetLastError()==ERROR_FILE_NOT_FOUND) - { + if (INVALID_FILE_ATTRIBUTES == GetFileAttributes(winring0_install_location) + && GetLastError() == ERROR_FILE_NOT_FOUND) { char module_path_buffer[MAX_PATH]; GetModuleFileNameA(NULL, module_path_buffer, MAX_PATH); std::string::size_type exe_loc = std::string(module_path_buffer).find_last_of("\\/"); - std::string driver_source_path = std::string(module_path_buffer).substr(0, exe_loc + 1) + winring0_filename; + std::string driver_source_path = std::string(module_path_buffer).substr(0, exe_loc + 1) + + winring0_filename; CopyFile(driver_source_path.c_str(), winring0_install_location, true); } - if(bIsWow64) - { + if (bIsWow64) { Wow64RevertWow64FsRedirection(wow64_fsredirection_OldValue); } SC_HANDLE service = OpenService(manager, driver_name.c_str(), SERVICE_ALL_ACCESS); - if(!service) - { + if (!service) { std::string service_sys_path = "System32\\Drivers\\" + winring0_filename; service = CreateService(manager, - driver_name.c_str(), - driver_name.c_str(), - SERVICE_ALL_ACCESS, - SERVICE_KERNEL_DRIVER, - SERVICE_AUTO_START, - SERVICE_ERROR_NORMAL, - service_sys_path.c_str(), - NULL, - NULL, - NULL, - NULL, - NULL); + driver_name.c_str(), + driver_name.c_str(), + SERVICE_ALL_ACCESS, + SERVICE_KERNEL_DRIVER, + SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, + service_sys_path.c_str(), + NULL, + NULL, + NULL, + NULL, + NULL); } CloseServiceHandle(service); CloseServiceHandle(manager); @@ -155,20 +162,19 @@ void InstallWinRing0() * * \******************************************************************************************/ -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { int exitval = EXIT_SUCCESS; #ifdef _WIN32 /*---------------------------------------------------------*\ | Windows only - Attach console output | \*---------------------------------------------------------*/ - if (AttachConsole(ATTACH_PARENT_PROCESS)) - { + if (AttachConsole(ATTACH_PARENT_PROCESS)) { /*---------------------------------------------------------*\ | We are running under some terminal context; otherwise | | leave the GUI and CRT alone | \*---------------------------------------------------------*/ - freopen("CONIN$", "r", stdin); + freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); } @@ -196,35 +202,34 @@ int main(int argc, char* argv[]) \*---------------------------------------------------------*/ unsigned int ret_flags = cli_pre_detection(argc, argv); - ResourceManager::get()->Initialize( - !(ret_flags & RET_FLAG_NO_AUTO_CONNECT), - !(ret_flags & RET_FLAG_NO_DETECT), - ret_flags & RET_FLAG_START_SERVER, - ret_flags & RET_FLAG_CLI_POST_DETECTION); + ResourceManager::get()->Initialize(!(ret_flags & RET_FLAG_NO_AUTO_CONNECT), + !(ret_flags & RET_FLAG_NO_DETECT), + ret_flags & RET_FLAG_START_SERVER, + ret_flags & RET_FLAG_CLI_POST_DETECTION); /*---------------------------------------------------------*\ | If the command line parser indicates that the GUI should | | run, or if there were no command line arguments, start the| | GUI. | \*---------------------------------------------------------*/ - if(ret_flags & RET_FLAG_START_GUI) - { + if (ret_flags & RET_FLAG_START_GUI) { LOG_TRACE("[main] initializing GUI"); - /*-----------------------------------------------------*\ +/*-----------------------------------------------------*\ | Enable high DPI scaling support | \*-----------------------------------------------------*/ - #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true); - QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true); - #endif +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true); + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true); +#endif - /*-----------------------------------------------------*\ +/*-----------------------------------------------------*\ | Enable high DPI fractional scaling support on Windows | \*-----------------------------------------------------*/ - #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && defined(Q_OS_WIN) - QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); - #endif +#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && defined(Q_OS_WIN) + QGuiApplication::setHighDpiScaleFactorRoundingPolicy( + Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); +#endif QApplication a(argc, argv); QGuiApplication::setDesktopFileName("org.openrgb.OpenRGB"); @@ -236,15 +241,13 @@ int main(int argc, char* argv[]) Ui::OpenRGBDialog dlg; LOG_TRACE("[main] Dialog created"); - if(ret_flags & RET_FLAG_I2C_TOOLS) - { + if (ret_flags & RET_FLAG_I2C_TOOLS) { dlg.AddI2CToolsPage(); } dlg.AddClientTab(); - if(ret_flags & RET_FLAG_START_MINIMIZED) - { + if (ret_flags & RET_FLAG_START_MINIMIZED) { #ifdef _WIN32 /*---------------------------------------------------------*\ | Show the window always, even if it will immediately be | @@ -258,17 +261,13 @@ int main(int argc, char* argv[]) MacUtils::ToggleApplicationDocklessState(false); #endif dlg.hide(); - } - else - { + } else { dlg.show(); } LOG_TRACE("[main] Ready to exec() the dialog"); exitval = a.exec(); - } - else - { + } else { /*---------------------------------------------------------*\ | If no GUI is needed, we let the background threads run | | as long as they need, but we need to AT LEAST wait for | @@ -276,16 +275,12 @@ int main(int argc, char* argv[]) \*---------------------------------------------------------*/ ResourceManager::get()->WaitForInitialization(); - if(ret_flags & RET_FLAG_START_SERVER) - { - NetworkServer* server = ResourceManager::get()->GetServer(); + if (ret_flags & RET_FLAG_START_SERVER) { + NetworkServer *server = ResourceManager::get()->GetServer(); - if(!server->GetOnline()) - { + if (!server->GetOnline()) { exitval = EXIT_FAILURE; - } - else - { + } else { WaitWhileServerOnline(server); } }