style refactor

This commit is contained in:
Ivan I. Ovchinnikov
2026-07-27 21:29:50 +03:00
parent 47b1e70663
commit 5a702fe0f8
9 changed files with 119 additions and 119 deletions
+18 -18
View File
@@ -5,38 +5,38 @@
#include <string> #include <string>
#include <libserialport.h> #include <libserialport.h>
struct SerialPortInfo {
std::string port_name;
std::string description;
};
class ConnectionWindow { class ConnectionWindow {
public: public:
ConnectionWindow(); ConnectionWindow();
~ConnectionWindow(); ~ConnectionWindow();
void Initialize(); void initialize();
void Render(bool* p_open); void render(bool* p_open);
bool IsConnected() const { return is_connected; } bool isConnected() const { return connected; }
struct sp_port* GetActivePort() const { return active_port; } struct sp_port* getActivePort() const { return activePort; }
void ForceLogMessage(const std::string& msg); void forceLogMessage(const std::string& msg);
std::string& GetSharedLog() { return tx_log; } std::string& getSharedLog() { return txLog; }
private: private:
void RefreshPorts(); void refreshPorts();
struct SerialPortInfo {
std::string portName;
std::string description;
};
std::vector<SerialPortInfo> ports; std::vector<SerialPortInfo> ports;
int selected_port_idx; int selectedPortIdx;
// Новые переменные для выпадающего списка Baud Rate // Новые переменные для выпадающего списка Baud Rate
std::vector<int> baud_rates; std::vector<int> baudRates;
int selected_baud_idx; int selectedBaudIdx;
bool is_connected; bool connected;
struct sp_port* active_port; struct sp_port* activePort;
std::string tx_log; std::string txLog;
}; };
#endif // SERIAL_SAMPLE_CONNECTIONWINDOW_H #endif // SERIAL_SAMPLE_CONNECTIONWINDOW_H
+1 -1
View File
@@ -8,7 +8,7 @@ public:
LogWindow() = default; LogWindow() = default;
~LogWindow() = default; ~LogWindow() = default;
void Render(bool* p_open, ConnectionWindow& conn_win); void render(bool* paramOpen, ConnectionWindow& connectionWindow);
}; };
#endif // SERIAL_SAMPLE_LOGWINDOW_H #endif // SERIAL_SAMPLE_LOGWINDOW_H
+3 -3
View File
@@ -12,11 +12,11 @@ public:
PayloadWindow(); PayloadWindow();
~PayloadWindow() = default; ~PayloadWindow() = default;
void Render(bool* p_open, ConnectionWindow& conn_win); void render(bool* p_open, ConnectionWindow& connectionWindow);
private: private:
void SendHexPayload(const std::string& hex_str, ConnectionWindow& conn_win); void sendHexPayload(const std::string& hexString, ConnectionWindow& connectionWindow);
char hex_input_buffer[256]; char hexInputBuffer[256];
}; };
#endif // SERIAL_SAMPLE_PAYLOADWINDOW_H #endif // SERIAL_SAMPLE_PAYLOADWINDOW_H
+12 -12
View File
@@ -11,24 +11,24 @@ public:
SerialApp(); SerialApp();
~SerialApp() = default; ~SerialApp() = default;
void Initialize(); void initialize();
void RenderUI(); void renderUI();
bool ShouldClose() const { return should_close; } bool isClosing() const { return shouldClose; }
private: private:
void RenderMainMenuBar(); void renderMainMenuBar();
bool LoadTheme(const std::string& filepath); // Метод парсинга файла темы bool loadTheme(const std::string& filepath); // Метод парсинга файла темы
bool show_connection_window = true; bool showConnectionWindow = true;
bool show_payload_window = true; bool showPayloadWindow = true;
bool show_log_window = true; bool showLogWindow = true;
bool should_close; bool shouldClose;
ConnectionWindow connection_window; ConnectionWindow connectionWindow;
PayloadWindow payload_window; PayloadWindow payloadWindow;
LogWindow log_window; LogWindow logWindow;
}; };
#endif // SERIAL_SAMPLE_SERIALAPP_H #endif // SERIAL_SAMPLE_SERIALAPP_H
+3 -3
View File
@@ -39,7 +39,7 @@ int main(int, char**) {
// Создаем и инициализируем наше изолированное приложение // Создаем и инициализируем наше изолированное приложение
SerialApp app; SerialApp app;
app.Initialize(); app.initialize();
// Главный цикл приложения // Главный цикл приложения
while (!glfwWindowShouldClose(window)) { while (!glfwWindowShouldClose(window)) {
@@ -51,8 +51,8 @@ int main(int, char**) {
ImGui::NewFrame(); ImGui::NewFrame();
// Рендерим наше кастомное UI // Рендерим наше кастомное UI
app.RenderUI(); app.renderUI();
if (app.ShouldClose()) { if (app.isClosing()) {
glfwSetWindowShouldClose(window, GLFW_TRUE); glfwSetWindowShouldClose(window, GLFW_TRUE);
} }
+49 -49
View File
@@ -3,29 +3,29 @@
#include <cstdio> #include <cstdio>
ConnectionWindow::ConnectionWindow() ConnectionWindow::ConnectionWindow()
: selected_port_idx(0), is_connected(false), active_port(nullptr) { : selectedPortIdx(0), connected(false), activePort(nullptr) {
// Заполняем массив стандартными скоростями UART // Заполняем массив стандартными скоростями UART
baud_rates = { 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600 }; baudRates = { 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600 };
// По умолчанию выбираем 9600 (индекс 0 в векторе) // По умолчанию выбираем 9600 (индекс 0 в векторе)
selected_baud_idx = 0; selectedBaudIdx = 0;
} }
ConnectionWindow::~ConnectionWindow() { ConnectionWindow::~ConnectionWindow() {
if (is_connected && active_port) { if (connected && activePort) {
sp_close(active_port); sp_close(activePort);
sp_free_port(active_port); sp_free_port(activePort);
} }
} }
void ConnectionWindow::Initialize() { void ConnectionWindow::initialize() {
RefreshPorts(); refreshPorts();
} }
void ConnectionWindow::RefreshPorts() { void ConnectionWindow::refreshPorts() {
ports.clear(); ports.clear();
selected_port_idx = 0; selectedPortIdx = 0;
struct sp_port** port_list; struct sp_port** port_list;
if (sp_list_ports(&port_list) == SP_OK) { if (sp_list_ports(&port_list) == SP_OK) {
@@ -33,7 +33,7 @@ void ConnectionWindow::RefreshPorts() {
struct sp_port* port = port_list[i]; struct sp_port* port = port_list[i];
SerialPortInfo info; SerialPortInfo info;
const char* name = sp_get_port_name(port); const char* name = sp_get_port_name(port);
info.port_name = name ? name : "Unknown"; info.portName = name ? name : "Unknown";
const char* desc = sp_get_port_description(port); const char* desc = sp_get_port_description(port);
info.description = desc ? desc : "No Description"; info.description = desc ? desc : "No Description";
ports.push_back(info); ports.push_back(info);
@@ -46,48 +46,48 @@ void ConnectionWindow::RefreshPorts() {
} }
} }
void ConnectionWindow::ForceLogMessage(const std::string& msg) { void ConnectionWindow::forceLogMessage(const std::string& msg) {
tx_log += msg + "\n"; txLog += msg + "\n";
} }
void ConnectionWindow::Render(bool* p_open) { void ConnectionWindow::render(bool* p_open) {
if (!ImGui::Begin("Connection Settings", p_open)) { if (!ImGui::Begin("Connection Settings", p_open)) {
ImGui::End(); ImGui::End();
return; return;
} }
if (ImGui::Button("Refresh Ports") && !is_connected) { if (ImGui::Button("Refresh Ports") && !connected) {
RefreshPorts(); refreshPorts();
} }
ImGui::SameLine(); ImGui::SameLine();
// 1. Выбор COM-порта // 1. Выбор COM-порта
std::string combo_preview = ports[selected_port_idx].port_name; std::string combo_preview = ports[selectedPortIdx].portName;
if (ports[selected_port_idx].port_name != "None") { if (ports[selectedPortIdx].portName != "None") {
combo_preview += " (" + ports[selected_port_idx].description + ")"; combo_preview += " (" + ports[selectedPortIdx].description + ")";
} }
ImGui::BeginDisabled(is_connected); ImGui::BeginDisabled(connected);
if (ImGui::BeginCombo("Serial Port", combo_preview.c_str())) { if (ImGui::BeginCombo("Serial Port", combo_preview.c_str())) {
for (int n = 0; n < ports.size(); n++) { for (int n = 0; n < ports.size(); n++) {
const bool is_selected = (selected_port_idx == n); const bool is_selected = (selectedPortIdx == n);
std::string item_text = ports[n].port_name + " - " + ports[n].description; std::string item_text = ports[n].portName + " - " + ports[n].description;
if (ImGui::Selectable(item_text.c_str(), is_selected)) { if (ImGui::Selectable(item_text.c_str(), is_selected)) {
selected_port_idx = n; selectedPortIdx = n;
} }
} }
ImGui::EndCombo(); ImGui::EndCombo();
} }
// 2. Выбор Baud Rate через выпадающий список // 2. Выбор Baud Rate через выпадающий список
std::string baud_preview = std::to_string(baud_rates[selected_baud_idx]); std::string baud_preview = std::to_string(baudRates[selectedBaudIdx]);
if (ImGui::BeginCombo("Baud Rate", baud_preview.c_str())) { if (ImGui::BeginCombo("Baud Rate", baud_preview.c_str())) {
for (int b = 0; b < baud_rates.size(); b++) { for (int b = 0; b < baudRates.size(); b++) {
const bool is_selected = (selected_baud_idx == b); const bool is_selected = (selectedBaudIdx == b);
std::string baud_item_text = std::to_string(baud_rates[b]); std::string baud_item_text = std::to_string(baudRates[b]);
if (ImGui::Selectable(baud_item_text.c_str(), is_selected)) { if (ImGui::Selectable(baud_item_text.c_str(), is_selected)) {
selected_baud_idx = b; selectedBaudIdx = b;
} }
} }
ImGui::EndCombo(); ImGui::EndCombo();
@@ -95,26 +95,26 @@ void ConnectionWindow::Render(bool* p_open) {
ImGui::EndDisabled(); ImGui::EndDisabled();
// 3. Логика подключения // 3. Логика подключения
if (!is_connected) { if (!connected) {
ImGui::BeginDisabled(ports[selected_port_idx].port_name == "None"); ImGui::BeginDisabled(ports[selectedPortIdx].portName == "None");
if (ImGui::Button("Connect", ImVec2(120, 0))) { if (ImGui::Button("Connect", ImVec2(120, 0))) {
if (sp_get_port_by_name(ports[selected_port_idx].port_name.c_str(), &active_port) == SP_OK) { if (sp_get_port_by_name(ports[selectedPortIdx].portName.c_str(), &activePort) == SP_OK) {
if (sp_open(active_port, SP_MODE_READ_WRITE) == SP_OK) { if (sp_open(activePort, SP_MODE_READ_WRITE) == SP_OK) {
// Передаем реальное значение скорости из выбранного индекса массива // Передаем реальное значение скорости из выбранного индекса массива
int real_baud = baud_rates[selected_baud_idx]; int real_baud = baudRates[selectedBaudIdx];
sp_set_baudrate(active_port, real_baud); sp_set_baudrate(activePort, real_baud);
sp_set_bits(active_port, 8); sp_set_bits(activePort, 8);
sp_set_parity(active_port, SP_PARITY_NONE); sp_set_parity(activePort, SP_PARITY_NONE);
sp_set_stopbits(active_port, 1); sp_set_stopbits(activePort, 1);
is_connected = true; connected = true;
ForceLogMessage("[SYSTEM] Connected to " + ports[selected_port_idx].port_name + " at " + std::to_string(real_baud) + " baud."); forceLogMessage("[SYSTEM] Connected to " + ports[selectedPortIdx].portName + " at " + std::to_string(real_baud) + " baud.");
} else { } else {
ForceLogMessage("[SYSTEM ERROR] Could not open port " + ports[selected_port_idx].port_name); forceLogMessage("[SYSTEM ERROR] Could not open port " + ports[selectedPortIdx].portName);
sp_free_port(active_port); sp_free_port(activePort);
active_port = nullptr; activePort = nullptr;
} }
} }
} }
@@ -122,19 +122,19 @@ void ConnectionWindow::Render(bool* p_open) {
} else { } else {
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.1f, 1.0f)); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.1f, 1.0f));
if (ImGui::Button("Disconnect", ImVec2(120, 0))) { if (ImGui::Button("Disconnect", ImVec2(120, 0))) {
if (active_port) { if (activePort) {
sp_close(active_port); sp_close(activePort);
sp_free_port(active_port); sp_free_port(activePort);
active_port = nullptr; activePort = nullptr;
} }
is_connected = false; connected = false;
ForceLogMessage("[SYSTEM] Disconnected."); forceLogMessage("[SYSTEM] Disconnected.");
} }
ImGui::PopStyleColor(); ImGui::PopStyleColor();
} }
ImGui::SameLine(); ImGui::SameLine();
ImGui::Text("Status: %s", is_connected ? "CONNECTED" : "DISCONNECTED"); ImGui::Text("Status: %s", connected ? "CONNECTED" : "DISCONNECTED");
ImGui::End(); ImGui::End();
} }
+3 -3
View File
@@ -2,13 +2,13 @@
#include "../include/ConnectionWindow.h" #include "../include/ConnectionWindow.h"
#include "imgui.h" #include "imgui.h"
void LogWindow::Render(bool* p_open, ConnectionWindow& conn_win) { void LogWindow::render(bool* paramOpen, ConnectionWindow& connectionWindow) {
if (!ImGui::Begin("Transaction Log", p_open)) { if (!ImGui::Begin("Transaction Log", paramOpen)) {
ImGui::End(); ImGui::End();
return; return;
} }
std::string& log_ref = conn_win.GetSharedLog(); std::string& log_ref = connectionWindow.getSharedLog();
ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), true, ImGuiWindowFlags_HorizontalScrollbar); ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), true, ImGuiWindowFlags_HorizontalScrollbar);
ImGui::TextUnformatted(log_ref.c_str()); ImGui::TextUnformatted(log_ref.c_str());
+12 -12
View File
@@ -8,15 +8,15 @@
#include <vector> #include <vector>
PayloadWindow::PayloadWindow() { PayloadWindow::PayloadWindow() {
std::snprintf(hex_input_buffer, sizeof(hex_input_buffer), "AA BB 01 02 03 FF"); std::snprintf(hexInputBuffer, sizeof(hexInputBuffer), "AA BB 01 02 03 FF");
} }
void PayloadWindow::SendHexPayload(const std::string& hex_str, ConnectionWindow& conn_win) { void PayloadWindow::sendHexPayload(const std::string& hexString, ConnectionWindow& connectionWindow) {
struct sp_port* port = conn_win.GetActivePort(); struct sp_port* port = connectionWindow.getActivePort();
if (!conn_win.IsConnected() || !port) return; if (!connectionWindow.isConnected() || !port) return;
std::vector<std::uint8_t> bytes; std::vector<std::uint8_t> bytes;
std::stringstream ss(hex_str); std::stringstream ss(hexString);
std::string byte_string; std::string byte_string;
while (ss >> byte_string) { while (ss >> byte_string) {
@@ -29,7 +29,7 @@ void PayloadWindow::SendHexPayload(const std::string& hex_str, ConnectionWindow&
} }
if (bytes.empty()) { if (bytes.empty()) {
conn_win.ForceLogMessage("[ERROR] No valid bytes found to send."); connectionWindow.forceLogMessage("[ERROR] No valid bytes found to send.");
return; return;
} }
@@ -41,25 +41,25 @@ void PayloadWindow::SendHexPayload(const std::string& hex_str, ConnectionWindow&
for (size_t i = 0; i < bytes.size(); ++i) { for (size_t i = 0; i < bytes.size(); ++i) {
log_ss << std::uppercase << std::hex << std::setw(2) << std::setfill('0') << (int)bytes[i] << " "; log_ss << std::uppercase << std::hex << std::setw(2) << std::setfill('0') << (int)bytes[i] << " ";
} }
conn_win.ForceLogMessage(log_ss.str()); connectionWindow.forceLogMessage(log_ss.str());
} else { } else {
conn_win.ForceLogMessage("[ERROR] Failed to write data to serial port."); connectionWindow.forceLogMessage("[ERROR] Failed to write data to serial port.");
} }
} }
void PayloadWindow::Render(bool* p_open, ConnectionWindow& conn_win) { void PayloadWindow::render(bool* p_open, ConnectionWindow& connectionWindow) {
if (!ImGui::Begin("Raw Payload Terminal", p_open)) { if (!ImGui::Begin("Raw Payload Terminal", p_open)) {
ImGui::End(); ImGui::End();
return; return;
} }
ImGui::InputText("HEX Bytes", hex_input_buffer, IM_ARRAYSIZE(hex_input_buffer)); ImGui::InputText("HEX Bytes", hexInputBuffer, IM_ARRAYSIZE(hexInputBuffer));
ImGui::TextDisabled("Example: AA BB 0F 45"); ImGui::TextDisabled("Example: AA BB 0F 45");
ImGui::Spacing(); ImGui::Spacing();
ImGui::BeginDisabled(!conn_win.IsConnected()); ImGui::BeginDisabled(!connectionWindow.isConnected());
if (ImGui::Button("SEND PACKET", ImVec2(-1, 35))) { if (ImGui::Button("SEND PACKET", ImVec2(-1, 35))) {
SendHexPayload(hex_input_buffer, conn_win); sendHexPayload(hexInputBuffer, connectionWindow);
} }
ImGui::EndDisabled(); ImGui::EndDisabled();
+18 -18
View File
@@ -5,13 +5,13 @@
#include <iostream> #include <iostream>
#include <unordered_map> #include <unordered_map>
SerialApp::SerialApp() : should_close(false) {} SerialApp::SerialApp() : shouldClose(false) {}
void SerialApp::Initialize() { void SerialApp::initialize() {
connection_window.Initialize(); connectionWindow.initialize();
// Загружаем тему при старте. Если лежит в корне сборки — просто имя файла. // Загружаем тему при старте. Если лежит в корне сборки — просто имя файла.
if (!LoadTheme("dracula.theme")) { if (!loadTheme("dracula.theme")) {
// Если файла нет, оставляем стандартную тему ImGui, чтобы приложение не упало // Если файла нет, оставляем стандартную тему ImGui, чтобы приложение не упало
ImGui::StyleColorsDark(); ImGui::StyleColorsDark();
} }
@@ -31,7 +31,7 @@ static ImVec4 HexToImVec4(const std::string& hex_str) {
return ImVec4(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); return ImVec4(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
} }
bool SerialApp::LoadTheme(const std::string& filepath) { bool SerialApp::loadTheme(const std::string& filepath) {
std::ifstream file(filepath); std::ifstream file(filepath);
if (!file.is_open()) { if (!file.is_open()) {
std::cerr << "[THEME ERROR] Файл темы не найден: " << filepath << std::endl; std::cerr << "[THEME ERROR] Файл темы не найден: " << filepath << std::endl;
@@ -100,33 +100,33 @@ bool SerialApp::LoadTheme(const std::string& filepath) {
return true; return true;
} }
void SerialApp::RenderUI() { void SerialApp::renderUI() {
RenderMainMenuBar(); renderMainMenuBar();
if (show_connection_window) { if (showConnectionWindow) {
connection_window.Render(&show_connection_window); connectionWindow.render(&showConnectionWindow);
} }
if (show_payload_window) { if (showPayloadWindow) {
payload_window.Render(&show_payload_window, connection_window); payloadWindow.render(&showPayloadWindow, connectionWindow);
} }
if (show_log_window) { if (showLogWindow) {
log_window.Render(&show_log_window, connection_window); logWindow.render(&showLogWindow, connectionWindow);
} }
} }
void SerialApp::RenderMainMenuBar() { void SerialApp::renderMainMenuBar() {
if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("File")) { if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("Exit", "Alt+F4")) { if (ImGui::MenuItem("Exit", "Alt+F4")) {
should_close = true; shouldClose = true;
} }
ImGui::EndMenu(); ImGui::EndMenu();
} }
if (ImGui::BeginMenu("Windows")) { if (ImGui::BeginMenu("Windows")) {
ImGui::MenuItem("1. Connection Settings", nullptr, &show_connection_window); ImGui::MenuItem("1. Connection Settings", nullptr, &showConnectionWindow);
ImGui::MenuItem("2. Raw Payload Terminal", nullptr, &show_payload_window); ImGui::MenuItem("2. Raw Payload Terminal", nullptr, &showPayloadWindow);
ImGui::MenuItem("3. Transaction Log", nullptr, &show_log_window); ImGui::MenuItem("3. Transaction Log", nullptr, &showLogWindow);
ImGui::EndMenu(); ImGui::EndMenu();
} }
ImGui::EndMainMenuBar(); ImGui::EndMainMenuBar();