diff --git a/CMakeLists.txt b/CMakeLists.txt index dc8c58a3..a0de2ef4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,6 +24,7 @@ set(SAK_QT_COMPONENTS find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS ${SAK_QT_COMPONENTS}) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS ${SAK_QT_COMPONENTS}) +set(BUILD_TESTING OFF) include(.cmake/sak_common.cmake) include(.cmake/sak_common_deploy.cmake) @@ -44,7 +45,6 @@ if(SAK_USING_GLOG) set(WITH_GTEST OFF) set(WITH_GFLAGS OFF) - set(BUILD_TESTING OFF) sak_add_subdiretory("glog-master") endif() diff --git a/src/assistants/CMakeLists.txt b/src/assistants/CMakeLists.txt index 8effd38c..836ac261 100644 --- a/src/assistants/CMakeLists.txt +++ b/src/assistants/CMakeLists.txt @@ -22,6 +22,10 @@ macro(sak_add_assistant dir_name app_name) ${ASSISTANT_SOURCES} ${CMAKE_SOURCE_DIR}/qtswissarmyknife.qrc) + if(WIN32) + list(APPEND APP_ASSISTANT_SOURCES ${CMAKE_SOURCE_DIR}/windows.rc) + endif() + sak_add_executable(${app_name} ${APP_ASSISTANT_SOURCES}) sak_auto_execute_deployqt(${app_name}) sak_set_target_properties(${app_name}) diff --git a/src/assistants/ascii/main.cc b/src/assistants/ascii/main.cc index ff8ae995..33c5c377 100644 --- a/src/assistants/ascii/main.cc +++ b/src/assistants/ascii/main.cc @@ -12,11 +12,15 @@ #include "sakasciiassistant.h" #include "sakcommonmainwindow.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("Ascii Assistant"), "SAK.AsciiAssistant"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app = CreateCommonMainWindowApplication(argc, + argv, + QObject::tr( + "Ascii Assistant"), + "SAK.AsciiAssistant"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/assistants/ascii/src/sakasciiassistant.cc b/src/assistants/ascii/src/sakasciiassistant.cc index 2ed0d879..d9682658 100644 --- a/src/assistants/ascii/src/sakasciiassistant.cc +++ b/src/assistants/ascii/src/sakasciiassistant.cc @@ -15,14 +15,17 @@ #include "ui_sakasciiassistant.h" SAKAsciiAssistant::SAKAsciiAssistant(QWidget* parent) - : QWidget(parent), ui_(new Ui::SAKAsciiAssistant) { - ui_->setupUi(this); + : QWidget(parent) + , ui_(new Ui::SAKAsciiAssistant) +{ + ui_->setupUi(this); - const QPixmap pixmap = QPixmap::fromImage(QImage(":/resources/ASCII.png")); - resize(pixmap.size()); - ui_->image_->setPixmap(pixmap); + const QPixmap pixmap = QPixmap::fromImage(QImage(":/resources/ASCII.png")); + resize(pixmap.size()); + ui_->image_->setPixmap(pixmap); } -SAKAsciiAssistant::~SAKAsciiAssistant() { - delete ui_; +SAKAsciiAssistant::~SAKAsciiAssistant() +{ + delete ui_; } diff --git a/src/assistants/ascii/src/sakasciiassistant.h b/src/assistants/ascii/src/sakasciiassistant.h index 89364bdc..7ffe19bb 100644 --- a/src/assistants/ascii/src/sakasciiassistant.h +++ b/src/assistants/ascii/src/sakasciiassistant.h @@ -17,14 +17,15 @@ namespace Ui { class SAKAsciiAssistant; } -class SAKAsciiAssistant : public QWidget { - Q_OBJECT - public: - Q_INVOKABLE SAKAsciiAssistant(QWidget* parent = Q_NULLPTR); - ~SAKAsciiAssistant(); +class SAKAsciiAssistant : public QWidget +{ + Q_OBJECT +public: + Q_INVOKABLE SAKAsciiAssistant(QWidget* parent = Q_NULLPTR); + ~SAKAsciiAssistant(); - private: - Ui::SAKAsciiAssistant* ui_; +private: + Ui::SAKAsciiAssistant* ui_; }; -#endif // SAKASCIIASSISTANT_H +#endif // SAKASCIIASSISTANT_H diff --git a/src/assistants/base64/main.cc b/src/assistants/base64/main.cc index 4302a5c8..94de705e 100644 --- a/src/assistants/base64/main.cc +++ b/src/assistants/base64/main.cc @@ -12,11 +12,15 @@ #include "sakbase64assistant.h" #include "sakcommonmainwindow.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("Base64 Assisatnt"), "SAK.Base64Assisatnt"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app + = CreateCommonMainWindowApplication(argc, + argv, + QObject::tr("Base64 Assisatnt"), + "SAK.Base64Assisatnt"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/assistants/base64/src/sakbase64assistant.cc b/src/assistants/base64/src/sakbase64assistant.cc index 885a7f22..9920ff4a 100644 --- a/src/assistants/base64/src/sakbase64assistant.cc +++ b/src/assistants/base64/src/sakbase64assistant.cc @@ -18,55 +18,57 @@ #include "ui_sakbase64assistant.h" SAKBase64Assisatnt::SAKBase64Assisatnt(QWidget* parent) - : QWidget(parent), ui_(new Ui::SAKBase64Assisatnt) { - ui_->setupUi(this); - connect(ui_->image_, &QPushButton::clicked, this, - &SAKBase64Assisatnt::OnImageClicked); - connect(ui_->decrypt_, &QPushButton::clicked, this, - &SAKBase64Assisatnt::OnDecryptClicked); - connect(ui_->encrypt_, &QPushButton::clicked, this, - &SAKBase64Assisatnt::OnEncryptClicked); + : QWidget(parent) + , ui_(new Ui::SAKBase64Assisatnt) +{ + ui_->setupUi(this); + connect(ui_->image_, &QPushButton::clicked, this, &SAKBase64Assisatnt::OnImageClicked); + connect(ui_->decrypt_, &QPushButton::clicked, this, &SAKBase64Assisatnt::OnDecryptClicked); + connect(ui_->encrypt_, &QPushButton::clicked, this, &SAKBase64Assisatnt::OnEncryptClicked); } -SAKBase64Assisatnt::~SAKBase64Assisatnt() { - delete ui_; +SAKBase64Assisatnt::~SAKBase64Assisatnt() +{ + delete ui_; } -void SAKBase64Assisatnt::OnImageClicked() { - QString cipher_text = ui_->cipher_text_->toPlainText(); - QByteArray base64 = cipher_text.toUtf8(); - QByteArray bytes = QByteArray::fromBase64(base64); +void SAKBase64Assisatnt::OnImageClicked() +{ + QString cipher_text = ui_->cipher_text_->toPlainText(); + QByteArray base64 = cipher_text.toUtf8(); + QByteArray bytes = QByteArray::fromBase64(base64); - QPixmap pix; - if (!pix.loadFromData(bytes)) { - QMessageBox::warning(this, tr("Data error"), - tr("Data can not convert image.")); - return; - } + QPixmap pix; + if (!pix.loadFromData(bytes)) { + QMessageBox::warning(this, tr("Data error"), tr("Data can not convert image.")); + return; + } - QLabel* label = new QLabel(this); - label->resize(pix.size()); - label->setPixmap(pix); + QLabel* label = new QLabel(this); + label->resize(pix.size()); + label->setPixmap(pix); - QDialog dialog(this); - dialog.setLayout(new QHBoxLayout()); - dialog.layout()->addWidget(label); - dialog.setModal(true); - dialog.exec(); + QDialog dialog(this); + dialog.setLayout(new QHBoxLayout()); + dialog.layout()->addWidget(label); + dialog.setModal(true); + dialog.exec(); } -void SAKBase64Assisatnt::OnEncryptClicked() { - QString plain_text = ui_->plain_text_->toPlainText(); - QByteArray byte_array = plain_text.toUtf8(); - QByteArray base64 = byte_array.toBase64(); - QString ciper_text = QString::fromLatin1(base64); - ui_->cipher_text_->setPlainText(ciper_text); +void SAKBase64Assisatnt::OnEncryptClicked() +{ + QString plain_text = ui_->plain_text_->toPlainText(); + QByteArray byte_array = plain_text.toUtf8(); + QByteArray base64 = byte_array.toBase64(); + QString ciper_text = QString::fromLatin1(base64); + ui_->cipher_text_->setPlainText(ciper_text); } -void SAKBase64Assisatnt::OnDecryptClicked() { - QString cipher_text = ui_->cipher_text_->toPlainText(); - QByteArray base64 = cipher_text.toUtf8(); - QByteArray byte_array = QByteArray::fromBase64(base64); - QString plain_text = QString::fromUtf8(byte_array); - ui_->plain_text_->setPlainText(plain_text); +void SAKBase64Assisatnt::OnDecryptClicked() +{ + QString cipher_text = ui_->cipher_text_->toPlainText(); + QByteArray base64 = cipher_text.toUtf8(); + QByteArray byte_array = QByteArray::fromBase64(base64); + QString plain_text = QString::fromUtf8(byte_array); + ui_->plain_text_->setPlainText(plain_text); } diff --git a/src/assistants/base64/src/sakbase64assistant.h b/src/assistants/base64/src/sakbase64assistant.h index b2bac765..0e4f99ef 100644 --- a/src/assistants/base64/src/sakbase64assistant.h +++ b/src/assistants/base64/src/sakbase64assistant.h @@ -16,19 +16,20 @@ namespace Ui { class SAKBase64Assisatnt; } -class SAKBase64Assisatnt : public QWidget { - Q_OBJECT - public: - Q_INVOKABLE SAKBase64Assisatnt(QWidget* parent = Q_NULLPTR); - ~SAKBase64Assisatnt(); +class SAKBase64Assisatnt : public QWidget +{ + Q_OBJECT +public: + Q_INVOKABLE SAKBase64Assisatnt(QWidget* parent = Q_NULLPTR); + ~SAKBase64Assisatnt(); - private: - Ui::SAKBase64Assisatnt* ui_; +private: + Ui::SAKBase64Assisatnt* ui_; - private: - void OnImageClicked(); - void OnEncryptClicked(); - void OnDecryptClicked(); +private: + void OnImageClicked(); + void OnEncryptClicked(); + void OnDecryptClicked(); }; -#endif // SAKBASE64ASSISTANT_H +#endif // SAKBASE64ASSISTANT_H diff --git a/src/assistants/broadcast/main.cc b/src/assistants/broadcast/main.cc index fa9ffcf4..33a75aea 100644 --- a/src/assistants/broadcast/main.cc +++ b/src/assistants/broadcast/main.cc @@ -12,11 +12,12 @@ #include "sakbroadcastassistant.h" #include "sakcommonmainwindow.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("Broadcast Assistant"), "SAK.BroadcastAssistant"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app = CreateCommonMainWindowApplication( + argc, argv, QObject::tr("Broadcast Assistant"), "SAK.BroadcastAssistant"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/assistants/broadcast/src/sakbroadcastassistant.cc b/src/assistants/broadcast/src/sakbroadcastassistant.cc index d370666a..9f4a84fb 100644 --- a/src/assistants/broadcast/src/sakbroadcastassistant.cc +++ b/src/assistants/broadcast/src/sakbroadcastassistant.cc @@ -13,157 +13,166 @@ #include #include -#include "sakcommondatastructure.h" #include "sakbroadcastthread.h" +#include "sakcommondatastructure.h" #include "ui_sakbroadcastassistant.h" SAKBroadcastAssistant::SAKBroadcastAssistant(QWidget* parent) - : QWidget(parent), ui_(new Ui::SAKBroadcastAssistant) { - ui_->setupUi(this); - broadcast_thread_ = new SAKBroadcastThread(this); - connect(broadcast_thread_, &SAKBroadcastThread::started, this, - [=]() { UpdateUiState(true); }); - connect(broadcast_thread_, &SAKBroadcastThread::finished, this, - [=]() { UpdateUiState(false); }); - connect(broadcast_thread_, &SAKBroadcastThread::BytesWritten, this, - [=](const QByteArray& bytes) { - QByteArray temp = bytes; - int format = ui_->comboBoxOutputFormat->currentData().toInt(); - auto cookedFormat = - SAKCommonDataStructure::SAKEnumTextFormatOutput(format); - auto bytesString = - SAKCommonDataStructure::byteArrayToString(temp, cookedFormat); - auto info = QDateTime::currentDateTime().toString("hh:mm:ss"); - info += " Tx: "; - info = QString("%1").arg(info); - info += bytesString; - ui_->textBrowserInformation->append(info); - }); - connect(ui_->comboBoxBroadcastFormat, &QComboBox::currentTextChanged, this, - [=](const QString& text) { - Q_UNUSED(text); - SAKCommonDataStructure::setLineEditTextFormat( - ui_->lineEditBroadcastData, - ui_->comboBoxBroadcastFormat->currentData().toInt()); - }); - connect(ui_->pushButtonBroadcast, &QPushButton::clicked, this, - &SAKBroadcastAssistant::OnBroadcastPushButtonClicked); + : QWidget(parent) + , ui_(new Ui::SAKBroadcastAssistant) +{ + ui_->setupUi(this); + broadcast_thread_ = new SAKBroadcastThread(this); + connect(broadcast_thread_, &SAKBroadcastThread::started, this, [=]() { UpdateUiState(true); }); + connect(broadcast_thread_, &SAKBroadcastThread::finished, this, [=]() { UpdateUiState(false); }); + connect(broadcast_thread_, &SAKBroadcastThread::BytesWritten, this, [=](const QByteArray& bytes) { + QByteArray temp = bytes; + int format = ui_->comboBoxOutputFormat->currentData().toInt(); + auto cookedFormat = SAKCommonDataStructure::SAKEnumTextFormatOutput(format); + auto bytesString = SAKCommonDataStructure::byteArrayToString(temp, cookedFormat); + auto info = QDateTime::currentDateTime().toString("hh:mm:ss"); + info += " Tx: "; + info = QString("%1").arg(info); + info += bytesString; + ui_->textBrowserInformation->append(info); + }); + connect(ui_->comboBoxBroadcastFormat, + &QComboBox::currentTextChanged, + this, + [=](const QString& text) { + Q_UNUSED(text); + SAKCommonDataStructure::setLineEditTextFormat(ui_->lineEditBroadcastData, + ui_->comboBoxBroadcastFormat + ->currentData() + .toInt()); + }); + connect(ui_->pushButtonBroadcast, + &QPushButton::clicked, + this, + &SAKBroadcastAssistant::OnBroadcastPushButtonClicked); - InitUi(); - setWindowTitle(tr("Broadcast Assistant")); + InitUi(); + setWindowTitle(tr("Broadcast Assistant")); } -SAKBroadcastAssistant::~SAKBroadcastAssistant() { delete ui_; } - -void SAKBroadcastAssistant::UpdateUiState(bool started) { - ui_->pushButtonBroadcast->setEnabled(true); - ui_->pushButtonBroadcast->setText(started ? tr("Terminate") - : tr("Broadcast")); - - ui_->comboBoxBroadcastAddress->setEnabled(!started); - ui_->lineEditBroadcastPort->setEnabled(!started); - ui_->comboBoxBroadcastInterval->setEnabled(!started); - ui_->comboBoxBroadcastPrefix->setEnabled(!started); - ui_->comboBoxBroadcastSuffix->setEnabled(!started); - ui_->comboBoxBroadcastFormat->setEnabled(!started); - ui_->lineEditBroadcastData->setEnabled(!started); +SAKBroadcastAssistant::~SAKBroadcastAssistant() +{ + delete ui_; } -void SAKBroadcastAssistant::InitUi() { - ui_->textBrowserInformation->document()->setMaximumBlockCount(2000); +void SAKBroadcastAssistant::UpdateUiState(bool started) +{ + ui_->pushButtonBroadcast->setEnabled(true); + ui_->pushButtonBroadcast->setText(started ? tr("Terminate") : tr("Broadcast")); - InitUiBroadcastAddress(); - InitUiBroadcastInterval(); - - SAKCommonDataStructure::setComboBoxTextInputFormat( - ui_->comboBoxBroadcastFormat); - SAKCommonDataStructure::setComboBoxTextOutputFormat( - ui_->comboBoxOutputFormat); - SAKCommonDataStructure::setupSuffix(ui_->comboBoxBroadcastPrefix); - SAKCommonDataStructure::setupSuffix(ui_->comboBoxBroadcastSuffix); + ui_->comboBoxBroadcastAddress->setEnabled(!started); + ui_->lineEditBroadcastPort->setEnabled(!started); + ui_->comboBoxBroadcastInterval->setEnabled(!started); + ui_->comboBoxBroadcastPrefix->setEnabled(!started); + ui_->comboBoxBroadcastSuffix->setEnabled(!started); + ui_->comboBoxBroadcastFormat->setEnabled(!started); + ui_->lineEditBroadcastData->setEnabled(!started); } -void SAKBroadcastAssistant::InitUiBroadcastAddress() { - ui_->comboBoxBroadcastAddress->clear(); - auto bd = QHostAddress(QHostAddress::Broadcast); - ui_->comboBoxBroadcastAddress->addItem(bd.toString()); +void SAKBroadcastAssistant::InitUi() +{ + ui_->textBrowserInformation->document()->setMaximumBlockCount(2000); - auto interfaces = QNetworkInterface::allInterfaces(); - for (auto& interface : interfaces) { - auto entries = interface.addressEntries(); - for (auto& entry : entries) { - auto broadcast_ip = entry.broadcast().toString(); - if (!broadcast_ip.isEmpty()) { - int count = ui_->comboBoxBroadcastAddress->count(); - bool existed = false; - for (int i = 0; i < count; i++) { - auto itemText = ui_->comboBoxBroadcastAddress->itemText(i); - if (itemText == broadcast_ip) { - existed = true; - break; - } + InitUiBroadcastAddress(); + InitUiBroadcastInterval(); + + SAKCommonDataStructure::setComboBoxTextInputFormat(ui_->comboBoxBroadcastFormat); + SAKCommonDataStructure::setComboBoxTextOutputFormat(ui_->comboBoxOutputFormat); + SAKCommonDataStructure::setupSuffix(ui_->comboBoxBroadcastPrefix); + SAKCommonDataStructure::setupSuffix(ui_->comboBoxBroadcastSuffix); +} + +void SAKBroadcastAssistant::InitUiBroadcastAddress() +{ + ui_->comboBoxBroadcastAddress->clear(); + auto bd = QHostAddress(QHostAddress::Broadcast); + ui_->comboBoxBroadcastAddress->addItem(bd.toString()); + + auto interfaces = QNetworkInterface::allInterfaces(); + for (auto& interface : interfaces) { + auto entries = interface.addressEntries(); + for (auto& entry : entries) { + auto broadcast_ip = entry.broadcast().toString(); + if (!broadcast_ip.isEmpty()) { + int count = ui_->comboBoxBroadcastAddress->count(); + bool existed = false; + for (int i = 0; i < count; i++) { + auto itemText = ui_->comboBoxBroadcastAddress->itemText(i); + if (itemText == broadcast_ip) { + existed = true; + break; + } + } + + if (!existed) { + ui_->comboBoxBroadcastAddress->addItem(broadcast_ip); + } + } } - - if (!existed) { - ui_->comboBoxBroadcastAddress->addItem(broadcast_ip); - } - } } - } } -void SAKBroadcastAssistant::InitUiBroadcastInterval() { - ui_->comboBoxBroadcastInterval->clear(); - for (int i = 20; i <= 100; i += 20) { - ui_->comboBoxBroadcastInterval->addItem(QString::number(i), i); - } - - for (int i = 200; i <= 1000; i += 200) { - ui_->comboBoxBroadcastInterval->addItem(QString::number(i), i); - } - - for (int i = 2000; i <= 10000; i += 2000) { - ui_->comboBoxBroadcastInterval->addItem(QString::number(i), i); - } - - ui_->comboBoxBroadcastInterval->setCurrentText("1000"); -} - -QByteArray SAKBroadcastAssistant::PacketData() { - QByteArray bytes; - - int prefixType = ui_->comboBoxBroadcastPrefix->currentData().toInt(); - QByteArray prefix = SAKCommonDataStructure::prefix(prefixType).toLatin1(); - - int format = ui_->comboBoxBroadcastFormat->currentData().toInt(); - QString text = ui_->lineEditBroadcastData->text(); - QByteArray data = SAKCommonDataStructure::stringToByteArray(text, format); - - int suffixType = ui_->comboBoxBroadcastSuffix->currentData().toInt(); - QByteArray suffix = SAKCommonDataStructure::suffix(suffixType).toLatin1(); - - bytes.append(prefix); - bytes.append(data); - bytes.append(suffix); - return bytes; -} - -void SAKBroadcastAssistant::OnBroadcastPushButtonClicked() { - ui_->pushButtonBroadcast->setEnabled(false); - - if (broadcast_thread_->isRunning()) { - broadcast_thread_->exit(); - } else { - auto bytes = PacketData(); - if (bytes.isEmpty()) { - ui_->pushButtonBroadcast->setEnabled(true); - return; +void SAKBroadcastAssistant::InitUiBroadcastInterval() +{ + ui_->comboBoxBroadcastInterval->clear(); + for (int i = 20; i <= 100; i += 20) { + ui_->comboBoxBroadcastInterval->addItem(QString::number(i), i); } - broadcast_thread_->SetBroadcastInformation( - ui_->comboBoxBroadcastAddress->currentText(), - ui_->lineEditBroadcastPort->text().toInt(), - ui_->comboBoxBroadcastInterval->currentData().toInt(), bytes); - broadcast_thread_->start(); - } + for (int i = 200; i <= 1000; i += 200) { + ui_->comboBoxBroadcastInterval->addItem(QString::number(i), i); + } + + for (int i = 2000; i <= 10000; i += 2000) { + ui_->comboBoxBroadcastInterval->addItem(QString::number(i), i); + } + + ui_->comboBoxBroadcastInterval->setCurrentText("1000"); +} + +QByteArray SAKBroadcastAssistant::PacketData() +{ + QByteArray bytes; + + int prefixType = ui_->comboBoxBroadcastPrefix->currentData().toInt(); + QByteArray prefix = SAKCommonDataStructure::prefix(prefixType).toLatin1(); + + int format = ui_->comboBoxBroadcastFormat->currentData().toInt(); + QString text = ui_->lineEditBroadcastData->text(); + QByteArray data = SAKCommonDataStructure::stringToByteArray(text, format); + + int suffixType = ui_->comboBoxBroadcastSuffix->currentData().toInt(); + QByteArray suffix = SAKCommonDataStructure::suffix(suffixType).toLatin1(); + + bytes.append(prefix); + bytes.append(data); + bytes.append(suffix); + return bytes; +} + +void SAKBroadcastAssistant::OnBroadcastPushButtonClicked() +{ + ui_->pushButtonBroadcast->setEnabled(false); + + if (broadcast_thread_->isRunning()) { + broadcast_thread_->exit(); + } else { + auto bytes = PacketData(); + if (bytes.isEmpty()) { + ui_->pushButtonBroadcast->setEnabled(true); + return; + } + + broadcast_thread_ + ->SetBroadcastInformation(ui_->comboBoxBroadcastAddress->currentText(), + ui_->lineEditBroadcastPort->text().toInt(), + ui_->comboBoxBroadcastInterval->currentData().toInt(), + bytes); + broadcast_thread_->start(); + } } diff --git a/src/assistants/broadcast/src/sakbroadcastassistant.h b/src/assistants/broadcast/src/sakbroadcastassistant.h index 07164fa3..712699aa 100644 --- a/src/assistants/broadcast/src/sakbroadcastassistant.h +++ b/src/assistants/broadcast/src/sakbroadcastassistant.h @@ -17,24 +17,25 @@ class SAKBroadcastAssistant; } class SAKBroadcastThread; -class SAKBroadcastAssistant : public QWidget { - Q_OBJECT - public: - Q_INVOKABLE SAKBroadcastAssistant(QWidget* parent = Q_NULLPTR); - ~SAKBroadcastAssistant(); +class SAKBroadcastAssistant : public QWidget +{ + Q_OBJECT +public: + Q_INVOKABLE SAKBroadcastAssistant(QWidget* parent = Q_NULLPTR); + ~SAKBroadcastAssistant(); - private: - Ui::SAKBroadcastAssistant* ui_; - SAKBroadcastThread* broadcast_thread_; +private: + Ui::SAKBroadcastAssistant* ui_; + SAKBroadcastThread* broadcast_thread_; - private: - void InitUi(); - void InitUiBroadcastAddress(); - void InitUiBroadcastInterval(); - void UpdateUiState(bool started); - QByteArray PacketData(); +private: + void InitUi(); + void InitUiBroadcastAddress(); + void InitUiBroadcastInterval(); + void UpdateUiState(bool started); + QByteArray PacketData(); - void OnBroadcastPushButtonClicked(); + void OnBroadcastPushButtonClicked(); }; -#endif // SAKBROADCASTASSISTANT_H +#endif // SAKBROADCASTASSISTANT_H diff --git a/src/assistants/broadcast/src/sakbroadcastthread.cc b/src/assistants/broadcast/src/sakbroadcastthread.cc index a7414776..a4590674 100644 --- a/src/assistants/broadcast/src/sakbroadcastthread.cc +++ b/src/assistants/broadcast/src/sakbroadcastthread.cc @@ -12,60 +12,67 @@ #include #include -SAKBroadcastThread::SAKBroadcastThread(QObject* parent) : QThread{parent} {} +SAKBroadcastThread::SAKBroadcastThread(QObject* parent) + : QThread{parent} +{} -SAKBroadcastThread::~SAKBroadcastThread() { - if (isRunning()) { - exit(); - wait(); - } +SAKBroadcastThread::~SAKBroadcastThread() +{ + if (isRunning()) { + exit(); + wait(); + } } void SAKBroadcastThread::SetBroadcastInformation(const QString& address, - quint16 port, int interval, - const QByteArray& data) { - parameters_mutext_.lock(); - parameters_.address = address; - parameters_.port = port; - parameters_.interval = interval; - parameters_.data = data; - parameters_mutext_.unlock(); + quint16 port, + int interval, + const QByteArray& data) +{ + parameters_mutext_.lock(); + parameters_.address = address; + parameters_.port = port; + parameters_.interval = interval; + parameters_.data = data; + parameters_mutext_.unlock(); } -void SAKBroadcastThread::run() { - QUdpSocket* udp_socket = new QUdpSocket(); - if (!udp_socket->bind()) { - qWarning() << udp_socket->errorString(); - return; - } - - parameters_mutext_.lock(); - auto parameters = parameters_; - parameters_mutext_.unlock(); - - QTimer* tx_timer = new QTimer(); - tx_timer->setSingleShot(true); - tx_timer->setInterval(parameters.interval < 20 ? 20 : parameters.interval); - connect(tx_timer, &QTimer::timeout, tx_timer, [=]() { - qint64 ret = udp_socket->writeDatagram( - parameters.data, QHostAddress(parameters.address), parameters.port); - if (ret < 0) { - qWarning() << udp_socket->error(); - } else { - emit BytesWritten(parameters.data); +void SAKBroadcastThread::run() +{ + QUdpSocket* udp_socket = new QUdpSocket(); + if (!udp_socket->bind()) { + qWarning() << udp_socket->errorString(); + return; } + parameters_mutext_.lock(); + auto parameters = parameters_; + parameters_mutext_.unlock(); + + QTimer* tx_timer = new QTimer(); + tx_timer->setSingleShot(true); + tx_timer->setInterval(parameters.interval < 20 ? 20 : parameters.interval); + connect(tx_timer, &QTimer::timeout, tx_timer, [=]() { + qint64 ret = udp_socket->writeDatagram(parameters.data, + QHostAddress(parameters.address), + parameters.port); + if (ret < 0) { + qWarning() << udp_socket->error(); + } else { + emit BytesWritten(parameters.data); + } + + tx_timer->start(); + }); tx_timer->start(); - }); - tx_timer->start(); - exec(); + exec(); - tx_timer->stop(); - tx_timer->deleteLater(); - tx_timer = Q_NULLPTR; + tx_timer->stop(); + tx_timer->deleteLater(); + tx_timer = Q_NULLPTR; - udp_socket->close(); - udp_socket->deleteLater(); - udp_socket = Q_NULLPTR; + udp_socket->close(); + udp_socket->deleteLater(); + udp_socket = Q_NULLPTR; } diff --git a/src/assistants/broadcast/src/sakbroadcastthread.h b/src/assistants/broadcast/src/sakbroadcastthread.h index e5d84e54..fe131b05 100644 --- a/src/assistants/broadcast/src/sakbroadcastthread.h +++ b/src/assistants/broadcast/src/sakbroadcastthread.h @@ -13,31 +13,35 @@ #include #include -class SAKBroadcastThread : public QThread { - Q_OBJECT - public: - explicit SAKBroadcastThread(QObject* parent = Q_NULLPTR); - ~SAKBroadcastThread(); +class SAKBroadcastThread : public QThread +{ + Q_OBJECT +public: + explicit SAKBroadcastThread(QObject* parent = Q_NULLPTR); + ~SAKBroadcastThread(); - void SetBroadcastInformation(const QString& address, quint16 port, - int interval, const QByteArray& data); + void SetBroadcastInformation(const QString& address, + quint16 port, + int interval, + const QByteArray& data); - signals: - void BytesWritten(const QByteArray& bytes); +signals: + void BytesWritten(const QByteArray& bytes); - protected: - void run() final; +protected: + void run() final; - private: - struct Parameters { - QString address; - quint16 port; - int interval; - QByteArray data; - } parameters_; +private: + struct Parameters + { + QString address; + quint16 port; + int interval; + QByteArray data; + } parameters_; - private: - QMutex parameters_mutext_; +private: + QMutex parameters_mutext_; }; -#endif // SAKBROADCASTTHREAD_H +#endif // SAKBROADCASTTHREAD_H diff --git a/src/assistants/crc/main.cc b/src/assistants/crc/main.cc index ed215232..aa7e4bbb 100644 --- a/src/assistants/crc/main.cc +++ b/src/assistants/crc/main.cc @@ -9,14 +9,18 @@ ******************************************************************************/ #include -#include "sakcrcassistant.h" #include "sakcommonmainwindow.h" +#include "sakcrcassistant.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("CRC Assistant"), "SAK.CRCAssistant"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app = CreateCommonMainWindowApplication(argc, + argv, + QObject::tr( + "CRC Assistant"), + "SAK.CRCAssistant"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/assistants/crc/src/sakcrcassistant.cc b/src/assistants/crc/src/sakcrcassistant.cc index bc4bf69e..0a98314c 100644 --- a/src/assistants/crc/src/sakcrcassistant.cc +++ b/src/assistants/crc/src/sakcrcassistant.cc @@ -18,213 +18,217 @@ #include "ui_sakcrcassistant.h" SAKCRCAssistant::SAKCRCAssistant(QWidget* parent) - : QWidget(parent), - log_category_("CRCAssistant"), - crc_interface_(new SAKCommonCrcInterface), - mUi(new Ui::SAKCRCAssistant) { - mUi->setupUi(this); - mWidthComboBox = mUi->comboBoxWidth; - mWidthComboBox->addItem(QString::number(8)); - mWidthComboBox->addItem(QString::number(16)); - mWidthComboBox->addItem(QString::number(32)); - mWidthComboBox->setEnabled(false); + : QWidget(parent) + , log_category_("CRCAssistant") + , crc_interface_(new SAKCommonCrcInterface) + , mUi(new Ui::SAKCRCAssistant) +{ + mUi->setupUi(this); + mWidthComboBox = mUi->comboBoxWidth; + mWidthComboBox->addItem(QString::number(8)); + mWidthComboBox->addItem(QString::number(16)); + mWidthComboBox->addItem(QString::number(32)); + mWidthComboBox->setEnabled(false); - mParameterComboBox = mUi->comboBoxName; - mParameterComboBox->clear(); + mParameterComboBox = mUi->comboBoxName; + mParameterComboBox->clear(); - mRefinCheckBox = mUi->checkBoxRefIn; - mRefoutCheckBox = mUi->checkBoxRefOut; - mPolyLineEdit = mUi->lineEditPoly; - mInitLineEdit = mUi->lineEditInit; - mXorLineEdit = mUi->lineEditXOROUT; + mRefinCheckBox = mUi->checkBoxRefIn; + mRefoutCheckBox = mUi->checkBoxRefOut; + mPolyLineEdit = mUi->lineEditPoly; + mInitLineEdit = mUi->lineEditInit; + mXorLineEdit = mUi->lineEditXOROUT; - mRefinCheckBox->setEnabled(false); - mRefoutCheckBox->setEnabled(false); - mPolyLineEdit->setReadOnly(true); - mInitLineEdit->setReadOnly(true); - mXorLineEdit->setReadOnly(true); + mRefinCheckBox->setEnabled(false); + mRefoutCheckBox->setEnabled(false); + mPolyLineEdit->setReadOnly(true); + mInitLineEdit->setReadOnly(true); + mXorLineEdit->setReadOnly(true); - mHexRadioBt = mUi->radioButtonHex; - mAsciiRadioBt = mUi->radioButtonASCII; + mHexRadioBt = mUi->radioButtonHex; + mAsciiRadioBt = mUi->radioButtonASCII; - mHexCRCOutput = mUi->lineEditOutputHex; - mBinCRCOutput = mUi->lineEditOutputBin; - mHexCRCOutput->setReadOnly(true); - mBinCRCOutput->setReadOnly(true); + mHexCRCOutput = mUi->lineEditOutputHex; + mBinCRCOutput = mUi->lineEditOutputBin; + mHexCRCOutput->setReadOnly(true); + mBinCRCOutput->setReadOnly(true); - mInputTextEdit = mUi->textEdit; + mInputTextEdit = mUi->textEdit; - mCalculatedBt = mUi->pushButtonCalculate; - mLabelPolyFormula = mUi->labelPolyFormula; - mLabelInfo = mUi->labelInfo; - mLabelInfo->installEventFilter(this); - mLabelInfo->setCursor(QCursor(Qt::PointingHandCursor)); + mCalculatedBt = mUi->pushButtonCalculate; + mLabelPolyFormula = mUi->labelPolyFormula; + mLabelInfo = mUi->labelInfo; + mLabelInfo->installEventFilter(this); + mLabelInfo->setCursor(QCursor(Qt::PointingHandCursor)); - InitParameterModel(); - connect(mParameterComboBox, SIGNAL(currentIndexChanged(int)), this, - SLOT(ChangedParameterModel(int))); - connect(mCalculatedBt, SIGNAL(clicked()), this, SLOT(Calculate())); - connect(mInputTextEdit, SIGNAL(textChanged()), this, - SLOT(TextFormatControl())); + InitParameterModel(); + connect(mParameterComboBox, + SIGNAL(currentIndexChanged(int)), + this, + SLOT(ChangedParameterModel(int))); + connect(mCalculatedBt, SIGNAL(clicked()), this, SLOT(Calculate())); + connect(mInputTextEdit, SIGNAL(textChanged()), this, SLOT(TextFormatControl())); } -SAKCRCAssistant::~SAKCRCAssistant() { - QLoggingCategory category(log_category_); - qCInfo(category) << "Goodbye CRCCalculator"; - delete crc_interface_; - delete mUi; -} - -void SAKCRCAssistant::InitParameterModel() { - mParameterComboBox->clear(); - QStringList list = crc_interface_->supportedParameterModels(); - mParameterComboBox->addItems(list); - - QMetaEnum models = - QMetaEnum::fromType(); - bool ok = false; - int ret = models.keyToValue( - mParameterComboBox->currentText().toLatin1().constData(), &ok); - SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8; - if (ok) { - model = static_cast(ret); - } - - int bitsWidth = crc_interface_->bitsWidth(model); - mWidthComboBox->setCurrentIndex( - mWidthComboBox->findText(QString::number(bitsWidth))); - mLabelPolyFormula->setText(crc_interface_->friendlyPoly(model)); -} - -void SAKCRCAssistant::Calculate() { - QByteArray inputArray; - if (mHexRadioBt->isChecked()) { - QString str = mInputTextEdit->toPlainText(); - QStringList strList = str.split(' '); - char ch; - for (int i = 0; i < strList.length(); i++) { - if (strList.at(i).isEmpty()) { - continue; - } - ch = static_cast(strList.at(i).toInt(Q_NULLPTR, 16)); - inputArray.append(ch); - } - } else { - inputArray = mInputTextEdit->toPlainText().toLatin1(); - } - - if (inputArray.isEmpty()) { - return; - } - - int bitsWidth = mWidthComboBox->currentText().toInt(); - QMetaEnum models = - QMetaEnum::fromType(); - bool ok = false; - int ret = models.keyToValue( - mParameterComboBox->currentText().toLatin1().constData(), &ok); - SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8; - if (ok) { - model = static_cast(ret); - } else { - Q_ASSERT_X(false, __FUNCTION__, "Unknown crc parameters model!"); - } - - QString crcHexString = "error"; - QString crcBinString = "error"; - - if (bitsWidth == 8) { - uint8_t crc = crc_interface_->crcCalculate( - reinterpret_cast(inputArray.data()), - static_cast(inputArray.length()), model); - crcHexString = QString("0x%1").arg(QString::number(crc, 16), 2, '0'); - crcBinString = QString("%1").arg(QString::number(crc, 2), 8, '0'); - } else if (bitsWidth == 16) { - uint16_t crc = crc_interface_->crcCalculate( - reinterpret_cast(inputArray.data()), - static_cast(inputArray.length()), model); - crcHexString = QString("0x%1").arg(QString::number(crc, 16), 4, '0'); - crcBinString = QString("%1").arg(QString::number(crc, 2), 16, '0'); - } else if (bitsWidth == 32) { - uint32_t crc = crc_interface_->crcCalculate( - reinterpret_cast(inputArray.data()), - static_cast(inputArray.length()), model); - crcHexString = QString("0x%1").arg(QString::number(crc, 16), 8, '0'); - crcBinString = QString("%1").arg(QString::number(crc, 2), 32, '0'); - } else { - qWarning() << "Not supported bits width!"; - } - - mHexCRCOutput->setText(crcHexString); - mBinCRCOutput->setText(crcBinString); -} - -void SAKCRCAssistant::TextFormatControl() { - if (mAsciiRadioBt->isChecked()) { - return; - } - disconnect(mInputTextEdit, SIGNAL(textChanged()), this, - SLOT(textFormatControl())); - - QString strTemp; - QString plaintext = mInputTextEdit->toPlainText(); - static QRegularExpression reg("[^0-9a-fA-F]"); - plaintext.remove(reg); - for (int i = 0; i < plaintext.length(); i++) { - if ((i != 0) && (i % 2 == 0)) { - strTemp.append(QChar(' ')); - } - strTemp.append(plaintext.at(i)); - } - mInputTextEdit->setText(strTemp.toUpper()); - mInputTextEdit->moveCursor(QTextCursor::End); - - connect(mInputTextEdit, SIGNAL(textChanged()), this, - SLOT(textFormatControl())); -} - -void SAKCRCAssistant::ChangedParameterModel(int index) { - Q_UNUSED(index) - QMetaEnum models = - QMetaEnum::fromType(); - bool ok = false; - SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8; - int ret = models.keyToValue( - mParameterComboBox->currentText().toLatin1().constData(), &ok); - if (ok) { - model = static_cast(ret); - } else { +SAKCRCAssistant::~SAKCRCAssistant() +{ QLoggingCategory category(log_category_); - qCWarning(category) << "Unknown parameter model!"; - Q_ASSERT_X(false, __FUNCTION__, "Unknown parameter model!"); - return; - } - - int bitsWidth = crc_interface_->bitsWidth(model); - mWidthComboBox->setCurrentIndex( - mWidthComboBox->findText(QString::number(bitsWidth))); - mPolyLineEdit->setText(QString("0x%1").arg( - QString::number(static_cast(crc_interface_->poly(model)), 16), - bitsWidth / 4, '0')); - mInitLineEdit->setText(QString("0x%1").arg( - QString::number(static_cast(crc_interface_->initialValue(model)), - 16), - bitsWidth / 4, '0')); - mXorLineEdit->setText(QString("0x%1").arg( - QString::number(static_cast(crc_interface_->xorValue(model)), 16), - bitsWidth / 4, '0')); - mRefinCheckBox->setChecked(crc_interface_->isInputReversal(model)); - mRefoutCheckBox->setChecked(crc_interface_->isOutputReversal(model)); - mLabelPolyFormula->setText(crc_interface_->friendlyPoly(model)); + qCInfo(category) << "Goodbye CRCCalculator"; + delete crc_interface_; + delete mUi; } -bool SAKCRCAssistant::eventFilter(QObject* watched, QEvent* event) { - if (event->type() == QEvent::MouseButtonDblClick) { - if (watched == mLabelInfo) { - QDesktopServices::openUrl(QUrl(QString("http://www.ip33.com/crc.html"))); - return true; +void SAKCRCAssistant::InitParameterModel() +{ + mParameterComboBox->clear(); + QStringList list = crc_interface_->supportedParameterModels(); + mParameterComboBox->addItems(list); + + QMetaEnum models = QMetaEnum::fromType(); + bool ok = false; + int ret = models.keyToValue(mParameterComboBox->currentText().toLatin1().constData(), &ok); + SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8; + if (ok) { + model = static_cast(ret); } - } - return QWidget::eventFilter(watched, event); + int bitsWidth = crc_interface_->bitsWidth(model); + mWidthComboBox->setCurrentIndex(mWidthComboBox->findText(QString::number(bitsWidth))); + mLabelPolyFormula->setText(crc_interface_->friendlyPoly(model)); +} + +void SAKCRCAssistant::Calculate() +{ + QByteArray inputArray; + if (mHexRadioBt->isChecked()) { + QString str = mInputTextEdit->toPlainText(); + QStringList strList = str.split(' '); + char ch; + for (int i = 0; i < strList.length(); i++) { + if (strList.at(i).isEmpty()) { + continue; + } + ch = static_cast(strList.at(i).toInt(Q_NULLPTR, 16)); + inputArray.append(ch); + } + } else { + inputArray = mInputTextEdit->toPlainText().toLatin1(); + } + + if (inputArray.isEmpty()) { + return; + } + + int bitsWidth = mWidthComboBox->currentText().toInt(); + QMetaEnum models = QMetaEnum::fromType(); + bool ok = false; + int ret = models.keyToValue(mParameterComboBox->currentText().toLatin1().constData(), &ok); + SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8; + if (ok) { + model = static_cast(ret); + } else { + Q_ASSERT_X(false, __FUNCTION__, "Unknown crc parameters model!"); + } + + QString crcHexString = "error"; + QString crcBinString = "error"; + + if (bitsWidth == 8) { + uint8_t crc = crc_interface_ + ->crcCalculate(reinterpret_cast(inputArray.data()), + static_cast(inputArray.length()), + model); + crcHexString = QString("0x%1").arg(QString::number(crc, 16), 2, '0'); + crcBinString = QString("%1").arg(QString::number(crc, 2), 8, '0'); + } else if (bitsWidth == 16) { + uint16_t crc = crc_interface_ + ->crcCalculate(reinterpret_cast(inputArray.data()), + static_cast(inputArray.length()), + model); + crcHexString = QString("0x%1").arg(QString::number(crc, 16), 4, '0'); + crcBinString = QString("%1").arg(QString::number(crc, 2), 16, '0'); + } else if (bitsWidth == 32) { + uint32_t crc = crc_interface_ + ->crcCalculate(reinterpret_cast(inputArray.data()), + static_cast(inputArray.length()), + model); + crcHexString = QString("0x%1").arg(QString::number(crc, 16), 8, '0'); + crcBinString = QString("%1").arg(QString::number(crc, 2), 32, '0'); + } else { + qWarning() << "Not supported bits width!"; + } + + mHexCRCOutput->setText(crcHexString); + mBinCRCOutput->setText(crcBinString); +} + +void SAKCRCAssistant::TextFormatControl() +{ + if (mAsciiRadioBt->isChecked()) { + return; + } + disconnect(mInputTextEdit, SIGNAL(textChanged()), this, SLOT(textFormatControl())); + + QString strTemp; + QString plaintext = mInputTextEdit->toPlainText(); + static QRegularExpression reg("[^0-9a-fA-F]"); + plaintext.remove(reg); + for (int i = 0; i < plaintext.length(); i++) { + if ((i != 0) && (i % 2 == 0)) { + strTemp.append(QChar(' ')); + } + strTemp.append(plaintext.at(i)); + } + mInputTextEdit->setText(strTemp.toUpper()); + mInputTextEdit->moveCursor(QTextCursor::End); + + connect(mInputTextEdit, SIGNAL(textChanged()), this, SLOT(textFormatControl())); +} + +void SAKCRCAssistant::ChangedParameterModel(int index) +{ + Q_UNUSED(index) + QMetaEnum models = QMetaEnum::fromType(); + bool ok = false; + SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8; + int ret = models.keyToValue(mParameterComboBox->currentText().toLatin1().constData(), &ok); + if (ok) { + model = static_cast(ret); + } else { + QLoggingCategory category(log_category_); + qCWarning(category) << "Unknown parameter model!"; + Q_ASSERT_X(false, __FUNCTION__, "Unknown parameter model!"); + return; + } + + int bitsWidth = crc_interface_->bitsWidth(model); + mWidthComboBox->setCurrentIndex(mWidthComboBox->findText(QString::number(bitsWidth))); + mPolyLineEdit->setText( + QString("0x%1").arg(QString::number(static_cast(crc_interface_->poly(model)), 16), + bitsWidth / 4, + '0')); + mInitLineEdit->setText( + QString("0x%1").arg(QString::number(static_cast(crc_interface_->initialValue(model)), + 16), + bitsWidth / 4, + '0')); + mXorLineEdit->setText( + QString("0x%1").arg(QString::number(static_cast(crc_interface_->xorValue(model)), 16), + bitsWidth / 4, + '0')); + mRefinCheckBox->setChecked(crc_interface_->isInputReversal(model)); + mRefoutCheckBox->setChecked(crc_interface_->isOutputReversal(model)); + mLabelPolyFormula->setText(crc_interface_->friendlyPoly(model)); +} + +bool SAKCRCAssistant::eventFilter(QObject* watched, QEvent* event) +{ + if (event->type() == QEvent::MouseButtonDblClick) { + if (watched == mLabelInfo) { + QDesktopServices::openUrl(QUrl(QString("http://www.ip33.com/crc.html"))); + return true; + } + } + + return QWidget::eventFilter(watched, event); } diff --git a/src/assistants/crc/src/sakcrcassistant.h b/src/assistants/crc/src/sakcrcassistant.h index d6ad328c..e9833844 100644 --- a/src/assistants/crc/src/sakcrcassistant.h +++ b/src/assistants/crc/src/sakcrcassistant.h @@ -27,43 +27,44 @@ class SAKCRCAssistant; } class SAKCommonCrcInterface; -class SAKCRCAssistant : public QWidget { - Q_OBJECT - public: - Q_INVOKABLE SAKCRCAssistant(QWidget* parent = Q_NULLPTR); - ~SAKCRCAssistant(); +class SAKCRCAssistant : public QWidget +{ + Q_OBJECT +public: + Q_INVOKABLE SAKCRCAssistant(QWidget* parent = Q_NULLPTR); + ~SAKCRCAssistant(); - protected: - bool eventFilter(QObject* watched, QEvent* event); +protected: + bool eventFilter(QObject* watched, QEvent* event); - private: - const char* log_category_; - SAKCommonCrcInterface* crc_interface_; +private: + const char* log_category_; + SAKCommonCrcInterface* crc_interface_; - private: - void InitParameterModel(); +private: + void InitParameterModel(); - private slots: - void Calculate(); - void TextFormatControl(); - void ChangedParameterModel(int index); +private slots: + void Calculate(); + void TextFormatControl(); + void ChangedParameterModel(int index); - private: - Ui::SAKCRCAssistant* mUi; - QComboBox* mWidthComboBox; - QComboBox* mParameterComboBox; - QCheckBox* mRefinCheckBox; - QCheckBox* mRefoutCheckBox; - QLineEdit* mPolyLineEdit; - QLineEdit* mInitLineEdit; - QLineEdit* mXorLineEdit; - QRadioButton* mHexRadioBt; - QRadioButton* mAsciiRadioBt; - QLineEdit* mHexCRCOutput; - QLineEdit* mBinCRCOutput; - QTextEdit* mInputTextEdit; - QPushButton* mCalculatedBt; - QLabel* mLabelPolyFormula; - QLabel* mLabelInfo; +private: + Ui::SAKCRCAssistant* mUi; + QComboBox* mWidthComboBox; + QComboBox* mParameterComboBox; + QCheckBox* mRefinCheckBox; + QCheckBox* mRefoutCheckBox; + QLineEdit* mPolyLineEdit; + QLineEdit* mInitLineEdit; + QLineEdit* mXorLineEdit; + QRadioButton* mHexRadioBt; + QRadioButton* mAsciiRadioBt; + QLineEdit* mHexCRCOutput; + QLineEdit* mBinCRCOutput; + QTextEdit* mInputTextEdit; + QPushButton* mCalculatedBt; + QLabel* mLabelPolyFormula; + QLabel* mLabelInfo; }; #endif diff --git a/src/assistants/filecheck/main.cc b/src/assistants/filecheck/main.cc index 733671f5..188d8393 100644 --- a/src/assistants/filecheck/main.cc +++ b/src/assistants/filecheck/main.cc @@ -12,12 +12,12 @@ #include "sakcommonmainwindow.h" #include "sakfilecheckassistant.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("File Check Assistant"), - "SAK.FileCheckAssistant"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app = CreateCommonMainWindowApplication( + argc, argv, QObject::tr("File Check Assistant"), "SAK.FileCheckAssistant"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/assistants/filecheck/src/sakcryptographichashcalculator.cc b/src/assistants/filecheck/src/sakcryptographichashcalculator.cc index 65b1b89a..821aba5f 100644 --- a/src/assistants/filecheck/src/sakcryptographichashcalculator.cc +++ b/src/assistants/filecheck/src/sakcryptographichashcalculator.cc @@ -15,124 +15,132 @@ #include #include "sakfilecheckassistant.h" -SAKCryptographicHashCalculator::SAKCryptographicHashCalculator( - SAKFileCheckAssistant* controller, QObject* parent) - : QThread(parent), mCryptographicHashController(controller) { - connect(this, &SAKCryptographicHashCalculator::updateResult, controller, +SAKCryptographicHashCalculator::SAKCryptographicHashCalculator(SAKFileCheckAssistant* controller, + QObject* parent) + : QThread(parent) + , mCryptographicHashController(controller) +{ + connect(this, + &SAKCryptographicHashCalculator::updateResult, + controller, &SAKFileCheckAssistant::updateResult); - connect(this, &SAKCryptographicHashCalculator::outputMessage, controller, + connect(this, + &SAKCryptographicHashCalculator::outputMessage, + controller, &SAKFileCheckAssistant::outputMessage); - connect(this, &SAKCryptographicHashCalculator::updateProgressBar, controller, + connect(this, + &SAKCryptographicHashCalculator::updateProgressBar, + controller, &SAKFileCheckAssistant::updateProgressBar); - connect(this, &SAKCryptographicHashCalculator::remainTimeChanged, controller, + connect(this, + &SAKCryptographicHashCalculator::remainTimeChanged, + controller, &SAKFileCheckAssistant::changeRemainTime); } -void SAKCryptographicHashCalculator::run() { - QCryptographicHash::Algorithm algorithm = - mCryptographicHashController->algorithm(); - QCryptographicHash cryptographicHash(algorithm); - cryptographicHash.reset(); +void SAKCryptographicHashCalculator::run() +{ + QCryptographicHash::Algorithm algorithm = mCryptographicHashController->algorithm(); + QCryptographicHash cryptographicHash(algorithm); + cryptographicHash.reset(); - QString fileName = mCryptographicHashController->fileName(); - QFile file(fileName); - if (file.open(QFile::ReadOnly)) { - qint64 allBytes = file.size(); - emit progressBarMaxValueChanged(allBytes); + QString fileName = mCryptographicHashController->fileName(); + QFile file(fileName); + if (file.open(QFile::ReadOnly)) { + qint64 allBytes = file.size(); + emit progressBarMaxValueChanged(allBytes); - qint64 consumeBytes = 0; - qint64 remainBytes = 0; - qint64 percent = 0; - qint64 percenTemp = 0; - qint64 startTime = 0; - qint64 endTime = 0; - qint64 consumeTime = 0; - qint64 remainTime = 0; + qint64 consumeBytes = 0; + qint64 remainBytes = 0; + qint64 percent = 0; + qint64 percenTemp = 0; + qint64 startTime = 0; + qint64 endTime = 0; + qint64 consumeTime = 0; + qint64 remainTime = 0; - qint64 hours = 0; - qint64 minutes = 0; - qint64 seconds = 0; - qint64 hoursTemp = 0; - qint64 minutesTemp = 0; - qint64 secondsTemp = 0; + qint64 hours = 0; + qint64 minutes = 0; + qint64 seconds = 0; + qint64 hoursTemp = 0; + qint64 minutesTemp = 0; + qint64 secondsTemp = 0; - // The number of bytes read at a time - int dataBlock = 1024 * 1024; + // The number of bytes read at a time + int dataBlock = 1024 * 1024; - while (1) { - startTime = QDateTime::currentDateTime().toMSecsSinceEpoch(); + while (1) { + startTime = QDateTime::currentDateTime().toMSecsSinceEpoch(); - QByteArray array = file.read(dataBlock); - consumeBytes += array.length(); - remainBytes = allBytes - consumeBytes; + QByteArray array = file.read(dataBlock); + consumeBytes += array.length(); + remainBytes = allBytes - consumeBytes; - // Effectively reduce the frequency of signal transmission - percenTemp = (consumeBytes * 100) / allBytes; - if (percenTemp != percent) { - percent = percenTemp; - emit updateProgressBar(percent); - } + // Effectively reduce the frequency of signal transmission + percenTemp = (consumeBytes * 100) / allBytes; + if (percenTemp != percent) { + percent = percenTemp; + emit updateProgressBar(percent); + } - // Returns an empty array. There are two possibilities. - // One is that the file has been read, and the other is that the file has - // been read incorrectly. Both cases are considered to be the end of the - // check calculation - if (array.isEmpty()) { - outputMessage(tr("Calculating finished"), false); - QApplication::beep(); - break; - } + // Returns an empty array. There are two possibilities. + // One is that the file has been read, and the other is that the file has + // been read incorrectly. Both cases are considered to be the end of the + // check calculation + if (array.isEmpty()) { + outputMessage(tr("Calculating finished"), false); + QApplication::beep(); + break; + } - cryptographicHash.addData(array); + cryptographicHash.addData(array); - // Calculating remaining time - endTime = QDateTime::currentDateTime().toMSecsSinceEpoch(); - consumeTime = endTime - startTime; + // Calculating remaining time + endTime = QDateTime::currentDateTime().toMSecsSinceEpoch(); + consumeTime = endTime - startTime; - if (consumeTime != 0) { - consumeTimeList.append(consumeTime); - while (consumeTimeList.length() > 1000) { - consumeTimeList.removeFirst(); + if (consumeTime != 0) { + consumeTimeList.append(consumeTime); + while (consumeTimeList.length() > 1000) { + consumeTimeList.removeFirst(); + } + qint64 averageConsumeTime = 0; + for (auto& var : consumeTimeList) { + averageConsumeTime += var; + } + averageConsumeTime = averageConsumeTime / consumeTimeList.count(); + if (averageConsumeTime > 0) { + remainTime = remainBytes / dataBlock * averageConsumeTime; + + hoursTemp = (remainTime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000); + minutesTemp = ((remainTime % (24 * 60 * 60 * 1000)) % (60 * 60 * 1000)) + / (1 * 60 * 1000); + secondsTemp = (((remainTime % (24 * 60 * 60 * 1000)) % (60 * 60 * 1000)) + % (1 * 60 * 1000)) + / 1000; + + if ((hours != hoursTemp) || (minutes != minutesTemp) + || (seconds != secondsTemp)) { + hours = hoursTemp; + minutes = minutesTemp; + seconds = secondsTemp; + emit remainTimeChanged(QString("%1:%2:%3") + .arg(QString::number(hours), 2, '0') + .arg(QString::number(minutes), 2, '0') + .arg(QString::number(seconds), 2, '0')); + } + } + } + + // Responsing the interruption requested + if (isInterruptionRequested()) { + return; + } } - qint64 averageConsumeTime = 0; - for (auto& var : consumeTimeList) { - averageConsumeTime += var; - } - averageConsumeTime = averageConsumeTime / consumeTimeList.count(); - if (averageConsumeTime > 0) { - remainTime = remainBytes / dataBlock * averageConsumeTime; - hoursTemp = (remainTime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000); - minutesTemp = - ((remainTime % (24 * 60 * 60 * 1000)) % (60 * 60 * 1000)) / - (1 * 60 * 1000); - secondsTemp = - (((remainTime % (24 * 60 * 60 * 1000)) % (60 * 60 * 1000)) % - (1 * 60 * 1000)) / - 1000; - - if ((hours != hoursTemp) || (minutes != minutesTemp) || - (seconds != secondsTemp)) { - hours = hoursTemp; - minutes = minutesTemp; - seconds = secondsTemp; - emit remainTimeChanged(QString("%1:%2:%3") - .arg(QString::number(hours), 2, '0') - .arg(QString::number(minutes), 2, '0') - .arg(QString::number(seconds), 2, '0')); - } - } - } - - // Responsing the interruption requested - if (isInterruptionRequested()) { - return; - } + QByteArray result = cryptographicHash.result(); + emit updateResult(result); + } else { + outputMessage(file.errorString(), true); } - - QByteArray result = cryptographicHash.result(); - emit updateResult(result); - } else { - outputMessage(file.errorString(), true); - } } diff --git a/src/assistants/filecheck/src/sakcryptographichashcalculator.h b/src/assistants/filecheck/src/sakcryptographichashcalculator.h index 6031e562..d68af1b5 100644 --- a/src/assistants/filecheck/src/sakcryptographichashcalculator.h +++ b/src/assistants/filecheck/src/sakcryptographichashcalculator.h @@ -13,24 +13,24 @@ #include class SAKFileCheckAssistant; -class SAKCryptographicHashCalculator : public QThread { - Q_OBJECT - public: - SAKCryptographicHashCalculator(SAKFileCheckAssistant* controller, - QObject* parent = Q_NULLPTR); +class SAKCryptographicHashCalculator : public QThread +{ + Q_OBJECT +public: + SAKCryptographicHashCalculator(SAKFileCheckAssistant* controller, QObject* parent = Q_NULLPTR); - private: - SAKFileCheckAssistant* mCryptographicHashController; - QList consumeTimeList; +private: + SAKFileCheckAssistant* mCryptographicHashController; + QList consumeTimeList; - private: - void run() final; - signals: - void outputMessage(QString msg, bool isErrMsg); - void updateResult(QByteArray result); - void progressBarMaxValueChanged(qint64 value); - void updateProgressBar(qint64 currentValue); - void remainTimeChanged(QString remainTime); +private: + void run() final; +signals: + void outputMessage(QString msg, bool isErrMsg); + void updateResult(QByteArray result); + void progressBarMaxValueChanged(qint64 value); + void updateProgressBar(qint64 currentValue); + void remainTimeChanged(QString remainTime); }; #endif diff --git a/src/assistants/filecheck/src/sakfilecheckassistant.cc b/src/assistants/filecheck/src/sakfilecheckassistant.cc index 070153ab..95c92e69 100644 --- a/src/assistants/filecheck/src/sakfilecheckassistant.cc +++ b/src/assistants/filecheck/src/sakfilecheckassistant.cc @@ -17,168 +17,181 @@ #include "ui_sakfilecheckassistant.h" SAKFileCheckAssistant::SAKFileCheckAssistant(QWidget* parent) - : QWidget(parent), - mFileName(QString("C:/Windows/explorer.exe")), - mAlgorithm(QCryptographicHash::Md5), - mCalculator(Q_NULLPTR), - mUi(new Ui::SAKFileCheckAssistant) { - mUi->setupUi(this); + : QWidget(parent) + , mFileName(QString("C:/Windows/explorer.exe")) + , mAlgorithm(QCryptographicHash::Md5) + , mCalculator(Q_NULLPTR) + , mUi(new Ui::SAKFileCheckAssistant) +{ + mUi->setupUi(this); - // Initializing data member about ui - mFilePathlineEdit = mUi->filePathlineEdit; - mAlgorithmComboBox = mUi->algorithmComboBox; - mResultLineEdit = mUi->resultLineEdit; - mCalculatorProgressBar = mUi->calculatorProgressBar; - mOpenPushButton = mUi->openPushButton; - mStartStopPushButton = mUi->startStopPushButton; - mUpperCheckBox = mUi->upperCheckBox; - mMessageLabel = mUi->messageLabel; - mRemainTimeLabel = mUi->remainTimeLabel; - mFilePathlineEdit->setText(mFileName); + // Initializing data member about ui + mFilePathlineEdit = mUi->filePathlineEdit; + mAlgorithmComboBox = mUi->algorithmComboBox; + mResultLineEdit = mUi->resultLineEdit; + mCalculatorProgressBar = mUi->calculatorProgressBar; + mOpenPushButton = mUi->openPushButton; + mStartStopPushButton = mUi->startStopPushButton; + mUpperCheckBox = mUi->upperCheckBox; + mMessageLabel = mUi->messageLabel; + mRemainTimeLabel = mUi->remainTimeLabel; + mFilePathlineEdit->setText(mFileName); - // Appending algorithms to combo box + // Appending algorithms to combo box #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - QMetaEnum algorithms = - QMetaEnum::fromType(); + QMetaEnum algorithms = QMetaEnum::fromType(); #else - QMetaEnum algorithms = QMetaEnum::fromType(); + QMetaEnum algorithms = QMetaEnum::fromType(); #endif - QStringList algorithmsStringList; - for (int i = 0; i < algorithms.keyCount(); i++) { - algorithmsStringList.append(QString(algorithms.key(i))); - } - mAlgorithmComboBox->addItems(algorithmsStringList); - mAlgorithmComboBox->setCurrentText("Md5"); + QStringList algorithmsStringList; + for (int i = 0; i < algorithms.keyCount(); i++) { + algorithmsStringList.append(QString(algorithms.key(i))); + } + mAlgorithmComboBox->addItems(algorithmsStringList); + mAlgorithmComboBox->setCurrentText("Md5"); - mFilePathlineEdit->setReadOnly(true); - mResultLineEdit->setReadOnly(true); - mCalculatorProgressBar->setMinimum(0); - mCalculatorProgressBar->setMaximum(100); - mCalculatorProgressBar->setValue(0); + mFilePathlineEdit->setReadOnly(true); + mResultLineEdit->setReadOnly(true); + mCalculatorProgressBar->setMinimum(0); + mCalculatorProgressBar->setMaximum(100); + mCalculatorProgressBar->setValue(0); - // It will clean the message which was showed on the info label when the timer - // is timeout - mClearMessageTimer.setInterval(SAK_CLEAR_MESSAGE_INTERVAL); - connect(&mClearMessageTimer, &QTimer::timeout, this, - &SAKFileCheckAssistant::clearMessage); + // It will clean the message which was showed on the info label when the timer + // is timeout + mClearMessageTimer.setInterval(SAK_CLEAR_MESSAGE_INTERVAL); + connect(&mClearMessageTimer, &QTimer::timeout, this, &SAKFileCheckAssistant::clearMessage); - mUpperCheckBox->setChecked(true); - setWindowTitle(tr("File Check Assistant")); + mUpperCheckBox->setChecked(true); + setWindowTitle(tr("File Check Assistant")); } -SAKFileCheckAssistant::~SAKFileCheckAssistant() { - delete mUi; - if (mCalculator) { - mCalculator->blockSignals(true); - mCalculator->requestInterruption(); - mCalculator->exit(); - mCalculator->wait(); - mCalculator->deleteLater(); - mCalculator = Q_NULLPTR; - } +SAKFileCheckAssistant::~SAKFileCheckAssistant() +{ + delete mUi; + if (mCalculator) { + mCalculator->blockSignals(true); + mCalculator->requestInterruption(); + mCalculator->exit(); + mCalculator->wait(); + mCalculator->deleteLater(); + mCalculator = Q_NULLPTR; + } } -void SAKFileCheckAssistant::setUiEnable(bool enable) { - mAlgorithmComboBox->setEnabled(enable); - mOpenPushButton->setEnabled(enable); +void SAKFileCheckAssistant::setUiEnable(bool enable) +{ + mAlgorithmComboBox->setEnabled(enable); + mOpenPushButton->setEnabled(enable); } -QString SAKFileCheckAssistant::fileName() { return mFileName; } - -QCryptographicHash::Algorithm SAKFileCheckAssistant::algorithm() { - return mAlgorithm; +QString SAKFileCheckAssistant::fileName() +{ + return mFileName; } -void SAKFileCheckAssistant::updateResult(QByteArray result) { - QString resultString = QString(result.toHex()); - if (mUpperCheckBox->isChecked()) { - mResultLineEdit->setText(resultString.toUpper()); - } else { - mResultLineEdit->setText(resultString); - } +QCryptographicHash::Algorithm SAKFileCheckAssistant::algorithm() +{ + return mAlgorithm; } -void SAKFileCheckAssistant::outputMessage(QString msg, bool isErrMsg) { - if (isErrMsg) { - QApplication::beep(); - msg = QString("%1").arg(msg); - } else { - msg = QString("%1").arg(msg); - } - - mMessageLabel->setText(msg); - mClearMessageTimer.start(); +void SAKFileCheckAssistant::updateResult(QByteArray result) +{ + QString resultString = QString(result.toHex()); + if (mUpperCheckBox->isChecked()) { + mResultLineEdit->setText(resultString.toUpper()); + } else { + mResultLineEdit->setText(resultString); + } } -void SAKFileCheckAssistant::updateProgressBar(int currentValue) { - mCalculatorProgressBar->setValue(currentValue); +void SAKFileCheckAssistant::outputMessage(QString msg, bool isErrMsg) +{ + if (isErrMsg) { + QApplication::beep(); + msg = QString("%1").arg(msg); + } else { + msg = QString("%1").arg(msg); + } + + mMessageLabel->setText(msg); + mClearMessageTimer.start(); } -void SAKFileCheckAssistant::changeRemainTime(QString remainTime) { - QString str = tr("Remaining time"); - mRemainTimeLabel->setText(QString("%1 %2").arg(str, remainTime)); +void SAKFileCheckAssistant::updateProgressBar(int currentValue) +{ + mCalculatorProgressBar->setValue(currentValue); } -void SAKFileCheckAssistant::finished() { on_startStopPushButton_clicked(); } - -void SAKFileCheckAssistant::clearMessage() { - mClearMessageTimer.stop(); - mMessageLabel->clear(); - mRemainTimeLabel->clear(); +void SAKFileCheckAssistant::changeRemainTime(QString remainTime) +{ + QString str = tr("Remaining time"); + mRemainTimeLabel->setText(QString("%1 %2").arg(str, remainTime)); } -void SAKFileCheckAssistant::on_openPushButton_clicked() { - mFileName = QFileDialog::getOpenFileName(); - mFilePathlineEdit->setText(mFileName); - if (!mFileName.isEmpty()) { - mStartStopPushButton->setEnabled(true); - } - - mCalculatorProgressBar->setValue(0); - mResultLineEdit->clear(); - mMessageLabel->clear(); +void SAKFileCheckAssistant::finished() +{ + on_startStopPushButton_clicked(); } -void SAKFileCheckAssistant::on_algorithmComboBox_currentIndexChanged( - int index) { +void SAKFileCheckAssistant::clearMessage() +{ + mClearMessageTimer.stop(); + mMessageLabel->clear(); + mRemainTimeLabel->clear(); +} + +void SAKFileCheckAssistant::on_openPushButton_clicked() +{ + mFileName = QFileDialog::getOpenFileName(); + mFilePathlineEdit->setText(mFileName); + if (!mFileName.isEmpty()) { + mStartStopPushButton->setEnabled(true); + } + + mCalculatorProgressBar->setValue(0); + mResultLineEdit->clear(); + mMessageLabel->clear(); +} + +void SAKFileCheckAssistant::on_algorithmComboBox_currentIndexChanged(int index) +{ #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - QMetaEnum algorithms = - QMetaEnum::fromType(); + QMetaEnum algorithms = QMetaEnum::fromType(); #else - QMetaEnum algorithms = QMetaEnum::fromType(); + QMetaEnum algorithms = QMetaEnum::fromType(); #endif - mAlgorithm = - static_cast(algorithms.value(index)); - mResultLineEdit->clear(); - mCalculatorProgressBar->setValue(0); + mAlgorithm = static_cast(algorithms.value(index)); + mResultLineEdit->clear(); + mCalculatorProgressBar->setValue(0); } -void SAKFileCheckAssistant::on_startStopPushButton_clicked() { - if (mCalculator) { - mCalculator->blockSignals(true); - mCalculator->requestInterruption(); - mCalculator->exit(); - mCalculator->wait(); - mCalculator->deleteLater(); - mCalculator = Q_NULLPTR; - setUiEnable(true); - mStartStopPushButton->setText(tr("Calculate")); - setUiEnable(true); - } else { - mCalculator = new SAKCryptographicHashCalculator(this); - connect(mCalculator, &QThread::finished, this, - &SAKFileCheckAssistant::finished); - mCalculator->start(); - mStartStopPushButton->setText(tr("StopCalculating")); - setUiEnable(false); - } +void SAKFileCheckAssistant::on_startStopPushButton_clicked() +{ + if (mCalculator) { + mCalculator->blockSignals(true); + mCalculator->requestInterruption(); + mCalculator->exit(); + mCalculator->wait(); + mCalculator->deleteLater(); + mCalculator = Q_NULLPTR; + setUiEnable(true); + mStartStopPushButton->setText(tr("Calculate")); + setUiEnable(true); + } else { + mCalculator = new SAKCryptographicHashCalculator(this); + connect(mCalculator, &QThread::finished, this, &SAKFileCheckAssistant::finished); + mCalculator->start(); + mStartStopPushButton->setText(tr("StopCalculating")); + setUiEnable(false); + } } -void SAKFileCheckAssistant::on_upperCheckBox_clicked() { - QString temp = mResultLineEdit->text(); - if (mUpperCheckBox->isChecked()) { - mResultLineEdit->setText(temp.toUpper()); - } else { - mResultLineEdit->setText(temp.toLower()); - } +void SAKFileCheckAssistant::on_upperCheckBox_clicked() +{ + QString temp = mResultLineEdit->text(); + if (mUpperCheckBox->isChecked()) { + mResultLineEdit->setText(temp.toUpper()); + } else { + mResultLineEdit->setText(temp.toLower()); + } } diff --git a/src/assistants/filecheck/src/sakfilecheckassistant.h b/src/assistants/filecheck/src/sakfilecheckassistant.h index 0c4cf428..c7147697 100644 --- a/src/assistants/filecheck/src/sakfilecheckassistant.h +++ b/src/assistants/filecheck/src/sakfilecheckassistant.h @@ -25,67 +25,68 @@ class SAKFileCheckAssistant; } class SAKCryptographicHashCalculator; -class SAKFileCheckAssistant : public QWidget { - Q_OBJECT - public: - Q_INVOKABLE SAKFileCheckAssistant(QWidget* parent = Q_NULLPTR); - ~SAKFileCheckAssistant(); +class SAKFileCheckAssistant : public QWidget +{ + Q_OBJECT +public: + Q_INVOKABLE SAKFileCheckAssistant(QWidget* parent = Q_NULLPTR); + ~SAKFileCheckAssistant(); - void setUiEnable(bool enable); - QString fileName(); - QCryptographicHash::Algorithm algorithm(); - void updateResult(QByteArray result); - void outputMessage(QString msg, bool isErrMsg = false); - void updateProgressBar(int currentValue); - void changeRemainTime(QString remainTime); + void setUiEnable(bool enable); + QString fileName(); + QCryptographicHash::Algorithm algorithm(); + void updateResult(QByteArray result); + void outputMessage(QString msg, bool isErrMsg = false); + void updateProgressBar(int currentValue); + void changeRemainTime(QString remainTime); #if QT_VERSION < QT_VERSION_CHECK(5, 9, 0) - // The QtCryptographicHashCalculator::Algorithm enum is not export with Q_ENUM - // in Qt5.6.0 - enum Algorithm { + // The QtCryptographicHashCalculator::Algorithm enum is not export with Q_ENUM + // in Qt5.6.0 + enum Algorithm { #ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1 - Md4, - Md5, + Md4, + Md5, #endif - Sha1 = 2, + Sha1 = 2, #ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1 - Sha224, - Sha256, - Sha384, - Sha512, - Sha3_224, - Sha3_256, - Sha3_384, - Sha3_512 + Sha224, + Sha256, + Sha384, + Sha512, + Sha3_224, + Sha3_256, + Sha3_384, + Sha3_512 #endif - }; - Q_ENUM(Algorithm) + }; + Q_ENUM(Algorithm) #endif - private: - void finished(); - void clearMessage(); +private: + void finished(); + void clearMessage(); - private: - QString mFileName; - QCryptographicHash::Algorithm mAlgorithm; - SAKCryptographicHashCalculator* mCalculator; - QTimer mClearMessageTimer; +private: + QString mFileName; + QCryptographicHash::Algorithm mAlgorithm; + SAKCryptographicHashCalculator* mCalculator; + QTimer mClearMessageTimer; - private: - Ui::SAKFileCheckAssistant* mUi; - QLineEdit* mFilePathlineEdit; - QComboBox* mAlgorithmComboBox; - QLineEdit* mResultLineEdit; - QProgressBar* mCalculatorProgressBar; - QPushButton* mOpenPushButton; - QPushButton* mStartStopPushButton; - QCheckBox* mUpperCheckBox; - QLabel* mMessageLabel; - QLabel* mRemainTimeLabel; - private slots: - void on_openPushButton_clicked(); - void on_algorithmComboBox_currentIndexChanged(int index); - void on_startStopPushButton_clicked(); - void on_upperCheckBox_clicked(); +private: + Ui::SAKFileCheckAssistant* mUi; + QLineEdit* mFilePathlineEdit; + QComboBox* mAlgorithmComboBox; + QLineEdit* mResultLineEdit; + QProgressBar* mCalculatorProgressBar; + QPushButton* mOpenPushButton; + QPushButton* mStartStopPushButton; + QCheckBox* mUpperCheckBox; + QLabel* mMessageLabel; + QLabel* mRemainTimeLabel; +private slots: + void on_openPushButton_clicked(); + void on_algorithmComboBox_currentIndexChanged(int index); + void on_startStopPushButton_clicked(); + void on_upperCheckBox_clicked(); }; #endif diff --git a/src/assistants/number/main.cc b/src/assistants/number/main.cc index c5ea907f..a7c0b822 100644 --- a/src/assistants/number/main.cc +++ b/src/assistants/number/main.cc @@ -12,11 +12,15 @@ #include "sakcommonmainwindow.h" #include "saknumberassistant.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("Number Assistant"), "SAK.NumberAssistant"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app + = CreateCommonMainWindowApplication(argc, + argv, + QObject::tr("Number Assistant"), + "SAK.NumberAssistant"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/assistants/number/src/saknumberassistant.cc b/src/assistants/number/src/saknumberassistant.cc index 30899527..2fbfe5d5 100644 --- a/src/assistants/number/src/saknumberassistant.cc +++ b/src/assistants/number/src/saknumberassistant.cc @@ -14,151 +14,172 @@ #include "ui_saknumberassistant.h" SAKNumberAssistant::SAKNumberAssistant(QWidget* parent) - : QWidget(parent), ui_(new Ui::SAKNumberAssistant) { - ui_->setupUi(this); - common_interface_ = new SAKCommonInterface(this); - common_interface_->setLineEditValidator(ui_->rawDataLineEdit, - SAKCommonInterface::ValidatorFloat); - - connect(ui_->hexRawDataCheckBox, &QCheckBox::clicked, this, - &SAKNumberAssistant::OnHexRawDataCheckBoxClicked); - connect(ui_->createPushButton, &QPushButton::clicked, this, - &SAKNumberAssistant::OnCreatePushButtonClicked); - connect(ui_->rawDataLineEdit, &QLineEdit::textChanged, this, - &SAKNumberAssistant::OnRawDataLineEditTextChanged); - connect(ui_->bigEndianCheckBox, &QCheckBox::clicked, this, - &SAKNumberAssistant::OnBigEndianCheckBoxClicked); - connect(ui_->floatRadioButton, &QRadioButton::clicked, this, - &SAKNumberAssistant::OnFloatRadioButtonClicked); - connect(ui_->doubleRadioButton, &QRadioButton::clicked, this, - &SAKNumberAssistant::OnDoubleRadioButtonClicked); - - OnCreatePushButtonClicked(); -} - -SAKNumberAssistant::~SAKNumberAssistant() { delete ui_; } - -void SAKNumberAssistant::FixedLength(QStringList& stringList) { - if (ui_->bigEndianCheckBox->isChecked()) { - if (ui_->floatRadioButton->isChecked()) { - if (stringList.length() < int(sizeof(float))) { - int len = int(sizeof(float)) - stringList.length(); - for (int i = 0; i < len; i++) { - stringList.prepend(QString(" 00")); - } - } - } else { - if (stringList.length() < int(sizeof(double))) { - int len = int(sizeof(double)) - stringList.length(); - for (int i = 0; i < len; i++) { - stringList.prepend(QString(" 00")); - } - } - } - } else { - if (ui_->floatRadioButton->isChecked()) { - if (stringList.length() < int(sizeof(float))) { - int len = int(sizeof(float)) - stringList.length(); - for (int i = 0; i < len; i++) { - stringList.append(QString(" 00")); - } - } - } else { - if (stringList.length() < int(sizeof(double))) { - int len = int(sizeof(double)) - stringList.length(); - for (int i = 0; i < len; i++) { - stringList.append(QString(" 00")); - } - } - } - } -} - -void SAKNumberAssistant::OnHexRawDataCheckBoxClicked() { - ui_->rawDataLineEdit->clear(); - if (ui_->hexRawDataCheckBox->isChecked()) { - common_interface_->setLineEditValidator(ui_->rawDataLineEdit, - SAKCommonInterface::ValidatorHex); - } else { + : QWidget(parent) + , ui_(new Ui::SAKNumberAssistant) +{ + ui_->setupUi(this); + common_interface_ = new SAKCommonInterface(this); common_interface_->setLineEditValidator(ui_->rawDataLineEdit, SAKCommonInterface::ValidatorFloat); - } + + connect(ui_->hexRawDataCheckBox, + &QCheckBox::clicked, + this, + &SAKNumberAssistant::OnHexRawDataCheckBoxClicked); + connect(ui_->createPushButton, + &QPushButton::clicked, + this, + &SAKNumberAssistant::OnCreatePushButtonClicked); + connect(ui_->rawDataLineEdit, + &QLineEdit::textChanged, + this, + &SAKNumberAssistant::OnRawDataLineEditTextChanged); + connect(ui_->bigEndianCheckBox, + &QCheckBox::clicked, + this, + &SAKNumberAssistant::OnBigEndianCheckBoxClicked); + connect(ui_->floatRadioButton, + &QRadioButton::clicked, + this, + &SAKNumberAssistant::OnFloatRadioButtonClicked); + connect(ui_->doubleRadioButton, + &QRadioButton::clicked, + this, + &SAKNumberAssistant::OnDoubleRadioButtonClicked); + + OnCreatePushButtonClicked(); } -void SAKNumberAssistant::OnCreatePushButtonClicked() { - if (ui_->hexRawDataCheckBox->isChecked()) { - ui_->rawDataLineEdit->setMaxLength(ui_->floatRadioButton->isChecked() ? 11 - : 23); - QString rawDataString = ui_->rawDataLineEdit->text().trimmed(); - QStringList rawDataStringList = rawDataString.split(' '); - FixedLength(rawDataStringList); +SAKNumberAssistant::~SAKNumberAssistant() +{ + delete ui_; +} - QByteArray data; - for (int i = 0; i < rawDataStringList.length(); i++) { - bool isBigEndian = ui_->bigEndianCheckBox->isChecked(); - quint8 value = - quint8(rawDataStringList - .at(isBigEndian ? i : rawDataStringList.length() - 1 - i) - .toInt()); - data.append(reinterpret_cast(&value), 1); - } - - if (ui_->floatRadioButton->isChecked()) { - float* f = reinterpret_cast(data.data()); - ui_->friendlyCookedDataLineEdit->setText(QString("%1").arg(*f)); - data = SAKInterface::arrayToHex(data, ' '); - ui_->hexCookedDataLineEdit->setText(QString(data)); - } else { - double* d = reinterpret_cast(data.data()); - ui_->friendlyCookedDataLineEdit->setText(QString("%1").arg(*d)); - data = SAKInterface::arrayToHex(data, ' '); - ui_->hexCookedDataLineEdit->setText(QString(data)); - } - } else { - QByteArray data; - ui_->rawDataLineEdit->setMaxLength(INT_MAX); - if (ui_->floatRadioButton->isChecked()) { - float value = ui_->rawDataLineEdit->text().trimmed().toFloat(); - if (ui_->bigEndianCheckBox->isChecked()) { - // To big endian - float temp = value; - quint8* ptr = reinterpret_cast(&value); - for (int i = 0; i < int(sizeof(value)); i++) { - ptr[i] = reinterpret_cast(&temp)[int(sizeof(value)) - 1 - i]; +void SAKNumberAssistant::FixedLength(QStringList& stringList) +{ + if (ui_->bigEndianCheckBox->isChecked()) { + if (ui_->floatRadioButton->isChecked()) { + if (stringList.length() < int(sizeof(float))) { + int len = int(sizeof(float)) - stringList.length(); + for (int i = 0; i < len; i++) { + stringList.prepend(QString(" 00")); + } + } + } else { + if (stringList.length() < int(sizeof(double))) { + int len = int(sizeof(double)) - stringList.length(); + for (int i = 0; i < len; i++) { + stringList.prepend(QString(" 00")); + } + } } - } - data.append(reinterpret_cast(&value), sizeof(value)); } else { - double value = ui_->rawDataLineEdit->text().trimmed().toFloat(); - if (ui_->bigEndianCheckBox->isChecked()) { - // To big endian - double temp = value; - quint8* ptr = reinterpret_cast(&value); - for (int i = 0; i < int(sizeof(value)); i++) { - ptr[i] = reinterpret_cast(&temp)[int(sizeof(value)) - 1 - i]; + if (ui_->floatRadioButton->isChecked()) { + if (stringList.length() < int(sizeof(float))) { + int len = int(sizeof(float)) - stringList.length(); + for (int i = 0; i < len; i++) { + stringList.append(QString(" 00")); + } + } + } else { + if (stringList.length() < int(sizeof(double))) { + int len = int(sizeof(double)) - stringList.length(); + for (int i = 0; i < len; i++) { + stringList.append(QString(" 00")); + } + } } - } - data.append(reinterpret_cast(&value), sizeof(value)); } - ui_->friendlyCookedDataLineEdit->setText(ui_->rawDataLineEdit->text()); - data = SAKInterface::arrayToHex(data, ' '); - ui_->hexCookedDataLineEdit->setText(QString(data)); - } } -void SAKNumberAssistant::OnRawDataLineEditTextChanged(const QString& text) { - Q_UNUSED(text); - OnCreatePushButtonClicked(); +void SAKNumberAssistant::OnHexRawDataCheckBoxClicked() +{ + ui_->rawDataLineEdit->clear(); + if (ui_->hexRawDataCheckBox->isChecked()) { + common_interface_->setLineEditValidator(ui_->rawDataLineEdit, + SAKCommonInterface::ValidatorHex); + } else { + common_interface_->setLineEditValidator(ui_->rawDataLineEdit, + SAKCommonInterface::ValidatorFloat); + } } -void SAKNumberAssistant::OnBigEndianCheckBoxClicked() { - OnCreatePushButtonClicked(); +void SAKNumberAssistant::OnCreatePushButtonClicked() +{ + if (ui_->hexRawDataCheckBox->isChecked()) { + ui_->rawDataLineEdit->setMaxLength(ui_->floatRadioButton->isChecked() ? 11 : 23); + QString rawDataString = ui_->rawDataLineEdit->text().trimmed(); + QStringList rawDataStringList = rawDataString.split(' '); + FixedLength(rawDataStringList); + + QByteArray data; + for (int i = 0; i < rawDataStringList.length(); i++) { + bool isBigEndian = ui_->bigEndianCheckBox->isChecked(); + quint8 value = quint8( + rawDataStringList.at(isBigEndian ? i : rawDataStringList.length() - 1 - i).toInt()); + data.append(reinterpret_cast(&value), 1); + } + + if (ui_->floatRadioButton->isChecked()) { + float* f = reinterpret_cast(data.data()); + ui_->friendlyCookedDataLineEdit->setText(QString("%1").arg(*f)); + data = SAKInterface::arrayToHex(data, ' '); + ui_->hexCookedDataLineEdit->setText(QString(data)); + } else { + double* d = reinterpret_cast(data.data()); + ui_->friendlyCookedDataLineEdit->setText(QString("%1").arg(*d)); + data = SAKInterface::arrayToHex(data, ' '); + ui_->hexCookedDataLineEdit->setText(QString(data)); + } + } else { + QByteArray data; + ui_->rawDataLineEdit->setMaxLength(INT_MAX); + if (ui_->floatRadioButton->isChecked()) { + float value = ui_->rawDataLineEdit->text().trimmed().toFloat(); + if (ui_->bigEndianCheckBox->isChecked()) { + // To big endian + float temp = value; + quint8* ptr = reinterpret_cast(&value); + for (int i = 0; i < int(sizeof(value)); i++) { + ptr[i] = reinterpret_cast(&temp)[int(sizeof(value)) - 1 - i]; + } + } + data.append(reinterpret_cast(&value), sizeof(value)); + } else { + double value = ui_->rawDataLineEdit->text().trimmed().toFloat(); + if (ui_->bigEndianCheckBox->isChecked()) { + // To big endian + double temp = value; + quint8* ptr = reinterpret_cast(&value); + for (int i = 0; i < int(sizeof(value)); i++) { + ptr[i] = reinterpret_cast(&temp)[int(sizeof(value)) - 1 - i]; + } + } + data.append(reinterpret_cast(&value), sizeof(value)); + } + ui_->friendlyCookedDataLineEdit->setText(ui_->rawDataLineEdit->text()); + data = SAKInterface::arrayToHex(data, ' '); + ui_->hexCookedDataLineEdit->setText(QString(data)); + } } -void SAKNumberAssistant::OnFloatRadioButtonClicked() { - OnCreatePushButtonClicked(); +void SAKNumberAssistant::OnRawDataLineEditTextChanged(const QString& text) +{ + Q_UNUSED(text); + OnCreatePushButtonClicked(); } -void SAKNumberAssistant::OnDoubleRadioButtonClicked() { - OnCreatePushButtonClicked(); +void SAKNumberAssistant::OnBigEndianCheckBoxClicked() +{ + OnCreatePushButtonClicked(); +} + +void SAKNumberAssistant::OnFloatRadioButtonClicked() +{ + OnCreatePushButtonClicked(); +} + +void SAKNumberAssistant::OnDoubleRadioButtonClicked() +{ + OnCreatePushButtonClicked(); } diff --git a/src/assistants/number/src/saknumberassistant.h b/src/assistants/number/src/saknumberassistant.h index 09200ea1..9ee1ace6 100644 --- a/src/assistants/number/src/saknumberassistant.h +++ b/src/assistants/number/src/saknumberassistant.h @@ -17,28 +17,29 @@ class SAKNumberAssistant; } class SAKCommonInterface; -class SAKNumberAssistant : public QWidget { - Q_OBJECT - public: - Q_INVOKABLE SAKNumberAssistant(QWidget* parent = Q_NULLPTR); - ~SAKNumberAssistant(); +class SAKNumberAssistant : public QWidget +{ + Q_OBJECT +public: + Q_INVOKABLE SAKNumberAssistant(QWidget* parent = Q_NULLPTR); + ~SAKNumberAssistant(); - private: - SAKCommonInterface* common_interface_; +private: + SAKCommonInterface* common_interface_; - private: - void FixedLength(QStringList& stringList); +private: + void FixedLength(QStringList& stringList); - private: - Ui::SAKNumberAssistant* ui_; +private: + Ui::SAKNumberAssistant* ui_; - private slots: - void OnHexRawDataCheckBoxClicked(); - void OnCreatePushButtonClicked(); - void OnRawDataLineEditTextChanged(const QString& text); - void OnBigEndianCheckBoxClicked(); - void OnFloatRadioButtonClicked(); - void OnDoubleRadioButtonClicked(); +private slots: + void OnHexRawDataCheckBoxClicked(); + void OnCreatePushButtonClicked(); + void OnRawDataLineEditTextChanged(const QString& text); + void OnBigEndianCheckBoxClicked(); + void OnFloatRadioButtonClicked(); + void OnDoubleRadioButtonClicked(); }; -#endif // SAKNUMBERASSISTANT_H +#endif // SAKNUMBERASSISTANT_H diff --git a/src/assistants/sakassistantsfactory.cc b/src/assistants/sakassistantsfactory.cc index bb0be3bb..c96063ff 100644 --- a/src/assistants/sakassistantsfactory.cc +++ b/src/assistants/sakassistantsfactory.cc @@ -10,8 +10,8 @@ #include "sakassistantsfactory.h" -#include #include +#include #ifdef SAK_IMPORT_MODULE_FILECHECKASSISTANT #include "sakfilecheckassistant.h" @@ -35,65 +35,65 @@ #include "sakbase64assistant.h" #endif -SAKAssistantsFactory::SAKAssistantsFactory(QObject* parent) : QObject(parent) { +SAKAssistantsFactory::SAKAssistantsFactory(QObject* parent) + : QObject(parent) +{ #ifdef SAK_IMPORT_MODULE_FILECHECKASSISTANT - RegisterAssistantMetaType(kCrcAssistant, - tr("CRC Assistant")); + RegisterAssistantMetaType(kCrcAssistant, tr("CRC Assistant")); #endif #ifdef SAK_IMPORT_MODULE_CRCASSISTANT - RegisterAssistantMetaType(kFileCheckAssistant, - tr("File Check Assistant")); + RegisterAssistantMetaType(kFileCheckAssistant, + tr("File Check Assistant")); #endif #ifdef SAK_IMPORT_MODULE_ASCIIASSISTANT - RegisterAssistantMetaType(kAsciiAssistant, - tr("ASCII Assistant")); + RegisterAssistantMetaType(kAsciiAssistant, tr("ASCII Assistant")); #endif #ifdef SAK_IMPORT_MODULE_FLOATASSISTANT - RegisterAssistantMetaType(kFileCheckAssistant, - tr("Number Assistant")); + RegisterAssistantMetaType(kFileCheckAssistant, tr("Number Assistant")); #endif #ifdef SAK_IMPORT_MODULE_STRINGASSISTANT - RegisterAssistantMetaType(kStringAssistant, - tr("String Assistant")); + RegisterAssistantMetaType(kStringAssistant, tr("String Assistant")); #endif #ifdef SAK_IMPORT_MODULE_BROADCASTASSISTANT - RegisterAssistantMetaType(kBroadcastAssistant, - tr("Broadcast Assistant")); + RegisterAssistantMetaType(kBroadcastAssistant, tr("Broadcast Assistant")); #endif #ifdef SAK_IMPORT_MODULE_BASE64ASSISTANT - RegisterAssistantMetaType(kBase64Assistant, - tr("Base64 Assistant")); + RegisterAssistantMetaType(kBase64Assistant, tr("Base64 Assistant")); #endif } -QList SAKAssistantsFactory::SupportedAssistants() { - return type_name_map_.keys(); +QList SAKAssistantsFactory::SupportedAssistants() +{ + return type_name_map_.keys(); } -QString SAKAssistantsFactory::GetAssistantName(int type) const { - if (type_name_map_.contains(type)) { - return type_name_map_.value(type); - } +QString SAKAssistantsFactory::GetAssistantName(int type) const +{ + if (type_name_map_.contains(type)) { + return type_name_map_.value(type); + } - QString name = QString("UnknowType(%1)").arg(type); - return name; + QString name = QString("UnknowType(%1)").arg(type); + return name; } -SAKAssistantsFactory* SAKAssistantsFactory::Instance() { - static SAKAssistantsFactory* factory = nullptr; - if (!factory) { - factory = new SAKAssistantsFactory(qApp); - } +SAKAssistantsFactory* SAKAssistantsFactory::Instance() +{ + static SAKAssistantsFactory* factory = nullptr; + if (!factory) { + factory = new SAKAssistantsFactory(qApp); + } - return factory; + return factory; } -QWidget* SAKAssistantsFactory::NewAssistant(int type) { - if (meta_object_map_.contains(type)) { - const QMetaObject meta_obj = meta_object_map_.value(type); - QObject* obj = meta_obj.newInstance(); - return qobject_cast(obj); - } +QWidget* SAKAssistantsFactory::NewAssistant(int type) +{ + if (meta_object_map_.contains(type)) { + const QMetaObject meta_obj = meta_object_map_.value(type); + QObject* obj = meta_obj.newInstance(); + return qobject_cast(obj); + } - return Q_NULLPTR; + return Q_NULLPTR; } diff --git a/src/assistants/sakassistantsfactory.h b/src/assistants/sakassistantsfactory.h index 3204a646..ade883f3 100644 --- a/src/assistants/sakassistantsfactory.h +++ b/src/assistants/sakassistantsfactory.h @@ -13,39 +13,41 @@ #include #include -class SAKAssistantsFactory : QObject { - Q_OBJECT - private: - SAKAssistantsFactory(QObject* parent = Q_NULLPTR); +class SAKAssistantsFactory : QObject +{ + Q_OBJECT +private: + SAKAssistantsFactory(QObject* parent = Q_NULLPTR); - private: - enum Assistants { - kCrcAssistant, - kFileCheckAssistant, - kAsciiAssistant, - kNumberAssistant, - kStringAssistant, - kBroadcastAssistant, - kBase64Assistant - }; +private: + enum Assistants { + kCrcAssistant, + kFileCheckAssistant, + kAsciiAssistant, + kNumberAssistant, + kStringAssistant, + kBroadcastAssistant, + kBase64Assistant + }; - public: - static SAKAssistantsFactory* Instance(); +public: + static SAKAssistantsFactory* Instance(); - QList SupportedAssistants(); - QString GetAssistantName(int type) const; - QWidget* NewAssistant(int type); + QList SupportedAssistants(); + QString GetAssistantName(int type) const; + QWidget* NewAssistant(int type); - private: - QMap type_name_map_; - QMap meta_object_map_; +private: + QMap type_name_map_; + QMap meta_object_map_; - private: - template - void RegisterAssistantMetaType(int type, const QString& assistant_name) { - type_name_map_.insert(type, assistant_name); - meta_object_map_.insert(type, T::staticMetaObject); - } +private: + template + void RegisterAssistantMetaType(int type, const QString& assistant_name) + { + type_name_map_.insert(type, assistant_name); + meta_object_map_.insert(type, T::staticMetaObject); + } }; -#endif // SAKASSISTANTSFACTORY_H +#endif // SAKASSISTANTSFACTORY_H diff --git a/src/assistants/string/main.cc b/src/assistants/string/main.cc index 27fe7f40..1a14f355 100644 --- a/src/assistants/string/main.cc +++ b/src/assistants/string/main.cc @@ -12,11 +12,15 @@ #include "sakcommonmainwindow.h" #include "sakstringassistant.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("String Assistant"), "SAK.StringAssistant"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app + = CreateCommonMainWindowApplication(argc, + argv, + QObject::tr("String Assistant"), + "SAK.StringAssistant"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/assistants/string/src/sakstringassistant.cc b/src/assistants/string/src/sakstringassistant.cc index 8ab24e7f..d1f5ae97 100644 --- a/src/assistants/string/src/sakstringassistant.cc +++ b/src/assistants/string/src/sakstringassistant.cc @@ -13,65 +13,73 @@ #include "ui_sakstringassistant.h" SAKStringAssistant::SAKStringAssistant(QWidget* parent) - : QWidget(parent), ui_(new Ui::SAKStringAssistant) { - ui_->setupUi(this); - SAKCommonDataStructure::setComboBoxTextInputFormat(ui_->inputFormatComboBox); - SAKCommonDataStructure::setComboBoxTextOutputFormat( - ui_->outputFormatComboBox); + : QWidget(parent) + , ui_(new Ui::SAKStringAssistant) +{ + ui_->setupUi(this); + SAKCommonDataStructure::setComboBoxTextInputFormat(ui_->inputFormatComboBox); + SAKCommonDataStructure::setComboBoxTextOutputFormat(ui_->outputFormatComboBox); - connect(ui_->textEdit, &QTextEdit::textChanged, this, - &SAKStringAssistant::OnTextEditTextChanged); - connect(ui_->inputFormatComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKStringAssistant::OnInputFormatComboBoxCurrentIndexChanged); - connect(ui_->createPushButton, &QPushButton::clicked, this, - &SAKStringAssistant::OnCreatePushButtonClicked); - connect(ui_->outputFormatComboBox, &QComboBox::currentTextChanged, this, - &SAKStringAssistant::OnOutputFormatComboBoxCurrentTextChanged); + connect(ui_->textEdit, + &QTextEdit::textChanged, + this, + &SAKStringAssistant::OnTextEditTextChanged); + connect(ui_->inputFormatComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKStringAssistant::OnInputFormatComboBoxCurrentIndexChanged); + connect(ui_->createPushButton, + &QPushButton::clicked, + this, + &SAKStringAssistant::OnCreatePushButtonClicked); + connect(ui_->outputFormatComboBox, + &QComboBox::currentTextChanged, + this, + &SAKStringAssistant::OnOutputFormatComboBoxCurrentTextChanged); } -SAKStringAssistant::~SAKStringAssistant() { delete ui_; } +SAKStringAssistant::~SAKStringAssistant() +{ + delete ui_; +} -void SAKStringAssistant::OnTextEditTextChanged() { - if (!ui_->textEdit->blockSignals(true)) { - QString inputString = ui_->textEdit->toPlainText(); - auto inputFormat = - static_cast( +void SAKStringAssistant::OnTextEditTextChanged() +{ + if (!ui_->textEdit->blockSignals(true)) { + QString inputString = ui_->textEdit->toPlainText(); + auto inputFormat = static_cast( ui_->inputFormatComboBox->currentData().toInt()); - QString cookedString = - SAKCommonDataStructure::formattingString(inputString, inputFormat); - ui_->textEdit->setText(cookedString); - ui_->textEdit->moveCursor(QTextCursor::End); - ui_->textEdit->blockSignals(false); + QString cookedString = SAKCommonDataStructure::formattingString(inputString, inputFormat); + ui_->textEdit->setText(cookedString); + ui_->textEdit->moveCursor(QTextCursor::End); + ui_->textEdit->blockSignals(false); + OnCreatePushButtonClicked(); + } else { + Q_ASSERT_X(false, __FUNCTION__, "Oh, No!"); + } +} + +void SAKStringAssistant::OnInputFormatComboBoxCurrentIndexChanged(int index) +{ + Q_UNUSED(index); + ui_->textEdit->clear(); OnCreatePushButtonClicked(); - } else { - Q_ASSERT_X(false, __FUNCTION__, "Oh, No!"); - } } -void SAKStringAssistant::OnInputFormatComboBoxCurrentIndexChanged(int index) { - Q_UNUSED(index); - ui_->textEdit->clear(); - OnCreatePushButtonClicked(); +void SAKStringAssistant::OnCreatePushButtonClicked() +{ + QString inputString = ui_->textEdit->toPlainText(); + auto inputFormat = static_cast( + ui_->inputFormatComboBox->currentData().toInt()); + QByteArray inputArray = SAKCommonDataStructure::stringToByteArray(inputString, inputFormat); + auto outputFormat = static_cast( + ui_->outputFormatComboBox->currentData().toInt()); + auto outputString = SAKCommonDataStructure::byteArrayToString(inputArray, outputFormat); + ui_->textBrowser->setText(outputString); } -void SAKStringAssistant::OnCreatePushButtonClicked() { - QString inputString = ui_->textEdit->toPlainText(); - auto inputFormat = - static_cast( - ui_->inputFormatComboBox->currentData().toInt()); - QByteArray inputArray = - SAKCommonDataStructure::stringToByteArray(inputString, inputFormat); - auto outputFormat = - static_cast( - ui_->outputFormatComboBox->currentData().toInt()); - auto outputString = - SAKCommonDataStructure::byteArrayToString(inputArray, outputFormat); - ui_->textBrowser->setText(outputString); -} - -void SAKStringAssistant::OnOutputFormatComboBoxCurrentTextChanged( - const QString& text) { - Q_UNUSED(text); - OnCreatePushButtonClicked(); +void SAKStringAssistant::OnOutputFormatComboBoxCurrentTextChanged(const QString& text) +{ + Q_UNUSED(text); + OnCreatePushButtonClicked(); } diff --git a/src/assistants/string/src/sakstringassistant.h b/src/assistants/string/src/sakstringassistant.h index 7611c425..52b64afd 100644 --- a/src/assistants/string/src/sakstringassistant.h +++ b/src/assistants/string/src/sakstringassistant.h @@ -15,20 +15,21 @@ namespace Ui { class SAKStringAssistant; } -class SAKStringAssistant : public QWidget { - Q_OBJECT - public: - Q_INVOKABLE SAKStringAssistant(QWidget* parent = Q_NULLPTR); - ~SAKStringAssistant(); +class SAKStringAssistant : public QWidget +{ + Q_OBJECT +public: + Q_INVOKABLE SAKStringAssistant(QWidget* parent = Q_NULLPTR); + ~SAKStringAssistant(); - private: - Ui::SAKStringAssistant* ui_; +private: + Ui::SAKStringAssistant* ui_; - private slots: - void OnTextEditTextChanged(); - void OnInputFormatComboBoxCurrentIndexChanged(int index); - void OnCreatePushButtonClicked(); - void OnOutputFormatComboBoxCurrentTextChanged(const QString& text); +private slots: + void OnTextEditTextChanged(); + void OnInputFormatComboBoxCurrentIndexChanged(int index); + void OnCreatePushButtonClicked(); + void OnOutputFormatComboBoxCurrentTextChanged(const QString& text); }; -#endif // SAKSTRINGASSISTANT_H +#endif // SAKSTRINGASSISTANT_H diff --git a/src/canbusstudio/canbusstudio/sakcanbus.cc b/src/canbusstudio/canbusstudio/sakcanbus.cc index b0b5cb36..ba24dbf8 100644 --- a/src/canbusstudio/canbusstudio/sakcanbus.cc +++ b/src/canbusstudio/canbusstudio/sakcanbus.cc @@ -9,6 +9,8 @@ ******************************************************************************/ #include "sakcanbus.h" -SAKCanBus::SAKCanBus(QObject* parent) : QThread(parent) {} +SAKCanBus::SAKCanBus(QObject* parent) + : QThread(parent) +{} SAKCanBus::~SAKCanBus() {} diff --git a/src/canbusstudio/canbusstudioui/sakcanbusstudioui.cc b/src/canbusstudio/canbusstudioui/sakcanbusstudioui.cc index cae9f3eb..3cd5966b 100644 --- a/src/canbusstudio/canbusstudioui/sakcanbusstudioui.cc +++ b/src/canbusstudio/canbusstudioui/sakcanbusstudioui.cc @@ -23,468 +23,521 @@ const QLoggingCategory gLC("sak.canstudio"); SAKCanBusUi::SAKCanBusUi(QWidget* parent) - : QWidget{parent}, ui(new Ui::SAKCanBusUi), mDevice(Q_NULLPTR) { - if (!mSettings) { - mSettings = SAKSettings::instance(); - } + : QWidget{parent} + , ui(new Ui::SAKCanBusUi) + , mDevice(Q_NULLPTR) +{ + if (!mSettings) { + mSettings = SAKSettings::instance(); + } - ui->setupUi(this); - initUi(); - initSetting(); + ui->setupUi(this); + initUi(); + initSetting(); - // Device is not connected. - updateUiState(false); + // Device is not connected. + updateUiState(false); } -SAKCanBusUi::~SAKCanBusUi() { delete ui; } - -void SAKCanBusUi::initUi() { - initUiSelectPlugin(); - initUiSpecifyConfiguration(); - initUiCanFrame(); - initUiSendCanFrame(); +SAKCanBusUi::~SAKCanBusUi() +{ + delete ui; } -void SAKCanBusUi::initUiSelectPlugin() { - ui->pluginComboBox->clear(); - ui->pluginComboBox->addItems(QCanBus::instance()->plugins()); - ui->disconnectPushButton->setEnabled(false); - ui->connectPushButton->setEnabled(true); - - connect(ui->pluginComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKCanBusUi::onPluginChanged); - connect(ui->disconnectPushButton, &QPushButton::clicked, this, - &SAKCanBusUi::onDisconnectClicked); - connect(ui->connectPushButton, &QPushButton::clicked, this, - &SAKCanBusUi::onConnectClicked); +void SAKCanBusUi::initUi() +{ + initUiSelectPlugin(); + initUiSpecifyConfiguration(); + initUiCanFrame(); + initUiSendCanFrame(); } -void SAKCanBusUi::initUiSpecifyConfiguration() { - setOptions(ui->loopbackComboBox, true); - setOptions(ui->receivOwnComboBox, true); - setOptions(ui->canFdComboBox, false); - setBitRates(ui->bitrateComboBox, false); - setBitRates(ui->dataBitrateComboBox, true); +void SAKCanBusUi::initUiSelectPlugin() +{ + ui->pluginComboBox->clear(); + ui->pluginComboBox->addItems(QCanBus::instance()->plugins()); + ui->disconnectPushButton->setEnabled(false); + ui->connectPushButton->setEnabled(true); - ui->interfaceNameComboBox->lineEdit()->setPlaceholderText(tr("can0")); - - connect(ui->customConfigurationCheckBox, &QCheckBox::clicked, this, - &SAKCanBusUi::onCustomConfigurationChanged); - connect(ui->loopbackComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKCanBusUi::onLoopbackIndexChanged); - connect(ui->receivOwnComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKCanBusUi::onReceiveOwnIndexChanged); - connect(ui->canFdComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKCanBusUi::onCanFdIndexChanged); - connect(ui->bitrateComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKCanBusUi::onBitrateChanged); - connect(ui->dataBitrateComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKCanBusUi::onDataBitrateChanged); - connect(ui->customBitrateCheckBox, &QCheckBox::clicked, this, - &SAKCanBusUi::onCustomBitrateChanged); - connect(ui->customDataBitrateCheckBox, &QCheckBox::clicked, this, - &SAKCanBusUi::onCustomDataBitrateChanged); + connect(ui->pluginComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKCanBusUi::onPluginChanged); + connect(ui->disconnectPushButton, + &QPushButton::clicked, + this, + &SAKCanBusUi::onDisconnectClicked); + connect(ui->connectPushButton, &QPushButton::clicked, this, &SAKCanBusUi::onConnectClicked); } -void SAKCanBusUi::initUiCanFrame() { - ui->frameTypeComboBox->clear(); - ui->frameTypeComboBox->addItem(tr("DataFrame"), QCanBusFrame::DataFrame); - ui->frameTypeComboBox->addItem(tr("ErrorFrame"), QCanBusFrame::ErrorFrame); - ui->frameTypeComboBox->addItem(tr("RemoteRequestFrame"), - QCanBusFrame::RemoteRequestFrame); +void SAKCanBusUi::initUiSpecifyConfiguration() +{ + setOptions(ui->loopbackComboBox, true); + setOptions(ui->receivOwnComboBox, true); + setOptions(ui->canFdComboBox, false); + setBitRates(ui->bitrateComboBox, false); + setBitRates(ui->dataBitrateComboBox, true); - connect(ui->frameTypeComboBox, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKCanBusUi::onFrameTypeChanged); - connect(ui->extendedFormatCheckBox, &QCheckBox::clicked, this, - &SAKCanBusUi::onExtendedFormatChanged); - connect(ui->flexibleDataRateCheckBox, &QCheckBox::clicked, this, - &SAKCanBusUi::onFlexibleDataRateChanged); - connect(ui->bitrateSwitchCheckBox, &QCheckBox::clicked, this, - &SAKCanBusUi::onBitrateSwitchChanged); + ui->interfaceNameComboBox->lineEdit()->setPlaceholderText(tr("can0")); + + connect(ui->customConfigurationCheckBox, + &QCheckBox::clicked, + this, + &SAKCanBusUi::onCustomConfigurationChanged); + connect(ui->loopbackComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKCanBusUi::onLoopbackIndexChanged); + connect(ui->receivOwnComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKCanBusUi::onReceiveOwnIndexChanged); + connect(ui->canFdComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKCanBusUi::onCanFdIndexChanged); + connect(ui->bitrateComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKCanBusUi::onBitrateChanged); + connect(ui->dataBitrateComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKCanBusUi::onDataBitrateChanged); + connect(ui->customBitrateCheckBox, + &QCheckBox::clicked, + this, + &SAKCanBusUi::onCustomBitrateChanged); + connect(ui->customDataBitrateCheckBox, + &QCheckBox::clicked, + this, + &SAKCanBusUi::onCustomDataBitrateChanged); } -void SAKCanBusUi::initUiSendCanFrame() { - const QString inputTips = tr("Hex"); - ui->frameIdComboBox->lineEdit()->setPlaceholderText(inputTips); - ui->payloadComboBox->lineEdit()->setPlaceholderText(inputTips); +void SAKCanBusUi::initUiCanFrame() +{ + ui->frameTypeComboBox->clear(); + ui->frameTypeComboBox->addItem(tr("DataFrame"), QCanBusFrame::DataFrame); + ui->frameTypeComboBox->addItem(tr("ErrorFrame"), QCanBusFrame::ErrorFrame); + ui->frameTypeComboBox->addItem(tr("RemoteRequestFrame"), QCanBusFrame::RemoteRequestFrame); - connect(ui->sendPushButton, &QPushButton::clicked, this, - &SAKCanBusUi::onSendButtonClicked); + connect(ui->frameTypeComboBox, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKCanBusUi::onFrameTypeChanged); + connect(ui->extendedFormatCheckBox, + &QCheckBox::clicked, + this, + &SAKCanBusUi::onExtendedFormatChanged); + connect(ui->flexibleDataRateCheckBox, + &QCheckBox::clicked, + this, + &SAKCanBusUi::onFlexibleDataRateChanged); + connect(ui->bitrateSwitchCheckBox, + &QCheckBox::clicked, + this, + &SAKCanBusUi::onBitrateSwitchChanged); } -void SAKCanBusUi::initSetting() { - initSettingSelectPlugin(); - initSettingSpecifyConfiguration(); - initSettingCanFrame(); - initSettingSendCanFrame(); +void SAKCanBusUi::initUiSendCanFrame() +{ + const QString inputTips = tr("Hex"); + ui->frameIdComboBox->lineEdit()->setPlaceholderText(inputTips); + ui->payloadComboBox->lineEdit()->setPlaceholderText(inputTips); + + connect(ui->sendPushButton, &QPushButton::clicked, this, &SAKCanBusUi::onSendButtonClicked); } -void SAKCanBusUi::initSettingSelectPlugin() { - setCurrentIndex(ui->pluginComboBox, mSettingKeyCtx.pluginIndex); +void SAKCanBusUi::initSetting() +{ + initSettingSelectPlugin(); + initSettingSpecifyConfiguration(); + initSettingCanFrame(); + initSettingSendCanFrame(); } -void SAKCanBusUi::initSettingSpecifyConfiguration() { - QString name = mSettings->value(mSettingKeyCtx.interfaceName).toString(); - ui->interfaceNameComboBox->lineEdit()->setText(name); - - setChecked(ui->customConfigurationCheckBox, - mSettingKeyCtx.customConfiguration); - setCurrentIndex(ui->loopbackComboBox, mSettingKeyCtx.loopback); - setCurrentIndex(ui->receivOwnComboBox, mSettingKeyCtx.receiveOwn); - setCurrentIndex(ui->bitrateComboBox, mSettingKeyCtx.bitrate); - setCurrentIndex(ui->canFdComboBox, mSettingKeyCtx.canFd); - setCurrentIndex(ui->dataBitrateComboBox, mSettingKeyCtx.dataBitRate); - setChecked(ui->customBitrateCheckBox, mSettingKeyCtx.customBitRate); - setChecked(ui->customDataBitrateCheckBox, mSettingKeyCtx.customDataBitRate); - - bool enable = mSettings->value(mSettingKeyCtx.customConfiguration).toBool(); - setCustomConfigurationEnable(enable); +void SAKCanBusUi::initSettingSelectPlugin() +{ + setCurrentIndex(ui->pluginComboBox, mSettingKeyCtx.pluginIndex); } -void SAKCanBusUi::initSettingCanFrame() { - setCurrentIndex(ui->frameTypeComboBox, mSettingKeyCtx.frameTypeIndex); - setChecked(ui->extendedFormatCheckBox, mSettingKeyCtx.extendedFormat); - setChecked(ui->flexibleDataRateCheckBox, mSettingKeyCtx.flexibleDataRate); - setChecked(ui->bitrateSwitchCheckBox, mSettingKeyCtx.bitrateSwitch); +void SAKCanBusUi::initSettingSpecifyConfiguration() +{ + QString name = mSettings->value(mSettingKeyCtx.interfaceName).toString(); + ui->interfaceNameComboBox->lineEdit()->setText(name); - onFrameTypeChanged(); + setChecked(ui->customConfigurationCheckBox, mSettingKeyCtx.customConfiguration); + setCurrentIndex(ui->loopbackComboBox, mSettingKeyCtx.loopback); + setCurrentIndex(ui->receivOwnComboBox, mSettingKeyCtx.receiveOwn); + setCurrentIndex(ui->bitrateComboBox, mSettingKeyCtx.bitrate); + setCurrentIndex(ui->canFdComboBox, mSettingKeyCtx.canFd); + setCurrentIndex(ui->dataBitrateComboBox, mSettingKeyCtx.dataBitRate); + setChecked(ui->customBitrateCheckBox, mSettingKeyCtx.customBitRate); + setChecked(ui->customDataBitrateCheckBox, mSettingKeyCtx.customDataBitRate); + + bool enable = mSettings->value(mSettingKeyCtx.customConfiguration).toBool(); + setCustomConfigurationEnable(enable); +} + +void SAKCanBusUi::initSettingCanFrame() +{ + setCurrentIndex(ui->frameTypeComboBox, mSettingKeyCtx.frameTypeIndex); + setChecked(ui->extendedFormatCheckBox, mSettingKeyCtx.extendedFormat); + setChecked(ui->flexibleDataRateCheckBox, mSettingKeyCtx.flexibleDataRate); + setChecked(ui->bitrateSwitchCheckBox, mSettingKeyCtx.bitrateSwitch); + + onFrameTypeChanged(); } void SAKCanBusUi::initSettingSendCanFrame() {} -void SAKCanBusUi::onPluginChanged() { - int index = ui->pluginComboBox->currentIndex(); - mSettings->setValue(mSettingKeyCtx.pluginIndex, index); +void SAKCanBusUi::onPluginChanged() +{ + int index = ui->pluginComboBox->currentIndex(); + mSettings->setValue(mSettingKeyCtx.pluginIndex, index); } -void SAKCanBusUi::onDisconnectClicked() { - if (mDevice) { - mDevice->disconnectDevice(); - mDevice->deleteLater(); - mDevice = Q_NULLPTR; - } +void SAKCanBusUi::onDisconnectClicked() +{ + if (mDevice) { + mDevice->disconnectDevice(); + mDevice->deleteLater(); + mDevice = Q_NULLPTR; + } - updateUiState(false); + updateUiState(false); } -void SAKCanBusUi::onConnectClicked() { - const QString pluginName = ui->pluginComboBox->currentText(); - const QString interfaceName = ui->interfaceNameComboBox->currentText(); +void SAKCanBusUi::onConnectClicked() +{ + const QString pluginName = ui->pluginComboBox->currentText(); + const QString interfaceName = ui->interfaceNameComboBox->currentText(); - if (interfaceName.isEmpty()) { - QMessageBox::warning(this, tr("Interface Name is Empty"), - tr("Interface name is empty, " - "please input the name then try again!")); - return; - } + if (interfaceName.isEmpty()) { + QMessageBox::warning(this, + tr("Interface Name is Empty"), + tr("Interface name is empty, " + "please input the name then try again!")); + return; + } - QString errorString; - mDevice = QCanBus::instance()->createDevice(pluginName, interfaceName, - &errorString); - if (!mDevice) { - qCWarning(gLC) << errorString; - return; - } + QString errorString; + mDevice = QCanBus::instance()->createDevice(pluginName, interfaceName, &errorString); + if (!mDevice) { + qCWarning(gLC) << errorString; + return; + } - connect(mDevice, &QCanBusDevice::errorOccurred, this, - &SAKCanBusUi::onErrorOccure); - connect(mDevice, &QCanBusDevice::framesReceived, this, - &SAKCanBusUi::onFrameReceived); - connect(mDevice, &QCanBusDevice::framesWritten, this, - &SAKCanBusUi::onFrameWritten); + connect(mDevice, &QCanBusDevice::errorOccurred, this, &SAKCanBusUi::onErrorOccure); + connect(mDevice, &QCanBusDevice::framesReceived, this, &SAKCanBusUi::onFrameReceived); + connect(mDevice, &QCanBusDevice::framesWritten, this, &SAKCanBusUi::onFrameWritten); - auto items = configurationItems(); - for (const ConfigurationItem& item : items) { - mDevice->setConfigurationParameter(item.first, item.second); - } + auto items = configurationItems(); + for (const ConfigurationItem& item : items) { + mDevice->setConfigurationParameter(item.first, item.second); + } - if (!mDevice->connectDevice()) { - qCWarning(gLC) << tr("Connection error: %1").arg(mDevice->errorString()); - QMessageBox::warning( - this, tr("Connection Error"), - tr("Connection error: %1").arg(mDevice->errorString())); - mDevice->deleteLater(); - mDevice = Q_NULLPTR; - return; - } + if (!mDevice->connectDevice()) { + qCWarning(gLC) << tr("Connection error: %1").arg(mDevice->errorString()); + QMessageBox::warning(this, + tr("Connection Error"), + tr("Connection error: %1").arg(mDevice->errorString())); + mDevice->deleteLater(); + mDevice = Q_NULLPTR; + return; + } - mSettings->setValue(mSettingKeyCtx.interfaceName, interfaceName); - updateUiState(true); + mSettings->setValue(mSettingKeyCtx.interfaceName, interfaceName); + updateUiState(true); } -void SAKCanBusUi::onLoopbackIndexChanged(int index) { - mSettings->setValue(mSettingKeyCtx.loopback, index); +void SAKCanBusUi::onLoopbackIndexChanged(int index) +{ + mSettings->setValue(mSettingKeyCtx.loopback, index); } -void SAKCanBusUi::onCustomConfigurationChanged() { - bool checked = ui->customConfigurationCheckBox->isChecked(); - setCustomConfigurationEnable(checked); - mSettings->setValue(mSettingKeyCtx.customConfiguration, checked); +void SAKCanBusUi::onCustomConfigurationChanged() +{ + bool checked = ui->customConfigurationCheckBox->isChecked(); + setCustomConfigurationEnable(checked); + mSettings->setValue(mSettingKeyCtx.customConfiguration, checked); } -void SAKCanBusUi::onReceiveOwnIndexChanged(int index) { - mSettings->setValue(mSettingKeyCtx.receiveOwn, index); +void SAKCanBusUi::onReceiveOwnIndexChanged(int index) +{ + mSettings->setValue(mSettingKeyCtx.receiveOwn, index); } -void SAKCanBusUi::onCanFdIndexChanged(int index) { - mSettings->setValue(mSettingKeyCtx.canFd, index); +void SAKCanBusUi::onCanFdIndexChanged(int index) +{ + mSettings->setValue(mSettingKeyCtx.canFd, index); } -void SAKCanBusUi::onBitrateChanged(int index) { - mSettings->setValue(mSettingKeyCtx.bitrate, index); +void SAKCanBusUi::onBitrateChanged(int index) +{ + mSettings->setValue(mSettingKeyCtx.bitrate, index); } -void SAKCanBusUi::onDataBitrateChanged(int index) { - mSettings->setValue(mSettingKeyCtx.dataBitRate, index); +void SAKCanBusUi::onDataBitrateChanged(int index) +{ + mSettings->setValue(mSettingKeyCtx.dataBitRate, index); } -void SAKCanBusUi::onCustomBitrateChanged() { - bool checked = ui->customBitrateCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.customBitRate, checked); +void SAKCanBusUi::onCustomBitrateChanged() +{ + bool checked = ui->customBitrateCheckBox->isChecked(); + mSettings->setValue(mSettingKeyCtx.customBitRate, checked); - ui->bitrateComboBox->setEditable(checked); + ui->bitrateComboBox->setEditable(checked); } -void SAKCanBusUi::onCustomDataBitrateChanged() { - bool checked = ui->customDataBitrateCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.customDataBitRate, checked); +void SAKCanBusUi::onCustomDataBitrateChanged() +{ + bool checked = ui->customDataBitrateCheckBox->isChecked(); + mSettings->setValue(mSettingKeyCtx.customDataBitRate, checked); - ui->dataBitrateComboBox->setEditable(true); + ui->dataBitrateComboBox->setEditable(true); } -void SAKCanBusUi::onFrameTypeChanged() { - int index = ui->frameTypeComboBox->currentIndex(); - mSettings->setValue(mSettingKeyCtx.frameTypeIndex, index); +void SAKCanBusUi::onFrameTypeChanged() +{ + int index = ui->frameTypeComboBox->currentIndex(); + mSettings->setValue(mSettingKeyCtx.frameTypeIndex, index); - int type = ui->frameTypeComboBox->currentData().toInt(); - if (type == QCanBusFrame::DataFrame) { - ui->flexibleDataRateCheckBox->setEnabled(true); + int type = ui->frameTypeComboBox->currentData().toInt(); + if (type == QCanBusFrame::DataFrame) { + ui->flexibleDataRateCheckBox->setEnabled(true); + bool checked = ui->flexibleDataRateCheckBox->isChecked(); + ui->bitrateSwitchCheckBox->setEnabled(checked); + } else { + ui->flexibleDataRateCheckBox->setEnabled(false); + ui->bitrateSwitchCheckBox->setEnabled(false); + } +} + +void SAKCanBusUi::onExtendedFormatChanged() +{ + bool checked = ui->extendedFormatCheckBox->isChecked(); + mSettings->setValue(mSettingKeyCtx.extendedFormat, checked); +} + +void SAKCanBusUi::onFlexibleDataRateChanged() +{ bool checked = ui->flexibleDataRateCheckBox->isChecked(); + mSettings->setValue(mSettingKeyCtx.flexibleDataRate, checked); + ui->bitrateSwitchCheckBox->setEnabled(checked); - } else { - ui->flexibleDataRateCheckBox->setEnabled(false); - ui->bitrateSwitchCheckBox->setEnabled(false); - } } -void SAKCanBusUi::onExtendedFormatChanged() { - bool checked = ui->extendedFormatCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.extendedFormat, checked); +void SAKCanBusUi::onBitrateSwitchChanged() +{ + bool checked = ui->bitrateSwitchCheckBox->isChecked(); + mSettings->setValue(mSettingKeyCtx.bitrateSwitch, checked); } -void SAKCanBusUi::onFlexibleDataRateChanged() { - bool checked = ui->flexibleDataRateCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.flexibleDataRate, checked); +void SAKCanBusUi::onSendButtonClicked() +{ + if (!mDevice) { + QString title = tr("Device is Not Ready"); + QString msg = tr("Device is not ready," + " please connect the device then try angin!"); + QMessageBox::warning(this, title, msg); + return; + } - ui->bitrateSwitchCheckBox->setEnabled(checked); -} + const uint frameId = ui->frameIdComboBox->currentText().toUInt(Q_NULLPTR, 16); + QString data = ui->payloadComboBox->currentText().trimmed(); + const QByteArray payload = QByteArray::fromHex(data.remove(QLatin1Char(' ')).toLatin1()); -void SAKCanBusUi::onBitrateSwitchChanged() { - bool checked = ui->bitrateSwitchCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.bitrateSwitch, checked); -} + QCanBusFrame frame = QCanBusFrame(frameId, payload); + frame.setExtendedFrameFormat(ui->extendedFormatCheckBox->isChecked()); -void SAKCanBusUi::onSendButtonClicked() { - if (!mDevice) { - QString title = tr("Device is Not Ready"); - QString msg = - tr("Device is not ready," - " please connect the device then try angin!"); - QMessageBox::warning(this, title, msg); - return; - } + if (ui->flexibleDataRateCheckBox->isEnabled()) { + frame.setFlexibleDataRateFormat(ui->flexibleDataRateCheckBox->isChecked()); + } - const uint frameId = ui->frameIdComboBox->currentText().toUInt(Q_NULLPTR, 16); - QString data = ui->payloadComboBox->currentText().trimmed(); - const QByteArray payload = - QByteArray::fromHex(data.remove(QLatin1Char(' ')).toLatin1()); + if (ui->bitrateSwitchCheckBox->isEnabled()) { + frame.setBitrateSwitch(ui->bitrateSwitchCheckBox); + } - QCanBusFrame frame = QCanBusFrame(frameId, payload); - frame.setExtendedFrameFormat(ui->extendedFormatCheckBox->isChecked()); + if (mDevice->writeFrame(frame)) { + QString view; + if (frame.frameType() == QCanBusFrame::ErrorFrame) { + view = mDevice->interpretErrorFrame(frame); + } else { + view = frame.toString(); + } - if (ui->flexibleDataRateCheckBox->isEnabled()) { - frame.setFlexibleDataRateFormat(ui->flexibleDataRateCheckBox->isChecked()); - } - - if (ui->bitrateSwitchCheckBox->isEnabled()) { - frame.setBitrateSwitch(ui->bitrateSwitchCheckBox); - } - - if (mDevice->writeFrame(frame)) { - QString view; - if (frame.frameType() == QCanBusFrame::ErrorFrame) { - view = mDevice->interpretErrorFrame(frame); + QString flag = QString("[Tx] "); + outputMessage(flag + view); } else { - view = frame.toString(); + qCWarning(gLC) << mDevice->errorString(); + } +} + +void SAKCanBusUi::onErrorOccure(QCanBusDevice::CanBusError error) +{ + if (mDevice) { + Q_UNUSED(error); + QMessageBox::warning(this, tr("Error Occure"), mDevice->errorString()); + onDisconnectClicked(); + } +} + +void SAKCanBusUi::onFrameReceived() +{ + if (!mDevice) { + return; } - QString flag = QString("[Tx] "); - outputMessage(flag + view); - } else { - qCWarning(gLC) << mDevice->errorString(); - } -} + while (mDevice->framesAvailable()) { + const QCanBusFrame frame = mDevice->readFrame(); -void SAKCanBusUi::onErrorOccure(QCanBusDevice::CanBusError error) { - if (mDevice) { - Q_UNUSED(error); - QMessageBox::warning(this, tr("Error Occure"), mDevice->errorString()); - onDisconnectClicked(); - } -} + QString view; + if (frame.frameType() == QCanBusFrame::ErrorFrame) { + view = mDevice->interpretErrorFrame(frame); + } else { + view = frame.toString(); + } -void SAKCanBusUi::onFrameReceived() { - if (!mDevice) { - return; - } - - while (mDevice->framesAvailable()) { - const QCanBusFrame frame = mDevice->readFrame(); - - QString view; - if (frame.frameType() == QCanBusFrame::ErrorFrame) { - view = mDevice->interpretErrorFrame(frame); - } else { - view = frame.toString(); + QString flag = QString("[Rx] "); + outputMessage(flag + view); } - - QString flag = QString("[Rx] "); - outputMessage(flag + view); - } } -void SAKCanBusUi::onFrameWritten(qint64 framesCount) { - qCInfo(gLC) << framesCount; +void SAKCanBusUi::onFrameWritten(qint64 framesCount) +{ + qCInfo(gLC) << framesCount; } -void SAKCanBusUi::setOptions(QComboBox* cb, bool usingUnspecified) { - if (cb) { - cb->clear(); - if (usingUnspecified) { - cb->addItem(tr("unspecified"), QVariant()); +void SAKCanBusUi::setOptions(QComboBox* cb, bool usingUnspecified) +{ + if (cb) { + cb->clear(); + if (usingUnspecified) { + cb->addItem(tr("unspecified"), QVariant()); + } + cb->addItem(tr("false"), QVariant(false)); + cb->addItem(tr("true"), QVariant(true)); } - cb->addItem(tr("false"), QVariant(false)); - cb->addItem(tr("true"), QVariant(true)); - } } -void SAKCanBusUi::setCurrentIndex(QComboBox* cb, const QString& key) { - int index = mSettings->value(key).toInt(); - if (index >= 0 && index <= cb->count() - 1) { - cb->setCurrentIndex(index); - } +void SAKCanBusUi::setCurrentIndex(QComboBox* cb, const QString& key) +{ + int index = mSettings->value(key).toInt(); + if (index >= 0 && index <= cb->count() - 1) { + cb->setCurrentIndex(index); + } } -void SAKCanBusUi::setChecked(QCheckBox* cb, const QString& key) { - if (cb) { - bool checked = mSettings->value(key).toBool(); - cb->setChecked(checked); - } +void SAKCanBusUi::setChecked(QCheckBox* cb, const QString& key) +{ + if (cb) { + bool checked = mSettings->value(key).toBool(); + cb->setChecked(checked); + } } -void SAKCanBusUi::setCustomConfigurationEnable(bool enable) { - ui->errorFilterComboBox->setEnabled(enable); - ui->loopbackComboBox->setEnabled(enable); - ui->receivOwnComboBox->setEnabled(enable); - ui->canFdComboBox->setEnabled(enable); - ui->bitrateComboBox->setEnabled(enable); - ui->dataBitrateComboBox->setEnabled(enable); - ui->customBitrateCheckBox->setEnabled(enable); - ui->customDataBitrateCheckBox->setEnabled(enable); +void SAKCanBusUi::setCustomConfigurationEnable(bool enable) +{ + ui->errorFilterComboBox->setEnabled(enable); + ui->loopbackComboBox->setEnabled(enable); + ui->receivOwnComboBox->setEnabled(enable); + ui->canFdComboBox->setEnabled(enable); + ui->bitrateComboBox->setEnabled(enable); + ui->dataBitrateComboBox->setEnabled(enable); + ui->customBitrateCheckBox->setEnabled(enable); + ui->customDataBitrateCheckBox->setEnabled(enable); } -void SAKCanBusUi::outputMessage(const QString& msg) { - QString datetimeString = +void SAKCanBusUi::outputMessage(const QString& msg) +{ + QString datetimeString = #if 0 QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss.zzz"); #else - QDateTime::currentDateTime().toString("hh:mm:ss.zzz"); + QDateTime::currentDateTime().toString("hh:mm:ss.zzz"); #endif - QString cookedMsg; - cookedMsg = QString("%1 ").arg(datetimeString); - cookedMsg += msg; + QString cookedMsg; + cookedMsg = QString("%1 ").arg(datetimeString); + cookedMsg += msg; - ui->textBrowser->append(cookedMsg); + ui->textBrowser->append(cookedMsg); } -void SAKCanBusUi::updateUiState(bool connected) { - ui->connectPushButton->setEnabled(!connected); - ui->disconnectPushButton->setEnabled(connected); +void SAKCanBusUi::updateUiState(bool connected) +{ + ui->connectPushButton->setEnabled(!connected); + ui->disconnectPushButton->setEnabled(connected); - ui->interfaceNameComboBox->setEnabled(!connected); - ui->customConfigurationCheckBox->setEnabled(!connected); - if (connected) { - setCustomConfigurationEnable(false); - } else { - bool checked = ui->customConfigurationCheckBox->isChecked(); - setCustomConfigurationEnable(checked); - } -} - -QVector SAKCanBusUi::configurationItems() { - QVector items; - ConfigurationItem item; - - QString errorFilter = ui->errorFilterComboBox->currentText(); - if (!errorFilter.isEmpty()) { - bool ok = false; - int dec = errorFilter.toInt(&ok); - if (ok) { - item.first = QCanBusDevice::ErrorFilterKey; - item.second = QVariant::fromValue(QCanBusFrame::FrameErrors(dec)); - items.append(item); + ui->interfaceNameComboBox->setEnabled(!connected); + ui->customConfigurationCheckBox->setEnabled(!connected); + if (connected) { + setCustomConfigurationEnable(false); + } else { + bool checked = ui->customConfigurationCheckBox->isChecked(); + setCustomConfigurationEnable(checked); } - } - - item.first = QCanBusDevice::LoopbackKey; - item.second = ui->loopbackComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::ReceiveOwnKey; - item.second = ui->receivOwnComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::CanFdKey; - item.second = ui->canFdComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::BitRateKey; - item.second = ui->bitrateComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::DataBitRateKey; - item.second = ui->dataBitrateComboBox->currentData(); - items.append(item); - - return items; } -void SAKCanBusUi::setBitRates(QComboBox* cb, bool isFlexibleDataRateEnable) { - if (!cb) { - return; - } +QVector SAKCanBusUi::configurationItems() +{ + QVector items; + ConfigurationItem item; - const QVector rates = {10000, 20000, 50000, 100000, 125000, - 250000, 500000, 800000, 1000000}; - - const QVector dataRates = {2000000, 4000000, 8000000}; - - cb->clear(); - - for (int rate : rates) { - cb->addItem(QString::number(rate), rate); - } - - if (isFlexibleDataRateEnable) { - for (int rate : dataRates) { - cb->addItem(QString::number(rate), rate); + QString errorFilter = ui->errorFilterComboBox->currentText(); + if (!errorFilter.isEmpty()) { + bool ok = false; + int dec = errorFilter.toInt(&ok); + if (ok) { + item.first = QCanBusDevice::ErrorFilterKey; + item.second = QVariant::fromValue(QCanBusFrame::FrameErrors(dec)); + items.append(item); + } + } + + item.first = QCanBusDevice::LoopbackKey; + item.second = ui->loopbackComboBox->currentData(); + items.append(item); + + item.first = QCanBusDevice::ReceiveOwnKey; + item.second = ui->receivOwnComboBox->currentData(); + items.append(item); + + item.first = QCanBusDevice::CanFdKey; + item.second = ui->canFdComboBox->currentData(); + items.append(item); + + item.first = QCanBusDevice::BitRateKey; + item.second = ui->bitrateComboBox->currentData(); + items.append(item); + + item.first = QCanBusDevice::DataBitRateKey; + item.second = ui->dataBitrateComboBox->currentData(); + items.append(item); + + return items; +} + +void SAKCanBusUi::setBitRates(QComboBox* cb, bool isFlexibleDataRateEnable) +{ + if (!cb) { + return; + } + + const QVector rates = {10000, 20000, 50000, 100000, 125000, 250000, 500000, 800000, 1000000}; + + const QVector dataRates = {2000000, 4000000, 8000000}; + + cb->clear(); + + for (int rate : rates) { + cb->addItem(QString::number(rate), rate); + } + + if (isFlexibleDataRateEnable) { + for (int rate : dataRates) { + cb->addItem(QString::number(rate), rate); + } } - } } diff --git a/src/canbusstudio/canbusstudioui/sakcanbusstudioui.h b/src/canbusstudio/canbusstudioui/sakcanbusstudioui.h index ed65a38c..decf27d0 100644 --- a/src/canbusstudio/canbusstudioui/sakcanbusstudioui.h +++ b/src/canbusstudio/canbusstudioui/sakcanbusstudioui.h @@ -10,27 +10,32 @@ #ifndef SAKCANBUSSTUDIOUI_H #define SAKCANBUSSTUDIOUI_H -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include QT_BEGIN_NAMESPACE -namespace Ui { class SAKCanBusUi; } +namespace Ui { +class SAKCanBusUi; +} QT_END_NAMESPACE class SAKCanBusUi : public QWidget { Q_OBJECT typedef QPair ConfigurationItem; + public: Q_INVOKABLE SAKCanBusUi(QWidget *parent = Q_NULLPTR); ~SAKCanBusUi(); + private: - struct { + struct + { const QString pluginIndex = "CANStudio/pluginIndex"; const QString interfaceName = "CANStudio/interfaceName"; @@ -48,10 +53,12 @@ private: const QString flexibleDataRate = "CANStudio/fleibleDataRate"; const QString bitrateSwitch = "CANStudio/bitrateSwitch"; } mSettingKeyCtx; + private: Ui::SAKCanBusUi *ui; QSettings *mSettings{nullptr}; QCanBusDevice *mDevice{nullptr}; + private: void initUi(); void initUiSelectPlugin(); @@ -59,14 +66,12 @@ private: void initUiCanFrame(); void initUiSendCanFrame(); - void initSetting(); void initSettingSelectPlugin(); void initSettingSpecifyConfiguration(); void initSettingCanFrame(); void initSettingSendCanFrame(); - // These are slots. void onPluginChanged(); void onDisconnectClicked(); @@ -86,14 +91,13 @@ private: void onFlexibleDataRateChanged(); void onBitrateSwitchChanged(); - void onSendButtonClicked(); - // Slots about CAN bus device void onErrorOccure(QCanBusDevice::CanBusError error); void onFrameReceived(); void onFrameWritten(qint64 framesCount); + private: void setOptions(QComboBox *cb, bool usingUnspecified); void setCurrentIndex(QComboBox *cb, const QString &key); diff --git a/src/canbusstudio/main.cc b/src/canbusstudio/main.cc index cc14d99b..e07b7c2c 100644 --- a/src/canbusstudio/main.cc +++ b/src/canbusstudio/main.cc @@ -12,11 +12,15 @@ #include "sakcanbusstudioui.h" #include "sakcommonmainwindow.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("CAN Bus Studio"), "SAK.CanBusStudio"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app = CreateCommonMainWindowApplication(argc, + argv, + QObject::tr( + "CAN Bus Studio"), + "SAK.CanBusStudio"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/common/common/sakblescanner.cc b/src/common/common/sakblescanner.cc index 7c570829..50f070d1 100644 --- a/src/common/common/sakblescanner.cc +++ b/src/common/common/sakblescanner.cc @@ -13,119 +13,148 @@ #include #include -#define BLE_ERR_SIG \ - void (QBluetoothDeviceDiscoveryAgent::*)( \ - QBluetoothDeviceDiscoveryAgent::Error) +#define BLE_ERR_SIG void (QBluetoothDeviceDiscoveryAgent::*)(QBluetoothDeviceDiscoveryAgent::Error) SAKBleScanner::SAKBleScanner(QObject* parent) - : QThread(parent), mDiscover(Q_NULLPTR) {} + : QThread(parent) + , mDiscover(Q_NULLPTR) +{} SAKBleScanner::~SAKBleScanner() {} -void SAKBleScanner::startDiscover() { start(); } - -void SAKBleScanner::stopDiscover() { exit(); } - -bool SAKBleScanner::isActive() { return isRunning(); } - -QVariant SAKBleScanner::deviceInfo(int index) { - mDeviceInfoListMutex.lock(); - if (index >= 0 && index < mDeviceInfoList.length()) { - QBluetoothDeviceInfo info = mDeviceInfoList.at(index); - return QVariant::fromValue(info); - } - mDeviceInfoListMutex.unlock(); - - return QVariant(); +void SAKBleScanner::startDiscover() +{ + start(); } -QString SAKBleScanner::deviceName(const QVariant& deviceInfo) { - auto cookedInfo = deviceInfo.value(); - return cookedInfo.name(); +void SAKBleScanner::stopDiscover() +{ + exit(); } -void SAKBleScanner::run() { - mDiscover = new QBluetoothDeviceDiscoveryAgent(); - connect(mDiscover, &QBluetoothDeviceDiscoveryAgent::finished, this, - &SAKBleScanner::onDiscoveryFinished); +bool SAKBleScanner::isActive() +{ + return isRunning(); +} + +QVariant SAKBleScanner::deviceInfo(int index) +{ + mDeviceInfoListMutex.lock(); + if (index >= 0 && index < mDeviceInfoList.length()) { + QBluetoothDeviceInfo info = mDeviceInfoList.at(index); + return QVariant::fromValue(info); + } + mDeviceInfoListMutex.unlock(); + + return QVariant(); +} + +QString SAKBleScanner::deviceName(const QVariant& deviceInfo) +{ + auto cookedInfo = deviceInfo.value(); + return cookedInfo.name(); +} + +void SAKBleScanner::run() +{ + mDiscover = new QBluetoothDeviceDiscoveryAgent(); + connect(mDiscover, + &QBluetoothDeviceDiscoveryAgent::finished, + this, + &SAKBleScanner::onDiscoveryFinished); #if QT_VERSION >= QT_VERSION_CHECK(6, 2, 0) - connect(mDiscover, &QBluetoothDeviceDiscoveryAgent::errorOccurred, this, - &SAKBleScanner::onDiscoveryErrorOccurred); + connect(mDiscover, + &QBluetoothDeviceDiscoveryAgent::errorOccurred, + this, + &SAKBleScanner::onDiscoveryErrorOccurred); #else - connect(mDiscover, - static_cast(&QBluetoothDeviceDiscoveryAgent::error), - this, &SAKBleScanner::onDiscoveryErrorOccurred); + connect(mDiscover, + static_cast(&QBluetoothDeviceDiscoveryAgent::error), + this, + &SAKBleScanner::onDiscoveryErrorOccurred); #endif - connect(mDiscover, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, - &SAKBleScanner::onDiscoveryDeviceDiscovered); + connect(mDiscover, + &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, + this, + &SAKBleScanner::onDiscoveryDeviceDiscovered); - // 10s-1minute - int interval = mTimeoutInterval < 10 ? 10 : mTimeoutInterval; - interval = interval > 120 ? 120 : interval; - mDiscover->setLowEnergyDiscoveryTimeout(interval * 1000); + // 10s-1minute + int interval = mTimeoutInterval < 10 ? 10 : mTimeoutInterval; + interval = interval > 120 ? 120 : interval; + mDiscover->setLowEnergyDiscoveryTimeout(interval * 1000); #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) - mDeviceInfoListMutex.lock(); - mDeviceInfoList.clear(); - mDeviceInfoListMutex.unlock(); - mDiscover->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod); + mDeviceInfoListMutex.lock(); + mDeviceInfoList.clear(); + mDeviceInfoListMutex.unlock(); + mDiscover->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod); #endif - exec(); + exec(); } -void SAKBleScanner::onDiscoveryFinished() { - emit devicesInfoListChanged(); - exit(); +void SAKBleScanner::onDiscoveryFinished() +{ + emit devicesInfoListChanged(); + exit(); } -void SAKBleScanner::onDiscoveryErrorOccurred( - QBluetoothDeviceDiscoveryAgent::Error error) { - Q_UNUSED(error); - qCWarning(mLoggingCategory) - << "QBluetoothDeviceDiscoveryAgent error:" << mDiscover->errorString(); - exit(); - emit errorOccurred(mDiscover->errorString()); +void SAKBleScanner::onDiscoveryErrorOccurred(QBluetoothDeviceDiscoveryAgent::Error error) +{ + Q_UNUSED(error); + qCWarning(mLoggingCategory) << "QBluetoothDeviceDiscoveryAgent error:" + << mDiscover->errorString(); + exit(); + emit errorOccurred(mDiscover->errorString()); } -void SAKBleScanner::onDiscoveryDeviceDiscovered( - const QBluetoothDeviceInfo& info) { - const QString name = info.name(); - qCInfo(mLoggingCategory) << "new ble device:" << name; +void SAKBleScanner::onDiscoveryDeviceDiscovered(const QBluetoothDeviceInfo& info) +{ + const QString name = info.name(); + qCInfo(mLoggingCategory) << "new ble device:" << name; - if (!mNameFiltter.isEmpty()) { - if (!name.contains(mNameFiltter)) { - qCInfo(mLoggingCategory) << "device is ignored:" << name; - return; + if (!mNameFiltter.isEmpty()) { + if (!name.contains(mNameFiltter)) { + qCInfo(mLoggingCategory) << "device is ignored:" << name; + return; + } } - } - mDeviceInfoListMutex.lock(); - mDeviceInfoList.append(info); - mDeviceInfoListMutex.unlock(); - emit deviceDiscovered(info); + mDeviceInfoListMutex.lock(); + mDeviceInfoList.append(info); + mDeviceInfoListMutex.unlock(); + emit deviceDiscovered(info); } -QVariantList SAKBleScanner::devicesInfoList() { - QVariantList list; - mDeviceInfoListMutex.lock(); - for (auto& info : mDeviceInfoList) { - list.append(QVariant::fromValue(info)); - } - mDeviceInfoListMutex.unlock(); +QVariantList SAKBleScanner::devicesInfoList() +{ + QVariantList list; + mDeviceInfoListMutex.lock(); + for (auto& info : mDeviceInfoList) { + list.append(QVariant::fromValue(info)); + } + mDeviceInfoListMutex.unlock(); - return list; + return list; } -int SAKBleScanner::timeoutInterval() { return mTimeoutInterval; } - -void SAKBleScanner::setTimeoutInterval(int interval) { - mTimeoutInterval = interval; - emit timeoutIntervalChanged(); +int SAKBleScanner::timeoutInterval() +{ + return mTimeoutInterval; } -QString SAKBleScanner::namefiltter() { return mNameFiltter; } - -void SAKBleScanner::setNameFiltter(const QString& flag) { - mNameFiltter = flag; - emit filtterNameChanged(); +void SAKBleScanner::setTimeoutInterval(int interval) +{ + mTimeoutInterval = interval; + emit timeoutIntervalChanged(); +} + +QString SAKBleScanner::namefiltter() +{ + return mNameFiltter; +} + +void SAKBleScanner::setNameFiltter(const QString& flag) +{ + mNameFiltter = flag; + emit filtterNameChanged(); } diff --git a/src/common/common/sakblescanner.h b/src/common/common/sakblescanner.h index 839ce884..ceaea261 100644 --- a/src/common/common/sakblescanner.h +++ b/src/common/common/sakblescanner.h @@ -10,23 +10,20 @@ #ifndef SAKBLESCANNER_H #define SAKBLESCANNER_H +#include +#include +#include #include #include #include -#include -#include -#include - class SAKBleScanner : public QThread { Q_OBJECT - Q_PROPERTY(QVariantList deviceInfoList READ devicesInfoList - NOTIFY devicesInfoListChanged) - Q_PROPERTY(int timeoutInterval READ timeoutInterval - WRITE setTimeoutInterval NOTIFY timeoutIntervalChanged) - Q_PROPERTY(QString namefiltter READ namefiltter WRITE setNameFiltter - NOTIFY filtterNameChanged) + Q_PROPERTY(QVariantList deviceInfoList READ devicesInfoList NOTIFY devicesInfoListChanged) + Q_PROPERTY(int timeoutInterval READ timeoutInterval WRITE setTimeoutInterval NOTIFY + timeoutIntervalChanged) + Q_PROPERTY(QString namefiltter READ namefiltter WRITE setNameFiltter NOTIFY filtterNameChanged) public: explicit SAKBleScanner(QObject *parent = nullptr); ~SAKBleScanner(); @@ -56,8 +53,8 @@ private: void onDiscoveryErrorOccurred(QBluetoothDeviceDiscoveryAgent::Error error); void onDiscoveryDeviceDiscovered(const QBluetoothDeviceInfo &info); -//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ -//Properties + //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ + //Properties public: QVariantList devicesInfoList(); int timeoutInterval(); diff --git a/src/common/common/sakcommoncrcinterface.cc b/src/common/common/sakcommoncrcinterface.cc index e70f1848..d9c812fb 100644 --- a/src/common/common/sakcommoncrcinterface.cc +++ b/src/common/common/sakcommoncrcinterface.cc @@ -14,146 +14,148 @@ #include "sakcommoncrcinterface.h" SAKCommonCrcInterface::SAKCommonCrcInterface(QObject* parent) - : QObject(parent) {} + : QObject(parent) +{} -QStringList SAKCommonCrcInterface::supportedParameterModels() { - modelStrings.clear(); - QMetaEnum models = QMetaEnum::fromType(); +QStringList SAKCommonCrcInterface::supportedParameterModels() +{ + modelStrings.clear(); + QMetaEnum models = QMetaEnum::fromType(); - const char* ch = Q_NULLPTR; - for (int i = 0; i < models.keyCount(); i++) { - ch = models.valueToKey(i); - if (ch) { - modelStrings.append(QString(ch)); + const char* ch = Q_NULLPTR; + for (int i = 0; i < models.keyCount(); i++) { + ch = models.valueToKey(i); + if (ch) { + modelStrings.append(QString(ch)); + } } - } - return modelStrings; + return modelStrings; } -uint32_t SAKCommonCrcInterface::poly( - SAKCommonCrcInterface::SAKEnumCrcModel model) { - uint32_t poly = 0; +uint32_t SAKCommonCrcInterface::poly(SAKCommonCrcInterface::SAKEnumCrcModel model) +{ + uint32_t poly = 0; - switch (model) { + switch (model) { case CRC_8: case CRC_8_ITU: case CRC_8_ROHC: - poly = 0x07; - break; + poly = 0x07; + break; case CRC_8_MAXIM: - poly = 0x31; - break; + poly = 0x31; + break; case CRC_16_IBM: case CRC_16_MAXIM: case CRC_16_USB: case CRC_16_MODBUS: - poly = 0x8005; - break; + poly = 0x8005; + break; case CRC_16_CCITT: case CRC_16_XMODEM: case CRC_16_CCITT_FALSE: case CRC_16_x25: - poly = 0x1021; - break; + poly = 0x1021; + break; case CRC_16_DNP: - poly = 0x3d65; - break; + poly = 0x3d65; + break; case CRC_32: case CRC_32_MPEG2: - poly = 0x04c11db7; - break; - } + poly = 0x04c11db7; + break; + } - return poly; + return poly; } -uint32_t SAKCommonCrcInterface::xorValue( - SAKCommonCrcInterface::SAKEnumCrcModel model) { - uint32_t value = 0; +uint32_t SAKCommonCrcInterface::xorValue(SAKCommonCrcInterface::SAKEnumCrcModel model) +{ + uint32_t value = 0; - switch (model) { + switch (model) { case CRC_8: case CRC_8_ROHC: case CRC_8_MAXIM: - value = 0x00; - break; + value = 0x00; + break; case CRC_8_ITU: - value = 0x55; - break; + value = 0x55; + break; case CRC_16_IBM: case CRC_16_MODBUS: case CRC_16_CCITT: case CRC_16_CCITT_FALSE: case CRC_16_XMODEM: - value = 0x0000; - break; + value = 0x0000; + break; case CRC_16_MAXIM: case CRC_16_USB: case CRC_16_x25: case CRC_16_DNP: - value = 0xffff; - break; + value = 0xffff; + break; case CRC_32: - value = 0xffffffff; - break; + value = 0xffffffff; + break; case CRC_32_MPEG2: - value = 0x00000000; - break; - } + value = 0x00000000; + break; + } - return value; + return value; } -uint32_t SAKCommonCrcInterface::initialValue( - SAKCommonCrcInterface::SAKEnumCrcModel model) { - uint32_t init = 0; +uint32_t SAKCommonCrcInterface::initialValue(SAKCommonCrcInterface::SAKEnumCrcModel model) +{ + uint32_t init = 0; - switch (model) { + switch (model) { case CRC_8: case CRC_8_ITU: case CRC_8_MAXIM: - init = 0x00; - break; + init = 0x00; + break; case CRC_8_ROHC: - init = 0xff; - break; + init = 0xff; + break; case CRC_16_IBM: case CRC_16_MAXIM: case CRC_16_CCITT: case CRC_16_XMODEM: case CRC_16_DNP: - init = 0x0000; - break; + init = 0x0000; + break; case CRC_16_USB: case CRC_16_MODBUS: case CRC_16_CCITT_FALSE: case CRC_16_x25: - init = 0xffff; - break; + init = 0xffff; + break; case CRC_32: case CRC_32_MPEG2: - init = 0xffffffff; - break; - } + init = 0xffffffff; + break; + } - return init; + return init; } -QString SAKCommonCrcInterface::friendlyPoly( - SAKCommonCrcInterface::SAKEnumCrcModel model) { - QString formula = QString("Error: Formula not found"); +QString SAKCommonCrcInterface::friendlyPoly(SAKCommonCrcInterface::SAKEnumCrcModel model) +{ + QString formula = QString("Error: Formula not found"); - switch (model) { + switch (model) { case CRC_8: case CRC_8_ITU: case CRC_8_ROHC: - formula = QString("x8 + x2 + x + 1"); - break; + formula = QString("x8 + x2 + x + 1"); + break; case CRC_8_MAXIM: - formula = QString("x8 + x5 + x4 + 1"); - break; + formula = QString("x8 + x5 + x4 + 1"); + break; case CRC_16_IBM: case CRC_16_MAXIM: case CRC_16_USB: @@ -162,32 +164,32 @@ QString SAKCommonCrcInterface::friendlyPoly( case CRC_16_CCITT_FALSE: case CRC_16_x25: case CRC_16_XMODEM: - formula = QString("x6 + x2 + x5 + 1"); - break; + formula = QString("x6 + x2 + x5 + 1"); + break; case CRC_16_DNP: - formula = QString("x6+x3+x2+x1+x0+x8+x6+x5+x2+1"); - break; + formula = QString("x6+x3+x2+x1+x0+x8+x6+x5+x2+1"); + break; case CRC_32: case CRC_32_MPEG2: - formula = QString("x32+x6+x3+x2+x6+x2+x1+x0+x8+x7+x5+x4+x2+x+1"); - break; - } + formula = QString("x32+x6+x3+x2+x6+x2+x1+x0+x8+x7+x5+x4+x2+x+1"); + break; + } - return formula; + return formula; } -bool SAKCommonCrcInterface::isInputReversal( - SAKCommonCrcInterface::SAKEnumCrcModel model) { - bool reversal = true; +bool SAKCommonCrcInterface::isInputReversal(SAKCommonCrcInterface::SAKEnumCrcModel model) +{ + bool reversal = true; - switch (model) { + switch (model) { case CRC_8: case CRC_8_ITU: case CRC_16_CCITT_FALSE: case CRC_16_XMODEM: case CRC_32_MPEG2: - reversal = false; - break; + reversal = false; + break; case CRC_8_ROHC: case CRC_8_MAXIM: @@ -199,25 +201,25 @@ bool SAKCommonCrcInterface::isInputReversal( case CRC_16_x25: case CRC_16_DNP: case CRC_32: - reversal = true; - break; - } + reversal = true; + break; + } - return reversal; + return reversal; } -bool SAKCommonCrcInterface::isOutputReversal( - SAKCommonCrcInterface::SAKEnumCrcModel model) { - bool reversal = true; +bool SAKCommonCrcInterface::isOutputReversal(SAKCommonCrcInterface::SAKEnumCrcModel model) +{ + bool reversal = true; - switch (model) { + switch (model) { case CRC_8: case CRC_8_ITU: case CRC_16_CCITT_FALSE: case CRC_16_XMODEM: case CRC_32_MPEG2: - reversal = false; - break; + reversal = false; + break; case CRC_8_ROHC: case CRC_8_MAXIM: @@ -229,23 +231,23 @@ bool SAKCommonCrcInterface::isOutputReversal( case CRC_16_x25: case CRC_16_DNP: case CRC_32: - reversal = true; - break; - } + reversal = true; + break; + } - return reversal; + return reversal; } -int SAKCommonCrcInterface::bitsWidth( - SAKCommonCrcInterface::SAKEnumCrcModel model) { - int ret = -1; - switch (model) { +int SAKCommonCrcInterface::bitsWidth(SAKCommonCrcInterface::SAKEnumCrcModel model) +{ + int ret = -1; + switch (model) { case CRC_8: case CRC_8_ITU: case CRC_8_ROHC: case CRC_8_MAXIM: - ret = 8; - break; + ret = 8; + break; case CRC_16_IBM: case CRC_16_MAXIM: case CRC_16_USB: @@ -255,43 +257,43 @@ int SAKCommonCrcInterface::bitsWidth( case CRC_16_x25: case CRC_16_XMODEM: case CRC_16_DNP: - ret = 16; - break; + ret = 16; + break; case CRC_32: case CRC_32_MPEG2: - ret = 32; - break; - } - return ret; + ret = 32; + break; + } + return ret; } #ifndef SAK_IMPORT_MODULE_TESTLIB -void SAKCommonCrcInterface::addCrcModelItemsToComboBox(QComboBox* comboBox) { - if (comboBox) { - comboBox->clear(); - QMetaEnum enums = - QMetaEnum::fromType(); - QStandardItemModel* itemModel = new QStandardItemModel(comboBox); - for (int i = 0; i < enums.keyCount(); i++) { - const QString key = enums.key(i); - // There may be a bug, I do not know whether will the itemModel - // take ownership of the item - // if not, a memory leak will occur after comboBox is destroyed. - QStandardItem* item = new QStandardItem(key); - item->setToolTip(key); - itemModel->appendRow(item); - } - comboBox->setModel(itemModel); - - // add item data - for (int i = 0; i < comboBox->count(); i++) { - for (int j = 0; j < enums.keyCount(); j++) { - if (comboBox->itemText(i) == QString(enums.key(j))) { - comboBox->setItemData(i, enums.value(j)); - break; +void SAKCommonCrcInterface::addCrcModelItemsToComboBox(QComboBox* comboBox) +{ + if (comboBox) { + comboBox->clear(); + QMetaEnum enums = QMetaEnum::fromType(); + QStandardItemModel* itemModel = new QStandardItemModel(comboBox); + for (int i = 0; i < enums.keyCount(); i++) { + const QString key = enums.key(i); + // There may be a bug, I do not know whether will the itemModel + // take ownership of the item + // if not, a memory leak will occur after comboBox is destroyed. + QStandardItem* item = new QStandardItem(key); + item->setToolTip(key); + itemModel->appendRow(item); + } + comboBox->setModel(itemModel); + + // add item data + for (int i = 0; i < comboBox->count(); i++) { + for (int j = 0; j < enums.keyCount(); j++) { + if (comboBox->itemText(i) == QString(enums.key(j))) { + comboBox->setItemData(i, enums.value(j)); + break; + } + } } - } } - } } #endif diff --git a/src/common/common/sakcommoncrcinterface.h b/src/common/common/sakcommoncrcinterface.h index f75658f9..def993f3 100644 --- a/src/common/common/sakcommoncrcinterface.h +++ b/src/common/common/sakcommoncrcinterface.h @@ -20,7 +20,7 @@ class SAKCommonCrcInterface : public QObject { Q_OBJECT public: - enum SAKEnumCrcModel{ + enum SAKEnumCrcModel { CRC_8, CRC_8_ITU, CRC_8_ROHC, @@ -41,7 +41,6 @@ public: }; Q_ENUM(SAKEnumCrcModel); - public: SAKCommonCrcInterface(QObject *parent = Q_NULLPTR); QStringList supportedParameterModels(); @@ -56,55 +55,52 @@ public: static void addCrcModelItemsToComboBox(QComboBox *comboBox); #endif - public: template - T crcCalculate(uint8_t *input, - uint64_t length, - SAKCommonCrcInterface::SAKEnumCrcModel model){ + T crcCalculate(uint8_t *input, uint64_t length, SAKCommonCrcInterface::SAKEnumCrcModel model) + { T crcReg = static_cast(initialValue(model)); T rawPoly = static_cast(poly(model)); uint8_t byte = 0; T temp = 1; - while (length--){ + while (length--) { byte = *(input++); - if (isInputReversal(model)){ - reverseInt(byte,byte); + if (isInputReversal(model)) { + reverseInt(byte, byte); } - crcReg ^= static_cast((byte << 8*(sizeof (T)-1))); - for(int i = 0;i < 8;i++){ - if(crcReg & (temp << (sizeof (T)*8-1))){ + crcReg ^= static_cast((byte << 8 * (sizeof(T) - 1))); + for (int i = 0; i < 8; i++) { + if (crcReg & (temp << (sizeof(T) * 8 - 1))) { crcReg = static_cast((crcReg << 1) ^ rawPoly); - }else { + } else { crcReg = static_cast(crcReg << 1); } } } - if (isOutputReversal(model)){ - reverseInt(crcReg,crcReg); + if (isOutputReversal(model)) { + reverseInt(crcReg, crcReg); } - T crc = (crcReg ^ static_cast(xorValue(model))) ; + T crc = (crcReg ^ static_cast(xorValue(model))); return crc; } - private: QStringList modelStrings; - private: template - bool reverseInt(const T &input, T &output){ - int bitsWidth = sizeof (input)*8; + bool reverseInt(const T &input, T &output) + { + int bitsWidth = sizeof(input) * 8; QString inputStr = QString("%1").arg(QString::number(input, 2), bitsWidth, '0'); QString outputStr; outputStr.resize(bitsWidth); - for (int i = 0; i < bitsWidth; i++){ - outputStr.replace(i, 1, inputStr.at(bitsWidth-1-i)); + for (int i = 0; i < bitsWidth; i++) { + outputStr.replace(i, 1, inputStr.at(bitsWidth - 1 - i)); } bool ok; diff --git a/src/common/common/sakcommondatastructure.cc b/src/common/common/sakcommondatastructure.cc index fcf3b33b..855e62db 100644 --- a/src/common/common/sakcommondatastructure.cc +++ b/src/common/common/sakcommondatastructure.cc @@ -16,380 +16,390 @@ #include SAKCommonDataStructure::SAKCommonDataStructure(QObject *parent) - : QObject(parent) {} + : QObject(parent) +{} SAKCommonDataStructure::~SAKCommonDataStructure() {} -void SAKCommonDataStructure::setComboBoxTextOutputFormat(QComboBox *comboBox) { - if (comboBox) { - QMap formatMap; - formatMap.insert(OutputFormatBin, QString("BIN")); - formatMap.insert(OutputFormatOct, QString("OCT")); - formatMap.insert(OutputFormatDec, QString("DEC")); - formatMap.insert(OutputFormatHex, QString("HEX")); - formatMap.insert(OutputFormatUtf8, QString("UTF8")); - formatMap.insert(OutputFormatUcs4, QString("UCS4")); - formatMap.insert(OutputFormatAscii, QString("ASCII")); - formatMap.insert(OutputFormatUtf16, QString("UTF16")); - formatMap.insert(OutputFormatLocal, QString("SYSTEM")); - setComboBoxItems(comboBox, formatMap, OutputFormatHex); - } -} - -void SAKCommonDataStructure::setComboBoxTextInputFormat(QComboBox *comboBox) { - if (comboBox) { +void SAKCommonDataStructure::setComboBoxTextOutputFormat(QComboBox *comboBox) +{ if (comboBox) { - QMap formatMap; - formatMap.insert(InputFormatBin, QString("BIN")); - formatMap.insert(InputFormatOct, QString("OTC")); - formatMap.insert(InputFormatDec, QString("DEC")); - formatMap.insert(InputFormatHex, QString("HEX")); - formatMap.insert(InputFormatAscii, QString("ASCII")); - formatMap.insert(InputFormatLocal, QString("SYSTEM")); - setComboBoxItems(comboBox, formatMap, InputFormatLocal); + QMap formatMap; + formatMap.insert(OutputFormatBin, QString("BIN")); + formatMap.insert(OutputFormatOct, QString("OCT")); + formatMap.insert(OutputFormatDec, QString("DEC")); + formatMap.insert(OutputFormatHex, QString("HEX")); + formatMap.insert(OutputFormatUtf8, QString("UTF8")); + formatMap.insert(OutputFormatUcs4, QString("UCS4")); + formatMap.insert(OutputFormatAscii, QString("ASCII")); + formatMap.insert(OutputFormatUtf16, QString("UTF16")); + formatMap.insert(OutputFormatLocal, QString("SYSTEM")); + setComboBoxItems(comboBox, formatMap, OutputFormatHex); } - } } -void SAKCommonDataStructure::setComboBoxTextWebSocketSendingType( - QComboBox *comboBox) { - if (comboBox) { - comboBox->addItem(tr("BIN"), - SAKCommonDataStructure::WebSocketSendingTypeBin); - comboBox->addItem(tr("TEXT"), - SAKCommonDataStructure::WebSocketSendingTypeText); - } +void SAKCommonDataStructure::setComboBoxTextInputFormat(QComboBox *comboBox) +{ + if (comboBox) { + if (comboBox) { + QMap formatMap; + formatMap.insert(InputFormatBin, QString("BIN")); + formatMap.insert(InputFormatOct, QString("OTC")); + formatMap.insert(InputFormatDec, QString("DEC")); + formatMap.insert(InputFormatHex, QString("HEX")); + formatMap.insert(InputFormatAscii, QString("ASCII")); + formatMap.insert(InputFormatLocal, QString("SYSTEM")); + setComboBoxItems(comboBox, formatMap, InputFormatLocal); + } + } } -QString SAKCommonDataStructure::formattingString( - QString &origingString, SAKEnumTextFormatInput format) { - QString cookedString; - if (format == SAKCommonDataStructure::InputFormatBin) { - origingString.remove(QRegularExpression("[^0-1]")); - for (int i = 0; i < origingString.length(); i++) { - if ((i != 0) && (i % 8 == 0)) { - cookedString.append(QChar(' ')); - } - cookedString.append(origingString.at(i)); +void SAKCommonDataStructure::setComboBoxTextWebSocketSendingType(QComboBox *comboBox) +{ + if (comboBox) { + comboBox->addItem(tr("BIN"), SAKCommonDataStructure::WebSocketSendingTypeBin); + comboBox->addItem(tr("TEXT"), SAKCommonDataStructure::WebSocketSendingTypeText); } - } else if (format == SAKCommonDataStructure::InputFormatOct) { - origingString.remove(QRegularExpression("[^0-7]")); - for (int i = 0; i < origingString.length(); i++) { - if ((i != 0) && (i % 2 == 0)) { - cookedString.append(QChar(' ')); - } - cookedString.append(origingString.at(i)); - } - } else if (format == SAKCommonDataStructure::InputFormatDec) { - origingString.remove(QRegularExpression("[^0-9]")); - for (int i = 0; i < origingString.length(); i++) { - if ((i != 0) && (i % 2 == 0)) { - cookedString.append(QChar(' ')); - } - cookedString.append(origingString.at(i)); - } - } else if (format == SAKCommonDataStructure::InputFormatHex) { - origingString.remove(QRegularExpression("[^0-9a-fA-F]")); - for (int i = 0; i < origingString.length(); i++) { - if ((i != 0) && (i % 2 == 0)) { - cookedString.append(QChar(' ')); - } - cookedString.append(origingString.at(i)); - } - } else if (format == SAKCommonDataStructure::InputFormatAscii) { - for (int i = 0; i < origingString.length(); i++) { - if (origingString.at(i).unicode() <= 127) { - cookedString.append(origingString.at(i)); - } - } - } else if (format == SAKCommonDataStructure::InputFormatLocal) { - cookedString = origingString; - } else { - Q_ASSERT_X(false, __FUNCTION__, "Unknown input model!"); - } - - return cookedString; } -QByteArray SAKCommonDataStructure::stringToByteArray( - QString &origingString, SAKEnumTextFormatInput format) { - QByteArray data; -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - auto behavior = QString::SkipEmptyParts; -#else - auto behavior = Qt::SkipEmptyParts; -#endif - if (format == SAKCommonDataStructure::InputFormatBin) { - QStringList strList = origingString.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 2); - data.append(reinterpret_cast(&value), 1); +QString SAKCommonDataStructure::formattingString(QString &origingString, + SAKEnumTextFormatInput format) +{ + QString cookedString; + if (format == SAKCommonDataStructure::InputFormatBin) { + origingString.remove(QRegularExpression("[^0-1]")); + for (int i = 0; i < origingString.length(); i++) { + if ((i != 0) && (i % 8 == 0)) { + cookedString.append(QChar(' ')); + } + cookedString.append(origingString.at(i)); + } + } else if (format == SAKCommonDataStructure::InputFormatOct) { + origingString.remove(QRegularExpression("[^0-7]")); + for (int i = 0; i < origingString.length(); i++) { + if ((i != 0) && (i % 2 == 0)) { + cookedString.append(QChar(' ')); + } + cookedString.append(origingString.at(i)); + } + } else if (format == SAKCommonDataStructure::InputFormatDec) { + origingString.remove(QRegularExpression("[^0-9]")); + for (int i = 0; i < origingString.length(); i++) { + if ((i != 0) && (i % 2 == 0)) { + cookedString.append(QChar(' ')); + } + cookedString.append(origingString.at(i)); + } + } else if (format == SAKCommonDataStructure::InputFormatHex) { + origingString.remove(QRegularExpression("[^0-9a-fA-F]")); + for (int i = 0; i < origingString.length(); i++) { + if ((i != 0) && (i % 2 == 0)) { + cookedString.append(QChar(' ')); + } + cookedString.append(origingString.at(i)); + } + } else if (format == SAKCommonDataStructure::InputFormatAscii) { + for (int i = 0; i < origingString.length(); i++) { + if (origingString.at(i).unicode() <= 127) { + cookedString.append(origingString.at(i)); + } + } + } else if (format == SAKCommonDataStructure::InputFormatLocal) { + cookedString = origingString; + } else { + Q_ASSERT_X(false, __FUNCTION__, "Unknown input model!"); } - } else if (format == SAKCommonDataStructure::InputFormatOct) { - QStringList strList = origingString.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 8); - data.append(reinterpret_cast(&value), 1); - } - } else if (format == SAKCommonDataStructure::InputFormatDec) { - QStringList strList = origingString.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 10); - data.append(reinterpret_cast(&value), 1); - } - } else if (format == SAKCommonDataStructure::InputFormatHex) { - QStringList strList = origingString.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 16); - data.append(reinterpret_cast(&value), 1); - } - } else if (format == SAKCommonDataStructure::InputFormatAscii) { - data = origingString.toLatin1(); - } else if (format == SAKCommonDataStructure::InputFormatLocal) { - data = origingString.toLocal8Bit(); - } else { - data = origingString.toUtf8(); - Q_ASSERT_X(false, __FUNCTION__, "Unknown input mode!"); - } - return data; + return cookedString; } QByteArray SAKCommonDataStructure::stringToByteArray(QString &origingString, - int format) { - auto cookedFormat = - static_cast(format); - return stringToByteArray(origingString, cookedFormat); -} - -QString SAKCommonDataStructure::byteArrayToString( - QByteArray &origingData, SAKEnumTextFormatOutput format) { - QString str; - if (format == SAKCommonDataStructure::OutputFormatBin) { - for (int i = 0; i < origingData.length(); i++) { - str.append(QString("%1 ").arg( - QString::number(static_cast(origingData.at(i)), 2), 8, '0')); - } - } else if (format == SAKCommonDataStructure::OutputFormatOct) { - for (int i = 0; i < origingData.length(); i++) { - str.append(QString("%1 ").arg( - QString::number(static_cast(origingData.at(i)), 8), 3, '0')); - } - } else if (format == SAKCommonDataStructure::OutputFormatDec) { - for (int i = 0; i < origingData.length(); i++) { - str.append(QString("%1 ").arg( - QString::number(static_cast(origingData.at(i)), 10))); - } - } else if (format == SAKCommonDataStructure::OutputFormatHex) { - for (int i = 0; i < origingData.length(); i++) { - str.append(QString("%1 ").arg( - QString::number(static_cast(origingData.at(i)), 16), 2, - '0')); - } - } else if (format == SAKCommonDataStructure::OutputFormatAscii) { - str.append(QString::fromLatin1(origingData)); - } else if (format == SAKCommonDataStructure::OutputFormatUtf8) { - str.append(QString::fromUtf8(origingData)); - } else if (format == SAKCommonDataStructure::OutputFormatUtf16) { - str.append(QString::fromUtf16( - reinterpret_cast(origingData.constData()), - origingData.length() / sizeof(char16_t))); - } else if (format == SAKCommonDataStructure::OutputFormatUcs4) { - str.append(QString::fromUcs4( - reinterpret_cast(origingData.constData()), - origingData.length() / sizeof(char32_t))); - } else if (format == SAKCommonDataStructure::OutputFormatLocal) { - str.append(QString::fromLocal8Bit(origingData)); - } else { - str.append(QString::fromUtf8(origingData)); - Q_ASSERT_X(false, __FUNCTION__, "Unknown output mode!"); - } - - return str; -} - -void SAKCommonDataStructure::setLineEditTextFormat( - QLineEdit *lineEdit, SAKEnumTextFormatInput format) { - QMap regExpMap; - QRegularExpression binRegExp = - QRegularExpression("([01][01][01][01][01][01][01][01][ ])*"); - QRegularExpression otcRegExp = QRegularExpression("([0-7][0-7][ ])*"); - QRegularExpression decRegExp = QRegularExpression("([0-9][0-9][ ])*"); - QRegularExpression hexRegExp = - QRegularExpression("([0-9a-fA-F][0-9a-fA-F][ ])*"); - QRegularExpression asciiRegExp = QRegularExpression("([ -~])*"); - regExpMap.insert(SAKCommonDataStructure::InputFormatBin, - new QRegularExpressionValidator(binRegExp)); - regExpMap.insert(SAKCommonDataStructure::InputFormatOct, - new QRegularExpressionValidator(otcRegExp)); - regExpMap.insert(SAKCommonDataStructure::InputFormatDec, - new QRegularExpressionValidator(decRegExp)); - regExpMap.insert(SAKCommonDataStructure::InputFormatHex, - new QRegularExpressionValidator(hexRegExp)); - regExpMap.insert(SAKCommonDataStructure::InputFormatAscii, - new QRegularExpressionValidator(asciiRegExp)); - regExpMap.insert(SAKCommonDataStructure::InputFormatLocal, Q_NULLPTR); - - if (lineEdit) { - if (lineEdit->validator()) { - delete lineEdit->validator(); - lineEdit->setValidator(Q_NULLPTR); - } - - if (regExpMap.contains(format)) { - QRegularExpressionValidator *validator = regExpMap.value(format); - lineEdit->setValidator(validator); + SAKEnumTextFormatInput format) +{ + QByteArray data; +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) + auto behavior = QString::SkipEmptyParts; +#else + auto behavior = Qt::SkipEmptyParts; +#endif + if (format == SAKCommonDataStructure::InputFormatBin) { + QStringList strList = origingString.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 2); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKCommonDataStructure::InputFormatOct) { + QStringList strList = origingString.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 8); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKCommonDataStructure::InputFormatDec) { + QStringList strList = origingString.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 10); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKCommonDataStructure::InputFormatHex) { + QStringList strList = origingString.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 16); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKCommonDataStructure::InputFormatAscii) { + data = origingString.toLatin1(); + } else if (format == SAKCommonDataStructure::InputFormatLocal) { + data = origingString.toLocal8Bit(); } else { - lineEdit->setValidator(Q_NULLPTR); + data = origingString.toUtf8(); + Q_ASSERT_X(false, __FUNCTION__, "Unknown input mode!"); } - } + + return data; +} + +QByteArray SAKCommonDataStructure::stringToByteArray(QString &origingString, int format) +{ + auto cookedFormat = static_cast(format); + return stringToByteArray(origingString, cookedFormat); +} + +QString SAKCommonDataStructure::byteArrayToString(QByteArray &origingData, + SAKEnumTextFormatOutput format) +{ + QString str; + if (format == SAKCommonDataStructure::OutputFormatBin) { + for (int i = 0; i < origingData.length(); i++) { + str.append( + QString("%1 ").arg(QString::number(static_cast(origingData.at(i)), 2), + 8, + '0')); + } + } else if (format == SAKCommonDataStructure::OutputFormatOct) { + for (int i = 0; i < origingData.length(); i++) { + str.append( + QString("%1 ").arg(QString::number(static_cast(origingData.at(i)), 8), + 3, + '0')); + } + } else if (format == SAKCommonDataStructure::OutputFormatDec) { + for (int i = 0; i < origingData.length(); i++) { + str.append( + QString("%1 ").arg(QString::number(static_cast(origingData.at(i)), 10))); + } + } else if (format == SAKCommonDataStructure::OutputFormatHex) { + for (int i = 0; i < origingData.length(); i++) { + str.append( + QString("%1 ").arg(QString::number(static_cast(origingData.at(i)), 16), + 2, + '0')); + } + } else if (format == SAKCommonDataStructure::OutputFormatAscii) { + str.append(QString::fromLatin1(origingData)); + } else if (format == SAKCommonDataStructure::OutputFormatUtf8) { + str.append(QString::fromUtf8(origingData)); + } else if (format == SAKCommonDataStructure::OutputFormatUtf16) { + str.append(QString::fromUtf16(reinterpret_cast(origingData.constData()), + origingData.length() / sizeof(char16_t))); + } else if (format == SAKCommonDataStructure::OutputFormatUcs4) { + str.append(QString::fromUcs4(reinterpret_cast(origingData.constData()), + origingData.length() / sizeof(char32_t))); + } else if (format == SAKCommonDataStructure::OutputFormatLocal) { + str.append(QString::fromLocal8Bit(origingData)); + } else { + str.append(QString::fromUtf8(origingData)); + Q_ASSERT_X(false, __FUNCTION__, "Unknown output mode!"); + } + + return str; } void SAKCommonDataStructure::setLineEditTextFormat(QLineEdit *lineEdit, - int format) { - auto cookedFormat = static_cast(format); - SAKCommonDataStructure::setLineEditTextFormat(lineEdit, cookedFormat); -} + SAKEnumTextFormatInput format) +{ + QMap regExpMap; + QRegularExpression binRegExp = QRegularExpression("([01][01][01][01][01][01][01][01][ ])*"); + QRegularExpression otcRegExp = QRegularExpression("([0-7][0-7][ ])*"); + QRegularExpression decRegExp = QRegularExpression("([0-9][0-9][ ])*"); + QRegularExpression hexRegExp = QRegularExpression("([0-9a-fA-F][0-9a-fA-F][ ])*"); + QRegularExpression asciiRegExp = QRegularExpression("([ -~])*"); + regExpMap.insert(SAKCommonDataStructure::InputFormatBin, + new QRegularExpressionValidator(binRegExp)); + regExpMap.insert(SAKCommonDataStructure::InputFormatOct, + new QRegularExpressionValidator(otcRegExp)); + regExpMap.insert(SAKCommonDataStructure::InputFormatDec, + new QRegularExpressionValidator(decRegExp)); + regExpMap.insert(SAKCommonDataStructure::InputFormatHex, + new QRegularExpressionValidator(hexRegExp)); + regExpMap.insert(SAKCommonDataStructure::InputFormatAscii, + new QRegularExpressionValidator(asciiRegExp)); + regExpMap.insert(SAKCommonDataStructure::InputFormatLocal, Q_NULLPTR); -QString SAKCommonDataStructure::suffix(SAKEmnuSuffixType type) { - return suffix(int(type)); -} + if (lineEdit) { + if (lineEdit->validator()) { + delete lineEdit->validator(); + lineEdit->setValidator(Q_NULLPTR); + } -QString SAKCommonDataStructure::suffix(int type) { - switch (type) { - case SuffixsTypeNone: - return ""; - case SuffixsTypeR: - return "\r"; - case SuffixsTypeN: - return "\n"; - case SuffixsTypeRN: - return "\r\n"; - case SuffixsTypeNR: - return "\n\r"; - default: - return ""; - } -} - -QString SAKCommonDataStructure::friendlySuffix(SAKEmnuSuffixType type) { - switch (type) { - case SuffixsTypeNone: - return tr("None"); - case SuffixsTypeR: - return "\\r"; - case SuffixsTypeN: - return "\\n"; - case SuffixsTypeRN: - return "\\r\\n"; - case SuffixsTypeNR: - return "\\n\\r"; - default: - return tr("None"); - } -} - -QString SAKCommonDataStructure::prefix(int type) { - switch (type) { - case PrefixTypeNone: - return ""; - case PrefixTypeR: - return "\r"; - case PrefixTypeN: - return "\n"; - case PrefixTypeRN: - return "\r\n"; - case PrefixTypeNR: - return "\n\r"; - default: - return ""; - } -} - -QString SAKCommonDataStructure::friendlyPrefix(SAKEnumPrefixType type) { - switch (type) { - case PrefixTypeNone: - return ""; - case PrefixTypeR: - return "\\r"; - case PrefixTypeN: - return "\\n"; - case PrefixTypeRN: - return "\\r\\n"; - case PrefixTypeNR: - return "\\n\\r"; - default: - return ""; - } -} - -void SAKCommonDataStructure::setupSuffix(QComboBox *comboBox) { - if (comboBox) { - QMap formatMap; - formatMap.insert(SuffixsTypeNone, friendlySuffix(SuffixsTypeNone)); - formatMap.insert(SuffixsTypeR, friendlySuffix(SuffixsTypeR)); - formatMap.insert(SuffixsTypeN, friendlySuffix(SuffixsTypeN)); - formatMap.insert(SuffixsTypeRN, friendlySuffix(SuffixsTypeRN)); - formatMap.insert(SuffixsTypeNR, friendlySuffix(SuffixsTypeNR)); - setComboBoxItems(comboBox, formatMap, SuffixsTypeNone); - } -} - -void SAKCommonDataStructure::formattingInputText(QTextEdit *textEdit, - int model) { - if (textEdit) { - textEdit->blockSignals(true); - QString plaintext = textEdit->toPlainText(); - if (!plaintext.isEmpty()) { - auto cookedModel = - static_cast(model); - QString cookedString = - SAKCommonDataStructure::formattingString(plaintext, cookedModel); - textEdit->setText(cookedString); - textEdit->moveCursor(QTextCursor::End); + if (regExpMap.contains(format)) { + QRegularExpressionValidator *validator = regExpMap.value(format); + lineEdit->setValidator(validator); + } else { + lineEdit->setValidator(Q_NULLPTR); + } + } +} + +void SAKCommonDataStructure::setLineEditTextFormat(QLineEdit *lineEdit, int format) +{ + auto cookedFormat = static_cast(format); + SAKCommonDataStructure::setLineEditTextFormat(lineEdit, cookedFormat); +} + +QString SAKCommonDataStructure::suffix(SAKEmnuSuffixType type) +{ + return suffix(int(type)); +} + +QString SAKCommonDataStructure::suffix(int type) +{ + switch (type) { + case SuffixsTypeNone: + return ""; + case SuffixsTypeR: + return "\r"; + case SuffixsTypeN: + return "\n"; + case SuffixsTypeRN: + return "\r\n"; + case SuffixsTypeNR: + return "\n\r"; + default: + return ""; + } +} + +QString SAKCommonDataStructure::friendlySuffix(SAKEmnuSuffixType type) +{ + switch (type) { + case SuffixsTypeNone: + return tr("None"); + case SuffixsTypeR: + return "\\r"; + case SuffixsTypeN: + return "\\n"; + case SuffixsTypeRN: + return "\\r\\n"; + case SuffixsTypeNR: + return "\\n\\r"; + default: + return tr("None"); + } +} + +QString SAKCommonDataStructure::prefix(int type) +{ + switch (type) { + case PrefixTypeNone: + return ""; + case PrefixTypeR: + return "\r"; + case PrefixTypeN: + return "\n"; + case PrefixTypeRN: + return "\r\n"; + case PrefixTypeNR: + return "\n\r"; + default: + return ""; + } +} + +QString SAKCommonDataStructure::friendlyPrefix(SAKEnumPrefixType type) +{ + switch (type) { + case PrefixTypeNone: + return ""; + case PrefixTypeR: + return "\\r"; + case PrefixTypeN: + return "\\n"; + case PrefixTypeRN: + return "\\r\\n"; + case PrefixTypeNR: + return "\\n\\r"; + default: + return ""; + } +} + +void SAKCommonDataStructure::setupSuffix(QComboBox *comboBox) +{ + if (comboBox) { + QMap formatMap; + formatMap.insert(SuffixsTypeNone, friendlySuffix(SuffixsTypeNone)); + formatMap.insert(SuffixsTypeR, friendlySuffix(SuffixsTypeR)); + formatMap.insert(SuffixsTypeN, friendlySuffix(SuffixsTypeN)); + formatMap.insert(SuffixsTypeRN, friendlySuffix(SuffixsTypeRN)); + formatMap.insert(SuffixsTypeNR, friendlySuffix(SuffixsTypeNR)); + setComboBoxItems(comboBox, formatMap, SuffixsTypeNone); + } +} + +void SAKCommonDataStructure::formattingInputText(QTextEdit *textEdit, int model) +{ + if (textEdit) { + textEdit->blockSignals(true); + QString plaintext = textEdit->toPlainText(); + if (!plaintext.isEmpty()) { + auto cookedModel = static_cast(model); + QString cookedString = SAKCommonDataStructure::formattingString(plaintext, cookedModel); + textEdit->setText(cookedString); + textEdit->moveCursor(QTextCursor::End); + } + textEdit->blockSignals(false); } - textEdit->blockSignals(false); - } } void SAKCommonDataStructure::setComboBoxItems(QComboBox *comboBox, QMap &formatMap, - int currentData) { - if (comboBox) { - comboBox->clear(); - QMapIterator mapIterator(formatMap); - QStandardItemModel *itemModel = new QStandardItemModel(comboBox); - while (mapIterator.hasNext()) { - mapIterator.next(); - QStandardItem *item = new QStandardItem(mapIterator.value()); - item->setToolTip(mapIterator.value()); - itemModel->appendRow(item); - } - comboBox->setModel(itemModel); - comboBox->setCurrentIndex(currentData); + int currentData) +{ + if (comboBox) { + comboBox->clear(); + QMapIterator mapIterator(formatMap); + QStandardItemModel *itemModel = new QStandardItemModel(comboBox); + while (mapIterator.hasNext()) { + mapIterator.next(); + QStandardItem *item = new QStandardItem(mapIterator.value()); + item->setToolTip(mapIterator.value()); + itemModel->appendRow(item); + } + comboBox->setModel(itemModel); + comboBox->setCurrentIndex(currentData); - // Reset the iterator... - while (mapIterator.hasPrevious()) { - mapIterator.previous(); - } + // Reset the iterator... + while (mapIterator.hasPrevious()) { + mapIterator.previous(); + } - // Set item data of combo box - int index = 0; - while (mapIterator.hasNext()) { - mapIterator.next(); - comboBox->setItemData(index, QVariant::fromValue(mapIterator.key())); - index += 1; - } + // Set item data of combo box + int index = 0; + while (mapIterator.hasNext()) { + mapIterator.next(); + comboBox->setItemData(index, QVariant::fromValue(mapIterator.key())); + index += 1; + } - // Try to set the current index. - for (int i = 0; i < comboBox->count(); i++) { - if (comboBox->itemData(i).toInt() == currentData) { - comboBox->setCurrentIndex(i); - } + // Try to set the current index. + for (int i = 0; i < comboBox->count(); i++) { + if (comboBox->itemData(i).toInt() == currentData) { + comboBox->setCurrentIndex(i); + } + } } - } } diff --git a/src/common/common/sakcommondatastructure.h b/src/common/common/sakcommondatastructure.h index 17b12465..2736df23 100644 --- a/src/common/common/sakcommondatastructure.h +++ b/src/common/common/sakcommondatastructure.h @@ -10,10 +10,10 @@ #ifndef SAKCOMMONDATASTRUCTURE_H #define SAKCOMMONDATASTRUCTURE_H +#include #include #include #include -#include #ifdef SAK_IMPORT_MODULE_SERIALPORT #include @@ -27,11 +27,11 @@ /// @brief The class define some data structure of the project. /// Also, It provides some interface about these data structure. -class SAKCommonDataStructure:public QObject +class SAKCommonDataStructure : public QObject { Q_OBJECT public: - SAKCommonDataStructure(QObject* parent = Q_NULLPTR); + SAKCommonDataStructure(QObject *parent = Q_NULLPTR); ~SAKCommonDataStructure(); // Input text format @@ -75,17 +75,12 @@ public: }; Q_ENUM(SAKEmnuSuffixType); - enum SAKEnumPrefixType { - PrefixTypeNone, - PrefixTypeR, - PrefixTypeN, - PrefixTypeRN, - PrefixTypeNR - }; + enum SAKEnumPrefixType { PrefixTypeNone, PrefixTypeR, PrefixTypeN, PrefixTypeRN, PrefixTypeNR }; Q_ENUM(SAKEnumPrefixType); #ifdef SAK_IMPORT_MODULE_TEST - struct SAKStructTestParametersContext { + struct SAKStructTestParametersContext + { bool openFailed; bool readCircularly; int readInterval; @@ -98,7 +93,8 @@ public: #endif #ifdef SAK_IMPORT_MODULE_SERIALPORT - struct SAKStructSerialPortParametersContext { + struct SAKStructSerialPortParametersContext + { QString portName; qint32 baudRate; QSerialPort::DataBits dataBits; @@ -112,7 +108,8 @@ public: #ifdef SAK_IMPORT_MODULE_UDP #ifdef SAK_IMPORT_MODULE_UDP_CLIENT - struct SAKStructUdpClientParametersContext { + struct SAKStructUdpClientParametersContext + { QString peerHost; quint16 peerPort; QString localHost; @@ -120,7 +117,8 @@ public: bool specifyLocalInfo; bool pauseSending; }; - struct SAKStructUdpServerParametersContext { + struct SAKStructUdpServerParametersContext + { QString serverHost; quint16 serverPort; @@ -133,7 +131,8 @@ public: #ifdef SAK_IMPORT_MODULE_TCP #ifdef SAK_IMPORT_MODULE_TCP_CLIENT - struct SAKStructTcpClientParametersContext { + struct SAKStructTcpClientParametersContext + { QString localHost; quint16 localPort; QString serverHost; @@ -143,7 +142,8 @@ public: }; #endif #ifdef SAK_IMPORT_MODULE_TCP_SERVER - struct SAKStructTcpServerParametersContext { + struct SAKStructTcpServerParametersContext + { QString serverHost; quint16 serverPort; QString currentClientHost; @@ -153,13 +153,15 @@ public: #endif #ifdef SAK_IMPORT_MODULE_WEBSOCKET #ifdef SAK_IMPORT_MODULE_WEBSOCKET_CLIENT - struct SAKStructWSClientParametersContext { + struct SAKStructWSClientParametersContext + { QString serverAddress; quint32 sendingType; }; #endif #ifdef SAK_IMPORT_MODULE_WEBSOCKET_SERVER - struct SAKStructWSServerParametersContext { + struct SAKStructWSServerParametersContext + { QString serverHost; quint16 serverPort; QString currentClientHost; @@ -170,7 +172,8 @@ public: #endif #ifdef SAK_IMPORT_MODULE_BLE #ifdef SAK_IMPORT_MODULE_BLE_CENTRAL - struct SAKStructBleCentralParametersContext { + struct SAKStructBleCentralParametersContext + { QBluetoothDeviceInfo info; QString uuid; }; @@ -200,8 +203,7 @@ public: * @param textEdit: Target text edit. * @param format: See SAKEnumTextInputFormat for more information. */ - static QString formattingString(QString &origingString, - SAKEnumTextFormatInput format); + static QString formattingString(QString &origingString, SAKEnumTextFormatInput format); /** * @brief stringToByteArray: Transmit a QString to a QByteArray. @@ -209,8 +211,7 @@ public: * @param format: See SAKEnumTextInputFormat for more information. * @return A QByteArray. */ - static QByteArray stringToByteArray(QString &origingString, - SAKEnumTextFormatInput format); + static QByteArray stringToByteArray(QString &origingString, SAKEnumTextFormatInput format); static QByteArray stringToByteArray(QString &origingString, int format); /** @@ -219,16 +220,14 @@ public: * @param format: See SAKEnumTextOutputFormat for more information. * @return A QString. */ - static QString byteArrayToString(QByteArray &origingData, - SAKEnumTextFormatOutput format); + static QString byteArrayToString(QByteArray &origingData, SAKEnumTextFormatOutput format); /** * @brief setLineEditTextFormat: Formating input * @param lineEdit: Target component * @param format: (SAKEnumTextInputFormat) */ - static void setLineEditTextFormat(QLineEdit *lineEdit, - SAKEnumTextFormatInput format); + static void setLineEditTextFormat(QLineEdit *lineEdit, SAKEnumTextFormatInput format); static void setLineEditTextFormat(QLineEdit *lineEdit, int format); static QString suffix(SAKEmnuSuffixType type); @@ -239,6 +238,7 @@ public: static void setupSuffix(QComboBox *comboBox); static void formattingInputText(QTextEdit *textEdit, int model); + private: static void setComboBoxItems(QComboBox *comboBox, QMap &formatMap, diff --git a/src/common/common/sakcommoninterface.cc b/src/common/common/sakcommoninterface.cc index e0b8fbb4..a27e7873 100644 --- a/src/common/common/sakcommoninterface.cc +++ b/src/common/common/sakcommoninterface.cc @@ -7,57 +7,48 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include -#include #include #include +#include +#include #include -#include #include #include +#include #ifdef SAK_IMPORT_MODULE_SERIALPORT #include #include #endif -#include "sakcommoninterface.h" #include "sakcommoncrcinterface.h" +#include "sakcommoninterface.h" SAKCommonInterface::SAKCommonInterface(QObject *parent) - :QObject (parent) -{ - -} + : QObject(parent) +{} void SAKCommonInterface::setLineEditValidator(QLineEdit *lineEdit, SAKEnumValidatorType type, int maxLength) -{ +{ QMap regExpMap; - regExpMap.insert(ValidatorBin, - QRegularExpression("([01][01][01][01][01][01][01][01][ ])*")); - regExpMap.insert(ValidatorOtc, - QRegularExpression("([0-7][0-7][ ])*")); - regExpMap.insert(ValidatorDec, - QRegularExpression("([0-9][0-9][ ])*")); - regExpMap.insert(ValidatorHex, - QRegularExpression("([0-9a-fA-F][0-9a-fA-F][ ])*")); - regExpMap.insert(ValidatorAscii, - QRegularExpression("([ -~])*")); - regExpMap.insert(ValidatorFloat, - QRegularExpression("^[-+]?[0-9]*\\.?[0-9]+$")); + regExpMap.insert(ValidatorBin, QRegularExpression("([01][01][01][01][01][01][01][01][ ])*")); + regExpMap.insert(ValidatorOtc, QRegularExpression("([0-7][0-7][ ])*")); + regExpMap.insert(ValidatorDec, QRegularExpression("([0-9][0-9][ ])*")); + regExpMap.insert(ValidatorHex, QRegularExpression("([0-9a-fA-F][0-9a-fA-F][ ])*")); + regExpMap.insert(ValidatorAscii, QRegularExpression("([ -~])*")); + regExpMap.insert(ValidatorFloat, QRegularExpression("^[-+]?[0-9]*\\.?[0-9]+$")); - if (lineEdit){ - if (lineEdit->validator()){ + if (lineEdit) { + if (lineEdit->validator()) { delete lineEdit->validator(); } - if (regExpMap.contains(type)){ - if (type != ValidatorNone){ - auto regExpValidator = - new QRegularExpressionValidator(regExpMap.value(type), - lineEdit); + if (regExpMap.contains(type)) { + if (type != ValidatorNone) { + auto regExpValidator = new QRegularExpressionValidator(regExpMap.value(type), + lineEdit); lineEdit->setValidator(regExpValidator); lineEdit->setMaxLength(maxLength); } @@ -68,11 +59,11 @@ void SAKCommonInterface::setLineEditValidator(QLineEdit *lineEdit, #ifdef SAK_IMPORT_MODULE_SERIALPORT void SAKCommonInterface::addSerialPortNametItemsToComboBox(QComboBox *comboBox) { - if (comboBox){ + if (comboBox) { comboBox->clear(); QList coms = QSerialPortInfo::availablePorts(); QStandardItemModel *itemModel = new QStandardItemModel(comboBox); - for(auto &var:coms){ + for (auto &var : coms) { QStandardItem *item = new QStandardItem(var.portName()); item->setToolTip(var.description()); itemModel->appendRow(item); @@ -86,10 +77,10 @@ void SAKCommonInterface::addSerialPortNametItemsToComboBox(QComboBox *comboBox) #ifdef SAK_IMPORT_MODULE_SERIALPORT void SAKCommonInterface::addSerialPortBaudRateItemsToComboBox(QComboBox *comboBox) { - if (comboBox){ + if (comboBox) { comboBox->clear(); QList bd = QSerialPortInfo::standardBaudRates(); - for (auto &var:bd) { + for (auto &var : bd) { comboBox->addItem(QString::number(var), QVariant::fromValue(var)); } @@ -101,7 +92,7 @@ void SAKCommonInterface::addSerialPortBaudRateItemsToComboBox(QComboBox *comboBo #ifdef SAK_IMPORT_MODULE_SERIALPORT void SAKCommonInterface::addSerialPortDataBitItemsToComboBox(QComboBox *comboBox) { - if (comboBox){ + if (comboBox) { comboBox->clear(); comboBox->addItem("8", QVariant::fromValue(int(QSerialPort::Data8))); comboBox->addItem("7", QVariant::fromValue(int(QSerialPort::Data7))); @@ -114,16 +105,13 @@ void SAKCommonInterface::addSerialPortDataBitItemsToComboBox(QComboBox *comboBox #ifdef SAK_IMPORT_MODULE_SERIALPORT void SAKCommonInterface::addSerialPortStopBitItemsToComboBox(QComboBox *comboBox) { - if (comboBox){ + if (comboBox) { comboBox->clear(); - comboBox->addItem("1", - QVariant::fromValue(int(QSerialPort::OneStop))); + comboBox->addItem("1", QVariant::fromValue(int(QSerialPort::OneStop))); #ifdef Q_OS_WINDOWS - comboBox->addItem("1.5", - QVariant::fromValue(int(QSerialPort::OneAndHalfStop))); + comboBox->addItem("1.5", QVariant::fromValue(int(QSerialPort::OneAndHalfStop))); #endif - comboBox->addItem("2", - QVariant::fromValue(int(QSerialPort::TwoStop))); + comboBox->addItem("2", QVariant::fromValue(int(QSerialPort::TwoStop))); } } #endif @@ -131,18 +119,13 @@ void SAKCommonInterface::addSerialPortStopBitItemsToComboBox(QComboBox *comboBox #ifdef SAK_IMPORT_MODULE_SERIALPORT void SAKCommonInterface::addSerialPortParityItemsToComboBox(QComboBox *comboBox) { - if (comboBox){ + if (comboBox) { comboBox->clear(); - comboBox->addItem(tr("No"), - QVariant::fromValue(int(QSerialPort::NoParity))); - comboBox->addItem(tr("Even"), - QVariant::fromValue(int(QSerialPort::EvenParity))); - comboBox->addItem(tr("Odd"), - QVariant::fromValue(int(QSerialPort::OddParity))); - comboBox->addItem(tr("Space"), - QVariant::fromValue(int(QSerialPort::SpaceParity))); - comboBox->addItem(tr("Mark"), - QVariant::fromValue(int(QSerialPort::MarkParity))); + comboBox->addItem(tr("No"), QVariant::fromValue(int(QSerialPort::NoParity))); + comboBox->addItem(tr("Even"), QVariant::fromValue(int(QSerialPort::EvenParity))); + comboBox->addItem(tr("Odd"), QVariant::fromValue(int(QSerialPort::OddParity))); + comboBox->addItem(tr("Space"), QVariant::fromValue(int(QSerialPort::SpaceParity))); + comboBox->addItem(tr("Mark"), QVariant::fromValue(int(QSerialPort::MarkParity))); } } #endif @@ -150,14 +133,11 @@ void SAKCommonInterface::addSerialPortParityItemsToComboBox(QComboBox *comboBox) #ifdef SAK_IMPORT_MODULE_SERIALPORT void SAKCommonInterface::addSerialPortFlowControlItemsToComboBox(QComboBox *comboBox) { - if (comboBox){ + if (comboBox) { comboBox->clear(); - comboBox->addItem(tr("No"), - QVariant::fromValue(int(QSerialPort::NoFlowControl))); - comboBox->addItem(tr("Hardware"), - QVariant::fromValue(int(QSerialPort::HardwareControl))); - comboBox->addItem(tr("Software"), - QVariant::fromValue(int(QSerialPort::SoftwareControl))); + comboBox->addItem(tr("No"), QVariant::fromValue(int(QSerialPort::NoFlowControl))); + comboBox->addItem(tr("Hardware"), QVariant::fromValue(int(QSerialPort::HardwareControl))); + comboBox->addItem(tr("Software"), QVariant::fromValue(int(QSerialPort::SoftwareControl))); } } #endif @@ -165,23 +145,23 @@ void SAKCommonInterface::addSerialPortFlowControlItemsToComboBox(QComboBox *comb void SAKCommonInterface::addIpItemsToComboBox(QComboBox *comboBox, bool appendHostAny) { QString localHost("127.0.0.1"); - if (comboBox){ + if (comboBox) { comboBox->clear(); comboBox->addItem(QString("::")); comboBox->addItem(QString("::1")); comboBox->addItem(QString("0.0.0.0")); comboBox->addItem(localHost); QList addresses = QNetworkInterface::allAddresses(); - for(auto &var:addresses){ + for (auto &var : addresses) { if (var.protocol() == QAbstractSocket::IPv4Protocol) { - if (var.toString().compare(localHost) == 0){ + if (var.toString().compare(localHost) == 0) { continue; } comboBox->addItem(var.toString()); } } - if (appendHostAny){ + if (appendHostAny) { comboBox->addItem(QString(SAK_HOST_ADDRESS_ANY)); } comboBox->setCurrentText(localHost); @@ -193,14 +173,14 @@ void SAKCommonInterface::setComboBoxIndexFromSettings(QSettings *settings, QComboBox *comboBox) { int index = settings->value(key).toInt(); - if (index >= 0 && index < comboBox->count()){ + if (index >= 0 && index < comboBox->count()) { comboBox->setCurrentIndex(index); } } void SAKCommonInterface::setSettingsValueFromComboBoxIndex(QSettings *settings, - QString key, - QComboBox *comboBox) + QString key, + QComboBox *comboBox) { int currentIndex = comboBox->currentIndex(); settings->setValue(key, currentIndex); diff --git a/src/common/common/sakcommoninterface.h b/src/common/common/sakcommoninterface.h index 2f3456d9..2c322eb2 100644 --- a/src/common/common/sakcommoninterface.h +++ b/src/common/common/sakcommoninterface.h @@ -10,38 +10,48 @@ #ifndef SAKCOMMONINTERFACE_H #define SAKCOMMONINTERFACE_H -#include #include -#include -#include #include +#include +#include +#include -#define microIni2CoB(settings, settingsGroup, structMember, comboBox)\ - SAKCommonInterface::setComboBoxIndexFromSettings(settings,\ - settingsGroup + QString("/") + QString(#structMember).split('.').last(),\ - comboBox) -#define microCoB2Ini(settings, settingsGroup, structMember, comboBox)\ - SAKCommonInterface::setSettingsValueFromComboBoxIndex(settings,\ - settingsGroup + QString("/") + QString(#structMember).split('.').last(),\ - comboBox) -#define microIni2LE(settings, settingsGroup, structMember, lineEdit)\ - SAKCommonInterface::setLineEditTextFromSettings(settings,\ - settingsGroup + QString("/") + QString(#structMember).split('.').last(),\ - lineEdit) -#define microLE2Ini(settings, settingsGroup, structMember, lineEdit)\ - SAKCommonInterface::setSettingsValueFromLineEditText(settings,\ - settingsGroup + QString("/") + QString(#structMember).split('.').last(),\ - lineEdit) -#define microIni2ChB(settings, settingsGroup, structMember, checkBox)\ - SAKCommonInterface::setCheckBoxValueFromSettings(settings,\ - settingsGroup + QString("/") + QString(#structMember).split('.').last(),\ - checkBox) -#define microChB2Ini(settings, settingsGroup, structMember, checkBox)\ - SAKCommonInterface::setSettingsValueFromCheckBox(settings,\ - settingsGroup + QString("/") + QString(#structMember).split('.').last(),\ - checkBox) +#define microIni2CoB(settings, settingsGroup, structMember, comboBox) \ + SAKCommonInterface::setComboBoxIndexFromSettings(settings, \ + settingsGroup + QString("/") \ + + QString(#structMember).split('.').last(), \ + comboBox) +#define microCoB2Ini(settings, settingsGroup, structMember, comboBox) \ + SAKCommonInterface::setSettingsValueFromComboBoxIndex(settings, \ + settingsGroup + QString("/") \ + + QString(#structMember) \ + .split('.') \ + .last(), \ + comboBox) +#define microIni2LE(settings, settingsGroup, structMember, lineEdit) \ + SAKCommonInterface::setLineEditTextFromSettings(settings, \ + settingsGroup + QString("/") \ + + QString(#structMember).split('.').last(), \ + lineEdit) +#define microLE2Ini(settings, settingsGroup, structMember, lineEdit) \ + SAKCommonInterface::setSettingsValueFromLineEditText(settings, \ + settingsGroup + QString("/") \ + + QString(#structMember) \ + .split('.') \ + .last(), \ + lineEdit) +#define microIni2ChB(settings, settingsGroup, structMember, checkBox) \ + SAKCommonInterface::setCheckBoxValueFromSettings(settings, \ + settingsGroup + QString("/") \ + + QString(#structMember).split('.').last(), \ + checkBox) +#define microChB2Ini(settings, settingsGroup, structMember, checkBox) \ + SAKCommonInterface::setSettingsValueFromCheckBox(settings, \ + settingsGroup + QString("/") \ + + QString(#structMember).split('.').last(), \ + checkBox) -class SAKCommonInterface:public QObject +class SAKCommonInterface : public QObject { Q_OBJECT public: @@ -77,9 +87,13 @@ public: #endif static void addIpItemsToComboBox(QComboBox *comboBox, bool appendHostAny = false); static void setComboBoxIndexFromSettings(QSettings *settings, QString key, QComboBox *comboBox); - static void setSettingsValueFromComboBoxIndex(QSettings *settings, QString key, QComboBox *comboBox); + static void setSettingsValueFromComboBoxIndex(QSettings *settings, + QString key, + QComboBox *comboBox); static void setLineEditTextFromSettings(QSettings *settings, QString key, QLineEdit *lineEdit); - static void setSettingsValueFromLineEditText(QSettings *settings, QString key, QLineEdit *lineEdit); + static void setSettingsValueFromLineEditText(QSettings *settings, + QString key, + QLineEdit *lineEdit); static void setCheckBoxValueFromSettings(QSettings *settings, QString key, QCheckBox *checkBox); static void setSettingsValueFromCheckBox(QSettings *settings, QString key, QCheckBox *checkBox); }; diff --git a/src/common/common/sakcrcinterface.cc b/src/common/common/sakcrcinterface.cc index 8281bd2c..80373316 100644 --- a/src/common/common/sakcrcinterface.cc +++ b/src/common/common/sakcrcinterface.cc @@ -12,10 +12,8 @@ #include "sakcrcinterface.h" SAKCrcInterface::SAKCrcInterface(QObject *parent) - :QObject (parent) -{ - -} + : QObject(parent) +{} QString SAKCrcInterface::calculateString(const QString &bytes, int format) { @@ -24,26 +22,21 @@ QString SAKCrcInterface::calculateString(const QString &bytes, int format) return QString(); } -QByteArray SAKCrcInterface::calculateBytes(const QByteArray &bytes, - int arithmetic, - int startIndex, - int endIndex, - bool bigEndian) +QByteArray SAKCrcInterface::calculateBytes( + const QByteArray &bytes, int arithmetic, int startIndex, int endIndex, bool bigEndian) { - auto parametersIsValid = [&]()->bool{ + auto parametersIsValid = [&]() -> bool { if (bytes.isEmpty() && (startIndex == 0) && (endIndex == 0)) { return true; } if (!(startIndex >= 0 && startIndex < bytes.length())) { - qCWarning(mLoggingCategory) << "start index is invalid:" - << startIndex; + qCWarning(mLoggingCategory) << "start index is invalid:" << startIndex; return false; } if (!(endIndex >= 0 && endIndex < bytes.length())) { - qCWarning(mLoggingCategory) << "end index is invalid:" - << endIndex; + qCWarning(mLoggingCategory) << "end index is invalid:" << endIndex; return false; } @@ -63,34 +56,34 @@ QByteArray SAKCrcInterface::calculateBytes(const QByteArray &bytes, uint64_t len = bytes.length() - startIndex - endIndex; QByteArray temp = bytes; if (bw == 8) { - uint8_t ret = crcCalculate( - reinterpret_cast(temp.data()) + startIndex, - len, SAKEnumCrcAlgorithm(arithmetic)); - retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); + uint8_t ret = crcCalculate(reinterpret_cast(temp.data()) + + startIndex, + len, + SAKEnumCrcAlgorithm(arithmetic)); + retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); } else if (bw == 16) { - uint16_t ret = crcCalculate( - reinterpret_cast(temp.data()) + startIndex, - len, SAKEnumCrcAlgorithm(arithmetic)); - retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); + uint16_t ret = crcCalculate(reinterpret_cast(temp.data()) + + startIndex, + len, + SAKEnumCrcAlgorithm(arithmetic)); + retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); } else if (bw == 32) { - uint32_t ret = crcCalculate( - reinterpret_cast(temp.data()) + startIndex, - len, SAKEnumCrcAlgorithm(arithmetic)); - retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); + uint32_t ret = crcCalculate(reinterpret_cast(temp.data()) + + startIndex, + len, + SAKEnumCrcAlgorithm(arithmetic)); + retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); } } else { if (bw == 8) { - uint8_t ret = crcCalculate( - nullptr, 0, SAKEnumCrcAlgorithm(arithmetic)); - retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); + uint8_t ret = crcCalculate(nullptr, 0, SAKEnumCrcAlgorithm(arithmetic)); + retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); } else if (bw == 16) { - uint16_t ret = crcCalculate( - nullptr, 0, SAKEnumCrcAlgorithm(arithmetic)); - retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); + uint16_t ret = crcCalculate(nullptr, 0, SAKEnumCrcAlgorithm(arithmetic)); + retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); } else if (bw == 32) { - uint32_t ret = crcCalculate( - nullptr, 0, SAKEnumCrcAlgorithm(arithmetic)); - retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); + uint32_t ret = crcCalculate(nullptr, 0, SAKEnumCrcAlgorithm(arithmetic)); + retBytes = QByteArray(reinterpret_cast(&ret), sizeof(ret)); } } @@ -113,7 +106,7 @@ QStringList SAKCrcInterface::supportedParameterModels() const char *ch = Q_NULLPTR; for (int i = 0; i < models.keyCount(); i++) { ch = models.valueToKey(i); - if (ch){ + if (ch) { modelStrings.append(QString(ch)); } } @@ -290,7 +283,7 @@ bool SAKCrcInterface::isInputReversal(SAKCrcInterface::SAKEnumCrcAlgorithm model case CRC_16_DNP: case CRC_32: reversal = true; - break; + break; } return reversal; @@ -320,7 +313,7 @@ bool SAKCrcInterface::isOutputReversal(SAKCrcInterface::SAKEnumCrcAlgorithm mode case CRC_16_DNP: case CRC_32: reversal = true; - break; + break; } return reversal; diff --git a/src/common/common/sakcrcinterface.h b/src/common/common/sakcrcinterface.h index 00dccf63..8c5efba5 100644 --- a/src/common/common/sakcrcinterface.h +++ b/src/common/common/sakcrcinterface.h @@ -10,15 +10,15 @@ #ifndef SAKCRCINTERFACE_H #define SAKCRCINTERFACE_H +#include #include #include -#include class SAKCrcInterface : public QObject { Q_OBJECT public: - enum SAKEnumCrcAlgorithm{ + enum SAKEnumCrcAlgorithm { CRC_8, CRC_8_ITU, CRC_8_ROHC, @@ -60,35 +60,34 @@ public: public: template - T crcCalculate(uint8_t *input, - uint64_t length, - SAKCrcInterface::SAKEnumCrcAlgorithm model){ + T crcCalculate(uint8_t *input, uint64_t length, SAKCrcInterface::SAKEnumCrcAlgorithm model) + { T crcReg = static_cast(initialValue(model)); T rawPoly = static_cast(poly(model)); uint8_t byte = 0; T temp = 1; - while (length--){ + while (length--) { byte = *(input++); - if (isInputReversal(model)){ - reverseInt(byte,byte); + if (isInputReversal(model)) { + reverseInt(byte, byte); } - crcReg ^= static_cast((byte << 8*(sizeof (T)-1))); - for(int i = 0;i < 8;i++){ - if(crcReg & (temp << (sizeof (T)*8-1))){ + crcReg ^= static_cast((byte << 8 * (sizeof(T) - 1))); + for (int i = 0; i < 8; i++) { + if (crcReg & (temp << (sizeof(T) * 8 - 1))) { crcReg = static_cast((crcReg << 1) ^ rawPoly); - }else { + } else { crcReg = static_cast(crcReg << 1); } } } - if (isOutputReversal(model)){ - reverseInt(crcReg,crcReg); + if (isOutputReversal(model)) { + reverseInt(crcReg, crcReg); } - T crc = (crcReg ^ static_cast(xorValue(model))) ; + T crc = (crcReg ^ static_cast(xorValue(model))); return crc; } @@ -98,13 +97,14 @@ private: private: template - bool reverseInt(const T &input, T &output){ - int bitsWidth = sizeof (input)*8; + bool reverseInt(const T &input, T &output) + { + int bitsWidth = sizeof(input) * 8; QString inputStr = QString("%1").arg(QString::number(input, 2), bitsWidth, '0'); QString outputStr; outputStr.resize(bitsWidth); - for (int i = 0; i < bitsWidth; i++){ - outputStr.replace(i, 1, inputStr.at(bitsWidth-1-i)); + for (int i = 0; i < bitsWidth; i++) { + outputStr.replace(i, 1, inputStr.at(bitsWidth - 1 - i)); } bool ok; diff --git a/src/common/common/sakdatastructure.cc b/src/common/common/sakdatastructure.cc index 20013318..26ed2d38 100644 --- a/src/common/common/sakdatastructure.cc +++ b/src/common/common/sakdatastructure.cc @@ -7,15 +7,13 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ +#include "sakdatastructure.h" #include "sakcrcinterface.h" #include "sakinterface.h" -#include "sakdatastructure.h" SAKDataStructure::SAKDataStructure(QObject *parent) : QObject{parent} -{ - -} +{} QString SAKDataStructure::affixesName(int affixes) { @@ -51,7 +49,6 @@ QByteArray SAKDataStructure::affixesData(int affixes) return QByteArray(""); } - QString SAKDataStructure::cookedString(int escapeCharacter, const QString &str) { return SAKDataStructure::cookEscapeCharacter(escapeCharacter, str); @@ -65,9 +62,9 @@ QByteArray SAKDataStructure::dataItemBytes(const EDStructDataItem &item) bytes = SAKInterface::string2array(text, item.itemTextFormat); SAKCrcInterface sakCrc; QByteArray crcBytes = sakCrc.calculateBytes(bytes, - item.itemCrcAlgorithm, - item.itemCrcStartIndex, - item.itemCrcEndIndex); + item.itemCrcAlgorithm, + item.itemCrcStartIndex, + item.itemCrcEndIndex); QByteArray prefix = SAKDataStructure::affixesData(item.itemPrefix); QByteArray suffix = SAKDataStructure::affixesData(item.itemSuffix); @@ -96,4 +93,3 @@ QString SAKDataStructure::cookEscapeCharacter(int option, const QString &str) return newStr; } - diff --git a/src/common/common/sakdatastructure.h b/src/common/common/sakdatastructure.h index d7028056..dc8f7a55 100644 --- a/src/common/common/sakdatastructure.h +++ b/src/common/common/sakdatastructure.h @@ -13,85 +13,79 @@ #include #include -class SAKDataStructure : public QObject { - Q_OBJECT - public: - explicit SAKDataStructure(QObject* parent = nullptr); +class SAKDataStructure : public QObject +{ + Q_OBJECT +public: + explicit SAKDataStructure(QObject* parent = nullptr); - enum SAKEnumTextFormat { - TextFormatBin, - TextFormatOct, - TextFormatDec, - TextFormatHex, - TextFormatAscii, - TextFormatUtf8 - }; - Q_ENUM(SAKEnumTextFormat) + enum SAKEnumTextFormat { + TextFormatBin, + TextFormatOct, + TextFormatDec, + TextFormatHex, + TextFormatAscii, + TextFormatUtf8 + }; + Q_ENUM(SAKEnumTextFormat) - enum SAKEnumEscapeCharacterOption { - EscapeCharacterOptionNone, - EscapeCharacterOptionR, - EscapeCharacterOptionN, - EscapeCharacterOptionRN, - EscapeCharacterOptionNR, - EscapeCharacterOptionRAndN - }; - Q_ENUM(SAKEnumEscapeCharacterOption) + enum SAKEnumEscapeCharacterOption { + EscapeCharacterOptionNone, + EscapeCharacterOptionR, + EscapeCharacterOptionN, + EscapeCharacterOptionRN, + EscapeCharacterOptionNR, + EscapeCharacterOptionRAndN + }; + Q_ENUM(SAKEnumEscapeCharacterOption) - enum SAKEnumAffixes { AffixesNone, AffixesR, AffixesN, AffixesRN, AffixesNR }; - Q_ENUM(SAKEnumAffixes) + enum SAKEnumAffixes { AffixesNone, AffixesR, AffixesN, AffixesRN, AffixesNR }; + Q_ENUM(SAKEnumAffixes) - enum EDEnumResponseOptions { - ResponseOptionDisable, - ResponseOptionEcho, - ResponseOptionAlways, - ResponseOptionInputEqualReference, - ResponseOptionInputContainReference, - ResponseOptionInputDiscontainReference - }; - Q_ENUM(EDEnumResponseOptions) + enum EDEnumResponseOptions { + ResponseOptionDisable, + ResponseOptionEcho, + ResponseOptionAlways, + ResponseOptionInputEqualReference, + ResponseOptionInputContainReference, + ResponseOptionInputDiscontainReference + }; + Q_ENUM(EDEnumResponseOptions) - enum SAKEnumPalette { - PaletteSystem, - PaletteLight, - PaletteDark, - PaletteCustom - }; - Q_ENUM(SAKEnumPalette) + enum SAKEnumPalette { PaletteSystem, PaletteLight, PaletteDark, PaletteCustom }; + Q_ENUM(SAKEnumPalette) #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - enum SAKHdpiPolicy { - HdpiPolicyRound = int(Qt::HighDpiScaleFactorRoundingPolicy::Round), - HdpiPolicyCeil = int(Qt::HighDpiScaleFactorRoundingPolicy::Ceil), - HdpiPolicyFloor = int(Qt::HighDpiScaleFactorRoundingPolicy::Floor), - HdpiPolicyRoundPreferFloor = - int(Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor), - HdpiPolicyPassThrough = - int(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough), - HdpiPolicySystem = 999 - }; - Q_ENUM(SAKHdpiPolicy) + enum SAKHdpiPolicy { + HdpiPolicyRound = int(Qt::HighDpiScaleFactorRoundingPolicy::Round), + HdpiPolicyCeil = int(Qt::HighDpiScaleFactorRoundingPolicy::Ceil), + HdpiPolicyFloor = int(Qt::HighDpiScaleFactorRoundingPolicy::Floor), + HdpiPolicyRoundPreferFloor = int(Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor), + HdpiPolicyPassThrough = int(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough), + HdpiPolicySystem = 999 + }; + Q_ENUM(SAKHdpiPolicy) #endif - struct EDStructDataItem { - int itemTextFormat; - int itemTextEscapeChracter; - QString itemText; - int itemPrefix; - int itemSuffix; + struct EDStructDataItem + { + int itemTextFormat; + int itemTextEscapeChracter; + QString itemText; + int itemPrefix; + int itemSuffix; - bool itemCrcEnable; - int itemCrcAlgorithm; - int itemCrcStartIndex; - int itemCrcEndIndex; - }; + bool itemCrcEnable; + int itemCrcAlgorithm; + int itemCrcStartIndex; + int itemCrcEndIndex; + }; - public: - static QString affixesName(int affixes); - static QByteArray affixesData(int affixes); - static QString cookedString(int escapeCharacter, const QString& str); - static QByteArray dataItemBytes(const EDStructDataItem& item); - Q_INVOKABLE static QString cookEscapeCharacter(int option, - const QString& str); +public: + static QString affixesName(int affixes); + static QByteArray affixesData(int affixes); + static QString cookedString(int escapeCharacter, const QString& str); + static QByteArray dataItemBytes(const EDStructDataItem& item); + Q_INVOKABLE static QString cookEscapeCharacter(int option, const QString& str); }; -#endif // SAKDATASTRUCTURE_H +#endif // SAKDATASTRUCTURE_H diff --git a/src/common/common/sakhighlighter.cc b/src/common/common/sakhighlighter.cc index 38fae98f..78ce2b80 100644 --- a/src/common/common/sakhighlighter.cc +++ b/src/common/common/sakhighlighter.cc @@ -2,8 +2,8 @@ * Copyright 2023 wuuhaii(qsaker@foxmail.com). All rights reserved. ******************************************************************************/ #include -#include #include +#include #ifdef SAK_IMPORT_MODULE_QML #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) #include @@ -14,23 +14,21 @@ SAKHighlighter::SAKHighlighter(QObject *parent) : QSyntaxHighlighter(parent) -{ - -} +{} void SAKHighlighter::setDoc(QVariant doc) { - auto obj = doc.value(); + auto obj = doc.value(); #ifdef SAK_IMPORT_MODULE_QML #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) if (obj->inherits("QQuickTextDocument")) { - setDocument(doc.value()->textDocument()); + setDocument(doc.value()->textDocument()); return; } #endif #endif if (obj->inherits("QTextDocument")) { - setDocument(doc.value()); + setDocument(doc.value()); } } diff --git a/src/common/common/sakinterface.cc b/src/common/common/sakinterface.cc index cfaff2ac..5e9b445e 100644 --- a/src/common/common/sakinterface.cc +++ b/src/common/common/sakinterface.cc @@ -27,191 +27,205 @@ #include "sakdatastructure.h" #include "sakinterface.h" -SAKInterface::SAKInterface(QObject* parent) : QObject{parent} {} +SAKInterface::SAKInterface(QObject* parent) + : QObject{parent} +{} -void SAKInterface::setMaximumBlockCount(QVariant doc, int maximum) { - auto obj = doc.value(); - if (obj) { +void SAKInterface::setMaximumBlockCount(QVariant doc, int maximum) +{ + auto obj = doc.value(); + if (obj) { #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) #ifdef SAK_IMPORT_MODULE_QML - auto quickTextDoc = qobject_cast(obj); - if (quickTextDoc) { - auto textDoc = quickTextDoc->textDocument(); - textDoc->setMaximumBlockCount(maximum); + auto quickTextDoc = qobject_cast(obj); + if (quickTextDoc) { + auto textDoc = quickTextDoc->textDocument(); + textDoc->setMaximumBlockCount(maximum); + } +#else + Q_UNUSED(doc) + Q_UNUSED(maximum) +#endif +#else + Q_UNUSED(doc) + Q_UNUSED(maximum) +#endif } -#else - Q_UNUSED(doc) - Q_UNUSED(maximum) -#endif -#else - Q_UNUSED(doc) - Q_UNUSED(maximum) -#endif - } } -void SAKInterface::setAppFont(const QString& fontFamily) { - qGuiApp->setFont(fontFamily); +void SAKInterface::setAppFont(const QString& fontFamily) +{ + qGuiApp->setFont(fontFamily); } -void SAKInterface::setClipboardText(const QString& text) { - QGuiApplication::clipboard()->setText(text); +void SAKInterface::setClipboardText(const QString& text) +{ + QGuiApplication::clipboard()->setText(text); } -bool SAKInterface::isQtHighDpiScalePolicy(int policy) { +bool SAKInterface::isQtHighDpiScalePolicy(int policy) +{ #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - QList policyList; - policyList << int(Qt::HighDpiScaleFactorRoundingPolicy::Round) - << int(Qt::HighDpiScaleFactorRoundingPolicy::Ceil) - << int(Qt::HighDpiScaleFactorRoundingPolicy::Floor) - << int(Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor) - << int(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); - return policyList.contains(policy); + QList policyList; + policyList << int(Qt::HighDpiScaleFactorRoundingPolicy::Round) + << int(Qt::HighDpiScaleFactorRoundingPolicy::Ceil) + << int(Qt::HighDpiScaleFactorRoundingPolicy::Floor) + << int(Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor) + << int(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); + return policyList.contains(policy); #else - Q_UNUSED(false) - return false; + Q_UNUSED(false) + return false; #endif } -QString SAKInterface::arrayToString(const QByteArray& array, int format) { - auto cookedArray = [](const QByteArray& array, int base, int len) -> QString { - QString str, numStr; - for (int i = 0; i < array.length(); i++) { - if (base == 10 || base == 8) { - numStr = QString::number(array.at(i), base); - str.append(QString("%1 ").arg(numStr)); - } else { - numStr = QString::number(quint8(array.at(i)), base); - str.append(QString("%1 ").arg(numStr, len, '0')); - } +QString SAKInterface::arrayToString(const QByteArray& array, int format) +{ + auto cookedArray = [](const QByteArray& array, int base, int len) -> QString { + QString str, numStr; + for (int i = 0; i < array.length(); i++) { + if (base == 10 || base == 8) { + numStr = QString::number(array.at(i), base); + str.append(QString("%1 ").arg(numStr)); + } else { + numStr = QString::number(quint8(array.at(i)), base); + str.append(QString("%1 ").arg(numStr, len, '0')); + } + } + return str; + }; + + if (SAKDataStructure::TextFormatBin == format) { + return cookedArray(array, 2, 8); + } else if (SAKDataStructure::TextFormatOct == format) { + return cookedArray(array, 8, 3); + } else if (SAKDataStructure::TextFormatDec == format) { + return cookedArray(array, 10, 3); + } else if (SAKDataStructure::TextFormatHex == format) { + return cookedArray(array, 16, 2); + } else if (SAKDataStructure::TextFormatAscii == format) { + return QString::fromLatin1(array); + } else { + return QString::fromUtf8(array); } - return str; - }; - - if (SAKDataStructure::TextFormatBin == format) { - return cookedArray(array, 2, 8); - } else if (SAKDataStructure::TextFormatOct == format) { - return cookedArray(array, 8, 3); - } else if (SAKDataStructure::TextFormatDec == format) { - return cookedArray(array, 10, 3); - } else if (SAKDataStructure::TextFormatHex == format) { - return cookedArray(array, 16, 2); - } else if (SAKDataStructure::TextFormatAscii == format) { - return QString::fromLatin1(array); - } else { - return QString::fromUtf8(array); - } } -QString SAKInterface::dateTimeString(const QString& format) { - return QDateTime::currentDateTime().toString(format); +QString SAKInterface::dateTimeString(const QString& format) +{ + return QDateTime::currentDateTime().toString(format); } -QString SAKInterface::cookedFileName(const QString& fileName) { - QString cookedFileName = fileName; +QString SAKInterface::cookedFileName(const QString& fileName) +{ + QString cookedFileName = fileName; #ifdef Q_OS_WIN - cookedFileName = cookedFileName.remove("file:///"); + cookedFileName = cookedFileName.remove("file:///"); #endif - return cookedFileName; + return cookedFileName; } -QString SAKInterface::string2hexString(const QString& str) { - return QString::fromLatin1(str.toUtf8().toHex()); +QString SAKInterface::string2hexString(const QString& str) +{ + return QString::fromLatin1(str.toUtf8().toHex()); } -QString SAKInterface::hexString2String(const QString& str) { - QByteArray arr = QByteArray::fromHex(str.toUtf8()); - return QString::fromUtf8(arr); +QString SAKInterface::hexString2String(const QString& str) +{ + QByteArray arr = QByteArray::fromHex(str.toUtf8()); + return QString::fromUtf8(arr); } -QString SAKInterface::buildDateTime(const QString& format) { - QString str = QString(__DATE__); - QDate date = QDate::fromString(str, "MMM d yyyy"); - if (!date.isValid()) { - date = QDate::fromString(str, "MMM d yyyy"); - } - QTime time = QTime::fromString(__TIME__, "hh:mm:ss"); - return QDateTime(date, time).toString(format); +QString SAKInterface::buildDateTime(const QString& format) +{ + QString str = QString(__DATE__); + QDate date = QDate::fromString(str, "MMM d yyyy"); + if (!date.isValid()) { + date = QDate::fromString(str, "MMM d yyyy"); + } + QTime time = QTime::fromString(__TIME__, "hh:mm:ss"); + return QDateTime(date, time).toString(format); } -QString SAKInterface::dateFormat() { - return QLocale::system().dateFormat(); +QString SAKInterface::dateFormat() +{ + return QLocale::system().dateFormat(); } -QString SAKInterface::timeFormat() { - return QLocale::system().timeFormat(); +QString SAKInterface::timeFormat() +{ + return QLocale::system().timeFormat(); } -QByteArray SAKInterface::string2array(const QString& input, int format) { - QByteArray data; +QByteArray SAKInterface::string2array(const QString& input, int format) +{ + QByteArray data; #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - auto behavior = QString::SkipEmptyParts; + auto behavior = QString::SkipEmptyParts; #else - auto behavior = Qt::SkipEmptyParts; + auto behavior = Qt::SkipEmptyParts; #endif - if (format == SAKDataStructure::TextFormatBin) { - QStringList strList = input.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 2); - data.append(reinterpret_cast(&value), 1); + if (format == SAKDataStructure::TextFormatBin) { + QStringList strList = input.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 2); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKDataStructure::TextFormatOct) { + QStringList strList = input.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 8); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKDataStructure::TextFormatDec) { + QStringList strList = input.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 10); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKDataStructure::TextFormatHex) { + QStringList strList = input.split(' ', behavior); + for (int i = 0; i < strList.length(); i++) { + QString str = strList.at(i); + qint8 value = QString(str).toInt(Q_NULLPTR, 16); + data.append(reinterpret_cast(&value), 1); + } + } else if (format == SAKDataStructure::TextFormatAscii) { + data = input.toLatin1(); + } else { + data = input.toUtf8(); } - } else if (format == SAKDataStructure::TextFormatOct) { - QStringList strList = input.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 8); - data.append(reinterpret_cast(&value), 1); - } - } else if (format == SAKDataStructure::TextFormatDec) { - QStringList strList = input.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 10); - data.append(reinterpret_cast(&value), 1); - } - } else if (format == SAKDataStructure::TextFormatHex) { - QStringList strList = input.split(' ', behavior); - for (int i = 0; i < strList.length(); i++) { - QString str = strList.at(i); - qint8 value = QString(str).toInt(Q_NULLPTR, 16); - data.append(reinterpret_cast(&value), 1); - } - } else if (format == SAKDataStructure::TextFormatAscii) { - data = input.toLatin1(); - } else { - data = input.toUtf8(); - } - return data; + return data; } -QByteArray SAKInterface::arrayAppendArray(const QByteArray& a1, - const QByteArray& a2) { - return a1 + a2; +QByteArray SAKInterface::arrayAppendArray(const QByteArray& a1, const QByteArray& a2) +{ + return a1 + a2; } -QByteArray SAKInterface::arrayToHex(const QByteArray& array, char separator) { - if (array.isEmpty()) { - return array; - } +QByteArray SAKInterface::arrayToHex(const QByteArray& array, char separator) +{ + if (array.isEmpty()) { + return array; + } - auto toHex = [](quint8 value) -> char { - return "0123456789abcdef"[value & 0xF]; - }; + auto toHex = [](quint8 value) -> char { return "0123456789abcdef"[value & 0xF]; }; - const int length = separator ? (array.size() * 3 - 1) : (array.size() * 2); - QByteArray hex(length, Qt::Uninitialized); - char* hexData = hex.data(); - const uchar* data = reinterpret_cast(array.constData()); - for (int i = 0, o = 0; i < array.size(); ++i) { - hexData[o++] = toHex(data[i] >> 4); - hexData[o++] = toHex(data[i] & 0xf); + const int length = separator ? (array.size() * 3 - 1) : (array.size() * 2); + QByteArray hex(length, Qt::Uninitialized); + char* hexData = hex.data(); + const uchar* data = reinterpret_cast(array.constData()); + for (int i = 0, o = 0; i < array.size(); ++i) { + hexData[o++] = toHex(data[i] >> 4); + hexData[o++] = toHex(data[i] & 0xf); - if ((separator) && (o < length)) - hexData[o++] = separator; - } - return hex; + if ((separator) && (o < length)) + hexData[o++] = separator; + } + return hex; } diff --git a/src/common/common/sakinterface.h b/src/common/common/sakinterface.h index 6dcde3a1..f73a771f 100644 --- a/src/common/common/sakinterface.h +++ b/src/common/common/sakinterface.h @@ -15,31 +15,30 @@ #define SAK_STATIC Q_INVOKABLE static -class SAKInterface : public QObject { - Q_OBJECT - public: - explicit SAKInterface(QObject* parent = nullptr); +class SAKInterface : public QObject +{ + Q_OBJECT +public: + explicit SAKInterface(QObject* parent = nullptr); - Q_INVOKABLE static void setMaximumBlockCount(QVariant doc, int maximum); - Q_INVOKABLE static void setAppFont(const QString& fontFamily); - Q_INVOKABLE static void setClipboardText(const QString& text); + Q_INVOKABLE static void setMaximumBlockCount(QVariant doc, int maximum); + Q_INVOKABLE static void setAppFont(const QString& fontFamily); + Q_INVOKABLE static void setClipboardText(const QString& text); - Q_INVOKABLE static bool isQtHighDpiScalePolicy(int policy); + Q_INVOKABLE static bool isQtHighDpiScalePolicy(int policy); - Q_INVOKABLE static QString arrayToString(const QByteArray& array, int format); - Q_INVOKABLE static QString dateTimeString(const QString& format); - Q_INVOKABLE static QString cookedFileName(const QString& fileName); - Q_INVOKABLE static QString string2hexString(const QString& str); - Q_INVOKABLE static QString hexString2String(const QString& str); - Q_INVOKABLE static QString buildDateTime(const QString& format); - Q_INVOKABLE static QString dateFormat(); - Q_INVOKABLE static QString timeFormat(); + Q_INVOKABLE static QString arrayToString(const QByteArray& array, int format); + Q_INVOKABLE static QString dateTimeString(const QString& format); + Q_INVOKABLE static QString cookedFileName(const QString& fileName); + Q_INVOKABLE static QString string2hexString(const QString& str); + Q_INVOKABLE static QString hexString2String(const QString& str); + Q_INVOKABLE static QString buildDateTime(const QString& format); + Q_INVOKABLE static QString dateFormat(); + Q_INVOKABLE static QString timeFormat(); - Q_INVOKABLE static QByteArray string2array(const QString& input, int format); - Q_INVOKABLE static QByteArray arrayAppendArray(const QByteArray& a1, - const QByteArray& a2); - Q_INVOKABLE static QByteArray arrayToHex(const QByteArray& array, - char separator = '\0'); + Q_INVOKABLE static QByteArray string2array(const QString& input, int format); + Q_INVOKABLE static QByteArray arrayAppendArray(const QByteArray& a1, const QByteArray& a2); + Q_INVOKABLE static QByteArray arrayToHex(const QByteArray& array, char separator = '\0'); }; -#endif // SAKINTERFACE_H +#endif // SAKINTERFACE_H diff --git a/src/common/common/saknetworkinterfacescanner.cc b/src/common/common/saknetworkinterfacescanner.cc index 3b0a7891..8f874b3b 100644 --- a/src/common/common/saknetworkinterfacescanner.cc +++ b/src/common/common/saknetworkinterfacescanner.cc @@ -13,45 +13,47 @@ #include SAKNetworkInterfaceScanner::SAKNetworkInterfaceScanner(QObject* parent) - : QObject{parent} { - refresh(); - mRefreshTimer = new QTimer(this); - mRefreshTimer->setInterval(1 * 1000); - mRefreshTimer->setSingleShot(true); - connect(mRefreshTimer, &QTimer::timeout, this, [=]() { + : QObject{parent} +{ refresh(); + mRefreshTimer = new QTimer(this); + mRefreshTimer->setInterval(1 * 1000); + mRefreshTimer->setSingleShot(true); + connect(mRefreshTimer, &QTimer::timeout, this, [=]() { + refresh(); + mRefreshTimer->start(); + }); + mRefreshTimer->start(); - }); - - mRefreshTimer->start(); } -void SAKNetworkInterfaceScanner::refresh() { - QStringList ipv4List, ipv6List; - auto addresses = QNetworkInterface::allAddresses(); - for (auto& address : addresses) { - auto str = address.toString(); +void SAKNetworkInterfaceScanner::refresh() +{ + QStringList ipv4List, ipv6List; + auto addresses = QNetworkInterface::allAddresses(); + for (auto& address : addresses) { + auto str = address.toString(); - if (address.protocol() == QAbstractSocket::IPv4Protocol) { - ipv4List.append(str); - } else if (address.protocol() == QAbstractSocket::IPv6Protocol) { - ipv6List.append(str); - } - } - - if (mEnableAutoRefresh) { - QStringList temp; - if (mEnableIpV4) { - temp.append(ipv4List); + if (address.protocol() == QAbstractSocket::IPv4Protocol) { + ipv4List.append(str); + } else if (address.protocol() == QAbstractSocket::IPv6Protocol) { + ipv6List.append(str); + } } - if (mEnableIpV6) { - temp.append(ipv6List); - } + if (mEnableAutoRefresh) { + QStringList temp; + if (mEnableIpV4) { + temp.append(ipv4List); + } - if (temp != mIpList) { - mIpList = temp; - emit ipListChanged(); + if (mEnableIpV6) { + temp.append(ipv6List); + } + + if (temp != mIpList) { + mIpList = temp; + emit ipListChanged(); + } } - } } diff --git a/src/common/common/saknetworkinterfacescanner.h b/src/common/common/saknetworkinterfacescanner.h index 5f36b508..a8010b9d 100644 --- a/src/common/common/saknetworkinterfacescanner.h +++ b/src/common/common/saknetworkinterfacescanner.h @@ -4,8 +4,8 @@ #ifndef SAKNETWORKINTERFACESCANNER_H #define SAKNETWORKINTERFACESCANNER_H -#include #include +#include class SAKNetworkInterfaceScanner : public QObject { @@ -13,7 +13,8 @@ class SAKNetworkInterfaceScanner : public QObject Q_PROPERTY(QStringList ipList READ ipList NOTIFY ipListChanged) Q_PROPERTY(bool enableIpV4 READ enableIpV4 WRITE setEnableIpV4 NOTIFY enableIpV4Changed) Q_PROPERTY(bool enableIpV6 READ enableIpV6 WRITE setEnableIpV6 NOTIFY enableIpV6Changed) - Q_PROPERTY(bool enableAutoRefresh READ enableAutoRefresh WRITE setEnableAutoRefresh NOTIFY enableAutoRefreshChanged) + Q_PROPERTY(bool enableAutoRefresh READ enableAutoRefresh WRITE setEnableAutoRefresh NOTIFY + enableAutoRefreshChanged) public: explicit SAKNetworkInterfaceScanner(QObject *parent = nullptr); @@ -25,22 +26,34 @@ private: private: QStringList mIpList; - QStringList ipList(){return mIpList;} + QStringList ipList() { return mIpList; } Q_SIGNAL void ipListChanged(); bool mEnableIpV4{true}; - bool enableIpV4(){return mEnableIpV4;} - void setEnableIpV4(bool enable){mEnableIpV4 = enable; emit enableIpV4Changed();} + bool enableIpV4() { return mEnableIpV4; } + void setEnableIpV4(bool enable) + { + mEnableIpV4 = enable; + emit enableIpV4Changed(); + } Q_SIGNAL void enableIpV4Changed(); bool mEnableIpV6{false}; - bool enableIpV6(){return mEnableIpV4;} - void setEnableIpV6(bool enable){mEnableIpV6 = enable; emit enableIpV6Changed();} + bool enableIpV6() { return mEnableIpV4; } + void setEnableIpV6(bool enable) + { + mEnableIpV6 = enable; + emit enableIpV6Changed(); + } Q_SIGNAL void enableIpV6Changed(); bool mEnableAutoRefresh{true}; - bool enableAutoRefresh(){return mEnableAutoRefresh;} - void setEnableAutoRefresh(bool enable){mEnableAutoRefresh = enable; emit enableAutoRefreshChanged();} + bool enableAutoRefresh() { return mEnableAutoRefresh; } + void setEnableAutoRefresh(bool enable) + { + mEnableAutoRefresh = enable; + emit enableAutoRefreshChanged(); + } Q_SIGNAL void enableAutoRefreshChanged(); }; diff --git a/src/common/common/sakserialportscanner.cc b/src/common/common/sakserialportscanner.cc index 1f976635..13dc64cd 100644 --- a/src/common/common/sakserialportscanner.cc +++ b/src/common/common/sakserialportscanner.cc @@ -1,9 +1,9 @@ /******************************************************************************* * Copyright 2023 wuuhaii(qsaker@foxmail.com). All rights reserved. ******************************************************************************/ +#include "sakserialportscanner.h" #include #include -#include "sakserialportscanner.h" SAKSerialPortScanner::SAKSerialPortScanner(QObject *parent) : QObject{parent} @@ -11,7 +11,7 @@ SAKSerialPortScanner::SAKSerialPortScanner(QObject *parent) nAutoUpdatePortNamesTimer = new QTimer(this); nAutoUpdatePortNamesTimer->setInterval(1000); nAutoUpdatePortNamesTimer->setSingleShot(true); - connect(nAutoUpdatePortNamesTimer, &QTimer::timeout, this, [=](){ + connect(nAutoUpdatePortNamesTimer, &QTimer::timeout, this, [=]() { refresh(); nAutoUpdatePortNamesTimer->start(); }); @@ -88,4 +88,3 @@ bool SAKSerialPortScanner::isBusy(const QString &portName) sp.close(); return busy; } - diff --git a/src/common/common/sakserialportscanner.h b/src/common/common/sakserialportscanner.h index 9540d1f5..cbeef60c 100644 --- a/src/common/common/sakserialportscanner.h +++ b/src/common/common/sakserialportscanner.h @@ -4,8 +4,8 @@ #ifndef SAKSERIALPORTSCANNER_H #define SAKSERIALPORTSCANNER_H -#include #include +#include class SAKSerialPortScanner : public QObject { @@ -30,11 +30,11 @@ private: private: QStringList mPortNames; - QStringList portNames(){return mPortNames;} + QStringList portNames() { return mPortNames; } Q_SIGNAL void portNamesChanged(); QStringList mBaudRates; - QStringList baudRates(){return mBaudRates;} + QStringList baudRates() { return mBaudRates; } Q_SIGNAL void baudRatesChanged(); }; diff --git a/src/common/common/saktablemodel.cc b/src/common/common/saktablemodel.cc index d8734f89..b5b16a38 100644 --- a/src/common/common/saktablemodel.cc +++ b/src/common/common/saktablemodel.cc @@ -11,16 +11,14 @@ SAKTableModel::SAKTableModel(QObject *parent) : QAbstractTableModel{parent} -{ - -} +{} int SAKTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) int count = 0; - emit const_cast(this)->invokeGetRowCount(count); + emit const_cast(this)->invokeGetRowCount(count); return count; } @@ -29,20 +27,18 @@ int SAKTableModel::columnCount(const QModelIndex &parent) const Q_UNUSED(parent) int column = 0; - emit const_cast(this)->invokeGetColumnCount(column); + emit const_cast(this)->invokeGetColumnCount(column); return column; } QVariant SAKTableModel::data(const QModelIndex &index, int role) const { QVariant d; - emit const_cast(this)->invokeGetData(d, index, role); + emit const_cast(this)->invokeGetData(d, index, role); return d; } -bool SAKTableModel::setData(const QModelIndex &index, - const QVariant &value, - int role) +bool SAKTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { bool result = false; emit invokeSetData(result, index, value, role); @@ -72,14 +68,9 @@ bool SAKTableModel::removeRows(int row, int count, const QModelIndex &parent) return result; } -QVariant SAKTableModel::headerData(int section, - Qt::Orientation orientation, - int role) const +QVariant SAKTableModel::headerData(int section, Qt::Orientation orientation, int role) const { QVariant d; - emit const_cast(this)->invokeGetHeaderData(d, - section, - orientation, - role); + emit const_cast(this)->invokeGetHeaderData(d, section, orientation, role); return d; } diff --git a/src/common/common/saktablemodel.h b/src/common/common/saktablemodel.h index 8d21bf84..825152ad 100644 --- a/src/common/common/saktablemodel.h +++ b/src/common/common/saktablemodel.h @@ -19,21 +19,14 @@ public: explicit SAKTableModel(QObject *parent = nullptr); public: - virtual int rowCount(const QModelIndex &parent - = QModelIndex()) const final; - virtual int columnCount(const QModelIndex &parent - = QModelIndex()) const final; - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const final; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const final; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const final; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const final; virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) final; - virtual bool insertRows(int row, - int count, - const QModelIndex &parent = QModelIndex()) final; - virtual bool removeRows(int row, - int count, - const QModelIndex &parent = QModelIndex()) final; + virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) final; + virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) final; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const final; @@ -42,9 +35,7 @@ signals: // You must connect these signals using Qt::DirectConnection way. void invokeGetRowCount(int &count); void invokeGetColumnCount(int &count); - void invokeGetData(QVariant &data, - const QModelIndex &index, - int role = Qt::DisplayRole); + void invokeGetData(QVariant &data, const QModelIndex &index, int role = Qt::DisplayRole); void invokeSetData(bool &result, const QModelIndex &index, const QVariant &value, diff --git a/src/common/common/saktranslator.cc b/src/common/common/saktranslator.cc index cbb69136..3b1497d1 100644 --- a/src/common/common/saktranslator.cc +++ b/src/common/common/saktranslator.cc @@ -15,9 +15,11 @@ #include "saktranslator.h" -SAKTranslator::SAKTranslator(QObject* parent) : QObject{parent} { - mFlagNameMap.insert("zh_CN", "简体中文"); - mFlagNameMap.insert("en", "English"); +SAKTranslator::SAKTranslator(QObject* parent) + : QObject{parent} +{ + mFlagNameMap.insert("zh_CN", "简体中文"); + mFlagNameMap.insert("en", "English"); #if 0 mFlagNameMap.insert("zh_TW", "繁體中文"); mFlagNameMap.insert("ar", "العربية"); @@ -43,40 +45,43 @@ SAKTranslator::SAKTranslator(QObject* parent) : QObject{parent} { #endif } -SAKTranslator* SAKTranslator::instance() { - static SAKTranslator* translator = Q_NULLPTR; - if (!translator) { - translator = new SAKTranslator(qApp); - } +SAKTranslator* SAKTranslator::instance() +{ + static SAKTranslator* translator = Q_NULLPTR; + if (!translator) { + translator = new SAKTranslator(qApp); + } - return translator; + return translator; } -QStringList SAKTranslator::languanges() { - return mFlagNameMap.values(); +QStringList SAKTranslator::languanges() +{ + return mFlagNameMap.values(); } -void SAKTranslator::setupLanguage(const QString& language) { - QCoreApplication::removeTranslator(&mTranslator); +void SAKTranslator::setupLanguage(const QString& language) +{ + QCoreApplication::removeTranslator(&mTranslator); - QString key = mFlagNameMap.key(language); - if (language.isEmpty()) { - qCWarning(mLoggingCategory) << "language is not specified," - " system language will be used"; - key = QLocale::system().name(); - } + QString key = mFlagNameMap.key(language); + if (language.isEmpty()) { + qCWarning(mLoggingCategory) << "language is not specified," + " system language will be used"; + key = QLocale::system().name(); + } - if (key.isEmpty()) { - qCWarning(mLoggingCategory) << "unsupported language, " - "english will be used"; - key = "en"; - } + if (key.isEmpty()) { + qCWarning(mLoggingCategory) << "unsupported language, " + "english will be used"; + key = "en"; + } - QString fileName = ":/resources/translations/sak_" + key + ".qm"; - if (mTranslator.load(fileName)) { - QCoreApplication::installTranslator(&mTranslator); - qCInfo(mLoggingCategory) << mFlagNameMap.value(key) << " has been setup!"; - } else { - qCWarning(mLoggingCategory) << "Load file failed: " << fileName; - } + QString fileName = ":/resources/translations/sak_" + key + ".qm"; + if (mTranslator.load(fileName)) { + QCoreApplication::installTranslator(&mTranslator); + qCInfo(mLoggingCategory) << mFlagNameMap.value(key) << " has been setup!"; + } else { + qCWarning(mLoggingCategory) << "Load file failed: " << fileName; + } } diff --git a/src/common/common/saktranslator.h b/src/common/common/saktranslator.h index 4866a232..f15f5be6 100644 --- a/src/common/common/saktranslator.h +++ b/src/common/common/saktranslator.h @@ -10,13 +10,13 @@ #ifndef SAKTRANSLATOR_H #define SAKTRANSLATOR_H -#include -#include #include #include +#include +#include +#include #include #include -#include class SAKTranslator : public QObject { @@ -26,7 +26,7 @@ private: explicit SAKTranslator(QObject *parent = nullptr); public: - static SAKTranslator* instance(); + static SAKTranslator *instance(); QStringList languanges(); void setupLanguage(const QString &language); diff --git a/src/common/commonui/sakaffixescombobox.cc b/src/common/commonui/sakaffixescombobox.cc index cdc00029..a74ee7ce 100644 --- a/src/common/commonui/sakaffixescombobox.cc +++ b/src/common/commonui/sakaffixescombobox.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakdatastructure.h" #include "sakaffixescombobox.h" +#include "sakdatastructure.h" SAKAffixesComboBox::SAKAffixesComboBox(QWidget *parent) : SAKComboBox(parent) diff --git a/src/common/commonui/sakbaudratecombobox.cc b/src/common/commonui/sakbaudratecombobox.cc index 0b57039f..062e5ba4 100644 --- a/src/common/commonui/sakbaudratecombobox.cc +++ b/src/common/commonui/sakbaudratecombobox.cc @@ -17,7 +17,7 @@ SAKBaudRateComboBox::SAKBaudRateComboBox(QWidget *parent) { clear(); QList bd = QSerialPortInfo::standardBaudRates(); - for (auto &var:bd) { + for (auto &var : bd) { addItem(QString::number(var), QVariant::fromValue(var)); } diff --git a/src/common/commonui/sakbluetoothdeviceInfocombobox.cc b/src/common/commonui/sakbluetoothdeviceInfocombobox.cc index 8ca21d30..24b7da3c 100644 --- a/src/common/commonui/sakbluetoothdeviceInfocombobox.cc +++ b/src/common/commonui/sakbluetoothdeviceInfocombobox.cc @@ -13,7 +13,9 @@ #include SAKBluetoothDeviceInfoComboBox::SAKBluetoothDeviceInfoComboBox(QWidget* parent) - : SAKComboBox(parent), mScanner(Q_NULLPTR) { + : SAKComboBox(parent) + , mScanner(Q_NULLPTR) +{ #if 0 mScanner = new SAKBleScanner(this); connect(mScanner, &SAKBleScanner::finished, @@ -27,73 +29,82 @@ SAKBluetoothDeviceInfoComboBox::SAKBluetoothDeviceInfoComboBox(QWidget* parent) #endif } -SAKBluetoothDeviceInfoComboBox::~SAKBluetoothDeviceInfoComboBox() { +SAKBluetoothDeviceInfoComboBox::~SAKBluetoothDeviceInfoComboBox() +{ #if 0 mScanner->stopDiscover(); #endif } -void SAKBluetoothDeviceInfoComboBox::startDiscover() { +void SAKBluetoothDeviceInfoComboBox::startDiscover() +{ #if 0 clear(); mScanner->startDiscover(); #endif } -void SAKBluetoothDeviceInfoComboBox::stopDiscover() { +void SAKBluetoothDeviceInfoComboBox::stopDiscover() +{ #if 0 mScanner->stopDiscover(); #endif } -bool SAKBluetoothDeviceInfoComboBox::isActive() { +bool SAKBluetoothDeviceInfoComboBox::isActive() +{ #if 0 return mScanner->isActive(); #endif - return false; + return false; } -void SAKBluetoothDeviceInfoComboBox::setTimeoutInterval(int interval) { +void SAKBluetoothDeviceInfoComboBox::setTimeoutInterval(int interval) +{ #if 0 mScanner->setTimeoutInterval(interval); #endif } -void SAKBluetoothDeviceInfoComboBox::setNameFiltter(const QString& filtter) { - // mScanner->setNameFiltter(filtter); +void SAKBluetoothDeviceInfoComboBox::setNameFiltter(const QString& filtter) +{ + // mScanner->setNameFiltter(filtter); } -void SAKBluetoothDeviceInfoComboBox::changeEvent(QEvent* event) { - SAKComboBox::changeEvent(event); - if ((event->type() == QEvent::EnabledChange) && isEnabled()) { - onFinished(); - } +void SAKBluetoothDeviceInfoComboBox::changeEvent(QEvent* event) +{ + SAKComboBox::changeEvent(event); + if ((event->type() == QEvent::EnabledChange) && isEnabled()) { + onFinished(); + } } -void SAKBluetoothDeviceInfoComboBox::onFinished() { - // if (!isEnabled()) { - // return; - // } +void SAKBluetoothDeviceInfoComboBox::onFinished() +{ + // if (!isEnabled()) { + // return; + // } - // clear(); - // auto infos = mScanner->devicesInfoList(); - // for (auto &info : infos) { - // QString name = mScanner->deviceName(info); - // addItem(name, info); - // } + // clear(); + // auto infos = mScanner->devicesInfoList(); + // for (auto &info : infos) { + // QString name = mScanner->deviceName(info); + // addItem(name, info); + // } - // emit finished(); + // emit finished(); } -void SAKBluetoothDeviceInfoComboBox::onDeviceDiscovered( - const QBluetoothDeviceInfo& info) { - if (!isEnabled()) { - return; - } +void SAKBluetoothDeviceInfoComboBox::onDeviceDiscovered(const QBluetoothDeviceInfo& info) +{ + if (!isEnabled()) { + return; + } - addItem(info.name(), QVariant::fromValue(info)); + addItem(info.name(), QVariant::fromValue(info)); } -void SAKBluetoothDeviceInfoComboBox::onErrorOccurred(const QString& errStr) { - QMessageBox::warning(this, tr("Error Occurred"), errStr); +void SAKBluetoothDeviceInfoComboBox::onErrorOccurred(const QString& errStr) +{ + QMessageBox::warning(this, tr("Error Occurred"), errStr); } diff --git a/src/common/commonui/sakbluetoothdeviceInfocombobox.h b/src/common/commonui/sakbluetoothdeviceInfocombobox.h index b4b6c931..f7e18561 100644 --- a/src/common/commonui/sakbluetoothdeviceInfocombobox.h +++ b/src/common/commonui/sakbluetoothdeviceInfocombobox.h @@ -12,8 +12,8 @@ #include -#include "sakcombobox.h" #include "sakblescanner.h" +#include "sakcombobox.h" class SAKBluetoothDeviceInfoComboBox : public SAKComboBox { diff --git a/src/common/commonui/sakcheckbox.cc b/src/common/commonui/sakcheckbox.cc index b284d55e..1f825c7d 100644 --- a/src/common/commonui/sakcheckbox.cc +++ b/src/common/commonui/sakcheckbox.cc @@ -11,28 +11,33 @@ #include "saksettings.h" -SAKCheckBox::SAKCheckBox(QWidget* parent) : QCheckBox(parent) { - connect(this, &SAKCheckBox::clicked, this, &SAKCheckBox::writeToSettingsFile); +SAKCheckBox::SAKCheckBox(QWidget* parent) + : QCheckBox(parent) +{ + connect(this, &SAKCheckBox::clicked, this, &SAKCheckBox::writeToSettingsFile); } -void SAKCheckBox::setGroupKey(const QString& group, const QString& key) { - mKey = group + "/" + key; - readFromSettingsFile(); +void SAKCheckBox::setGroupKey(const QString& group, const QString& key) +{ + mKey = group + "/" + key; + readFromSettingsFile(); } -void SAKCheckBox::readFromSettingsFile() { - if (mKey.isEmpty()) { - return; - } +void SAKCheckBox::readFromSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } - bool ret = SAKSettings::instance()->value(mKey).toBool(); - setChecked(ret); + bool ret = SAKSettings::instance()->value(mKey).toBool(); + setChecked(ret); } -void SAKCheckBox::writeToSettingsFile() { - if (mKey.isEmpty()) { - return; - } +void SAKCheckBox::writeToSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } - SAKSettings::instance()->setValue(mKey, isChecked()); + SAKSettings::instance()->setValue(mKey, isChecked()); } diff --git a/src/common/commonui/sakcheckbox.h b/src/common/commonui/sakcheckbox.h index 22401b2a..bb574ac7 100644 --- a/src/common/commonui/sakcheckbox.h +++ b/src/common/commonui/sakcheckbox.h @@ -17,8 +17,7 @@ class SAKCheckBox : public QCheckBox Q_OBJECT public: SAKCheckBox(QWidget *parent = nullptr); - void setGroupKey(const QString &group, - const QString &key); + void setGroupKey(const QString &group, const QString &key); private: QString mKey; diff --git a/src/common/commonui/sakcombobox.cc b/src/common/commonui/sakcombobox.cc index 7aec8c54..3b53a173 100644 --- a/src/common/commonui/sakcombobox.cc +++ b/src/common/commonui/sakcombobox.cc @@ -13,67 +13,71 @@ #include "saksettings.h" -SAKComboBox::SAKComboBox(QWidget* parent) : QComboBox(parent) { - connect(this, &SAKComboBox::currentTextChanged, this, - &SAKComboBox::writeToSettingsFile); +SAKComboBox::SAKComboBox(QWidget* parent) + : QComboBox(parent) +{ + connect(this, &SAKComboBox::currentTextChanged, this, &SAKComboBox::writeToSettingsFile); } -void SAKComboBox::setCurrentIndexFromData(const QVariant& data) { - int ret = findData(data); - if (ret != -1) { - setCurrentIndex(ret); - } +void SAKComboBox::setCurrentIndexFromData(const QVariant& data) +{ + int ret = findData(data); + if (ret != -1) { + setCurrentIndex(ret); + } } -void SAKComboBox::setGroupKey(const QString& group, const QString& key, - bool isIndex) { - mKey = group + "/" + key; - mIsIndex = isIndex; +void SAKComboBox::setGroupKey(const QString& group, const QString& key, bool isIndex) +{ + mKey = group + "/" + key; + mIsIndex = isIndex; - readFromSettingsFile(); + readFromSettingsFile(); } -void SAKComboBox::readFromSettingsFile() { - if (mKey.isEmpty()) { - return; - } +void SAKComboBox::readFromSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } - QVariant var = SAKSettings::instance()->value(mKey); - if (!var.isValid()) { - return; - } + QVariant var = SAKSettings::instance()->value(mKey); + if (!var.isValid()) { + return; + } - if (mIsIndex) { - int index = var.toInt(); + if (mIsIndex) { + int index = var.toInt(); + if (index >= 0 && index < count()) { + setCurrentIndex(index); + } + return; + } + + int index = findData(var); if (index >= 0 && index < count()) { - setCurrentIndex(index); + setCurrentIndex(index); + return; } - return; - } - int index = findData(var); - if (index >= 0 && index < count()) { - setCurrentIndex(index); - return; - } - - if (isEditable()) { - setCurrentText(var.toString()); - } -} - -void SAKComboBox::writeToSettingsFile() { - if (mKey.isEmpty()) { - return; - } - - if (mIsIndex) { - SAKSettings::instance()->setValue(mKey, currentIndex()); - } else { if (isEditable()) { - SAKSettings::instance()->setValue(mKey, currentText()); - } else { - SAKSettings::instance()->setValue(mKey, currentData()); + setCurrentText(var.toString()); + } +} + +void SAKComboBox::writeToSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } + + if (mIsIndex) { + SAKSettings::instance()->setValue(mKey, currentIndex()); + } else { + if (isEditable()) { + SAKSettings::instance()->setValue(mKey, currentText()); + } else { + SAKSettings::instance()->setValue(mKey, currentData()); + } } - } } diff --git a/src/common/commonui/sakcombobox.h b/src/common/commonui/sakcombobox.h index b4b6847d..8841c611 100644 --- a/src/common/commonui/sakcombobox.h +++ b/src/common/commonui/sakcombobox.h @@ -18,9 +18,7 @@ public: SAKComboBox(QWidget *parent = nullptr); void setCurrentIndexFromData(const QVariant &data); - void setGroupKey(const QString &group, - const QString &key, - bool isIndex = true); + void setGroupKey(const QString &group, const QString &key, bool isIndex = true); private: QString mKey; diff --git a/src/common/commonui/sakcommonmainwindow.cc b/src/common/commonui/sakcommonmainwindow.cc index a6449a19..d83f2f3f 100644 --- a/src/common/commonui/sakcommonmainwindow.cc +++ b/src/common/commonui/sakcommonmainwindow.cc @@ -31,265 +31,286 @@ #include "saktranslator.h" SAKCommonMainWindow::SAKCommonMainWindow(QWidget* parent) - : QMainWindow(parent) { - app_style_action_group_ = new QActionGroup(this); - language_action_group_ = new QActionGroup(this); - QString language = SAKSettings::instance()->language(); - SAKTranslator::instance()->setupLanguage(language); - Init(); + : QMainWindow(parent) +{ + app_style_action_group_ = new QActionGroup(this); + language_action_group_ = new QActionGroup(this); + QString language = SAKSettings::instance()->language(); + SAKTranslator::instance()->setupLanguage(language); + Init(); } SAKCommonMainWindow::~SAKCommonMainWindow() {} -void SAKCommonMainWindow::Init() { InitMenu(); } - -void SAKCommonMainWindow::InitMenu() { - InitMenuFile(); - InitMenuOption(); - InitMenuLanguage(); - InitMenuHelp(); +void SAKCommonMainWindow::Init() +{ + InitMenu(); } -void SAKCommonMainWindow::InitMenuFile() { - QMenuBar* menu_bar = menuBar(); - file_menu_ = menu_bar->addMenu(tr("&File")); - file_menu_->addAction(tr("&Exit"), this, &SAKCommonMainWindow::close); +void SAKCommonMainWindow::InitMenu() +{ + InitMenuFile(); + InitMenuOption(); + InitMenuLanguage(); + InitMenuHelp(); } -void SAKCommonMainWindow::InitMenuOption() { - option_menu_ = new QMenu(tr("&Options")); - menuBar()->addMenu(option_menu_); - - InitOptionMenuAppStyleMenu(); - InitOptionMenuSettingsMenu(); - InitOptionMenuHdpiPolicy(); +void SAKCommonMainWindow::InitMenuFile() +{ + QMenuBar* menu_bar = menuBar(); + file_menu_ = menu_bar->addMenu(tr("&File")); + file_menu_->addAction(tr("&Exit"), this, &SAKCommonMainWindow::close); } -void SAKCommonMainWindow::InitMenuLanguage() { - language_menu_ = new QMenu(tr("&Languages"), this); - menuBar()->addMenu(language_menu_); +void SAKCommonMainWindow::InitMenuOption() +{ + option_menu_ = new QMenu(tr("&Options")); + menuBar()->addMenu(option_menu_); - QStringList languages = SAKTranslator::instance()->languanges(); - for (auto& language : languages) { - QAction* action = new QAction(language, this); - action->setCheckable(true); - language_menu_->addAction(action); - language_action_group_->addAction(action); + InitOptionMenuAppStyleMenu(); + InitOptionMenuSettingsMenu(); + InitOptionMenuHdpiPolicy(); +} - connect(action, &QAction::triggered, this, [=]() { - SAKSettings::instance()->setLanguage(language); - TryToReboot(); - }); +void SAKCommonMainWindow::InitMenuLanguage() +{ + language_menu_ = new QMenu(tr("&Languages"), this); + menuBar()->addMenu(language_menu_); - QString setting_language = SAKSettings::instance()->language(); - if (setting_language == language) { - action->setChecked(true); + QStringList languages = SAKTranslator::instance()->languanges(); + for (auto& language : languages) { + QAction* action = new QAction(language, this); + action->setCheckable(true); + language_menu_->addAction(action); + language_action_group_->addAction(action); + + connect(action, &QAction::triggered, this, [=]() { + SAKSettings::instance()->setLanguage(language); + TryToReboot(); + }); + + QString setting_language = SAKSettings::instance()->language(); + if (setting_language == language) { + action->setChecked(true); + } } - } } -void SAKCommonMainWindow::InitMenuHelp() { - QMenuBar* menu_bar = menuBar(); - help_menu_ = menu_bar->addMenu(tr("&Help")); - help_menu_->addAction(QIcon(":/resources/images/GitHub.png"), "Github", this, - &SAKCommonMainWindow::OnGithubActionTriggered); - help_menu_->addAction(QIcon(":/resources/images/Gitee.png"), "Gitee", this, - &SAKCommonMainWindow::OnGiteeActionTriggered); - help_menu_->addAction(QIcon(":/resources/icon/IconQQGray.svg"), - tr("User QQ Group"), this, - &SAKCommonMainWindow::OnUserQqGroupTriggerd); - help_menu_->addAction(tr("&About"), this, - &SAKCommonMainWindow::OnAboutActionTriggered); +void SAKCommonMainWindow::InitMenuHelp() +{ + QMenuBar* menu_bar = menuBar(); + help_menu_ = menu_bar->addMenu(tr("&Help")); + help_menu_->addAction(QIcon(":/resources/images/GitHub.png"), + "Github", + this, + &SAKCommonMainWindow::OnGithubActionTriggered); + help_menu_->addAction(QIcon(":/resources/images/Gitee.png"), + "Gitee", + this, + &SAKCommonMainWindow::OnGiteeActionTriggered); + help_menu_->addAction(QIcon(":/resources/icon/IconQQGray.svg"), + tr("User QQ Group"), + this, + &SAKCommonMainWindow::OnUserQqGroupTriggerd); + help_menu_->addAction(tr("&About"), this, &SAKCommonMainWindow::OnAboutActionTriggered); } -void SAKCommonMainWindow::InitOptionMenuAppStyleMenu() { - QList actions = app_style_action_group_->actions(); - for (auto action : actions) { - app_style_action_group_->removeAction(action); - } +void SAKCommonMainWindow::InitOptionMenuAppStyleMenu() +{ + QList actions = app_style_action_group_->actions(); + for (auto action : actions) { + app_style_action_group_->removeAction(action); + } - QMenu* appStyleMenu = new QMenu(tr("Application Style"), this); - option_menu_->addMenu(appStyleMenu); - QStringList keys = QStyleFactory::keys(); - QString style = SAKSettings::instance()->appStyle(); - if (style.isEmpty()) { + QMenu* appStyleMenu = new QMenu(tr("Application Style"), this); + option_menu_->addMenu(appStyleMenu); + QStringList keys = QStyleFactory::keys(); + QString style = SAKSettings::instance()->appStyle(); + if (style.isEmpty()) { #if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0) - style = qApp->style()->name(); + style = qApp->style()->name(); #endif - } - - for (QString& key : keys) { - QAction* action = new QAction(key, this); - action->setObjectName(key); - action->setCheckable(true); - app_style_action_group_->addAction(action); - - if (key == style) { - action->setChecked(true); } + for (QString& key : keys) { + QAction* action = new QAction(key, this); + action->setObjectName(key); + action->setCheckable(true); + app_style_action_group_->addAction(action); + + if (key == style) { + action->setChecked(true); + } + + connect(action, &QAction::triggered, this, [=]() { + SAKSettings::instance()->setAppStyle(key); + TryToReboot(); + }); + } + + appStyleMenu->addActions(app_style_action_group_->actions()); +} + +void SAKCommonMainWindow::InitOptionMenuSettingsMenu() +{ + QMenu* menu = new QMenu(tr("Settings"), this); + option_menu_->addMenu(menu); + + QAction* action = new QAction(tr("Clear Configuration"), this); + menu->addAction(action); connect(action, &QAction::triggered, this, [=]() { - SAKSettings::instance()->setAppStyle(key); - TryToReboot(); + SAKSettings::instance()->setClearSettings(true); + TryToReboot(); + }); + action = new QAction(tr("Open configuration floder"), this); + menu->addAction(action); + connect(action, &QAction::triggered, this, [=]() { + QString file_name = SAKSettings::instance()->fileName(); + QUrl file_url = QUrl(file_name); + QString floder_url = file_name.remove(file_url.fileName()); + QDesktopServices::openUrl(floder_url); }); - } - - appStyleMenu->addActions(app_style_action_group_->actions()); } -void SAKCommonMainWindow::InitOptionMenuSettingsMenu() { - QMenu* menu = new QMenu(tr("Settings"), this); - option_menu_->addMenu(menu); - - QAction* action = new QAction(tr("Clear Configuration"), this); - menu->addAction(action); - connect(action, &QAction::triggered, this, [=]() { - SAKSettings::instance()->setClearSettings(true); - TryToReboot(); - }); - action = new QAction(tr("Open configuration floder"), this); - menu->addAction(action); - connect(action, &QAction::triggered, this, [=]() { - QString file_name = SAKSettings::instance()->fileName(); - QUrl file_url = QUrl(file_name); - QString floder_url = file_name.remove(file_url.fileName()); - QDesktopServices::openUrl(floder_url); - }); -} - -void SAKCommonMainWindow::InitOptionMenuHdpiPolicy() { - QMenu* menu = new QMenu(tr("HDPI Policy")); - QActionGroup* action_group = new QActionGroup(this); - int setting_policy = SAKSettings::instance()->hdpiPolicy(); +void SAKCommonMainWindow::InitOptionMenuHdpiPolicy() +{ + QMenu* menu = new QMenu(tr("HDPI Policy")); + QActionGroup* action_group = new QActionGroup(this); + int setting_policy = SAKSettings::instance()->hdpiPolicy(); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QList> policy_list; - typedef QPair policy_pair; - policy_list << policy_pair(SAKDataStructure::HdpiPolicyRound, - tr("Round up for .5 and above")); - policy_list << policy_pair(SAKDataStructure::HdpiPolicyCeil, - tr("Always round up")); - policy_list << policy_pair(SAKDataStructure::HdpiPolicyFloor, - tr("Always round down")); - policy_list << policy_pair(SAKDataStructure::HdpiPolicyRoundPreferFloor, - tr("Round up for .75 and above")); - policy_list << policy_pair(SAKDataStructure::HdpiPolicyPassThrough, - tr("Don't round")); - for (auto& policy : policy_list) { - QAction* action = new QAction(policy.second, this); - action_group->addAction(action); - if (setting_policy == policy.first) { - action->setCheckable(true); - } + QList> policy_list; + typedef QPair policy_pair; + policy_list << policy_pair(SAKDataStructure::HdpiPolicyRound, tr("Round up for .5 and above")); + policy_list << policy_pair(SAKDataStructure::HdpiPolicyCeil, tr("Always round up")); + policy_list << policy_pair(SAKDataStructure::HdpiPolicyFloor, tr("Always round down")); + policy_list << policy_pair(SAKDataStructure::HdpiPolicyRoundPreferFloor, + tr("Round up for .75 and above")); + policy_list << policy_pair(SAKDataStructure::HdpiPolicyPassThrough, tr("Don't round")); + for (auto& policy : policy_list) { + QAction* action = new QAction(policy.second, this); + action_group->addAction(action); + if (setting_policy == policy.first) { + action->setCheckable(true); + } - connect(action, &QAction::triggered, this, - [=]() { OnHdpiPolicyActionTriggered(policy.first); }); - } - menu->addActions(action_group->actions()); - option_menu_->addMenu(menu); + connect(action, &QAction::triggered, this, [=]() { + OnHdpiPolicyActionTriggered(policy.first); + }); + } + menu->addActions(action_group->actions()); + option_menu_->addMenu(menu); #endif #ifdef Q_OS_WIN #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QAction* system_action = new QAction(tr("System"), this); - system_action->setCheckable(true); - action_group->addAction(system_action); - menu->addSeparator(); - menu->addAction(system_action); + QAction* system_action = new QAction(tr("System"), this); + system_action->setCheckable(true); + action_group->addAction(system_action); + menu->addSeparator(); + menu->addAction(system_action); - if (setting_policy == SAKDataStructure::HdpiPolicySystem) { - system_action->setChecked(true); - } + if (setting_policy == SAKDataStructure::HdpiPolicySystem) { + system_action->setChecked(true); + } - connect(system_action, &QAction::triggered, this, [=]() { - SAKSettings::instance()->setHdpiPolicy(SAKDataStructure::HdpiPolicySystem); - CreateQtConf(); + connect(system_action, &QAction::triggered, this, [=]() { + SAKSettings::instance()->setHdpiPolicy(SAKDataStructure::HdpiPolicySystem); + CreateQtConf(); + TryToReboot(); + }); +#endif +#endif +} + +void SAKCommonMainWindow::OnHdpiPolicyActionTriggered(int policy) +{ + if (QFile::remove(GetQtConfFileName())) { + qCInfo(logging_category_) << GetQtConfFileName() << "was removed!"; + } else { + qCInfo(logging_category_) << "removed" << GetQtConfFileName() << "failed"; + } + + SAKSettings::instance()->setHdpiPolicy(int(policy)); TryToReboot(); - }); -#endif -#endif } -void SAKCommonMainWindow::OnHdpiPolicyActionTriggered(int policy) { - if (QFile::remove(GetQtConfFileName())) { - qCInfo(logging_category_) << GetQtConfFileName() << "was removed!"; - } else { - qCInfo(logging_category_) << "removed" << GetQtConfFileName() << "failed"; - } - - SAKSettings::instance()->setHdpiPolicy(int(policy)); - TryToReboot(); +void SAKCommonMainWindow::OnGithubActionTriggered() +{ + QDesktopServices::openUrl(QUrl(SAK_GITHUB_REPOSITORY_URL)); } -void SAKCommonMainWindow::OnGithubActionTriggered() { - QDesktopServices::openUrl(QUrl(SAK_GITHUB_REPOSITORY_URL)); +void SAKCommonMainWindow::OnGiteeActionTriggered() +{ + QDesktopServices::openUrl(QUrl(SAK_GITEE_REPOSITORY_URL)); } -void SAKCommonMainWindow::OnGiteeActionTriggered() { - QDesktopServices::openUrl(QUrl(SAK_GITEE_REPOSITORY_URL)); +void SAKCommonMainWindow::OnUserQqGroupTriggerd() +{ + QPixmap pix; + if (!pix.load(":/resources/images/QSAKQQ.jpg")) { + qCWarning(logging_category_) << "Can not load QSAKQQ.jpg."; + return; + } + + QLabel* label = new QLabel(this); + label->resize(pix.size()); + label->setPixmap(pix); + QDialog dialog; + dialog.setLayout(new QHBoxLayout()); + dialog.layout()->addWidget(label); + dialog.setModal(true); + dialog.exec(); } -void SAKCommonMainWindow::OnUserQqGroupTriggerd() { - QPixmap pix; - if (!pix.load(":/resources/images/QSAKQQ.jpg")) { - qCWarning(logging_category_) << "Can not load QSAKQQ.jpg."; - return; - } - - QLabel* label = new QLabel(this); - label->resize(pix.size()); - label->setPixmap(pix); - QDialog dialog; - dialog.setLayout(new QHBoxLayout()); - dialog.layout()->addWidget(label); - dialog.setModal(true); - dialog.exec(); +void SAKCommonMainWindow::OnAboutActionTriggered() +{ + QString year = SAKInterface::buildDateTime("yyyy"); + QString info; + info += centralWidget()->windowTitle() + tr("(Part of Qt Swiss Army knife)"); + info += "\n"; + info += tr("Author: ") + SAK_AUTHOR; + info += "\n"; + info += tr("Email: ") + SAK_AUTHOR_EMAIL; + info += "\n"; + info += tr("Commit: ") + SAK_GIT_COMMIT; + info += "\n"; + info += tr("Date: ") + SAK_GIT_COMMIT_TIME; + info += "\n"; + info += tr("Copyright 2023-%1 Qsaker(qsaker@foxmail.com). " + "All rights reserved.") + .arg(year); + QMessageBox::about(this, tr("About"), info); } -void SAKCommonMainWindow::OnAboutActionTriggered() { - QString year = SAKInterface::buildDateTime("yyyy"); - QString info; - info += centralWidget()->windowTitle() + tr("(Part of Qt Swiss Army knife)"); - info += "\n"; - info += tr("Author: ") + SAK_AUTHOR; - info += "\n"; - info += tr("Email: ") + SAK_AUTHOR_EMAIL; - info += "\n"; - info += tr("Commit: ") + SAK_GIT_COMMIT; - info += "\n"; - info += tr("Date: ") + SAK_GIT_COMMIT_TIME; - info += "\n"; - info += tr("Copyright 2023-%1 Qsaker(qsaker@foxmail.com). " - "All rights reserved.") - .arg(year); - QMessageBox::about(this, tr("About"), info); +void SAKCommonMainWindow::TryToReboot() +{ + int ret = QMessageBox::information(this, + tr("Reboot application to effective"), + tr("Need to reboot, reboot to effective now?"), + QMessageBox::Ok | QMessageBox::Cancel); + if (ret == QMessageBox::Ok) { + QProcess::startDetached(QCoreApplication::applicationFilePath()); + + qApp->closeAllWindows(); + qApp->exit(); + } } -void SAKCommonMainWindow::TryToReboot() { - int ret = - QMessageBox::information(this, tr("Reboot application to effective"), - tr("Need to reboot, reboot to effective now?"), - QMessageBox::Ok | QMessageBox::Cancel); - if (ret == QMessageBox::Ok) { - QProcess::startDetached(QCoreApplication::applicationFilePath()); - - qApp->closeAllWindows(); - qApp->exit(); - } +void SAKCommonMainWindow::CreateQtConf() +{ + QString fileName = GetQtConfFileName(); + QFile file(fileName); + if (file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) { + QTextStream out(&file); + out << "[Platforms]\nWindowsArguments = dpiawareness=0\n"; + file.close(); + } else { + qCWarning(logging_category_) << fileName; + qCWarning(logging_category_) << "can not open file:" << file.errorString(); + } } -void SAKCommonMainWindow::CreateQtConf() { - QString fileName = GetQtConfFileName(); - QFile file(fileName); - if (file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) { - QTextStream out(&file); - out << "[Platforms]\nWindowsArguments = dpiawareness=0\n"; - file.close(); - } else { - qCWarning(logging_category_) << fileName; - qCWarning(logging_category_) << "can not open file:" << file.errorString(); - } -} - -QString SAKCommonMainWindow::GetQtConfFileName() { - return qApp->applicationDirPath() + "/qt.conf"; +QString SAKCommonMainWindow::GetQtConfFileName() +{ + return qApp->applicationDirPath() + "/qt.conf"; } diff --git a/src/common/commonui/sakcommonmainwindow.h b/src/common/commonui/sakcommonmainwindow.h index 02e44dd9..2704ad4a 100644 --- a/src/common/commonui/sakcommonmainwindow.h +++ b/src/common/commonui/sakcommonmainwindow.h @@ -20,80 +20,83 @@ #include "sakinterface.h" #include "saksettings.h" -class SAKCommonMainWindow : public QMainWindow { - public: - SAKCommonMainWindow(QWidget* parent = Q_NULLPTR); - ~SAKCommonMainWindow(); +class SAKCommonMainWindow : public QMainWindow +{ +public: + SAKCommonMainWindow(QWidget* parent = Q_NULLPTR); + ~SAKCommonMainWindow(); - protected: - QMenu* file_menu_; - QMenu* option_menu_; - QMenu* language_menu_; - QMenu* help_menu_; +protected: + QMenu* file_menu_; + QMenu* option_menu_; + QMenu* language_menu_; + QMenu* help_menu_; - private: - QActionGroup* app_style_action_group_; - QActionGroup* language_action_group_; - const QLoggingCategory logging_category_{"SAK.CommonMainWindow"}; +private: + QActionGroup* app_style_action_group_; + QActionGroup* language_action_group_; + const QLoggingCategory logging_category_{"SAK.CommonMainWindow"}; - private: - void Init(); - void InitMenu(); - void InitMenuFile(); - void InitMenuOption(); - void InitMenuLanguage(); - void InitMenuHelp(); +private: + void Init(); + void InitMenu(); + void InitMenuFile(); + void InitMenuOption(); + void InitMenuLanguage(); + void InitMenuHelp(); - void InitOptionMenuAppStyleMenu(); - void InitOptionMenuSettingsMenu(); - void InitOptionMenuHdpiPolicy(); + void InitOptionMenuAppStyleMenu(); + void InitOptionMenuSettingsMenu(); + void InitOptionMenuHdpiPolicy(); - void OnHdpiPolicyActionTriggered(int policy); - void OnGithubActionTriggered(); - void OnGiteeActionTriggered(); - void OnUserQqGroupTriggerd(); - void OnAboutActionTriggered(); + void OnHdpiPolicyActionTriggered(int policy); + void OnGithubActionTriggered(); + void OnGiteeActionTriggered(); + void OnUserQqGroupTriggerd(); + void OnAboutActionTriggered(); - void TryToReboot(); - void CreateQtConf(); - QString GetQtConfFileName(); + void TryToReboot(); + void CreateQtConf(); + QString GetQtConfFileName(); }; -template -QApplication* CreateCommonMainWindowApplication( - int argc, char* argv[], const QString& title, - const char* logging_category_path) { - QCoreApplication::setOrganizationName(QString("Qsaker")); - QCoreApplication::setOrganizationDomain(QString("IT")); - QCoreApplication::setApplicationName(QString(title).remove(" ")); +template +QApplication* CreateCommonMainWindowApplication(int argc, + char* argv[], + const QString& title, + const char* logging_category_path) +{ + QCoreApplication::setOrganizationName(QString("Qsaker")); + QCoreApplication::setOrganizationDomain(QString("IT")); + QCoreApplication::setApplicationName(QString(title).remove(" ")); - // Application style. - QLoggingCategory logging_category(logging_category_path); - QString style = SAKSettings::instance()->appStyle(); - if (!style.isEmpty() && QStyleFactory::keys().contains(style)) { - qCInfo(logging_category) << "The application style is:" << style; - QApplication::setStyle(QStyleFactory::create(style)); - } + // Application style. + QLoggingCategory logging_category(logging_category_path); + QString style = SAKSettings::instance()->appStyle(); + if (!style.isEmpty() && QStyleFactory::keys().contains(style)) { + qCInfo(logging_category) << "The application style is:" << style; + QApplication::setStyle(QStyleFactory::create(style)); + } - // High dpi settings. + // High dpi settings. #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - int policy = SAKSettings::instance()->hdpiPolicy(); - if (SAKInterface::isQtHighDpiScalePolicy(policy)) { - auto cookedPolicy = Qt::HighDpiScaleFactorRoundingPolicy(policy); - QGuiApplication::setHighDpiScaleFactorRoundingPolicy(cookedPolicy); - } + int policy = SAKSettings::instance()->hdpiPolicy(); + if (SAKInterface::isQtHighDpiScalePolicy(policy)) { + auto cookedPolicy = Qt::HighDpiScaleFactorRoundingPolicy(policy); + QGuiApplication::setHighDpiScaleFactorRoundingPolicy(cookedPolicy); + } #endif - QApplication* app = new QApplication(argc, argv); + QApplication* app = new QApplication(argc, argv); - SAKCommonMainWindow* main_window = new SAKCommonMainWindow(); - T* assistant = new T(main_window); - main_window->setWindowTitle(title); - main_window->setCentralWidget(assistant); - main_window->resize(main_window->height() * 1.732, main_window->height()); - main_window->show(); + SAKCommonMainWindow* main_window = new SAKCommonMainWindow(); + T* assistant = new T(main_window); + main_window->setWindowTitle(title); + main_window->setCentralWidget(assistant); + main_window->resize(main_window->height() * 1.732, main_window->height()); + main_window->show(); - return app; + return app; } -#endif // SAKCOMMONMAINWINDOW_H +#endif // SAKCOMMONMAINWINDOW_H diff --git a/src/common/commonui/sakcrcalgorithmcombobox.cc b/src/common/commonui/sakcrcalgorithmcombobox.cc index e93f5238..d304a771 100644 --- a/src/common/commonui/sakcrcalgorithmcombobox.cc +++ b/src/common/commonui/sakcrcalgorithmcombobox.cc @@ -14,10 +14,10 @@ #include "sakcrcinterface.h" SAKCrcAlgorithmComboBox::SAKCrcAlgorithmComboBox(QWidget* parent) - : SAKComboBox(parent) { - QMetaEnum metaEnum = - QMetaEnum::fromType(); - for (int i = 0; i < metaEnum.keyCount(); i++) { - addItem(metaEnum.key(i), metaEnum.value(i)); - } + : SAKComboBox(parent) +{ + QMetaEnum metaEnum = QMetaEnum::fromType(); + for (int i = 0; i < metaEnum.keyCount(); i++) { + addItem(metaEnum.key(i), metaEnum.value(i)); + } } diff --git a/src/common/commonui/sakdatabitscombobox.cc b/src/common/commonui/sakdatabitscombobox.cc index 4917fd3f..4ac13662 100644 --- a/src/common/commonui/sakdatabitscombobox.cc +++ b/src/common/commonui/sakdatabitscombobox.cc @@ -12,9 +12,10 @@ #include SAKDataBitsComboBox::SAKDataBitsComboBox(QWidget* parent) - : SAKComboBox(parent) { - addItem("8", QSerialPort::Data8); - addItem("7", QSerialPort::Data7); - addItem("6", QSerialPort::Data6); - addItem("5", QSerialPort::Data5); + : SAKComboBox(parent) +{ + addItem("8", QSerialPort::Data8); + addItem("7", QSerialPort::Data7); + addItem("6", QSerialPort::Data6); + addItem("5", QSerialPort::Data5); } diff --git a/src/common/commonui/sakescapecharactercombobox.cc b/src/common/commonui/sakescapecharactercombobox.cc index b20a9677..5ae1f2d4 100644 --- a/src/common/commonui/sakescapecharactercombobox.cc +++ b/src/common/commonui/sakescapecharactercombobox.cc @@ -12,11 +12,12 @@ #include "sakdatastructure.h" SAKEscapeCharacterComboBox::SAKEscapeCharacterComboBox(QWidget* parent) - : SAKComboBox(parent) { - addItem(tr("None"), SAKDataStructure::EscapeCharacterOptionNone); - addItem("\\r", SAKDataStructure::EscapeCharacterOptionR); - addItem("\\n", SAKDataStructure::EscapeCharacterOptionN); - addItem("\\r\\n", SAKDataStructure::EscapeCharacterOptionRN); - addItem("\\n\\r", SAKDataStructure::EscapeCharacterOptionNR); - addItem("\\r + \\n", SAKDataStructure::EscapeCharacterOptionRAndN); + : SAKComboBox(parent) +{ + addItem(tr("None"), SAKDataStructure::EscapeCharacterOptionNone); + addItem("\\r", SAKDataStructure::EscapeCharacterOptionR); + addItem("\\n", SAKDataStructure::EscapeCharacterOptionN); + addItem("\\r\\n", SAKDataStructure::EscapeCharacterOptionRN); + addItem("\\n\\r", SAKDataStructure::EscapeCharacterOptionNR); + addItem("\\r + \\n", SAKDataStructure::EscapeCharacterOptionRAndN); } diff --git a/src/common/commonui/sakflowcontrolcombobox.cc b/src/common/commonui/sakflowcontrolcombobox.cc index 3c27843d..7a5a6631 100644 --- a/src/common/commonui/sakflowcontrolcombobox.cc +++ b/src/common/commonui/sakflowcontrolcombobox.cc @@ -12,8 +12,9 @@ #include SAKFlowControlComboBox::SAKFlowControlComboBox(QWidget* parent) - : SAKComboBox(parent) { - addItem(tr("No"), QSerialPort::NoFlowControl); - addItem(tr("Hardware"), QSerialPort::HardwareControl); - addItem(tr("Software"), QSerialPort::SoftwareControl); + : SAKComboBox(parent) +{ + addItem(tr("No"), QSerialPort::NoFlowControl); + addItem(tr("Hardware"), QSerialPort::HardwareControl); + addItem(tr("Software"), QSerialPort::SoftwareControl); } diff --git a/src/common/commonui/sakipcombobox.cc b/src/common/commonui/sakipcombobox.cc index c02d1a27..97678a1d 100644 --- a/src/common/commonui/sakipcombobox.cc +++ b/src/common/commonui/sakipcombobox.cc @@ -12,11 +12,13 @@ #include #include -SAKIpComboBox::SAKIpComboBox(QWidget* parent) : SAKComboBox(parent) { - auto addresses = QNetworkInterface::allAddresses(); - for (auto& address : addresses) { - if (address.protocol() == QAbstractSocket::IPv4Protocol) { - addItem(address.toString()); +SAKIpComboBox::SAKIpComboBox(QWidget* parent) + : SAKComboBox(parent) +{ + auto addresses = QNetworkInterface::allAddresses(); + for (auto& address : addresses) { + if (address.protocol() == QAbstractSocket::IPv4Protocol) { + addItem(address.toString()); + } } - } } diff --git a/src/common/commonui/saklineedit.cc b/src/common/commonui/saklineedit.cc index a8cf7926..085c6fd6 100644 --- a/src/common/commonui/saklineedit.cc +++ b/src/common/commonui/saklineedit.cc @@ -11,29 +11,33 @@ #include "saksettings.h" -SAKLineEdit::SAKLineEdit(QWidget* parent) : QLineEdit(parent) { - connect(this, &SAKLineEdit::textChanged, this, - &SAKLineEdit::writeToSettingsFile); +SAKLineEdit::SAKLineEdit(QWidget* parent) + : QLineEdit(parent) +{ + connect(this, &SAKLineEdit::textChanged, this, &SAKLineEdit::writeToSettingsFile); } -void SAKLineEdit::setGroupKey(const QString& group, const QString& key) { - mKey = group + "/" + key; - readFromSettingsFile(); +void SAKLineEdit::setGroupKey(const QString& group, const QString& key) +{ + mKey = group + "/" + key; + readFromSettingsFile(); } -void SAKLineEdit::readFromSettingsFile() { - if (mKey.isEmpty()) { - return; - } +void SAKLineEdit::readFromSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } - QString txt = SAKSettings::instance()->value(mKey).toString(); - setText(txt); + QString txt = SAKSettings::instance()->value(mKey).toString(); + setText(txt); } -void SAKLineEdit::writeToSettingsFile() { - if (mKey.isEmpty()) { - return; - } +void SAKLineEdit::writeToSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } - SAKSettings::instance()->setValue(mKey, text()); + SAKSettings::instance()->setValue(mKey, text()); } diff --git a/src/common/commonui/saklineedit.h b/src/common/commonui/saklineedit.h index 9d7e0481..410fb5bc 100644 --- a/src/common/commonui/saklineedit.h +++ b/src/common/commonui/saklineedit.h @@ -17,8 +17,7 @@ class SAKLineEdit : public QLineEdit Q_OBJECT public: SAKLineEdit(QWidget *parent = nullptr); - void setGroupKey(const QString &group, - const QString &key); + void setGroupKey(const QString &group, const QString &key); private: QString mKey; diff --git a/src/common/commonui/sakmenu.cc b/src/common/commonui/sakmenu.cc index 007fd6f1..afc3787f 100644 --- a/src/common/commonui/sakmenu.cc +++ b/src/common/commonui/sakmenu.cc @@ -12,19 +12,23 @@ #include SAKMenu::SAKMenu(const QString& title, QWidget* parent) - : QMenu(title, parent) {} + : QMenu(title, parent) +{} -SAKMenu::SAKMenu(QWidget* parent) : QMenu{parent} {} +SAKMenu::SAKMenu(QWidget* parent) + : QMenu{parent} +{} -void SAKMenu::mouseReleaseEvent(QMouseEvent* e) { - auto p = QCursor::pos(); - if (geometry().contains(p)) { - QAction* a = actionAt(e->pos()); - if (a) { - a->activate(QAction::Trigger); - return; +void SAKMenu::mouseReleaseEvent(QMouseEvent* e) +{ + auto p = QCursor::pos(); + if (geometry().contains(p)) { + QAction* a = actionAt(e->pos()); + if (a) { + a->activate(QAction::Trigger); + return; + } } - } - QMenu::mouseReleaseEvent(e); + QMenu::mouseReleaseEvent(e); } diff --git a/src/common/commonui/sakparitycombobox.cc b/src/common/commonui/sakparitycombobox.cc index 8489a575..8a3270f4 100644 --- a/src/common/commonui/sakparitycombobox.cc +++ b/src/common/commonui/sakparitycombobox.cc @@ -11,10 +11,12 @@ #include -SAKParityComboBox::SAKParityComboBox(QWidget* parent) : SAKComboBox(parent) { - addItem(tr("No"), QSerialPort::NoParity); - addItem(tr("Even"), QSerialPort::EvenParity); - addItem(tr("Odd"), QSerialPort::OddParity); - addItem(tr("Space"), QSerialPort::SpaceParity); - addItem(tr("Mark"), QSerialPort::MarkParity); +SAKParityComboBox::SAKParityComboBox(QWidget* parent) + : SAKComboBox(parent) +{ + addItem(tr("No"), QSerialPort::NoParity); + addItem(tr("Even"), QSerialPort::EvenParity); + addItem(tr("Odd"), QSerialPort::OddParity); + addItem(tr("Space"), QSerialPort::SpaceParity); + addItem(tr("Mark"), QSerialPort::MarkParity); } diff --git a/src/common/commonui/sakportnamecombobox.cc b/src/common/commonui/sakportnamecombobox.cc index 876a1b9e..dd0c416f 100644 --- a/src/common/commonui/sakportnamecombobox.cc +++ b/src/common/commonui/sakportnamecombobox.cc @@ -14,19 +14,21 @@ #include SAKPortNameComboBox::SAKPortNameComboBox(QWidget* parent) - : SAKComboBox(parent) { - refresh(); + : SAKComboBox(parent) +{ + refresh(); } -void SAKPortNameComboBox::refresh() { - clear(); - QList coms = QSerialPortInfo::availablePorts(); - QStandardItemModel* itemModel = new QStandardItemModel(this); - for (auto& var : coms) { - QStandardItem* item = new QStandardItem(var.portName()); - item->setToolTip(var.description()); - itemModel->appendRow(item); - } +void SAKPortNameComboBox::refresh() +{ + clear(); + QList coms = QSerialPortInfo::availablePorts(); + QStandardItemModel* itemModel = new QStandardItemModel(this); + for (auto& var : coms) { + QStandardItem* item = new QStandardItem(var.portName()); + item->setToolTip(var.description()); + itemModel->appendRow(item); + } - setModel(itemModel); + setModel(itemModel); } diff --git a/src/common/commonui/sakresponseoptioncombobox.cc b/src/common/commonui/sakresponseoptioncombobox.cc index 5f430742..0c476d9a 100644 --- a/src/common/commonui/sakresponseoptioncombobox.cc +++ b/src/common/commonui/sakresponseoptioncombobox.cc @@ -12,17 +12,17 @@ #include "sakdatastructure.h" SAKResponseOptionComboBox::SAKResponseOptionComboBox(QWidget* parent) - : SAKComboBox(parent) { + : SAKComboBox(parent) +{ #if 0 addItem(tr("Disable"), SAKDataStructure::ResponseOptionDisable); #endif - addItem(tr("Echo", "widget", __LINE__), SAKDataStructure::ResponseOptionEcho); - addItem(tr("Always", "widget", __LINE__), - SAKDataStructure::ResponseOptionAlways); - addItem(tr("RxEqualReference", "widget", __LINE__), - SAKDataStructure::ResponseOptionInputEqualReference); - addItem(tr("RxContainReference", "widget", __LINE__), - SAKDataStructure::ResponseOptionInputContainReference); - addItem(tr("RxDiscontainReference", "widget", __LINE__), - SAKDataStructure::ResponseOptionInputDiscontainReference); + addItem(tr("Echo", "widget", __LINE__), SAKDataStructure::ResponseOptionEcho); + addItem(tr("Always", "widget", __LINE__), SAKDataStructure::ResponseOptionAlways); + addItem(tr("RxEqualReference", "widget", __LINE__), + SAKDataStructure::ResponseOptionInputEqualReference); + addItem(tr("RxContainReference", "widget", __LINE__), + SAKDataStructure::ResponseOptionInputContainReference); + addItem(tr("RxDiscontainReference", "widget", __LINE__), + SAKDataStructure::ResponseOptionInputDiscontainReference); } diff --git a/src/common/commonui/sakspinbox.cc b/src/common/commonui/sakspinbox.cc index 43865289..8f066690 100644 --- a/src/common/commonui/sakspinbox.cc +++ b/src/common/commonui/sakspinbox.cc @@ -11,29 +11,36 @@ #include "saksettings.h" -SAKSpinBox::SAKSpinBox(QWidget* parent) : QSpinBox(parent) { - connect(this, static_cast(&QSpinBox::valueChanged), - this, &SAKSpinBox::writeToSettingsFile); +SAKSpinBox::SAKSpinBox(QWidget* parent) + : QSpinBox(parent) +{ + connect(this, + static_cast(&QSpinBox::valueChanged), + this, + &SAKSpinBox::writeToSettingsFile); } -void SAKSpinBox::setGroupKey(const QString& group, const QString& key) { - mKey = group + "/" + key; - readFromSettingsFile(); +void SAKSpinBox::setGroupKey(const QString& group, const QString& key) +{ + mKey = group + "/" + key; + readFromSettingsFile(); } -void SAKSpinBox::readFromSettingsFile() { - if (mKey.isEmpty()) { - return; - } +void SAKSpinBox::readFromSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } - int value = SAKSettings::instance()->value(mKey).toInt(); - setValue(value); + int value = SAKSettings::instance()->value(mKey).toInt(); + setValue(value); } -void SAKSpinBox::writeToSettingsFile() { - if (mKey.isEmpty()) { - return; - } +void SAKSpinBox::writeToSettingsFile() +{ + if (mKey.isEmpty()) { + return; + } - SAKSettings::instance()->setValue(mKey, value()); + SAKSettings::instance()->setValue(mKey, value()); } diff --git a/src/common/commonui/sakspinbox.h b/src/common/commonui/sakspinbox.h index 3727315a..83dff5a0 100644 --- a/src/common/commonui/sakspinbox.h +++ b/src/common/commonui/sakspinbox.h @@ -17,8 +17,7 @@ class SAKSpinBox : public QSpinBox Q_OBJECT public: SAKSpinBox(QWidget *parent = nullptr); - void setGroupKey(const QString &group, - const QString &key); + void setGroupKey(const QString &group, const QString &key); private: QString mKey; diff --git a/src/common/commonui/sakstopbitscombobox.cc b/src/common/commonui/sakstopbitscombobox.cc index aa37bcb6..c2624f3d 100644 --- a/src/common/commonui/sakstopbitscombobox.cc +++ b/src/common/commonui/sakstopbitscombobox.cc @@ -12,10 +12,11 @@ #include SAKStopBitsComboBox::SAKStopBitsComboBox(QWidget* parent) - : SAKComboBox(parent) { - addItem("1", QSerialPort::OneStop); + : SAKComboBox(parent) +{ + addItem("1", QSerialPort::OneStop); #ifdef Q_OS_WIN - addItem("1.5", QSerialPort::OneAndHalfStop); + addItem("1.5", QSerialPort::OneAndHalfStop); #endif - addItem("2", QSerialPort::TwoStop); + addItem("2", QSerialPort::TwoStop); } diff --git a/src/common/commonui/saktextformatcombobox.cc b/src/common/commonui/saktextformatcombobox.cc index 9cbfa49e..0688964f 100644 --- a/src/common/commonui/saktextformatcombobox.cc +++ b/src/common/commonui/saktextformatcombobox.cc @@ -12,15 +12,16 @@ #include "sakdatastructure.h" SAKTextFormatComboBox::SAKTextFormatComboBox(QWidget* parent) - : SAKComboBox(parent) { - addItem("Bin", SAKDataStructure::TextFormatBin); - addItem("Oct", SAKDataStructure::TextFormatOct); - addItem("Dec", SAKDataStructure::TextFormatDec); - addItem("Hex", SAKDataStructure::TextFormatHex); - addItem("Ascii", SAKDataStructure::TextFormatAscii); - addItem("Utf8", SAKDataStructure::TextFormatUtf8); + : SAKComboBox(parent) +{ + addItem("Bin", SAKDataStructure::TextFormatBin); + addItem("Oct", SAKDataStructure::TextFormatOct); + addItem("Dec", SAKDataStructure::TextFormatDec); + addItem("Hex", SAKDataStructure::TextFormatHex); + addItem("Ascii", SAKDataStructure::TextFormatAscii); + addItem("Utf8", SAKDataStructure::TextFormatUtf8); - blockSignals(true); - setCurrentIndex(5); - blockSignals(false); + blockSignals(true); + setCurrentIndex(5); + blockSignals(false); } diff --git a/src/common/commonui/sakuiinterface.cc b/src/common/commonui/sakuiinterface.cc index 62090f8d..027c8706 100644 --- a/src/common/commonui/sakuiinterface.cc +++ b/src/common/commonui/sakuiinterface.cc @@ -18,48 +18,48 @@ #include "sakdatastructure.h" -SAKUiInterface::SAKUiInterface(QObject* parent) : QObject{parent} {} +SAKUiInterface::SAKUiInterface(QObject* parent) + : QObject{parent} +{} -void SAKUiInterface::setValidator(QLineEdit* le, int textFormat) { - if (!le) { - return; - } +void SAKUiInterface::setValidator(QLineEdit* le, int textFormat) +{ + if (!le) { + return; + } - static QMap regExpMap; - if (regExpMap.isEmpty()) { - regExpMap.insert( - SAKDataStructure::TextFormatBin, - QRegularExpression("([01][01][01][01][01][01][01][01][ ])*")); - regExpMap.insert(SAKDataStructure::TextFormatOct, - QRegularExpression("([0-7][0-7][ ])*")); - regExpMap.insert(SAKDataStructure::TextFormatDec, - QRegularExpression("([0-9][0-9][ ])*")); - regExpMap.insert(SAKDataStructure::TextFormatHex, - QRegularExpression("([0-9a-fA-F][0-9a-fA-F][ ])*")); - regExpMap.insert(SAKDataStructure::TextFormatAscii, - QRegularExpression("([ -~])*")); - } + static QMap regExpMap; + if (regExpMap.isEmpty()) { + regExpMap.insert(SAKDataStructure::TextFormatBin, + QRegularExpression("([01][01][01][01][01][01][01][01][ ])*")); + regExpMap.insert(SAKDataStructure::TextFormatOct, QRegularExpression("([0-7][0-7][ ])*")); + regExpMap.insert(SAKDataStructure::TextFormatDec, QRegularExpression("([0-9][0-9][ ])*")); + regExpMap.insert(SAKDataStructure::TextFormatHex, + QRegularExpression("([0-9a-fA-F][0-9a-fA-F][ ])*")); + regExpMap.insert(SAKDataStructure::TextFormatAscii, QRegularExpression("([ -~])*")); + } - if (le->validator()) { - delete le->validator(); - } + if (le->validator()) { + delete le->validator(); + } - if (regExpMap.contains(textFormat)) { - QRegularExpression re = regExpMap.value(textFormat); - auto validator = new QRegularExpressionValidator(re, le); - le->setValidator(validator); - } else { - le->setValidator(nullptr); - } + if (regExpMap.contains(textFormat)) { + QRegularExpression re = regExpMap.value(textFormat); + auto validator = new QRegularExpressionValidator(re, le); + le->setValidator(validator); + } else { + le->setValidator(nullptr); + } - le->clear(); + le->clear(); } -QIcon SAKUiInterface::cookedIcon(const QIcon& icon) { - QPixmap pixmap = icon.pixmap(QSize(128, 128)); - QPainter painter(&pixmap); - painter.setCompositionMode(QPainter::CompositionMode_SourceIn); - painter.fillRect(pixmap.rect(), qApp->palette().windowText().color()); - QIcon colorIcon = QIcon(pixmap); - return colorIcon; +QIcon SAKUiInterface::cookedIcon(const QIcon& icon) +{ + QPixmap pixmap = icon.pixmap(QSize(128, 128)); + QPainter painter(&pixmap); + painter.setCompositionMode(QPainter::CompositionMode_SourceIn); + painter.fillRect(pixmap.rect(), qApp->palette().windowText().color()); + QIcon colorIcon = QIcon(pixmap); + return colorIcon; } diff --git a/src/common/commonui/sakuiinterface.h b/src/common/commonui/sakuiinterface.h index dfbb7de3..8ad711a5 100644 --- a/src/common/commonui/sakuiinterface.h +++ b/src/common/commonui/sakuiinterface.h @@ -10,8 +10,8 @@ #ifndef SAKUIINTERFACE_H #define SAKUIINTERFACE_H -#include #include +#include class SAKUiInterface : public QObject { diff --git a/src/common/commonui/sakwebsocketmessagetypecombobox.cc b/src/common/commonui/sakwebsocketmessagetypecombobox.cc index 1596e93a..403474d7 100644 --- a/src/common/commonui/sakwebsocketmessagetypecombobox.cc +++ b/src/common/commonui/sakwebsocketmessagetypecombobox.cc @@ -9,9 +9,9 @@ ******************************************************************************/ #include "sakwebsocketmessagetypecombobox.h" -sakwebsocketmessagetypecombobox::sakwebsocketmessagetypecombobox( - QWidget* parent) - : SAKComboBox{parent} { - addItem("Bin", 0); - addItem("Text", 1); +sakwebsocketmessagetypecombobox::sakwebsocketmessagetypecombobox(QWidget* parent) + : SAKComboBox{parent} +{ + addItem("Bin", 0); + addItem("Text", 1); } diff --git a/src/easydebug/main.cc b/src/easydebug/main.cc index 4bca8a7b..d6866170 100644 --- a/src/easydebug/main.cc +++ b/src/easydebug/main.cc @@ -15,46 +15,47 @@ #include "saklog.h" #include "saksettings.h" -int main(int argc, char* argv[]) { +int main(int argc, char* argv[]) +{ #ifndef QT_DEBUG - qInstallMessageHandler(SAKLog::messageOutput); + qInstallMessageHandler(SAKLog::messageOutput); #endif - // Initialize some information about application. - QCoreApplication::setOrganizationName(QString("Qsaker")); - QCoreApplication::setOrganizationDomain(QString("IT")); + // Initialize some information about application. + QCoreApplication::setOrganizationName(QString("Qsaker")); + QCoreApplication::setOrganizationDomain(QString("IT")); #ifdef SAK_RELEASE_FOR_APP_STORE - QCoreApplication::setApplicationName(QString("EasyDebug")); + QCoreApplication::setApplicationName(QString("EasyDebug")); #else - QCoreApplication::setApplicationName(QString("EasyDebug(Community)")); + QCoreApplication::setApplicationName(QString("EasyDebug(Community)")); #endif #ifdef SAK_VERSION - QCoreApplication::setApplicationVersion(SAK_VERSION); + QCoreApplication::setApplicationVersion(SAK_VERSION); #else - QCoreApplication::setApplicationVersion("0.0.0"); + QCoreApplication::setApplicationVersion("0.0.0"); #endif - QLoggingCategory lc{"SAK.Main"}; - // Remove settings file and database - if (SAKSettings::instance()->clearSettings()) { - SAKSettings::instance()->setClearSettings(false); - if (QFile::remove(SAKSettings::instance()->fileName())) { - qCInfo(lc) << "Remove settings file successfully."; - } else { - qCWarning(lc) << "Remove settings file failed!"; + QLoggingCategory lc{"SAK.Main"}; + // Remove settings file and database + if (SAKSettings::instance()->clearSettings()) { + SAKSettings::instance()->setClearSettings(false); + if (QFile::remove(SAKSettings::instance()->fileName())) { + qCInfo(lc) << "Remove settings file successfully."; + } else { + qCWarning(lc) << "Remove settings file failed!"; + } } - } - // High dpi settings. + // High dpi settings. #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - int policy = SAKSettings::instance()->hdpiPolicy(); - if (SAKInterface::isQtHighDpiScalePolicy(policy)) { - auto cookedPolicy = Qt::HighDpiScaleFactorRoundingPolicy(policy); - QGuiApplication::setHighDpiScaleFactorRoundingPolicy(cookedPolicy); - } + int policy = SAKSettings::instance()->hdpiPolicy(); + if (SAKInterface::isQtHighDpiScalePolicy(policy)) { + auto cookedPolicy = Qt::HighDpiScaleFactorRoundingPolicy(policy); + QGuiApplication::setHighDpiScaleFactorRoundingPolicy(cookedPolicy); + } #endif - SAKGuiApplication app(argc, argv); - SAKLog::instance()->start(); - return app.exec(); + SAKGuiApplication app(argc, argv); + SAKLog::instance()->start(); + return app.exec(); } diff --git a/src/easydebug/sakguiapplication.cc b/src/easydebug/sakguiapplication.cc index 2c8dda9d..b26f90c5 100644 --- a/src/easydebug/sakguiapplication.cc +++ b/src/easydebug/sakguiapplication.cc @@ -40,81 +40,72 @@ #include "sakwebsocketservertool.h" SAKGuiApplication::SAKGuiApplication(int argc, char* argv[]) - : QGuiApplication(argc, argv) { - QQuickStyle::setStyle("Material"); + : QGuiApplication(argc, argv) +{ + QQuickStyle::setStyle("Material"); - auto sakCrc = new SAKCrcInterface(this); - auto sakInterface = new SAKInterface(this); - auto sakDataStructure = new SAKDataStructure(this); + auto sakCrc = new SAKCrcInterface(this); + auto sakInterface = new SAKInterface(this); + auto sakDataStructure = new SAKDataStructure(this); - auto sakI18n = SAKTranslator::instance(); - auto sakSettings = SAKSettings::instance(); + auto sakI18n = SAKTranslator::instance(); + auto sakSettings = SAKSettings::instance(); - QString language = SAKSettings::instance()->language(); - SAKTranslator::instance()->setupLanguage(language); + QString language = SAKSettings::instance()->language(); + SAKTranslator::instance()->setupLanguage(language); - const QString reason = "Uncreatable type!"; - qmlRegisterType("SAK.Custom", 1, 0, "SAKDevice"); - qmlRegisterType("SAK.Custom", 1, 0, "SAKSettings"); - qmlRegisterType("SAK.Custom", 1, 0, "SAKBleScanner"); - qmlRegisterType("SAK.Custom", 1, 0, "SAKHighlighter"); - qmlRegisterType("SAK.Custom", 1, 0, "SAKCrcInterface"); - qmlRegisterType("SAK.Custom", 1, 0, - "SAKSerialPortScanner"); - qmlRegisterType("SAK.Custom", 1, 0, - "SAKNetworkInterfaceScanner"); + const QString reason = "Uncreatable type!"; + qmlRegisterType("SAK.Custom", 1, 0, "SAKDevice"); + qmlRegisterType("SAK.Custom", 1, 0, "SAKSettings"); + qmlRegisterType("SAK.Custom", 1, 0, "SAKBleScanner"); + qmlRegisterType("SAK.Custom", 1, 0, "SAKHighlighter"); + qmlRegisterType("SAK.Custom", 1, 0, "SAKCrcInterface"); + qmlRegisterType("SAK.Custom", 1, 0, "SAKSerialPortScanner"); + qmlRegisterType("SAK.Custom", 1, 0, "SAKNetworkInterfaceScanner"); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKBaseTool", - reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKMaskerTool", - reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKStorerTool", - reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKEmitterTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKToolsFactory", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKAnalyzerTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKPrestorerTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKResponserTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKUdpClientTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKUdpServerTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKTcpClientTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKTcpServerTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKBleCentralTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKSerialportTool", reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKTabelModelTool", reason); - qmlRegisterUncreatableType( - "SAK.Custom", 1, 0, "SAKCommunicationTool", reason); - qmlRegisterUncreatableType( - "SAK.Custom", 1, 0, "SAKWebSocketServerTool", reason); - qmlRegisterUncreatableType( - "SAK.Custom", 1, 0, "SAKWebSocketClientTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKBaseTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKMaskerTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKStorerTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKEmitterTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKToolsFactory", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKAnalyzerTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKPrestorerTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKResponserTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKUdpClientTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKUdpServerTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKTcpClientTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKTcpServerTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKBleCentralTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKSerialportTool", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKTabelModelTool", reason); + qmlRegisterUncreatableType("SAK.Custom", + 1, + 0, + "SAKCommunicationTool", + reason); + qmlRegisterUncreatableType("SAK.Custom", + 1, + 0, + "SAKWebSocketServerTool", + reason); + qmlRegisterUncreatableType("SAK.Custom", + 1, + 0, + "SAKWebSocketClientTool", + reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKInterface", - reason); - qmlRegisterUncreatableType("SAK.Custom", 1, 0, - "SAKDataStructure", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKInterface", reason); + qmlRegisterUncreatableType("SAK.Custom", 1, 0, "SAKDataStructure", reason); - mQmlAppEngine.rootContext()->setContextProperty("sakCrc", sakCrc); - mQmlAppEngine.rootContext()->setContextProperty("sakI18n", sakI18n); - mQmlAppEngine.rootContext()->setContextProperty("sakSettings", sakSettings); - mQmlAppEngine.rootContext()->setContextProperty("sakInterface", sakInterface); - mQmlAppEngine.rootContext()->setContextProperty("sakDataStructure", - sakDataStructure); - mQmlAppEngine.load("qrc:/qml/MainWindow.qml"); + mQmlAppEngine.rootContext()->setContextProperty("sakCrc", sakCrc); + mQmlAppEngine.rootContext()->setContextProperty("sakI18n", sakI18n); + mQmlAppEngine.rootContext()->setContextProperty("sakSettings", sakSettings); + mQmlAppEngine.rootContext()->setContextProperty("sakInterface", sakInterface); + mQmlAppEngine.rootContext()->setContextProperty("sakDataStructure", sakDataStructure); + mQmlAppEngine.load("qrc:/qml/MainWindow.qml"); } -QQmlApplicationEngine& SAKGuiApplication::qmlAppEngine() { - return mQmlAppEngine; +QQmlApplicationEngine& SAKGuiApplication::qmlAppEngine() +{ + return mQmlAppEngine; } diff --git a/src/log/logui/saklogui.cc b/src/log/logui/saklogui.cc index 8d23eeb3..583694be 100644 --- a/src/log/logui/saklogui.cc +++ b/src/log/logui/saklogui.cc @@ -17,78 +17,94 @@ #include "saklog.h" #include "ui_saklogui.h" -SAKLogUi::SAKLogUi(QWidget* parent) : QWidget(parent), ui(new Ui::SAKLogUi) { - ui->setupUi(this); - ui->comboBoxLevel->addItem(tr("Disable"), -1); - ui->comboBoxLevel->addItem(tr("Debug"), QtMsgType::QtDebugMsg); - ui->comboBoxLevel->addItem(tr("Info"), QtMsgType::QtInfoMsg); - ui->comboBoxLevel->addItem(tr("Warning"), QtMsgType::QtWarningMsg); - ui->comboBoxLevel->addItem(tr("Error"), QtMsgType::QtSystemMsg); +SAKLogUi::SAKLogUi(QWidget* parent) + : QWidget(parent) + , ui(new Ui::SAKLogUi) +{ + ui->setupUi(this); + ui->comboBoxLevel->addItem(tr("Disable"), -1); + ui->comboBoxLevel->addItem(tr("Debug"), QtMsgType::QtDebugMsg); + ui->comboBoxLevel->addItem(tr("Info"), QtMsgType::QtInfoMsg); + ui->comboBoxLevel->addItem(tr("Warning"), QtMsgType::QtWarningMsg); + ui->comboBoxLevel->addItem(tr("Error"), QtMsgType::QtSystemMsg); - ui->comboBoxLevel->setGroupKey("Log", "level"); - ui->comboBoxLifeCycle->setGroupKey("Log", "LifeCycle"); + ui->comboBoxLevel->setGroupKey("Log", "level"); + ui->comboBoxLifeCycle->setGroupKey("Log", "LifeCycle"); - connect(ui->comboBoxLevel, SIGNAL(currentIndexChanged(int)), this, - SLOT(onComboBoxLevelCurrentIndexChanged())); - connect(ui->comboBoxLifeCycle, SIGNAL(currentIndexChanged(int)), this, - SLOT(onComboBoxLifeCycleCurrentIndexChanged())); + connect(ui->comboBoxLevel, + SIGNAL(currentIndexChanged(int)), + this, + SLOT(onComboBoxLevelCurrentIndexChanged())); + connect(ui->comboBoxLifeCycle, + SIGNAL(currentIndexChanged(int)), + this, + SLOT(onComboBoxLifeCycleCurrentIndexChanged())); - QAbstractTableModel* tableModel = SAKLog::instance()->tableModel(); - QTableView* tableView = ui->tableView; - QHeaderView* headerView = tableView->horizontalHeader(); - QHeaderView* vHeaderView = tableView->verticalHeader(); - vHeaderView->hide(); - tableView->setModel(tableModel); - tableView->setAlternatingRowColors(true); + QAbstractTableModel* tableModel = SAKLog::instance()->tableModel(); + QTableView* tableView = ui->tableView; + QHeaderView* headerView = tableView->horizontalHeader(); + QHeaderView* vHeaderView = tableView->verticalHeader(); + vHeaderView->hide(); + tableView->setModel(tableModel); + tableView->setAlternatingRowColors(true); - int columnCount = tableModel->columnCount(); - QStringList headers; - for (int i = 0; i < columnCount; i++) { - auto orientation = Qt::Orientation::Horizontal; - QString str = tableModel->headerData(i, orientation).toString(); - headers.append(str); - } + int columnCount = tableModel->columnCount(); + QStringList headers; + for (int i = 0; i < columnCount; i++) { + auto orientation = Qt::Orientation::Horizontal; + QString str = tableModel->headerData(i, orientation).toString(); + headers.append(str); + } - QStandardItemModel* headerViewModel = new QStandardItemModel(headerView); - headerViewModel->setColumnCount(headers.count()); - headerViewModel->setHorizontalHeaderLabels(headers); + QStandardItemModel* headerViewModel = new QStandardItemModel(headerView); + headerViewModel->setColumnCount(headers.count()); + headerViewModel->setHorizontalHeaderLabels(headers); - headerView->setModel(headerViewModel); - headerView->setDefaultAlignment(Qt::AlignLeft); - headerView->setSectionResizeMode(2, QHeaderView::Stretch); + headerView->setModel(headerViewModel); + headerView->setDefaultAlignment(Qt::AlignLeft); + headerView->setSectionResizeMode(2, QHeaderView::Stretch); - connect(ui->pushButtonClear, &QPushButton::clicked, this, - &SAKLogUi::onPushButtonClearClicked); - connect(ui->pushButtonDirectory, &QPushButton::clicked, this, - &SAKLogUi::onPushButtonDirectoryClicked); - connect(ui->checkBoxPause, &QCheckBox::clicked, this, - &SAKLogUi::onCheckBoxPauseClicked); + connect(ui->pushButtonClear, &QPushButton::clicked, this, &SAKLogUi::onPushButtonClearClicked); + connect(ui->pushButtonDirectory, + &QPushButton::clicked, + this, + &SAKLogUi::onPushButtonDirectoryClicked); + connect(ui->checkBoxPause, &QCheckBox::clicked, this, &SAKLogUi::onCheckBoxPauseClicked); } -SAKLogUi::~SAKLogUi() { delete ui; } - -void SAKLogUi::onPushButtonClearClicked() { - QMessageBox::information(this, tr("Clear Log Outputted"), - tr("The log outputted will be empty," - " but the log file will not!")); - SAKLog::instance()->clear(); +SAKLogUi::~SAKLogUi() +{ + delete ui; } -void SAKLogUi::onPushButtonDirectoryClicked() { - QDesktopServices::openUrl(QUrl(SAKLog::instance()->logPath())); +void SAKLogUi::onPushButtonClearClicked() +{ + QMessageBox::information(this, + tr("Clear Log Outputted"), + tr("The log outputted will be empty," + " but the log file will not!")); + SAKLog::instance()->clear(); } -void SAKLogUi::onComboBoxLevelCurrentIndexChanged() { - int level = ui->comboBoxLevel->currentData().toInt(); - SAKLog::instance()->setLogLevel(level); +void SAKLogUi::onPushButtonDirectoryClicked() +{ + QDesktopServices::openUrl(QUrl(SAKLog::instance()->logPath())); } -void SAKLogUi::onComboBoxLifeCycleCurrentIndexChanged() { - int lefeCycle = ui->comboBoxLifeCycle->currentText().toInt(); - SAKLog::instance()->setLogLifeCycle(lefeCycle); +void SAKLogUi::onComboBoxLevelCurrentIndexChanged() +{ + int level = ui->comboBoxLevel->currentData().toInt(); + SAKLog::instance()->setLogLevel(level); } -void SAKLogUi::onCheckBoxPauseClicked() { - bool paused = ui->checkBoxPause->isChecked(); - SAKLog::instance()->setIsPaused(paused); +void SAKLogUi::onComboBoxLifeCycleCurrentIndexChanged() +{ + int lefeCycle = ui->comboBoxLifeCycle->currentText().toInt(); + SAKLog::instance()->setLogLifeCycle(lefeCycle); +} + +void SAKLogUi::onCheckBoxPauseClicked() +{ + bool paused = ui->checkBoxPause->isChecked(); + SAKLog::instance()->setIsPaused(paused); } diff --git a/src/main.cc b/src/main.cc index fa8db2e1..c79fc13e 100644 --- a/src/main.cc +++ b/src/main.cc @@ -149,7 +149,7 @@ static void sakInitAppStyle() } } -int main(const int argc, char* argv[]) +int main(const int argc, char *argv[]) { sakInitApp(); sakInitGoogleLogging(argv[0]); diff --git a/src/modbusstudio/main.cc b/src/modbusstudio/main.cc index 4d3ee9fe..d090b1e3 100644 --- a/src/modbusstudio/main.cc +++ b/src/modbusstudio/main.cc @@ -12,11 +12,14 @@ #include "sakcommonmainwindow.h" #include "sakmodbusui.h" -int main(int argc, char* argv[]) { - QApplication* app = CreateCommonMainWindowApplication( - argc, argv, QObject::tr("Modbus Studio"), "SAK.ModbusStudio"); - int ret = app->exec(); - app->deleteLater(); +int main(int argc, char* argv[]) +{ + QApplication* app = CreateCommonMainWindowApplication(argc, + argv, + QObject::tr("Modbus Studio"), + "SAK.ModbusStudio"); + int ret = app->exec(); + app->deleteLater(); - return ret; + return ret; } diff --git a/src/modbusstudio/modbusstudio/sakmodbusfactory.cc b/src/modbusstudio/modbusstudio/sakmodbusfactory.cc index 18534b26..b71f3214 100644 --- a/src/modbusstudio/modbusstudio/sakmodbusfactory.cc +++ b/src/modbusstudio/modbusstudio/sakmodbusfactory.cc @@ -20,274 +20,288 @@ #include "sakmodbusfactory.h" -SAKModbusFactory::SAKModbusFactory(QObject *parent) : QObject(parent) {} +SAKModbusFactory::SAKModbusFactory(QObject *parent) + : QObject(parent) +{} SAKModbusFactory::~SAKModbusFactory() {} -SAKModbusFactory *SAKModbusFactory::Instance() { - static SAKModbusFactory *factory = Q_NULLPTR; +SAKModbusFactory *SAKModbusFactory::Instance() +{ + static SAKModbusFactory *factory = Q_NULLPTR; - if (!factory) { - factory = new SAKModbusFactory(qApp); - } + if (!factory) { + factory = new SAKModbusFactory(qApp); + } - return factory; + return factory; } -const QString SAKModbusFactory::TypeName(int type) { - if (type == kModbusRtuSerialClient) { - return tr("RTU Client"); - } else if (type == kModbusRtuSerialServer) { - return tr("RTU Server"); - } else if (type == kModbusTcpClient) { - return tr("TCP Client"); - } else if (type == kModbusTcpServer) { - return tr("TCP Server"); - } +const QString SAKModbusFactory::TypeName(int type) +{ + if (type == kModbusRtuSerialClient) { + return tr("RTU Client"); + } else if (type == kModbusRtuSerialServer) { + return tr("RTU Server"); + } else if (type == kModbusTcpClient) { + return tr("TCP Client"); + } else if (type == kModbusTcpServer) { + return tr("TCP Server"); + } - Q_ASSERT_X(false, __FUNCTION__, "Unknown modebus device type"); - qCWarning(kLoggingCategory) << "Unknown modebus device type"; + Q_ASSERT_X(false, __FUNCTION__, "Unknown modebus device type"); + qCWarning(kLoggingCategory) << "Unknown modebus device type"; - return "Unknown"; + return "Unknown"; } -QModbusDevice *SAKModbusFactory::CreateDevice(int type) { - if (type == kModbusRtuSerialClient) { - qCInfo(kLoggingCategory) << "Create rtu serial client."; +QModbusDevice *SAKModbusFactory::CreateDevice(int type) +{ + if (type == kModbusRtuSerialClient) { + qCInfo(kLoggingCategory) << "Create rtu serial client."; #if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) - return new QModbusRtuSerialMaster(this); + return new QModbusRtuSerialMaster(this); #else - return new QModbusRtuSerialClient(this); + return new QModbusRtuSerialClient(this); #endif - } else if (type == kModbusRtuSerialServer) { - qCInfo(kLoggingCategory) << "Create rtu serial server."; + } else if (type == kModbusRtuSerialServer) { + qCInfo(kLoggingCategory) << "Create rtu serial server."; #if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) - return new QModbusRtuSerialSlave(this); + return new QModbusRtuSerialSlave(this); #else - return new QModbusRtuSerialServer(this); + return new QModbusRtuSerialServer(this); #endif - } else if (type == kModbusTcpClient) { - qCInfo(kLoggingCategory) << "Create tcp client."; - return new QModbusTcpClient(); - } else if (type == kModbusTcpServer) { - qCInfo(kLoggingCategory) << "Create tcp server."; - return new QModbusTcpServer(); - } - - Q_ASSERT_X(false, __FUNCTION__, "Unknown modebus device type"); - qCWarning(kLoggingCategory) << "Unknown modebus device type"; - - return Q_NULLPTR; -} - -bool SAKModbusFactory::IsTcpDevice(QModbusDevice *modbus_device) { - if (modbus_device) { - if (qobject_cast(modbus_device)) { - return true; - } else if (qobject_cast(modbus_device)) { - return true; + } else if (type == kModbusTcpClient) { + qCInfo(kLoggingCategory) << "Create tcp client."; + return new QModbusTcpClient(); + } else if (type == kModbusTcpServer) { + qCInfo(kLoggingCategory) << "Create tcp server."; + return new QModbusTcpServer(); } - } - return false; + Q_ASSERT_X(false, __FUNCTION__, "Unknown modebus device type"); + qCWarning(kLoggingCategory) << "Unknown modebus device type"; + + return Q_NULLPTR; } -bool SAKModbusFactory::IsRtuSerialDevice(QModbusDevice *modbus_device) { - if (modbus_device) { +bool SAKModbusFactory::IsTcpDevice(QModbusDevice *modbus_device) +{ + if (modbus_device) { + if (qobject_cast(modbus_device)) { + return true; + } else if (qobject_cast(modbus_device)) { + return true; + } + } + + return false; +} + +bool SAKModbusFactory::IsRtuSerialDevice(QModbusDevice *modbus_device) +{ + if (modbus_device) { #if QT_VERSION >= QT_VERSION_CHECK(6, 2, 0) - if (qobject_cast(modbus_device)) { + if (qobject_cast(modbus_device)) { #else - if (qobject_cast(modbus_device)) { + if (qobject_cast(modbus_device)) { #endif - return true; + return true; #if QT_VERSION >= QT_VERSION_CHECK(6, 2, 0) - } else if (qobject_cast(modbus_device)) { + } else if (qobject_cast(modbus_device)) { #else - } else if (qobject_cast(modbus_device)) { + } else if (qobject_cast(modbus_device)) { #endif - return true; + return true; + } } - } - return false; + return false; } -bool SAKModbusFactory::IsTcpDeviceType(int type) { - bool is_tcp = (type == kModbusTcpClient); - is_tcp |= (type == kModbusTcpServer); +bool SAKModbusFactory::IsTcpDeviceType(int type) +{ + bool is_tcp = (type == kModbusTcpClient); + is_tcp |= (type == kModbusTcpServer); - return is_tcp; + return is_tcp; } -bool SAKModbusFactory::IsRtuSerialDeviceType(int type) { - bool is_rtu = (type == kModbusRtuSerialClient); - is_rtu |= (type == kModbusRtuSerialServer); +bool SAKModbusFactory::IsRtuSerialDeviceType(int type) +{ + bool is_rtu = (type == kModbusRtuSerialClient); + is_rtu |= (type == kModbusRtuSerialServer); - return is_rtu; + return is_rtu; } -bool SAKModbusFactory::IsServerDevice(QModbusDevice *modbus_device) { - if (modbus_device && qobject_cast(modbus_device)) { - return true; - } - - return false; -} - -bool SAKModbusFactory::IsClientDevice(QModbusDevice *modbus_device) { - if (modbus_device && qobject_cast(modbus_device)) { - return true; - } - - return false; -} - -bool SAKModbusFactory::ConnectDeivce(QModbusDevice *modbus_device) { - if (modbus_device) { - return modbus_device->connectDevice(); - } - - return false; -} - -bool SAKModbusFactory::IsConnected(QModbusDevice *modbus_device) { - if (modbus_device) { - if (modbus_device->state() == QModbusDevice::ConnectedState) { - return true; +bool SAKModbusFactory::IsServerDevice(QModbusDevice *modbus_device) +{ + if (modbus_device && qobject_cast(modbus_device)) { + return true; } - } - return false; + return false; } -bool SAKModbusFactory::IsValidModbusReply(QModbusReply *reply) { - if (reply && !reply->isFinished()) { - return true; - } +bool SAKModbusFactory::IsClientDevice(QModbusDevice *modbus_device) +{ + if (modbus_device && qobject_cast(modbus_device)) { + return true; + } - return false; + return false; +} + +bool SAKModbusFactory::ConnectDeivce(QModbusDevice *modbus_device) +{ + if (modbus_device) { + return modbus_device->connectDevice(); + } + + return false; +} + +bool SAKModbusFactory::IsConnected(QModbusDevice *modbus_device) +{ + if (modbus_device) { + if (modbus_device->state() == QModbusDevice::ConnectedState) { + return true; + } + } + + return false; +} + +bool SAKModbusFactory::IsValidModbusReply(QModbusReply *reply) +{ + if (reply && !reply->isFinished()) { + return true; + } + + return false; } bool SAKModbusFactory::SetServerData(QModbusDevice *server, QModbusDataUnit::RegisterType table, - int address, int data, bool enable_log) { - bool is_ok = false; - if (server && qobject_cast(server)) { - QModbusServer *modbusServer = qobject_cast(server); - is_ok = modbusServer->setData(table, address, data); - if (enable_log) { - qCInfo(kLoggingCategory) - << "Set register data result:" << is_ok << "table:" << table - << "address:" << address << "data:" << data; + int address, + int data, + bool enable_log) +{ + bool is_ok = false; + if (server && qobject_cast(server)) { + QModbusServer *modbusServer = qobject_cast(server); + is_ok = modbusServer->setData(table, address, data); + if (enable_log) { + qCInfo(kLoggingCategory) << "Set register data result:" << is_ok << "table:" << table + << "address:" << address << "data:" << data; + } } - } - return is_ok; + return is_ok; } -QList SAKModbusFactory::GetServerData( - QModbusDevice *server, QModbusDataUnit::RegisterType table, int address, - int quantity) { - QList values; - if (server && qobject_cast(server)) { - QModbusServer *cooked_server = qobject_cast(server); - for (int i = address; i < quantity; i++) { - quint16 value; - if (cooked_server->data(table, i, &value)) { - values.append(value); - } else { - qCWarning(kLoggingCategory) << "Parameters error!"; - break; - } +QList SAKModbusFactory::GetServerData(QModbusDevice *server, + QModbusDataUnit::RegisterType table, + int address, + int quantity) +{ + QList values; + if (server && qobject_cast(server)) { + QModbusServer *cooked_server = qobject_cast(server); + for (int i = address; i < quantity; i++) { + quint16 value; + if (cooked_server->data(table, i, &value)) { + values.append(value); + } else { + qCWarning(kLoggingCategory) << "Parameters error!"; + break; + } + } + } else { + qCWarning(kLoggingCategory) << "Can not get values from null object!"; } - } else { - qCWarning(kLoggingCategory) << "Can not get values from null object!"; - } - return values; + return values; } -void SAKModbusFactory::DeleteModbusDevuce(QModbusDevice **modbus_device) { - if (*modbus_device) { - QModbusServer *server = qobject_cast(*modbus_device); - if (server) { - server->disconnect(); - } +void SAKModbusFactory::DeleteModbusDevuce(QModbusDevice **modbus_device) +{ + if (*modbus_device) { + QModbusServer *server = qobject_cast(*modbus_device); + if (server) { + server->disconnect(); + } - (*modbus_device)->deleteLater(); - (*modbus_device) = Q_NULLPTR; - } + (*modbus_device)->deleteLater(); + (*modbus_device) = Q_NULLPTR; + } } QModbusDevice *SAKModbusFactory::CreateRtuSerialDevice( - int type, const QString &port_name, int parity, int baud_rate, - int data_bits, int stop_bits) { - QModbusDevice *device = CreateDevice(type); - if (IsRtuSerialDevice(device)) { - device->setConnectionParameter(QModbusDevice::SerialPortNameParameter, - port_name); - device->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, - baud_rate); - device->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, - data_bits); - device->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, - stop_bits); - device->setConnectionParameter(QModbusDevice::SerialParityParameter, - parity); + int type, const QString &port_name, int parity, int baud_rate, int data_bits, int stop_bits) +{ + QModbusDevice *device = CreateDevice(type); + if (IsRtuSerialDevice(device)) { + device->setConnectionParameter(QModbusDevice::SerialPortNameParameter, port_name); + device->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, baud_rate); + device->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, data_bits); + device->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, stop_bits); + device->setConnectionParameter(QModbusDevice::SerialParityParameter, parity); - qCInfo(kLoggingCategory) - << "Set rtu serial modbus device parameters:" - << "port name:" << port_name << "baud rate:" << baud_rate - << "data bits:" << data_bits << "stop bits" << stop_bits << "parity" - << parity; - } + qCInfo(kLoggingCategory) << "Set rtu serial modbus device parameters:" + << "port name:" << port_name << "baud rate:" << baud_rate + << "data bits:" << data_bits << "stop bits" << stop_bits + << "parity" << parity; + } - return device; + return device; } -QModbusDevice *SAKModbusFactory::CreateTcpDevice(int type, QString address, - int port) { - QModbusDevice *device = CreateDevice(type); - if (IsTcpDevice(device)) { - device->setConnectionParameter(QModbusDevice::NetworkAddressParameter, - address); - device->setConnectionParameter(QModbusDevice::NetworkPortParameter, port); +QModbusDevice *SAKModbusFactory::CreateTcpDevice(int type, QString address, int port) +{ + QModbusDevice *device = CreateDevice(type); + if (IsTcpDevice(device)) { + device->setConnectionParameter(QModbusDevice::NetworkAddressParameter, address); + device->setConnectionParameter(QModbusDevice::NetworkPortParameter, port); - qCInfo(kLoggingCategory) << "Set tcp modbus device parameters:" - << "ip address:" << address << "port" << port; - } + qCInfo(kLoggingCategory) << "Set tcp modbus device parameters:" + << "ip address:" << address << "port" << port; + } - return device; + return device; } void SAKModbusFactory::SetClientDeviceParameters(QModbusDevice *client, int timeout, - int number_of_retries) { - if (client) { - qCInfo(kLoggingCategory) - << "Set modbus client device parameters:" - << "timeout:" << timeout << "number_of_retries" << number_of_retries; + int number_of_retries) +{ + if (client) { + qCInfo(kLoggingCategory) << "Set modbus client device parameters:" + << "timeout:" << timeout << "number_of_retries" + << number_of_retries; - QModbusClient *cooked_client = qobject_cast(client); - cooked_client->setTimeout(timeout); - cooked_client->setNumberOfRetries(number_of_retries); - } + QModbusClient *cooked_client = qobject_cast(client); + cooked_client->setTimeout(timeout); + cooked_client->setNumberOfRetries(number_of_retries); + } } void SAKModbusFactory::SetServerDeviceParameters(QModbusDevice *server, - int address, bool device_busy, - bool listen_only_mode) { - if (server) { - qCInfo(kLoggingCategory) - << "Set modbus server device parameters:" - << "address:" << address << "device busy" << device_busy - << "listen only mode:" << listen_only_mode; + int address, + bool device_busy, + bool listen_only_mode) +{ + if (server) { + qCInfo(kLoggingCategory) << "Set modbus server device parameters:" + << "address:" << address << "device busy" << device_busy + << "listen only mode:" << listen_only_mode; - QModbusServer *cooked_server = qobject_cast(server); - cooked_server->setServerAddress(address); - cooked_server->setValue(QModbusServer::DeviceBusy, device_busy); - cooked_server->setValue(QModbusServer::ListenOnlyMode, listen_only_mode); - } + QModbusServer *cooked_server = qobject_cast(server); + cooked_server->setServerAddress(address); + cooked_server->setValue(QModbusServer::DeviceBusy, device_busy); + cooked_server->setValue(QModbusServer::ListenOnlyMode, listen_only_mode); + } } QModbusReply *SAKModbusFactory::SendWriteRequest(QModbusDevice *modbus_device, @@ -298,37 +312,38 @@ QModbusReply *SAKModbusFactory::SendWriteRequest(QModbusDevice *modbus_device, #else QList values, #endif - int server_address) { - if (modbus_device && IsClientDevice(modbus_device)) { - auto cooked_type = QModbusDataUnit::RegisterType(register_type); - QModbusDataUnit dataUnit(cooked_type, start_address, values); - if (dataUnit.isValid()) { - qCInfo(kLoggingCategory) - << "register-type:" << register_type - << " start-address:" << start_address - << " serverAddress:" << server_address << " values:" << values; + int server_address) +{ + if (modbus_device && IsClientDevice(modbus_device)) { + auto cooked_type = QModbusDataUnit::RegisterType(register_type); + QModbusDataUnit dataUnit(cooked_type, start_address, values); + if (dataUnit.isValid()) { + qCInfo(kLoggingCategory) + << "register-type:" << register_type << " start-address:" << start_address + << " serverAddress:" << server_address << " values:" << values; - auto *client = qobject_cast(modbus_device); - QModbusReply *reply = client->sendWriteRequest(dataUnit, server_address); - return reply; - } else { - qCWarning(kLoggingCategory) << "Unvalid data unit!"; + auto *client = qobject_cast(modbus_device); + QModbusReply *reply = client->sendWriteRequest(dataUnit, server_address); + return reply; + } else { + qCWarning(kLoggingCategory) << "Unvalid data unit!"; + } } - } - return Q_NULLPTR; + return Q_NULLPTR; } QModbusReply *SAKModbusFactory::SendRawRequest(QModbusDevice *modbus_device, int server_address, int function_code, - const QByteArray &data) { - auto cooked_function_code = QModbusPdu::FunctionCode(function_code); - QModbusRequest request(cooked_function_code, data); - if (IsClientDevice(modbus_device)) { - QModbusClient *client = qobject_cast(modbus_device); - return client->sendRawRequest(request, server_address); - } + const QByteArray &data) +{ + auto cooked_function_code = QModbusPdu::FunctionCode(function_code); + QModbusRequest request(cooked_function_code, data); + if (IsClientDevice(modbus_device)) { + QModbusClient *client = qobject_cast(modbus_device); + return client->sendRawRequest(request, server_address); + } - return Q_NULLPTR; + return Q_NULLPTR; } diff --git a/src/modbusstudio/modbusstudio/sakmodbusfactory.h b/src/modbusstudio/modbusstudio/sakmodbusfactory.h index 5d394146..a1213a9e 100644 --- a/src/modbusstudio/modbusstudio/sakmodbusfactory.h +++ b/src/modbusstudio/modbusstudio/sakmodbusfactory.h @@ -16,64 +16,72 @@ #include #include -class SAKModbusFactory : public QObject { - Q_OBJECT - public: - enum ModbusDeviceType { - kModbusRtuSerialClient, - kModbusRtuSerialServer, - kModbusTcpClient, - kModbusTcpServer - }; - Q_ENUM(ModbusDeviceType) +class SAKModbusFactory : public QObject +{ + Q_OBJECT +public: + enum ModbusDeviceType { + kModbusRtuSerialClient, + kModbusRtuSerialServer, + kModbusTcpClient, + kModbusTcpServer + }; + Q_ENUM(ModbusDeviceType) - private: - SAKModbusFactory(QObject *parent = Q_NULLPTR); +private: + SAKModbusFactory(QObject *parent = Q_NULLPTR); - public: - ~SAKModbusFactory(); - static SAKModbusFactory *Instance(); +public: + ~SAKModbusFactory(); + static SAKModbusFactory *Instance(); - public: - const QString TypeName(int type); - QModbusDevice *CreateDevice(int type); - bool IsTcpDevice(QModbusDevice *modbus_device); - bool IsRtuSerialDevice(QModbusDevice *modbus_device); - bool IsTcpDeviceType(int type); - bool IsRtuSerialDeviceType(int type); - bool IsServerDevice(QModbusDevice *modbus_device); - bool IsClientDevice(QModbusDevice *modbus_device); - bool ConnectDeivce(QModbusDevice *modbus_device); - bool IsConnected(QModbusDevice *modbus_device); - bool IsValidModbusReply(QModbusReply *reply); - bool SetServerData(QModbusDevice *server, QModbusDataUnit::RegisterType table, - int address, int data, bool enable_log = true); - QList GetServerData(QModbusDevice *server, - QModbusDataUnit::RegisterType table, int address, - int quantity); - void DeleteModbusDevuce(QModbusDevice **modbus_device); +public: + const QString TypeName(int type); + QModbusDevice *CreateDevice(int type); + bool IsTcpDevice(QModbusDevice *modbus_device); + bool IsRtuSerialDevice(QModbusDevice *modbus_device); + bool IsTcpDeviceType(int type); + bool IsRtuSerialDeviceType(int type); + bool IsServerDevice(QModbusDevice *modbus_device); + bool IsClientDevice(QModbusDevice *modbus_device); + bool ConnectDeivce(QModbusDevice *modbus_device); + bool IsConnected(QModbusDevice *modbus_device); + bool IsValidModbusReply(QModbusReply *reply); + bool SetServerData(QModbusDevice *server, + QModbusDataUnit::RegisterType table, + int address, + int data, + bool enable_log = true); + QList GetServerData(QModbusDevice *server, + QModbusDataUnit::RegisterType table, + int address, + int quantity); + void DeleteModbusDevuce(QModbusDevice **modbus_device); - QModbusDevice *CreateRtuSerialDevice(int type, const QString &port_name, - int parity, int baud_rate, int data_bits, - int stop_bits); - QModbusDevice *CreateTcpDevice(int deviceType, QString address, int port); - void SetClientDeviceParameters(QModbusDevice *client, int timeout, - int number_of_retries); - void SetServerDeviceParameters(QModbusDevice *server, int address, - bool device_busy, bool listen_only_mode); - QModbusReply *SendWriteRequest(QModbusDevice *modbus_device, - int register_type, int start_address, + QModbusDevice *CreateRtuSerialDevice( + int type, const QString &port_name, int parity, int baud_rate, int data_bits, int stop_bits); + QModbusDevice *CreateTcpDevice(int deviceType, QString address, int port); + void SetClientDeviceParameters(QModbusDevice *client, int timeout, int number_of_retries); + void SetServerDeviceParameters(QModbusDevice *server, + int address, + bool device_busy, + bool listen_only_mode); + QModbusReply *SendWriteRequest(QModbusDevice *modbus_device, + int register_type, + int start_address, #if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) - QVector values, + QVector values, #else - QList values, + QList values, #endif - int server_address); - QModbusReply *SendRawRequest(QModbusDevice *modbus_device, int server_address, - int function_code, const QByteArray &data); + int server_address); + QModbusReply *SendRawRequest(QModbusDevice *modbus_device, + int server_address, + int function_code, + const QByteArray &data); - private: - const QLoggingCategory kLoggingCategory{"SAK.Modbus.Factory"}; +private: + const QLoggingCategory kLoggingCategory{"SAK.Modbus.Factory"}; }; -#endif // SAKMODBUSFACTORY_H +#endif // SAKMODBUSFACTORY_H diff --git a/src/modbusstudio/modbusstudioui/sakmodbusui.cc b/src/modbusstudio/modbusstudioui/sakmodbusui.cc index 3b11d459..0dabb21c 100644 --- a/src/modbusstudio/modbusstudioui/sakmodbusui.cc +++ b/src/modbusstudio/modbusstudioui/sakmodbusui.cc @@ -39,8 +39,8 @@ #include #endif -#include "saksettings.h" #include "sakmodbusfactory.h" +#include "saksettings.h" #include "ui_sakmodbusui.h" #define RXCOLOR "green" @@ -49,1091 +49,1187 @@ #define TXFLAG "tx:" #define MAX_HISTORY_INDEX 9 -struct SAKModbusUiSettingKeys { - const QString device_index = "SAKModbus/deviceIndex"; +struct SAKModbusUiSettingKeys +{ + const QString device_index = "SAKModbus/deviceIndex"; - const QString port_name = "SAKModbus/portName"; - const QString parity = "SAKModbus/parity"; - const QString baud_rate = "SAKModbus/baudRate"; - const QString data_bits = "SAKModbus/dataBits"; - const QString stop_bits = "SAKModbus/stopBits"; - const QString custom_baud_rate = "SAKModbus/customBaudRate"; + const QString port_name = "SAKModbus/portName"; + const QString parity = "SAKModbus/parity"; + const QString baud_rate = "SAKModbus/baudRate"; + const QString data_bits = "SAKModbus/dataBits"; + const QString stop_bits = "SAKModbus/stopBits"; + const QString custom_baud_rate = "SAKModbus/customBaudRate"; - const QString address = "SAKModbus/address"; - const QString port = "SAKModbus/port"; - const QString custom_address = "SAKModbus/customAddress"; + const QString address = "SAKModbus/address"; + const QString port = "SAKModbus/port"; + const QString custom_address = "SAKModbus/customAddress"; - const QString client_timeout = "SAKModbus/clientTimeout"; - const QString client_repeat_time = "SAKModbus/clientRepeatTime"; + const QString client_timeout = "SAKModbus/clientTimeout"; + const QString client_repeat_time = "SAKModbus/clientRepeatTime"; - const QString server_is_busy = "SAKModbus/serverIsBusy"; - const QString server_just_listen = "SAKModbus/serverJustListen"; - const QString server_address = "SAKModbus/serverAddress"; + const QString server_is_busy = "SAKModbus/serverIsBusy"; + const QString server_just_listen = "SAKModbus/serverJustListen"; + const QString server_address = "SAKModbus/serverAddress"; - const QString function_code = "SAKModbus/functionCode"; - const QString target_address = "SAKModbus/targetAddress"; - const QString start_address = "SAKModbus/startAddress"; - const QString address_number = "SAKModbus/addressNumber"; + const QString function_code = "SAKModbus/functionCode"; + const QString target_address = "SAKModbus/targetAddress"; + const QString start_address = "SAKModbus/startAddress"; + const QString address_number = "SAKModbus/addressNumber"; - const QString send_history = "SAKModbus/sendHistory"; - const QString send_history_index = "SAKModbus/sendHistoryIndex"; - const QString pdu = "pdu"; + const QString send_history = "SAKModbus/sendHistory"; + const QString send_history_index = "SAKModbus/sendHistoryIndex"; + const QString pdu = "pdu"; }; -class ReadOnlyDelegate : public QItemDelegate { - public: - ReadOnlyDelegate(QWidget *parent = Q_NULLPTR) : QItemDelegate(parent) {} - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const override { - Q_UNUSED(parent); - Q_UNUSED(option); - Q_UNUSED(index); - return Q_NULLPTR; - } +class ReadOnlyDelegate : public QItemDelegate +{ +public: + ReadOnlyDelegate(QWidget *parent = Q_NULLPTR) + : QItemDelegate(parent) + {} + QWidget *createEditor(QWidget *parent, + const QStyleOptionViewItem &option, + const QModelIndex &index) const override + { + Q_UNUSED(parent); + Q_UNUSED(option); + Q_UNUSED(index); + return Q_NULLPTR; + } }; SAKModbusUi::SAKModbusUi(QWidget *parent) - : QWidget{parent}, - ui_(new Ui::SAKModbusUi), - modbus_device_(Q_NULLPTR), - register_model_(Q_NULLPTR), - key_ctx_(new SAKModbusUiSettingKeys) { - if (!settings_) { - settings_ = SAKSettings::instance(); - } - - ui_->setupUi(this); - - InitComponents(); - InitSettings(); - InitSignals(); - - UpdateUiState(false); - OnDeviceTypeChanged(); - UpdateClientTableView(); - UpdateClientReadWriteButtonState(); -} - -SAKModbusUi::~SAKModbusUi() { delete ui_; } - -void SAKModbusUi::InitComponents() { - InitComponentDevices(); - InitComponentAddress(); - InitComponentPortName(); - InitComponnetBaudRate(); - InitComponnetDataBits(); - InitComponnetStopBits(); - InitComponnetParity(); - InitComponentFunctionCode(); - InitComponentRegisterTableView(); - InitComponentInput(); - InitComponentRegisterTabWidget(); -} - -void SAKModbusUi::InitComponentDevices() { - ui_->device_list_->addItem(tr("RtuClient"), - SAKModbusFactory::kModbusRtuSerialClient); - ui_->device_list_->addItem(tr("RtuServer"), - SAKModbusFactory::kModbusRtuSerialServer); - ui_->device_list_->addItem(tr("TcpClient"), - SAKModbusFactory::kModbusTcpClient); - ui_->device_list_->addItem(tr("TcpServer"), - SAKModbusFactory::kModbusTcpServer); -} - -void SAKModbusUi::InitComponentAddress() { - ui_->address_combo_box->clear(); - QList addresses = QNetworkInterface::allAddresses(); - for (QHostAddress &address : addresses) { - if (address.protocol() == QAbstractSocket::IPv4Protocol) { - ui_->address_combo_box->addItem(address.toString()); + : QWidget{parent} + , ui_(new Ui::SAKModbusUi) + , modbus_device_(Q_NULLPTR) + , register_model_(Q_NULLPTR) + , key_ctx_(new SAKModbusUiSettingKeys) +{ + if (!settings_) { + settings_ = SAKSettings::instance(); } - } + + ui_->setupUi(this); + + InitComponents(); + InitSettings(); + InitSignals(); + + UpdateUiState(false); + OnDeviceTypeChanged(); + UpdateClientTableView(); + UpdateClientReadWriteButtonState(); } -void SAKModbusUi::InitComponentPortName() { - ui_->port_name_->clear(); - QList infos = QSerialPortInfo::availablePorts(); - for (QSerialPortInfo &info : infos) { - ui_->port_name_->addItem(info.portName()); - } +SAKModbusUi::~SAKModbusUi() +{ + delete ui_; } -void SAKModbusUi::InitComponnetBaudRate() { - ui_->baud_rate_->clear(); - QList bds = QSerialPortInfo::standardBaudRates(); - for (qint32 &bd : bds) { - ui_->baud_rate_->addItem(QString::number(bd), bd); - } +void SAKModbusUi::InitComponents() +{ + InitComponentDevices(); + InitComponentAddress(); + InitComponentPortName(); + InitComponnetBaudRate(); + InitComponnetDataBits(); + InitComponnetStopBits(); + InitComponnetParity(); + InitComponentFunctionCode(); + InitComponentRegisterTableView(); + InitComponentInput(); + InitComponentRegisterTabWidget(); } -void SAKModbusUi::InitComponnetDataBits() { - ui_->data_bits_->clear(); - ui_->data_bits_->addItem("8", QSerialPort::Data8); - ui_->data_bits_->addItem("7", QSerialPort::Data7); - ui_->data_bits_->addItem("6", QSerialPort::Data6); - ui_->data_bits_->addItem("5", QSerialPort::Data5); +void SAKModbusUi::InitComponentDevices() +{ + ui_->device_list_->addItem(tr("RtuClient"), SAKModbusFactory::kModbusRtuSerialClient); + ui_->device_list_->addItem(tr("RtuServer"), SAKModbusFactory::kModbusRtuSerialServer); + ui_->device_list_->addItem(tr("TcpClient"), SAKModbusFactory::kModbusTcpClient); + ui_->device_list_->addItem(tr("TcpServer"), SAKModbusFactory::kModbusTcpServer); } -void SAKModbusUi::InitComponnetStopBits() { - ui_->stop_bits_->clear(); - ui_->stop_bits_->addItem("1", QSerialPort::OneStop); +void SAKModbusUi::InitComponentAddress() +{ + ui_->address_combo_box->clear(); + QList addresses = QNetworkInterface::allAddresses(); + for (QHostAddress &address : addresses) { + if (address.protocol() == QAbstractSocket::IPv4Protocol) { + ui_->address_combo_box->addItem(address.toString()); + } + } +} + +void SAKModbusUi::InitComponentPortName() +{ + ui_->port_name_->clear(); + QList infos = QSerialPortInfo::availablePorts(); + for (QSerialPortInfo &info : infos) { + ui_->port_name_->addItem(info.portName()); + } +} + +void SAKModbusUi::InitComponnetBaudRate() +{ + ui_->baud_rate_->clear(); + QList bds = QSerialPortInfo::standardBaudRates(); + for (qint32 &bd : bds) { + ui_->baud_rate_->addItem(QString::number(bd), bd); + } +} + +void SAKModbusUi::InitComponnetDataBits() +{ + ui_->data_bits_->clear(); + ui_->data_bits_->addItem("8", QSerialPort::Data8); + ui_->data_bits_->addItem("7", QSerialPort::Data7); + ui_->data_bits_->addItem("6", QSerialPort::Data6); + ui_->data_bits_->addItem("5", QSerialPort::Data5); +} + +void SAKModbusUi::InitComponnetStopBits() +{ + ui_->stop_bits_->clear(); + ui_->stop_bits_->addItem("1", QSerialPort::OneStop); #ifdef Q_OS_WIN - ui_->stop_bits_->addItem("1.5", QSerialPort::OneAndHalfStop); + ui_->stop_bits_->addItem("1.5", QSerialPort::OneAndHalfStop); #endif - ui_->stop_bits_->addItem("2", QSerialPort::TwoStop); + ui_->stop_bits_->addItem("2", QSerialPort::TwoStop); } -void SAKModbusUi::InitComponnetParity() { - ui_->parity_->clear(); - ui_->parity_->addItem(tr("NoParity"), QSerialPort::NoParity); - ui_->parity_->addItem(tr("EvenParity"), QSerialPort::EvenParity); - ui_->parity_->addItem(tr("OddParity"), QSerialPort::OddParity); - ui_->parity_->addItem(tr("SpaceParity"), QSerialPort::SpaceParity); - ui_->parity_->addItem(tr("MarkParity"), QSerialPort::MarkParity); +void SAKModbusUi::InitComponnetParity() +{ + ui_->parity_->clear(); + ui_->parity_->addItem(tr("NoParity"), QSerialPort::NoParity); + ui_->parity_->addItem(tr("EvenParity"), QSerialPort::EvenParity); + ui_->parity_->addItem(tr("OddParity"), QSerialPort::OddParity); + ui_->parity_->addItem(tr("SpaceParity"), QSerialPort::SpaceParity); + ui_->parity_->addItem(tr("MarkParity"), QSerialPort::MarkParity); } -void SAKModbusUi::InitComponentFunctionCode() { - const QString str0x01 = tr("0x01-ReadCoils"); - const QString str0x02 = tr("0x02-ReadDiscreteInputs"); - const QString str0x03 = tr("0x03-ReadHoldingRegisters"); - const QString str0x04 = tr("0x04-ReadInputRegisters"); - const QString str0x05 = tr("0x05-WriteSingleCoil"); - const QString str0x06 = tr("0x06-WriteSingleRegister"); - const QString str0x0f = tr("0x0f-WriteMultipleCoils"); - const QString str0x10 = tr("0x10-WriteMultipleRegisters"); +void SAKModbusUi::InitComponentFunctionCode() +{ + const QString str0x01 = tr("0x01-ReadCoils"); + const QString str0x02 = tr("0x02-ReadDiscreteInputs"); + const QString str0x03 = tr("0x03-ReadHoldingRegisters"); + const QString str0x04 = tr("0x04-ReadInputRegisters"); + const QString str0x05 = tr("0x05-WriteSingleCoil"); + const QString str0x06 = tr("0x06-WriteSingleRegister"); + const QString str0x0f = tr("0x0f-WriteMultipleCoils"); + const QString str0x10 = tr("0x10-WriteMultipleRegisters"); - int func0x01 = QModbusDataUnit::Coils; - int func0x02 = QModbusDataUnit::DiscreteInputs; - int func0x03 = QModbusDataUnit::HoldingRegisters; - int func0x04 = QModbusDataUnit::InputRegisters; - int func0x05 = QModbusDataUnit::Coils; - int func0x06 = QModbusDataUnit::HoldingRegisters; - int func0x0f = QModbusDataUnit::Coils; - int func0x10 = QModbusDataUnit::HoldingRegisters; + int func0x01 = QModbusDataUnit::Coils; + int func0x02 = QModbusDataUnit::DiscreteInputs; + int func0x03 = QModbusDataUnit::HoldingRegisters; + int func0x04 = QModbusDataUnit::InputRegisters; + int func0x05 = QModbusDataUnit::Coils; + int func0x06 = QModbusDataUnit::HoldingRegisters; + int func0x0f = QModbusDataUnit::Coils; + int func0x10 = QModbusDataUnit::HoldingRegisters; - ui_->function_code_->addItem(str0x01, func0x01); - ui_->function_code_->addItem(str0x02, func0x02); - ui_->function_code_->addItem(str0x03, func0x03); - ui_->function_code_->addItem(str0x04, func0x04); - ui_->function_code_->addItem(str0x05, func0x05); - ui_->function_code_->addItem(str0x06, func0x06); - ui_->function_code_->addItem(str0x0f, func0x0f); - ui_->function_code_->addItem(str0x10, func0x10); + ui_->function_code_->addItem(str0x01, func0x01); + ui_->function_code_->addItem(str0x02, func0x02); + ui_->function_code_->addItem(str0x03, func0x03); + ui_->function_code_->addItem(str0x04, func0x04); + ui_->function_code_->addItem(str0x05, func0x05); + ui_->function_code_->addItem(str0x06, func0x06); + ui_->function_code_->addItem(str0x0f, func0x0f); + ui_->function_code_->addItem(str0x10, func0x10); } -void SAKModbusUi::InitComponentRegisterTableView() { - QTableView *table_view = CreateTableView(1, ui_->client_registers_); - register_model_ = qobject_cast(table_view->model()); +void SAKModbusUi::InitComponentRegisterTableView() +{ + QTableView *table_view = CreateTableView(1, ui_->client_registers_); + register_model_ = qobject_cast(table_view->model()); } -void SAKModbusUi::InitComponentInput() { - QRegularExpression re("([0-9a-fA-F][0-9a-fA-F][ ])*"); - QLineEdit *le = ui_->pdu_->lineEdit(); - QRegularExpressionValidator *rev = new QRegularExpressionValidator(re, le); - le->setValidator(rev); - le->clear(); +void SAKModbusUi::InitComponentInput() +{ + QRegularExpression re("([0-9a-fA-F][0-9a-fA-F][ ])*"); + QLineEdit *le = ui_->pdu_->lineEdit(); + QRegularExpressionValidator *rev = new QRegularExpressionValidator(re, le); + le->setValidator(rev); + le->clear(); } -void SAKModbusUi::InitComponentRegisterTabWidget() { - QTabWidget *tab_widget = ui_->server_registers_; - QStringList titles = QStringList() - << tr("Coils") << tr("DiscreteInputs") - << tr("InputRegisters") << tr("HoldingRegisters"); - for (QString &title : titles) { - QTableView *table_view = CreateTableView(UINT16_MAX + 1, Q_NULLPTR); - table_view->verticalHeader()->hide(); - tab_widget->addTab(table_view, title); - } -} - -void SAKModbusUi::InitSettings() { - InitSettingsDevice(); - InitSettingsNetwork(); - InitSettingsSerialPort(); - InitSettingsClient(); - InitSettingsServer(); - InitSettingsClientOperations(); - InitSettingsInput(); -} - -void SAKModbusUi::InitSettingsDevice() { - int deviceIndex = settings_->value(key_ctx_->device_index).toInt(); - if (deviceIndex >= 0 && deviceIndex < ui_->device_list_->count()) { - ui_->device_list_->setCurrentIndex(deviceIndex); - } -} - -void SAKModbusUi::InitSettingsNetwork() { - QString address = settings_->value(key_ctx_->address).toString(); - ui_->address_combo_box->setCurrentText(address); - - QVariant portValiant = settings_->value(key_ctx_->port); - int port = portValiant.toInt(); - if (portValiant.isNull()) { - port = 502; - } - ui_->port_spin_box->setValue(port); -} - -void SAKModbusUi::InitSettingsSerialPort() { - auto SetComboBoxIndex = [](int index, QComboBox *cb) { - if (index >= 0 && index < cb->count()) { - cb->setCurrentIndex(index); +void SAKModbusUi::InitComponentRegisterTabWidget() +{ + QTabWidget *tab_widget = ui_->server_registers_; + QStringList titles = QStringList() << tr("Coils") << tr("DiscreteInputs") + << tr("InputRegisters") << tr("HoldingRegisters"); + for (QString &title : titles) { + QTableView *table_view = CreateTableView(UINT16_MAX + 1, Q_NULLPTR); + table_view->verticalHeader()->hide(); + tab_widget->addTab(table_view, title); } - }; - - QString portName = settings_->value(key_ctx_->port_name).toString(); - int index = ui_->port_name_->findText(portName); - SetComboBoxIndex(index, ui_->port_name_); - - index = settings_->value(key_ctx_->parity).toInt(); - SetComboBoxIndex(index, ui_->parity_); - - QString bd = settings_->value(key_ctx_->baud_rate).toString(); - ui_->baud_rate_->setCurrentText(bd); - - index = settings_->value(key_ctx_->data_bits).toInt(); - SetComboBoxIndex(index, ui_->data_bits_); - - index = settings_->value(key_ctx_->stop_bits).toInt(); - SetComboBoxIndex(index, ui_->stop_bits_); } -void SAKModbusUi::InitSettingsClient() { - int timeout = settings_->value(key_ctx_->client_timeout).toInt(); - ui_->timeout_->setValue(timeout < 100 ? 100 : timeout); - - const QString key = key_ctx_->client_repeat_time; - int repeatTimes = settings_->value(key).toInt(); - ui_->repeat_time_->setValue(repeatTimes); +void SAKModbusUi::InitSettings() +{ + InitSettingsDevice(); + InitSettingsNetwork(); + InitSettingsSerialPort(); + InitSettingsClient(); + InitSettingsServer(); + InitSettingsClientOperations(); + InitSettingsInput(); } -void SAKModbusUi::InitSettingsServer() { - bool isBusy = settings_->value(key_ctx_->server_is_busy).toBool(); - ui_->device_busy_->setChecked(isBusy); - - QString key = key_ctx_->server_just_listen; - bool just_listen = settings_->value(key).toBool(); - ui_->listen_only_mode_->setChecked(just_listen); - - int address = settings_->value(key_ctx_->server_address).toInt(); - ui_->server_address->setValue(address); -} - -void SAKModbusUi::InitSettingsClientOperations() { - int index = settings_->value(key_ctx_->function_code).toInt(); - if (index >= 0 && index < ui_->function_code_->count()) { - ui_->function_code_->setCurrentIndex(index); - } - - int address = settings_->value(key_ctx_->target_address).toInt(); - ui_->device_address_->setValue(address); - - int start = settings_->value(key_ctx_->start_address).toInt(); - ui_->start_address_->setValue(start); - - int number = settings_->value(key_ctx_->address_number).toInt(); - ui_->quantity_->setValue(number); -} - -void SAKModbusUi::InitSettingsInput() { - ui_->pdu_->clear(); - settings_->beginReadArray(key_ctx_->send_history); - for (int i = 0; i < 10; i++) { - settings_->setArrayIndex(i); - QString text = settings_->value(key_ctx_->pdu).toString(); - if (!text.isEmpty()) { - ui_->pdu_->addItem(text); +void SAKModbusUi::InitSettingsDevice() +{ + int deviceIndex = settings_->value(key_ctx_->device_index).toInt(); + if (deviceIndex >= 0 && deviceIndex < ui_->device_list_->count()) { + ui_->device_list_->setCurrentIndex(deviceIndex); } - } - settings_->endArray(); - - int index = settings_->value(key_ctx_->send_history_index).toInt(); - ui_->pdu_->setCurrentIndex(index - 1); } -void SAKModbusUi::InitSignals() { - InitSignalsDevice(); - InitSignalsNetworking(); - InitSignalsSerialPort(); - InitSignalsClient(); - InitSignalsServer(); - InitSignalsClientOperations(); +void SAKModbusUi::InitSettingsNetwork() +{ + QString address = settings_->value(key_ctx_->address).toString(); + ui_->address_combo_box->setCurrentText(address); + + QVariant portValiant = settings_->value(key_ctx_->port); + int port = portValiant.toInt(); + if (portValiant.isNull()) { + port = 502; + } + ui_->port_spin_box->setValue(port); } -void SAKModbusUi::InitSignalsDevice() { - connect(ui_->device_list_, - QOverload::of(&QComboBox::currentIndexChanged), this, - &SAKModbusUi::OnDeviceTypeChanged); - connect(ui_->open_button_, &QPushButton::clicked, this, - &SAKModbusUi::OnOpenClicked); - connect(ui_->cloese_button_, &QPushButton::clicked, this, - &SAKModbusUi::OnCloseClicked); +void SAKModbusUi::InitSettingsSerialPort() +{ + auto SetComboBoxIndex = [](int index, QComboBox *cb) { + if (index >= 0 && index < cb->count()) { + cb->setCurrentIndex(index); + } + }; + + QString portName = settings_->value(key_ctx_->port_name).toString(); + int index = ui_->port_name_->findText(portName); + SetComboBoxIndex(index, ui_->port_name_); + + index = settings_->value(key_ctx_->parity).toInt(); + SetComboBoxIndex(index, ui_->parity_); + + QString bd = settings_->value(key_ctx_->baud_rate).toString(); + ui_->baud_rate_->setCurrentText(bd); + + index = settings_->value(key_ctx_->data_bits).toInt(); + SetComboBoxIndex(index, ui_->data_bits_); + + index = settings_->value(key_ctx_->stop_bits).toInt(); + SetComboBoxIndex(index, ui_->stop_bits_); } -void SAKModbusUi::InitSignalsNetworking() { - connect(ui_->address_combo_box, &QComboBox::currentTextChanged, this, - &SAKModbusUi::OnAddressChanged); - connect(ui_->port_spin_box, QOverload::of(&QSpinBox::valueChanged), this, - &SAKModbusUi::OnPortChanged); +void SAKModbusUi::InitSettingsClient() +{ + int timeout = settings_->value(key_ctx_->client_timeout).toInt(); + ui_->timeout_->setValue(timeout < 100 ? 100 : timeout); + + const QString key = key_ctx_->client_repeat_time; + int repeatTimes = settings_->value(key).toInt(); + ui_->repeat_time_->setValue(repeatTimes); } -void SAKModbusUi::InitSignalsSerialPort() { - connect(ui_->port_name_, &QComboBox::currentTextChanged, this, - &SAKModbusUi::OnPortNameChanged); - connect(ui_->parity_, QOverload::of(&QComboBox::currentIndexChanged), - this, &SAKModbusUi::OnParityChanged); - connect(ui_->baud_rate_, &QComboBox::currentTextChanged, this, - &SAKModbusUi::OnBaudRateChanged); - connect(ui_->data_bits_, QOverload::of(&QComboBox::currentIndexChanged), - this, &SAKModbusUi::OnDataBitsChanged); - connect(ui_->stop_bits_, QOverload::of(&QComboBox::currentIndexChanged), - this, &SAKModbusUi::OnStopBistChanged); +void SAKModbusUi::InitSettingsServer() +{ + bool isBusy = settings_->value(key_ctx_->server_is_busy).toBool(); + ui_->device_busy_->setChecked(isBusy); + + QString key = key_ctx_->server_just_listen; + bool just_listen = settings_->value(key).toBool(); + ui_->listen_only_mode_->setChecked(just_listen); + + int address = settings_->value(key_ctx_->server_address).toInt(); + ui_->server_address->setValue(address); } -void SAKModbusUi::InitSignalsClient() { - connect(ui_->timeout_, QOverload::of(&QSpinBox::valueChanged), this, - &SAKModbusUi::OnClientTimeoutChanged); - connect(ui_->repeat_time_, QOverload::of(&QSpinBox::valueChanged), this, - &SAKModbusUi::OnClientRepeatTimeChanged); -} - -void SAKModbusUi::InitSignalsServer() { - connect(ui_->device_busy_, &QCheckBox::clicked, this, - &SAKModbusUi::OnServerIsBusyChanged); - connect(ui_->listen_only_mode_, &QCheckBox::clicked, this, - &SAKModbusUi::OnServerJustListenChanged); - connect(ui_->server_address, QOverload::of(&QSpinBox::valueChanged), - this, &SAKModbusUi::OnServerAddressChanged); -} - -void SAKModbusUi::InitSignalsClientOperations() { - connect(ui_->function_code_, &QComboBox::currentTextChanged, this, - &SAKModbusUi::OnFunctionCodeChanged); - connect(ui_->device_address_, QOverload::of(&QSpinBox::valueChanged), - this, &SAKModbusUi::OnTargetAddressChanged); - connect(ui_->start_address_, QOverload::of(&QSpinBox::valueChanged), - this, &SAKModbusUi::OnStartAddressChanged); - connect(ui_->quantity_, QOverload::of(&QSpinBox::valueChanged), this, - &SAKModbusUi::OnAddressNumberChanged); - connect(ui_->read_, &QPushButton::clicked, this, &SAKModbusUi::OnReadClicked); - connect(ui_->write_, &QPushButton::clicked, this, - &SAKModbusUi::OnWriteClicked); - connect(ui_->send_, &QPushButton::clicked, this, &SAKModbusUi::OnSendClicked); -} - -void SAKModbusUi::OnErrorOccurred() { - OutputMessage(modbus_device_->errorString(), true, "", "error"); - if (modbus_device_->error() == QModbusDevice::ConnectionError) { - const QString msg = modbus_device_->errorString(); - OnCloseClicked(); - QMessageBox::warning(this, tr("Error occured"), msg); - } -} - -void SAKModbusUi::OnDeviceTypeChanged() { - int type = ui_->device_list_->currentData().toInt(); - bool isSerial = (type == SAKModbusFactory::kModbusRtuSerialClient || - type == SAKModbusFactory::kModbusRtuSerialServer); - bool isClient = (type == SAKModbusFactory::kModbusRtuSerialClient || - type == SAKModbusFactory::kModbusTcpClient); - - // Hide ui component first then show ui component, - // or the window will be resize to the max size of default. - if (isSerial) { - ui_->networkGroupBox->setHidden(true); - ui_->serialPortGroupBox->setHidden(false); - } else { - ui_->serialPortGroupBox->setHidden(true); - ui_->networkGroupBox->setHidden(false); - } - - if (isClient) { - ui_->console_->setVisible(true); - ui_->serverGroupBox->setHidden(true); - ui_->registersGroupBox->setHidden(true); - ui_->clientOperationsGroupBox->setHidden(false); - ui_->clientCustomCommandGroupBox->setHidden(false); - ui_->clientRegistersGroupBox->setHidden(false); - } else { - ui_->console_->setVisible(false); - ui_->clientCustomCommandGroupBox->setHidden(true); - ui_->clientRegistersGroupBox->setHidden(true); - ui_->clientOperationsGroupBox->setHidden(true); - ui_->serverGroupBox->setHidden(false); - ui_->registersGroupBox->setHidden(false); - } - - settings_->setValue(key_ctx_->device_index, type); -} - -void SAKModbusUi::OnCloseClicked() { - SAKModbusFactory::Instance()->DeleteModbusDevuce(&modbus_device_); - UpdateUiState(false); -} - -void SAKModbusUi::OnOpenClicked() { - ui_->open_button_->setEnabled(false); - SAKModbusFactory::Instance()->DeleteModbusDevuce(&modbus_device_); - - modbus_device_ = CreateModbusDevice(); - - if (SAKModbusFactory::Instance()->IsServerDevice(modbus_device_)) { - if (!UpdateServerMap(modbus_device_)) { - ui_->open_button_->setEnabled(true); - qCWarning(kLoggingCategory) << "Can not reset server map!"; - return; +void SAKModbusUi::InitSettingsClientOperations() +{ + int index = settings_->value(key_ctx_->function_code).toInt(); + if (index >= 0 && index < ui_->function_code_->count()) { + ui_->function_code_->setCurrentIndex(index); } - UpdateServerParameters(); + int address = settings_->value(key_ctx_->target_address).toInt(); + ui_->device_address_->setValue(address); - QModbusServer *server = qobject_cast(modbus_device_); - UpdateServerRegistersData(); - connect(server, &QModbusServer::dataWritten, this, - &SAKModbusUi::OnDateWritten); - } else if (SAKModbusFactory::Instance()->IsClientDevice(modbus_device_)) { + int start = settings_->value(key_ctx_->start_address).toInt(); + ui_->start_address_->setValue(start); + + int number = settings_->value(key_ctx_->address_number).toInt(); + ui_->quantity_->setValue(number); +} + +void SAKModbusUi::InitSettingsInput() +{ + ui_->pdu_->clear(); + settings_->beginReadArray(key_ctx_->send_history); + for (int i = 0; i < 10; i++) { + settings_->setArrayIndex(i); + QString text = settings_->value(key_ctx_->pdu).toString(); + if (!text.isEmpty()) { + ui_->pdu_->addItem(text); + } + } + settings_->endArray(); + + int index = settings_->value(key_ctx_->send_history_index).toInt(); + ui_->pdu_->setCurrentIndex(index - 1); +} + +void SAKModbusUi::InitSignals() +{ + InitSignalsDevice(); + InitSignalsNetworking(); + InitSignalsSerialPort(); + InitSignalsClient(); + InitSignalsServer(); + InitSignalsClientOperations(); +} + +void SAKModbusUi::InitSignalsDevice() +{ + connect(ui_->device_list_, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKModbusUi::OnDeviceTypeChanged); + connect(ui_->open_button_, &QPushButton::clicked, this, &SAKModbusUi::OnOpenClicked); + connect(ui_->cloese_button_, &QPushButton::clicked, this, &SAKModbusUi::OnCloseClicked); +} + +void SAKModbusUi::InitSignalsNetworking() +{ + connect(ui_->address_combo_box, + &QComboBox::currentTextChanged, + this, + &SAKModbusUi::OnAddressChanged); + connect(ui_->port_spin_box, + QOverload::of(&QSpinBox::valueChanged), + this, + &SAKModbusUi::OnPortChanged); +} + +void SAKModbusUi::InitSignalsSerialPort() +{ + connect(ui_->port_name_, &QComboBox::currentTextChanged, this, &SAKModbusUi::OnPortNameChanged); + connect(ui_->parity_, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKModbusUi::OnParityChanged); + connect(ui_->baud_rate_, &QComboBox::currentTextChanged, this, &SAKModbusUi::OnBaudRateChanged); + connect(ui_->data_bits_, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKModbusUi::OnDataBitsChanged); + connect(ui_->stop_bits_, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SAKModbusUi::OnStopBistChanged); +} + +void SAKModbusUi::InitSignalsClient() +{ + connect(ui_->timeout_, + QOverload::of(&QSpinBox::valueChanged), + this, + &SAKModbusUi::OnClientTimeoutChanged); + connect(ui_->repeat_time_, + QOverload::of(&QSpinBox::valueChanged), + this, + &SAKModbusUi::OnClientRepeatTimeChanged); +} + +void SAKModbusUi::InitSignalsServer() +{ + connect(ui_->device_busy_, &QCheckBox::clicked, this, &SAKModbusUi::OnServerIsBusyChanged); + connect(ui_->listen_only_mode_, + &QCheckBox::clicked, + this, + &SAKModbusUi::OnServerJustListenChanged); + connect(ui_->server_address, + QOverload::of(&QSpinBox::valueChanged), + this, + &SAKModbusUi::OnServerAddressChanged); +} + +void SAKModbusUi::InitSignalsClientOperations() +{ + connect(ui_->function_code_, + &QComboBox::currentTextChanged, + this, + &SAKModbusUi::OnFunctionCodeChanged); + connect(ui_->device_address_, + QOverload::of(&QSpinBox::valueChanged), + this, + &SAKModbusUi::OnTargetAddressChanged); + connect(ui_->start_address_, + QOverload::of(&QSpinBox::valueChanged), + this, + &SAKModbusUi::OnStartAddressChanged); + connect(ui_->quantity_, + QOverload::of(&QSpinBox::valueChanged), + this, + &SAKModbusUi::OnAddressNumberChanged); + connect(ui_->read_, &QPushButton::clicked, this, &SAKModbusUi::OnReadClicked); + connect(ui_->write_, &QPushButton::clicked, this, &SAKModbusUi::OnWriteClicked); + connect(ui_->send_, &QPushButton::clicked, this, &SAKModbusUi::OnSendClicked); +} + +void SAKModbusUi::OnErrorOccurred() +{ + OutputMessage(modbus_device_->errorString(), true, "", "error"); + if (modbus_device_->error() == QModbusDevice::ConnectionError) { + const QString msg = modbus_device_->errorString(); + OnCloseClicked(); + QMessageBox::warning(this, tr("Error occured"), msg); + } +} + +void SAKModbusUi::OnDeviceTypeChanged() +{ + int type = ui_->device_list_->currentData().toInt(); + bool isSerial = (type == SAKModbusFactory::kModbusRtuSerialClient + || type == SAKModbusFactory::kModbusRtuSerialServer); + bool isClient = (type == SAKModbusFactory::kModbusRtuSerialClient + || type == SAKModbusFactory::kModbusTcpClient); + + // Hide ui component first then show ui component, + // or the window will be resize to the max size of default. + if (isSerial) { + ui_->networkGroupBox->setHidden(true); + ui_->serialPortGroupBox->setHidden(false); + } else { + ui_->serialPortGroupBox->setHidden(true); + ui_->networkGroupBox->setHidden(false); + } + + if (isClient) { + ui_->console_->setVisible(true); + ui_->serverGroupBox->setHidden(true); + ui_->registersGroupBox->setHidden(true); + ui_->clientOperationsGroupBox->setHidden(false); + ui_->clientCustomCommandGroupBox->setHidden(false); + ui_->clientRegistersGroupBox->setHidden(false); + } else { + ui_->console_->setVisible(false); + ui_->clientCustomCommandGroupBox->setHidden(true); + ui_->clientRegistersGroupBox->setHidden(true); + ui_->clientOperationsGroupBox->setHidden(true); + ui_->serverGroupBox->setHidden(false); + ui_->registersGroupBox->setHidden(false); + } + + settings_->setValue(key_ctx_->device_index, type); +} + +void SAKModbusUi::OnCloseClicked() +{ + SAKModbusFactory::Instance()->DeleteModbusDevuce(&modbus_device_); + UpdateUiState(false); +} + +void SAKModbusUi::OnOpenClicked() +{ + ui_->open_button_->setEnabled(false); + SAKModbusFactory::Instance()->DeleteModbusDevuce(&modbus_device_); + + modbus_device_ = CreateModbusDevice(); + + if (SAKModbusFactory::Instance()->IsServerDevice(modbus_device_)) { + if (!UpdateServerMap(modbus_device_)) { + ui_->open_button_->setEnabled(true); + qCWarning(kLoggingCategory) << "Can not reset server map!"; + return; + } + + UpdateServerParameters(); + + QModbusServer *server = qobject_cast(modbus_device_); + UpdateServerRegistersData(); + connect(server, &QModbusServer::dataWritten, this, &SAKModbusUi::OnDateWritten); + } else if (SAKModbusFactory::Instance()->IsClientDevice(modbus_device_)) { + UpdateClientParameters(); + } else { + ui_->open_button_->setEnabled(true); + qCWarning(kLoggingCategory) << "Can not create modbus devices!"; + return; + } + + connect(modbus_device_, &QModbusDevice::errorOccurred, this, &SAKModbusUi::OnErrorOccurred); + SAKModbusFactory *factory = SAKModbusFactory::Instance(); + bool connected = factory->ConnectDeivce(modbus_device_); + if (!connected) { + QString errStr = modbus_device_->errorString(); + QString info = tr("Can not open device: %1." + "Please check the parameters and try again!") + .arg(errStr); + QMessageBox::warning(this, tr("Can not open device"), info); + } + + UpdateUiState(connected); +} + +void SAKModbusUi::OnAddressChanged() +{ + settings_->setValue(key_ctx_->address, ui_->address_combo_box->currentText()); +} + +void SAKModbusUi::OnPortChanged() +{ + settings_->setValue(key_ctx_->port, ui_->port_spin_box->value()); +} + +void SAKModbusUi::OnPortNameChanged() +{ + settings_->setValue(key_ctx_->port_name, ui_->port_name_->currentText()); +} + +void SAKModbusUi::OnParityChanged() +{ + settings_->setValue(key_ctx_->parity, ui_->parity_->currentIndex()); +} + +void SAKModbusUi::OnBaudRateChanged() +{ + settings_->setValue(key_ctx_->baud_rate, ui_->baud_rate_->currentText()); +} + +void SAKModbusUi::OnDataBitsChanged() +{ + settings_->setValue(key_ctx_->data_bits, ui_->data_bits_->currentIndex()); +} + +void SAKModbusUi::OnStopBistChanged() +{ + settings_->setValue(key_ctx_->stop_bits, ui_->stop_bits_->currentIndex()); +} + +void SAKModbusUi::OnInvokeRefresh() +{ + InitComponentPortName(); +} + +void SAKModbusUi::OnClientTimeoutChanged() +{ + settings_->setValue(key_ctx_->client_timeout, ui_->timeout_->value()); UpdateClientParameters(); - } else { - ui_->open_button_->setEnabled(true); - qCWarning(kLoggingCategory) << "Can not create modbus devices!"; - return; - } - - connect(modbus_device_, &QModbusDevice::errorOccurred, this, - &SAKModbusUi::OnErrorOccurred); - SAKModbusFactory *factory = SAKModbusFactory::Instance(); - bool connected = factory->ConnectDeivce(modbus_device_); - if (!connected) { - QString errStr = modbus_device_->errorString(); - QString info = tr("Can not open device: %1." - "Please check the parameters and try again!") - .arg(errStr); - QMessageBox::warning(this, tr("Can not open device"), info); - } - - UpdateUiState(connected); } -void SAKModbusUi::OnAddressChanged() { - settings_->setValue(key_ctx_->address, ui_->address_combo_box->currentText()); +void SAKModbusUi::OnClientRepeatTimeChanged() +{ + settings_->setValue(key_ctx_->client_repeat_time, ui_->repeat_time_->value()); + UpdateClientParameters(); } -void SAKModbusUi::OnPortChanged() { - settings_->setValue(key_ctx_->port, ui_->port_spin_box->value()); +void SAKModbusUi::OnServerIsBusyChanged() +{ + settings_->setValue(key_ctx_->server_is_busy, ui_->device_busy_->isChecked()); + UpdateServerParameters(); } -void SAKModbusUi::OnPortNameChanged() { - settings_->setValue(key_ctx_->port_name, ui_->port_name_->currentText()); +void SAKModbusUi::OnServerJustListenChanged() +{ + settings_->setValue(key_ctx_->server_just_listen, ui_->listen_only_mode_->isChecked()); + UpdateServerParameters(); } -void SAKModbusUi::OnParityChanged() { - settings_->setValue(key_ctx_->parity, ui_->parity_->currentIndex()); +void SAKModbusUi::OnServerAddressChanged() +{ + settings_->setValue(key_ctx_->server_address, ui_->server_address->value()); + UpdateServerParameters(); } -void SAKModbusUi::OnBaudRateChanged() { - settings_->setValue(key_ctx_->baud_rate, ui_->baud_rate_->currentText()); +void SAKModbusUi::OnFunctionCodeChanged() +{ + settings_->setValue(key_ctx_->function_code, ui_->function_code_->currentIndex()); + UpdateClientReadWriteButtonState(); } -void SAKModbusUi::OnDataBitsChanged() { - settings_->setValue(key_ctx_->data_bits, ui_->data_bits_->currentIndex()); +void SAKModbusUi::OnTargetAddressChanged() +{ + settings_->setValue(key_ctx_->target_address, ui_->device_address_->value()); } -void SAKModbusUi::OnStopBistChanged() { - settings_->setValue(key_ctx_->stop_bits, ui_->stop_bits_->currentIndex()); +void SAKModbusUi::OnStartAddressChanged() +{ + settings_->setValue(key_ctx_->start_address, ui_->start_address_->value()); + UpdateClientTableView(); } -void SAKModbusUi::OnInvokeRefresh() { InitComponentPortName(); } - -void SAKModbusUi::OnClientTimeoutChanged() { - settings_->setValue(key_ctx_->client_timeout, ui_->timeout_->value()); - UpdateClientParameters(); +void SAKModbusUi::OnAddressNumberChanged() +{ + settings_->setValue(key_ctx_->address_number, ui_->quantity_->value()); + UpdateClientTableView(); } -void SAKModbusUi::OnClientRepeatTimeChanged() { - settings_->setValue(key_ctx_->client_repeat_time, ui_->repeat_time_->value()); - UpdateClientParameters(); -} - -void SAKModbusUi::OnServerIsBusyChanged() { - settings_->setValue(key_ctx_->server_is_busy, ui_->device_busy_->isChecked()); - UpdateServerParameters(); -} - -void SAKModbusUi::OnServerJustListenChanged() { - settings_->setValue(key_ctx_->server_just_listen, - ui_->listen_only_mode_->isChecked()); - UpdateServerParameters(); -} - -void SAKModbusUi::OnServerAddressChanged() { - settings_->setValue(key_ctx_->server_address, ui_->server_address->value()); - UpdateServerParameters(); -} - -void SAKModbusUi::OnFunctionCodeChanged() { - settings_->setValue(key_ctx_->function_code, - ui_->function_code_->currentIndex()); - UpdateClientReadWriteButtonState(); -} - -void SAKModbusUi::OnTargetAddressChanged() { - settings_->setValue(key_ctx_->target_address, ui_->device_address_->value()); -} - -void SAKModbusUi::OnStartAddressChanged() { - settings_->setValue(key_ctx_->start_address, ui_->start_address_->value()); - UpdateClientTableView(); -} - -void SAKModbusUi::OnAddressNumberChanged() { - settings_->setValue(key_ctx_->address_number, ui_->quantity_->value()); - UpdateClientTableView(); -} - -void SAKModbusUi::OnReadClicked() { - if (!IsConnected()) { - return; - } - - if (!SAKModbusFactory::Instance()->IsClientDevice(modbus_device_)) { - return; - } - - int register_type = ui_->function_code_->currentData().toInt(); - quint16 start_address = ui_->start_address_->value(); - quint16 quantity = ui_->quantity_->value(); - quint16 server_address = ui_->device_address_->value(); - quint8 function_code = GetClientFunctionCode(); - - qCInfo(kLoggingCategory) << "[SendReadRequest]" - << "register type:" << register_type - << "start address:" << start_address - << "quantity:" << quantity - << "server address:" << server_address; - - typedef QModbusDataUnit::RegisterType RegisterType; - RegisterType type = static_cast(register_type); - QModbusDataUnit data_unit(type, start_address, quantity); - QModbusClient *client = qobject_cast(modbus_device_); - QModbusReply *reply = client->sendReadRequest(data_unit, server_address); - if (!SAKModbusFactory::Instance()->IsValidModbusReply(reply)) { - return; - } - - QString info = ui_->function_code_->currentText(); - OutputMessage(info, false, TXCOLOR, TXFLAG); - connect(reply, &QModbusReply::finished, this, [=]() { - OutputModbusReply(reply, function_code); - - if (reply->error() == QModbusDevice::NoError) { - UpdateClientTableViewData(reply->result().values()); - reply->deleteLater(); +void SAKModbusUi::OnReadClicked() +{ + if (!IsConnected()) { + return; } - }); -} -void SAKModbusUi::OnWriteClicked() { - if (!IsConnected()) { - return; - } + if (!SAKModbusFactory::Instance()->IsClientDevice(modbus_device_)) { + return; + } - int registerType = ui_->function_code_->currentData().toInt(); - int start_address = ui_->start_address_->value(); - int server_address = ui_->device_address_->value(); - quint8 function_code = GetClientFunctionCode(); - QList values = GetClientRegisterValue(); - SAKModbusFactory *factory = SAKModbusFactory::Instance(); - QModbusReply *reply = factory->SendWriteRequest( - modbus_device_, registerType, start_address, values, server_address); - if (SAKModbusFactory::Instance()->IsValidModbusReply(reply)) { - connect(reply, &QModbusReply::finished, this, [=]() { - OutputModbusReply(reply, function_code); - reply->deleteLater(); - }); + int register_type = ui_->function_code_->currentData().toInt(); + quint16 start_address = ui_->start_address_->value(); + quint16 quantity = ui_->quantity_->value(); + quint16 server_address = ui_->device_address_->value(); + quint8 function_code = GetClientFunctionCode(); + + qCInfo(kLoggingCategory) << "[SendReadRequest]" + << "register type:" << register_type + << "start address:" << start_address << "quantity:" << quantity + << "server address:" << server_address; + + typedef QModbusDataUnit::RegisterType RegisterType; + RegisterType type = static_cast(register_type); + QModbusDataUnit data_unit(type, start_address, quantity); + QModbusClient *client = qobject_cast(modbus_device_); + QModbusReply *reply = client->sendReadRequest(data_unit, server_address); + if (!SAKModbusFactory::Instance()->IsValidModbusReply(reply)) { + return; + } QString info = ui_->function_code_->currentText(); OutputMessage(info, false, TXCOLOR, TXFLAG); - } -} - -void SAKModbusUi::OnSendClicked() { - if (!IsConnected()) { - return; - } - - quint8 server_address = ui_->device_address_->value(); - QByteArray pdu = GetClientPdu(); - QByteArray data = pdu; - if (!data.isEmpty()) { - data = data.remove(0, 1); - } - - int function_code = int(QModbusDataUnit::Invalid); - if (!pdu.isEmpty()) { - function_code = pdu.at(0); - } - SAKModbusFactory *factory = SAKModbusFactory::Instance(); - QModbusReply *reply = factory->SendRawRequest(modbus_device_, server_address, - function_code, data); - - qCWarning(kLoggingCategory) << "Send raw request:" - << "server address:" << server_address - << "function code:" << function_code - << "data:" << QString(pdu.toHex(' ')); - if (SAKModbusFactory::Instance()->IsValidModbusReply(reply)) { connect(reply, &QModbusReply::finished, this, [=]() { - OutputModbusReply(reply, function_code); - reply->deleteLater(); + OutputModbusReply(reply, function_code); + + if (reply->error() == QModbusDevice::NoError) { + UpdateClientTableViewData(reply->result().values()); + reply->deleteLater(); + } }); - - QString info = "pdu(No server address, no crc):"; - info += QString(pdu.toHex(' ')); - OutputMessage(info, false, TXCOLOR, TXFLAG); - } - - // Update settings data. - int index = settings_->value(key_ctx_->send_history_index).toInt(); - bool ret = - WriteSettingsArray(key_ctx_->send_history, key_ctx_->pdu, - QString(pdu.toHex(' ')), index, MAX_HISTORY_INDEX); - if (!ret) { - return; - } - - if (index > ui_->pdu_->count()) { - ui_->pdu_->addItem(QString(pdu.toHex(' '))); - } else { - ui_->pdu_->insertItem(index, QString(pdu.toHex(' '))); - } - - index = index + 1 > MAX_HISTORY_INDEX ? 0 : index + 1; - settings_->setValue(key_ctx_->send_history_index, index); } -void SAKModbusUi::OnDateWritten(QModbusDataUnit::RegisterType table, - int address, int size) { - qCInfo(kLoggingCategory) << "Data written:" - << "table:" << table << "start address:" << address - << "size:" << size; - QTableView *tv = GetTableView(table); - QStandardItemModel *model = qobject_cast(tv->model()); - QModbusServer *server = qobject_cast(modbus_device_); - QList data = - SAKModbusFactory::Instance()->GetServerData(server, table, address, size); - size = qMin(data.count(), size); - for (int i = 0; i < size; i++) { - int row = address + i; - int base = 16; - int width = base == 2 ? 16 : (base == 10 ? 5 : 4); - int value = data.at(i); - QString cooked_str = QString::number(value, base); - cooked_str = cooked_str.rightJustified(width, '0', true); - QStandardItem *item = model->item(row, 1); - if (item) { - item->setData(cooked_str, Qt::DisplayRole); - item->setTextAlignment(Qt::AlignCenter); +void SAKModbusUi::OnWriteClicked() +{ + if (!IsConnected()) { + return; } - } - tv->viewport()->update(); + int registerType = ui_->function_code_->currentData().toInt(); + int start_address = ui_->start_address_->value(); + int server_address = ui_->device_address_->value(); + quint8 function_code = GetClientFunctionCode(); + QList values = GetClientRegisterValue(); + SAKModbusFactory *factory = SAKModbusFactory::Instance(); + QModbusReply *reply = factory->SendWriteRequest(modbus_device_, + registerType, + start_address, + values, + server_address); + if (SAKModbusFactory::Instance()->IsValidModbusReply(reply)) { + connect(reply, &QModbusReply::finished, this, [=]() { + OutputModbusReply(reply, function_code); + reply->deleteLater(); + }); + + QString info = ui_->function_code_->currentText(); + OutputMessage(info, false, TXCOLOR, TXFLAG); + } } -void SAKModbusUi::OnItemChanged(QStandardItem *item) { - if (!item) { - return; - } +void SAKModbusUi::OnSendClicked() +{ + if (!IsConnected()) { + return; + } - if (item->column() != 1) { - return; - } + quint8 server_address = ui_->device_address_->value(); + QByteArray pdu = GetClientPdu(); + QByteArray data = pdu; + if (!data.isEmpty()) { + data = data.remove(0, 1); + } - if (SAKModbusFactory::Instance()->IsServerDevice(modbus_device_)) { - int address = item->row(); - int current_index = ui_->server_registers_->currentIndex(); - QModbusDataUnit::RegisterType table = QModbusDataUnit::Invalid; - if (current_index == 0) { - table = QModbusDataUnit::Coils; - } else if (current_index == 1) { - table = QModbusDataUnit::DiscreteInputs; - } else if (current_index == 2) { - table = QModbusDataUnit::InputRegisters; - } else if (current_index == 3) { - table = QModbusDataUnit::HoldingRegisters; + int function_code = int(QModbusDataUnit::Invalid); + if (!pdu.isEmpty()) { + function_code = pdu.at(0); + } + SAKModbusFactory *factory = SAKModbusFactory::Instance(); + QModbusReply *reply = factory->SendRawRequest(modbus_device_, + server_address, + function_code, + data); + + qCWarning(kLoggingCategory) << "Send raw request:" + << "server address:" << server_address + << "function code:" << function_code + << "data:" << QString(pdu.toHex(' ')); + if (SAKModbusFactory::Instance()->IsValidModbusReply(reply)) { + connect(reply, &QModbusReply::finished, this, [=]() { + OutputModbusReply(reply, function_code); + reply->deleteLater(); + }); + + QString info = "pdu(No server address, no crc):"; + info += QString(pdu.toHex(' ')); + OutputMessage(info, false, TXCOLOR, TXFLAG); + } + + // Update settings data. + int index = settings_->value(key_ctx_->send_history_index).toInt(); + bool ret = WriteSettingsArray(key_ctx_->send_history, + key_ctx_->pdu, + QString(pdu.toHex(' ')), + index, + MAX_HISTORY_INDEX); + if (!ret) { + return; + } + + if (index > ui_->pdu_->count()) { + ui_->pdu_->addItem(QString(pdu.toHex(' '))); } else { - Q_ASSERT_X(false, __FUNCTION__, "Unknow table type!"); - return; + ui_->pdu_->insertItem(index, QString(pdu.toHex(' '))); } - quint16 value = item->text().toInt(Q_NULLPTR, 16); - SAKModbusFactory::Instance()->SetServerData(modbus_device_, table, address, - value); - } + index = index + 1 > MAX_HISTORY_INDEX ? 0 : index + 1; + settings_->setValue(key_ctx_->send_history_index, index); } -QModbusDevice *SAKModbusUi::CreateModbusDevice() { - QModbusDevice *device = Q_NULLPTR; - int type = ui_->device_list_->currentData().toInt(); - if (SAKModbusFactory::Instance()->IsRtuSerialDeviceType(type)) { - QString port_name = ui_->port_name_->currentText(); - int parity = ui_->parity_->currentData().toInt(); - int baud_rate = ui_->baud_rate_->currentData().toInt(); - int data_bits = ui_->data_bits_->currentData().toInt(); - int stop_bits = ui_->stop_bits_->currentData().toInt(); - SAKModbusFactory *factory = SAKModbusFactory::Instance(); - device = factory->CreateRtuSerialDevice(type, port_name, parity, baud_rate, - data_bits, stop_bits); - } else if (SAKModbusFactory::Instance()->IsTcpDeviceType(type)) { - QString address = ui_->address_combo_box->currentText(); - int port = ui_->port_spin_box->value(); - SAKModbusFactory *factory = SAKModbusFactory::Instance(); - device = factory->CreateTcpDevice(type, address, port); - } else { - Q_ASSERT_X(false, __FUNCTION__, "Unknown device type"); - } +void SAKModbusUi::OnDateWritten(QModbusDataUnit::RegisterType table, int address, int size) +{ + qCInfo(kLoggingCategory) << "Data written:" + << "table:" << table << "start address:" << address << "size:" << size; + QTableView *tv = GetTableView(table); + QStandardItemModel *model = qobject_cast(tv->model()); + QModbusServer *server = qobject_cast(modbus_device_); + QList data = SAKModbusFactory::Instance()->GetServerData(server, table, address, size); + size = qMin(data.count(), size); + for (int i = 0; i < size; i++) { + int row = address + i; + int base = 16; + int width = base == 2 ? 16 : (base == 10 ? 5 : 4); + int value = data.at(i); + QString cooked_str = QString::number(value, base); + cooked_str = cooked_str.rightJustified(width, '0', true); + QStandardItem *item = model->item(row, 1); + if (item) { + item->setData(cooked_str, Qt::DisplayRole); + item->setTextAlignment(Qt::AlignCenter); + } + } - return device; + tv->viewport()->update(); } -QTableView *SAKModbusUi::CreateTableView(int row_count, - QTableView *table_view) { - if (!table_view) { - table_view = new QTableView(this); - } +void SAKModbusUi::OnItemChanged(QStandardItem *item) +{ + if (!item) { + return; + } - QHeaderView *hv = table_view->horizontalHeader(); - QStandardItemModel *model = new QStandardItemModel(table_view); - QStringList labels = QStringList() - << tr("Address") << tr("Value") << tr("Description"); - model->setHorizontalHeaderLabels(labels); - model->setColumnCount(3); - model->setRowCount(row_count); - table_view->setModel(model); - table_view->verticalHeader()->hide(); - table_view->setItemDelegateForColumn(0, new ReadOnlyDelegate(table_view)); - UpdateClientTableViewAddress(table_view, 0); - hv->setStretchLastSection(true); + if (item->column() != 1) { + return; + } - // Set the default value to 0. - model->blockSignals(true); - for (int row = 0; row < row_count; row++) { - QModelIndex index = model->index(row, 1); - QMap roles; - roles.insert(Qt::DisplayRole, "0000"); - model->setItemData(index, roles); + if (SAKModbusFactory::Instance()->IsServerDevice(modbus_device_)) { + int address = item->row(); + int current_index = ui_->server_registers_->currentIndex(); + QModbusDataUnit::RegisterType table = QModbusDataUnit::Invalid; + if (current_index == 0) { + table = QModbusDataUnit::Coils; + } else if (current_index == 1) { + table = QModbusDataUnit::DiscreteInputs; + } else if (current_index == 2) { + table = QModbusDataUnit::InputRegisters; + } else if (current_index == 3) { + table = QModbusDataUnit::HoldingRegisters; + } else { + Q_ASSERT_X(false, __FUNCTION__, "Unknow table type!"); + return; + } - QStandardItem *item = model->item(row, 1); - item->setTextAlignment(Qt::AlignCenter); - } - model->blockSignals(false); - - connect(model, &QStandardItemModel::itemChanged, this, - &SAKModbusUi::OnItemChanged); - - return table_view; + quint16 value = item->text().toInt(Q_NULLPTR, 16); + SAKModbusFactory::Instance()->SetServerData(modbus_device_, table, address, value); + } } -void SAKModbusUi::UpdateUiState(bool connected) { - ui_->device_list_->setEnabled(!connected); - ui_->cloese_button_->setEnabled(connected); - ui_->open_button_->setEnabled(!connected); - ui_->networkGroupBox->setEnabled(!connected); - ui_->serialPortGroupBox->setEnabled(!connected); +QModbusDevice *SAKModbusUi::CreateModbusDevice() +{ + QModbusDevice *device = Q_NULLPTR; + int type = ui_->device_list_->currentData().toInt(); + if (SAKModbusFactory::Instance()->IsRtuSerialDeviceType(type)) { + QString port_name = ui_->port_name_->currentText(); + int parity = ui_->parity_->currentData().toInt(); + int baud_rate = ui_->baud_rate_->currentData().toInt(); + int data_bits = ui_->data_bits_->currentData().toInt(); + int stop_bits = ui_->stop_bits_->currentData().toInt(); + SAKModbusFactory *factory = SAKModbusFactory::Instance(); + device = factory->CreateRtuSerialDevice(type, + port_name, + parity, + baud_rate, + data_bits, + stop_bits); + } else if (SAKModbusFactory::Instance()->IsTcpDeviceType(type)) { + QString address = ui_->address_combo_box->currentText(); + int port = ui_->port_spin_box->value(); + SAKModbusFactory *factory = SAKModbusFactory::Instance(); + device = factory->CreateTcpDevice(type, address, port); + } else { + Q_ASSERT_X(false, __FUNCTION__, "Unknown device type"); + } + + return device; +} + +QTableView *SAKModbusUi::CreateTableView(int row_count, QTableView *table_view) +{ + if (!table_view) { + table_view = new QTableView(this); + } + + QHeaderView *hv = table_view->horizontalHeader(); + QStandardItemModel *model = new QStandardItemModel(table_view); + QStringList labels = QStringList() << tr("Address") << tr("Value") << tr("Description"); + model->setHorizontalHeaderLabels(labels); + model->setColumnCount(3); + model->setRowCount(row_count); + table_view->setModel(model); + table_view->verticalHeader()->hide(); + table_view->setItemDelegateForColumn(0, new ReadOnlyDelegate(table_view)); + UpdateClientTableViewAddress(table_view, 0); + hv->setStretchLastSection(true); + + // Set the default value to 0. + model->blockSignals(true); + for (int row = 0; row < row_count; row++) { + QModelIndex index = model->index(row, 1); + QMap roles; + roles.insert(Qt::DisplayRole, "0000"); + model->setItemData(index, roles); + + QStandardItem *item = model->item(row, 1); + item->setTextAlignment(Qt::AlignCenter); + } + model->blockSignals(false); + + connect(model, &QStandardItemModel::itemChanged, this, &SAKModbusUi::OnItemChanged); + + return table_view; +} + +void SAKModbusUi::UpdateUiState(bool connected) +{ + ui_->device_list_->setEnabled(!connected); + ui_->cloese_button_->setEnabled(connected); + ui_->open_button_->setEnabled(!connected); + ui_->networkGroupBox->setEnabled(!connected); + ui_->serialPortGroupBox->setEnabled(!connected); #if 0 ui->clientGroupBox->setEnabled(!connected); ui->serverGroupBox->setEnabled(!connected); #endif } -void SAKModbusUi::UpdateClientTableView() { - int number = ui_->quantity_->value(); - int rowCount = register_model_->rowCount(); - if (number > rowCount) { - register_model_->insertRows(rowCount, number - rowCount); - } else if (number < rowCount) { - register_model_->removeRows(number, rowCount - number); - } - - // Update address. - int start_address = ui_->start_address_->value(); - UpdateClientTableViewAddress(ui_->client_registers_, start_address); -} - -void SAKModbusUi::UpdateClientTableViewData(const QList &values) { - for (int row = 0; row < values.count(); row++) { - int value = values.at(row); - QModelIndex index = register_model_->index(row, 1); - QMap roles; - QString str = QString("%1").arg(QString::number(value, 16), 4, '0'); - roles.insert(Qt::DisplayRole, str); - register_model_->setItemData(index, roles); - QStandardItem *item = register_model_->item(row, 1); - if (item) { - item->setTextAlignment(Qt::AlignCenter); - } - } - - // Refresh the view, or the new value will not be show. - ui_->client_registers_->viewport()->update(); -} - -void SAKModbusUi::UpdateClientReadWriteButtonState() { - QStringList list = ui_->function_code_->currentText().split('-'); - int code = list.length() ? list.first().toInt(Q_NULLPTR, 16) : 0; - bool is_reading_operation = false; - if (code == 0x01 || code == 0x02 || code == 0x03 || code == 0x04) { - is_reading_operation = true; - } - - if (code == 0x05 || code == 0x06) { - ui_->quantity_->setValue(1); - } - - ui_->read_->setEnabled(is_reading_operation); - ui_->write_->setEnabled(!is_reading_operation); -} - -void SAKModbusUi::UpdateClientParameters() { - int timeout = ui_->timeout_->value(); - int repeat_time = ui_->repeat_time_->value(); - SAKModbusFactory::Instance()->SetClientDeviceParameters(modbus_device_, - timeout, repeat_time); -} - -void SAKModbusUi::UpdateClientTableViewAddress(QTableView *view, - int start_address) { - auto *model = qobject_cast(view->model()); - for (int row = 0; row < model->rowCount(); row++) { - int address = row + start_address; - QString text = QString("%1").arg(QString::number(address), 5, '0'); - QModelIndex index = model->index(row, 0); - QMap roles; - roles.insert(Qt::DisplayRole, text); - model->setItemData(index, roles); - - QStandardItem *item = model->item(row, 0); - if (item) { - item->setTextAlignment(Qt::AlignCenter); - } - } -} - -void SAKModbusUi::UpdateServerParameters() { - bool device_busy = ui_->device_busy_->isChecked(); - bool listen_only_mode = ui_->listen_only_mode_->isChecked(); - int address = ui_->server_address->value(); - SAKModbusFactory::Instance()->SetServerDeviceParameters( - modbus_device_, address, device_busy, listen_only_mode); -} - -bool SAKModbusUi::UpdateServerMap(QModbusDevice *server) { - if (server && qobject_cast(server)) { - QVector values(UINT16_MAX + 1, 0); - QModbusDataUnit dataUnit(QModbusDataUnit::Coils, 0, values); - - QModbusDataUnitMap map; - map.insert(QModbusDataUnit::Coils, dataUnit); - map.insert(QModbusDataUnit::DiscreteInputs, dataUnit); - map.insert(QModbusDataUnit::HoldingRegisters, dataUnit); - map.insert(QModbusDataUnit::InputRegisters, dataUnit); - - QModbusServer *cooked_server = qobject_cast(server); - cooked_server->blockSignals(true); - bool is_ok = cooked_server->setMap(map); - cooked_server->blockSignals(false); - return is_ok; - } - - return false; -} - -void SAKModbusUi::UpdateServerRegistersData() { - for (int i = 0; i < 4; i++) { - QWidget *widget = ui_->server_registers_->widget(i); - QTableView *table_view = qobject_cast(widget); - auto *model = qobject_cast(table_view->model()); - int type = QModbusDataUnit::Invalid; - if (i == 0) { - type = QModbusDataUnit::Coils; - } else if (i == 1) { - type = QModbusDataUnit::DiscreteInputs; - } else if (i == 2) { - type = QModbusDataUnit::InputRegisters; - } else if (i == 3) { - type = QModbusDataUnit::HoldingRegisters; - } else { - qCWarning(kLoggingCategory) << "Unknown register type."; - continue; +void SAKModbusUi::UpdateClientTableView() +{ + int number = ui_->quantity_->value(); + int rowCount = register_model_->rowCount(); + if (number > rowCount) { + register_model_->insertRows(rowCount, number - rowCount); + } else if (number < rowCount) { + register_model_->removeRows(number, rowCount - number); } + // Update address. + int start_address = ui_->start_address_->value(); + UpdateClientTableViewAddress(ui_->client_registers_, start_address); +} + +void SAKModbusUi::UpdateClientTableViewData(const QList &values) +{ + for (int row = 0; row < values.count(); row++) { + int value = values.at(row); + QModelIndex index = register_model_->index(row, 1); + QMap roles; + QString str = QString("%1").arg(QString::number(value, 16), 4, '0'); + roles.insert(Qt::DisplayRole, str); + register_model_->setItemData(index, roles); + QStandardItem *item = register_model_->item(row, 1); + if (item) { + item->setTextAlignment(Qt::AlignCenter); + } + } + + // Refresh the view, or the new value will not be show. + ui_->client_registers_->viewport()->update(); +} + +void SAKModbusUi::UpdateClientReadWriteButtonState() +{ + QStringList list = ui_->function_code_->currentText().split('-'); + int code = list.length() ? list.first().toInt(Q_NULLPTR, 16) : 0; + bool is_reading_operation = false; + if (code == 0x01 || code == 0x02 || code == 0x03 || code == 0x04) { + is_reading_operation = true; + } + + if (code == 0x05 || code == 0x06) { + ui_->quantity_->setValue(1); + } + + ui_->read_->setEnabled(is_reading_operation); + ui_->write_->setEnabled(!is_reading_operation); +} + +void SAKModbusUi::UpdateClientParameters() +{ + int timeout = ui_->timeout_->value(); + int repeat_time = ui_->repeat_time_->value(); + SAKModbusFactory::Instance()->SetClientDeviceParameters(modbus_device_, timeout, repeat_time); +} + +void SAKModbusUi::UpdateClientTableViewAddress(QTableView *view, int start_address) +{ + auto *model = qobject_cast(view->model()); for (int row = 0; row < model->rowCount(); row++) { - QStandardItem *item = model->item(row, 1); - quint16 value = item ? item->text().toInt(Q_NULLPTR, 16) : 0; - auto table = static_cast(type); - SAKModbusFactory::Instance()->SetServerData(modbus_device_, table, row, - value, false); + int address = row + start_address; + QString text = QString("%1").arg(QString::number(address), 5, '0'); + QModelIndex index = model->index(row, 0); + QMap roles; + roles.insert(Qt::DisplayRole, text); + model->setItemData(index, roles); + + QStandardItem *item = model->item(row, 0); + if (item) { + item->setTextAlignment(Qt::AlignCenter); + } } - } } -quint8 SAKModbusUi::GetClientFunctionCode() { - QString txt = ui_->function_code_->currentText(); - QStringList list = txt.split('-', Qt::SkipEmptyParts); - if (list.length()) { - return list.first().toInt(Q_NULLPTR, 16); - } - - return 0; +void SAKModbusUi::UpdateServerParameters() +{ + bool device_busy = ui_->device_busy_->isChecked(); + bool listen_only_mode = ui_->listen_only_mode_->isChecked(); + int address = ui_->server_address->value(); + SAKModbusFactory::Instance()->SetServerDeviceParameters(modbus_device_, + address, + device_busy, + listen_only_mode); } -QList SAKModbusUi::GetClientRegisterValue() { - QList values; - for (int row = 0; row < register_model_->rowCount(); row++) { - QStandardItem *item = register_model_->item(row, 1); - if (item) { - QString text = item->text(); - values.append(text.toInt(Q_NULLPTR, 16)); - } else { - values.append(0); +bool SAKModbusUi::UpdateServerMap(QModbusDevice *server) +{ + if (server && qobject_cast(server)) { + QVector values(UINT16_MAX + 1, 0); + QModbusDataUnit dataUnit(QModbusDataUnit::Coils, 0, values); + + QModbusDataUnitMap map; + map.insert(QModbusDataUnit::Coils, dataUnit); + map.insert(QModbusDataUnit::DiscreteInputs, dataUnit); + map.insert(QModbusDataUnit::HoldingRegisters, dataUnit); + map.insert(QModbusDataUnit::InputRegisters, dataUnit); + + QModbusServer *cooked_server = qobject_cast(server); + cooked_server->blockSignals(true); + bool is_ok = cooked_server->setMap(map); + cooked_server->blockSignals(false); + return is_ok; } - } - return values; + return false; } -QByteArray SAKModbusUi::GetClientPdu() { - QString text = ui_->pdu_->currentText(); +void SAKModbusUi::UpdateServerRegistersData() +{ + for (int i = 0; i < 4; i++) { + QWidget *widget = ui_->server_registers_->widget(i); + QTableView *table_view = qobject_cast(widget); + auto *model = qobject_cast(table_view->model()); + int type = QModbusDataUnit::Invalid; + if (i == 0) { + type = QModbusDataUnit::Coils; + } else if (i == 1) { + type = QModbusDataUnit::DiscreteInputs; + } else if (i == 2) { + type = QModbusDataUnit::InputRegisters; + } else if (i == 3) { + type = QModbusDataUnit::HoldingRegisters; + } else { + qCWarning(kLoggingCategory) << "Unknown register type."; + continue; + } + + for (int row = 0; row < model->rowCount(); row++) { + QStandardItem *item = model->item(row, 1); + quint16 value = item ? item->text().toInt(Q_NULLPTR, 16) : 0; + auto table = static_cast(type); + SAKModbusFactory::Instance()->SetServerData(modbus_device_, table, row, value, false); + } + } +} + +quint8 SAKModbusUi::GetClientFunctionCode() +{ + QString txt = ui_->function_code_->currentText(); + QStringList list = txt.split('-', Qt::SkipEmptyParts); + if (list.length()) { + return list.first().toInt(Q_NULLPTR, 16); + } + + return 0; +} + +QList SAKModbusUi::GetClientRegisterValue() +{ + QList values; + for (int row = 0; row < register_model_->rowCount(); row++) { + QStandardItem *item = register_model_->item(row, 1); + if (item) { + QString text = item->text(); + values.append(text.toInt(Q_NULLPTR, 16)); + } else { + values.append(0); + } + } + + return values; +} + +QByteArray SAKModbusUi::GetClientPdu() +{ + QString text = ui_->pdu_->currentText(); #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - QStringList valueList = text.split(' ', QString::SkipEmptyParts); + QStringList valueList = text.split(' ', QString::SkipEmptyParts); #else - QStringList valueList = text.split(' ', Qt::SkipEmptyParts); + QStringList valueList = text.split(' ', Qt::SkipEmptyParts); #endif - QByteArray data; - for (QString &value : valueList) { - data.append(char(value.toInt(Q_NULLPTR, 16))); - } - - return data; -} - -QTableView *SAKModbusUi::GetTableView(QModbusDataUnit::RegisterType table) { - QWidget *tv = Q_NULLPTR; - if (table == QModbusDataUnit::Coils) { - tv = ui_->server_registers_->widget(0); - } else if (table == QModbusDataUnit::DiscreteInputs) { - tv = ui_->server_registers_->widget(1); - } else if (table == QModbusDataUnit::InputRegisters) { - tv = ui_->server_registers_->widget(2); - } else if (table == QModbusDataUnit::HoldingRegisters) { - tv = ui_->server_registers_->widget(3); - } else { - tv = ui_->server_registers_->widget(3); - qCWarning(kLoggingCategory) - << "Get table view failed: unknow register type!"; - } - - return qobject_cast(tv); -} - -QList SAKModbusUi::GetTableValues(QTableView *table_view, int row, - int count) { - if (!table_view) { - qCWarning(kLoggingCategory) << "Table view can not be null!"; - return QList(); - } - - auto *model = qobject_cast(table_view->model()); - if (!model) { - qCWarning(kLoggingCategory) << "Model can not be null!"; - return QList(); - } - - QList values; - for (int i = row; i < count; i++) { - QStandardItem *item = model->item(i, 1); - if (item) { - QString text = item->text(); - values.append(text.toInt(Q_NULLPTR, 16)); - } else { - values.append(0); + QByteArray data; + for (QString &value : valueList) { + data.append(char(value.toInt(Q_NULLPTR, 16))); } - } - return values; + return data; } -void SAKModbusUi::OutputModbusReply(QModbusReply *reply, int function_code) { - if (reply->error() != QModbusDevice::NoError) { - OutputMessage(reply->errorString(), true, "", "error"); - QMessageBox::warning(this, tr("Error occured"), reply->errorString()); - return; - } - - int server_address = reply->serverAddress(); - if (reply->type() == QModbusReply::ReplyType::Raw) { - QByteArray data = reply->rawResult().data(); - QString info = QString( - "(from address: %1, " - "function code: %2), " - "data unit: %3") - .arg(server_address) - .arg(function_code) - .arg(QString::fromLatin1(data.toHex(' '))); - OutputMessage(info, false, RXCOLOR, RXFLAG); - } else if (reply->type() == QModbusReply::ReplyType::Common) { - QString info = ui_->function_code_->currentText(); - OutputMessage(info, false, RXCOLOR, RXFLAG); - } -} - -void SAKModbusUi::OutputMessage(const QString &msg, bool isError, - const QString &color, const QString &flag) { - QString cookedMsg = QDateTime::currentDateTime().toString("hh:mm:ss.zzz"); - cookedMsg = QString("%1 ").arg(cookedMsg); - - QString cookedColor = color; - if (cookedColor.isEmpty()) { - if (isError) { - cookedColor = "red"; +QTableView *SAKModbusUi::GetTableView(QModbusDataUnit::RegisterType table) +{ + QWidget *tv = Q_NULLPTR; + if (table == QModbusDataUnit::Coils) { + tv = ui_->server_registers_->widget(0); + } else if (table == QModbusDataUnit::DiscreteInputs) { + tv = ui_->server_registers_->widget(1); + } else if (table == QModbusDataUnit::InputRegisters) { + tv = ui_->server_registers_->widget(2); + } else if (table == QModbusDataUnit::HoldingRegisters) { + tv = ui_->server_registers_->widget(3); } else { - cookedColor = "black"; + tv = ui_->server_registers_->widget(3); + qCWarning(kLoggingCategory) << "Get table view failed: unknow register type!"; } - } - cookedMsg += - flag.isEmpty() - ? "" - : QString("[%2] ").arg(cookedColor, flag); - cookedMsg += msg; - ui_->text_browser_->append(cookedMsg); + return qobject_cast(tv); } -bool SAKModbusUi::IsConnected() { - if (SAKModbusFactory::Instance()->IsConnected(modbus_device_)) { +QList SAKModbusUi::GetTableValues(QTableView *table_view, int row, int count) +{ + if (!table_view) { + qCWarning(kLoggingCategory) << "Table view can not be null!"; + return QList(); + } + + auto *model = qobject_cast(table_view->model()); + if (!model) { + qCWarning(kLoggingCategory) << "Model can not be null!"; + return QList(); + } + + QList values; + for (int i = row; i < count; i++) { + QStandardItem *item = model->item(i, 1); + if (item) { + QString text = item->text(); + values.append(text.toInt(Q_NULLPTR, 16)); + } else { + values.append(0); + } + } + + return values; +} + +void SAKModbusUi::OutputModbusReply(QModbusReply *reply, int function_code) +{ + if (reply->error() != QModbusDevice::NoError) { + OutputMessage(reply->errorString(), true, "", "error"); + QMessageBox::warning(this, tr("Error occured"), reply->errorString()); + return; + } + + int server_address = reply->serverAddress(); + if (reply->type() == QModbusReply::ReplyType::Raw) { + QByteArray data = reply->rawResult().data(); + QString info = QString("(from address: %1, " + "function code: %2), " + "data unit: %3") + .arg(server_address) + .arg(function_code) + .arg(QString::fromLatin1(data.toHex(' '))); + OutputMessage(info, false, RXCOLOR, RXFLAG); + } else if (reply->type() == QModbusReply::ReplyType::Common) { + QString info = ui_->function_code_->currentText(); + OutputMessage(info, false, RXCOLOR, RXFLAG); + } +} + +void SAKModbusUi::OutputMessage(const QString &msg, + bool isError, + const QString &color, + const QString &flag) +{ + QString cookedMsg = QDateTime::currentDateTime().toString("hh:mm:ss.zzz"); + cookedMsg = QString("%1 ").arg(cookedMsg); + + QString cookedColor = color; + if (cookedColor.isEmpty()) { + if (isError) { + cookedColor = "red"; + } else { + cookedColor = "black"; + } + } + + cookedMsg += flag.isEmpty() ? "" + : QString("[%2] ").arg(cookedColor, flag); + cookedMsg += msg; + ui_->text_browser_->append(cookedMsg); +} + +bool SAKModbusUi::IsConnected() +{ + if (SAKModbusFactory::Instance()->IsConnected(modbus_device_)) { + return true; + } + + QMessageBox::warning(this, + tr("Device is not Ready"), + tr("The modbus device is not ready, " + "please check settings and try again later!")); + return false; +} + +bool SAKModbusUi::WriteSettingsArray( + const QString &group, const QString &key, const QString &value, int index, int max_index) +{ + settings_->beginWriteArray(group); + for (int i = 0; i < max_index; i++) { + settings_->setArrayIndex(i); + QString v = settings_->value(key).toString(); + if (v == value) { + settings_->endArray(); + return false; + } + } + + settings_->setArrayIndex(index); + settings_->setValue(key, value); + settings_->endArray(); return true; - } - - QMessageBox::warning(this, tr("Device is not Ready"), - tr("The modbus device is not ready, " - "please check settings and try again later!")); - return false; -} - -bool SAKModbusUi::WriteSettingsArray(const QString &group, const QString &key, - const QString &value, int index, - int max_index) { - settings_->beginWriteArray(group); - for (int i = 0; i < max_index; i++) { - settings_->setArrayIndex(i); - QString v = settings_->value(key).toString(); - if (v == value) { - settings_->endArray(); - return false; - } - } - - settings_->setArrayIndex(index); - settings_->setValue(key, value); - settings_->endArray(); - return true; } diff --git a/src/modbusstudio/modbusstudioui/sakmodbusui.h b/src/modbusstudio/modbusstudioui/sakmodbusui.h index 9c8b6f50..675c7979 100644 --- a/src/modbusstudio/modbusstudioui/sakmodbusui.h +++ b/src/modbusstudio/modbusstudioui/sakmodbusui.h @@ -27,112 +27,113 @@ class SAKModbusUi; } struct SAKModbusUiSettingKeys; -class SAKModbusUi : public QWidget { - Q_OBJECT - public: - explicit SAKModbusUi(QWidget *parent = Q_NULLPTR); - ~SAKModbusUi(); +class SAKModbusUi : public QWidget +{ + Q_OBJECT +public: + explicit SAKModbusUi(QWidget *parent = Q_NULLPTR); + ~SAKModbusUi(); - signals: - void deviceChanged(QModbusDevice *device); +signals: + void deviceChanged(QModbusDevice *device); - private: - Ui::SAKModbusUi *ui_; - QModbusDevice *modbus_device_{Q_NULLPTR}; - QSettings *settings_{Q_NULLPTR}; - QStandardItemModel *register_model_{Q_NULLPTR}; - const QLoggingCategory kLoggingCategory{"SAK.Modbus"}; - SAKModbusUiSettingKeys *key_ctx_; +private: + Ui::SAKModbusUi *ui_; + QModbusDevice *modbus_device_{Q_NULLPTR}; + QSettings *settings_{Q_NULLPTR}; + QStandardItemModel *register_model_{Q_NULLPTR}; + const QLoggingCategory kLoggingCategory{"SAK.Modbus"}; + SAKModbusUiSettingKeys *key_ctx_; - private: - void InitComponents(); - void InitComponentDevices(); - void InitComponentAddress(); - void InitComponentPortName(); - void InitComponnetBaudRate(); - void InitComponnetDataBits(); - void InitComponnetStopBits(); - void InitComponnetParity(); - void InitComponentFunctionCode(); - void InitComponentRegisterTableView(); - void InitComponentInput(); - void InitComponentRegisterTabWidget(); +private: + void InitComponents(); + void InitComponentDevices(); + void InitComponentAddress(); + void InitComponentPortName(); + void InitComponnetBaudRate(); + void InitComponnetDataBits(); + void InitComponnetStopBits(); + void InitComponnetParity(); + void InitComponentFunctionCode(); + void InitComponentRegisterTableView(); + void InitComponentInput(); + void InitComponentRegisterTabWidget(); - void InitSettings(); - void InitSettingsDevice(); - void InitSettingsNetwork(); - void InitSettingsSerialPort(); - void InitSettingsClient(); - void InitSettingsServer(); - void InitSettingsClientOperations(); - void InitSettingsInput(); + void InitSettings(); + void InitSettingsDevice(); + void InitSettingsNetwork(); + void InitSettingsSerialPort(); + void InitSettingsClient(); + void InitSettingsServer(); + void InitSettingsClientOperations(); + void InitSettingsInput(); - void InitSignals(); - void InitSignalsDevice(); - void InitSignalsNetworking(); - void InitSignalsSerialPort(); - void InitSignalsClient(); - void InitSignalsServer(); - void InitSignalsClientOperations(); + void InitSignals(); + void InitSignalsDevice(); + void InitSignalsNetworking(); + void InitSignalsSerialPort(); + void InitSignalsClient(); + void InitSignalsServer(); + void InitSignalsClientOperations(); - void OnErrorOccurred(); - void OnDeviceTypeChanged(); - void OnCloseClicked(); - void OnOpenClicked(); - void OnAddressChanged(); - void OnPortChanged(); - void OnCustomAddressChanged(); - void OnPortNameChanged(); - void OnParityChanged(); - void OnBaudRateChanged(); - void OnDataBitsChanged(); - void OnStopBistChanged(); - void OnInvokeRefresh(); - void OnClientTimeoutChanged(); - void OnClientRepeatTimeChanged(); - void OnServerIsBusyChanged(); - void OnServerJustListenChanged(); - void OnServerAddressChanged(); - void OnFunctionCodeChanged(); - void OnTargetAddressChanged(); - void OnStartAddressChanged(); - void OnAddressNumberChanged(); + void OnErrorOccurred(); + void OnDeviceTypeChanged(); + void OnCloseClicked(); + void OnOpenClicked(); + void OnAddressChanged(); + void OnPortChanged(); + void OnCustomAddressChanged(); + void OnPortNameChanged(); + void OnParityChanged(); + void OnBaudRateChanged(); + void OnDataBitsChanged(); + void OnStopBistChanged(); + void OnInvokeRefresh(); + void OnClientTimeoutChanged(); + void OnClientRepeatTimeChanged(); + void OnServerIsBusyChanged(); + void OnServerJustListenChanged(); + void OnServerAddressChanged(); + void OnFunctionCodeChanged(); + void OnTargetAddressChanged(); + void OnStartAddressChanged(); + void OnAddressNumberChanged(); - void OnReadClicked(); - void OnWriteClicked(); - void OnSendClicked(); + void OnReadClicked(); + void OnWriteClicked(); + void OnSendClicked(); - void OnDateWritten(QModbusDataUnit::RegisterType table, int address, - int size); - void OnItemChanged(QStandardItem *item); + void OnDateWritten(QModbusDataUnit::RegisterType table, int address, int size); + void OnItemChanged(QStandardItem *item); - private: - QModbusDevice *CreateModbusDevice(); - QTableView *CreateTableView(int row_count, QTableView *table_view); +private: + QModbusDevice *CreateModbusDevice(); + QTableView *CreateTableView(int row_count, QTableView *table_view); - void UpdateUiState(bool connected); - void UpdateClientTableView(); - void UpdateClientTableViewData(const QList &values); - void UpdateClientReadWriteButtonState(); - void UpdateClientParameters(); - void UpdateClientTableViewAddress(QTableView *view, int start_address); - void UpdateServerParameters(); - bool UpdateServerMap(QModbusDevice *server); - void UpdateServerRegistersData(); + void UpdateUiState(bool connected); + void UpdateClientTableView(); + void UpdateClientTableViewData(const QList &values); + void UpdateClientReadWriteButtonState(); + void UpdateClientParameters(); + void UpdateClientTableViewAddress(QTableView *view, int start_address); + void UpdateServerParameters(); + bool UpdateServerMap(QModbusDevice *server); + void UpdateServerRegistersData(); - quint8 GetClientFunctionCode(); - QList GetClientRegisterValue(); - QByteArray GetClientPdu(); - QTableView *GetTableView(QModbusDataUnit::RegisterType table); - QList GetTableValues(QTableView *table_view, int row, int count); + quint8 GetClientFunctionCode(); + QList GetClientRegisterValue(); + QByteArray GetClientPdu(); + QTableView *GetTableView(QModbusDataUnit::RegisterType table); + QList GetTableValues(QTableView *table_view, int row, int count); - void OutputModbusReply(QModbusReply *reply, int function_code); - void OutputMessage(const QString &msg, bool isError, - const QString &color = QString(), - const QString &flag = QString()); - bool IsConnected(); - bool WriteSettingsArray(const QString &group, const QString &key, - const QString &value, int index, int max_index); + void OutputModbusReply(QModbusReply *reply, int function_code); + void OutputMessage(const QString &msg, + bool isError, + const QString &color = QString(), + const QString &flag = QString()); + bool IsConnected(); + bool WriteSettingsArray( + const QString &group, const QString &key, const QString &value, int index, int max_index); }; -#endif // SAKMODBUSUI_H +#endif // SAKMODBUSUI_H diff --git a/src/preferences/preferences/SAKPreferences.cc b/src/preferences/preferences/SAKPreferences.cc index 77b2a6b1..2ccf7408 100644 --- a/src/preferences/preferences/SAKPreferences.cc +++ b/src/preferences/preferences/SAKPreferences.cc @@ -11,6 +11,4 @@ SAKPreferences::SAKPreferences(QObject *parent) : QObject{parent} -{ - -} +{} diff --git a/src/preferences/preferences/SAKPreferences.h b/src/preferences/preferences/SAKPreferences.h index 7ff49eb8..e3023c10 100644 --- a/src/preferences/preferences/SAKPreferences.h +++ b/src/preferences/preferences/SAKPreferences.h @@ -19,7 +19,6 @@ public: explicit SAKPreferences(QObject *parent = nullptr); signals: - }; #endif // SAKPREFERENCES_HH diff --git a/src/preferences/preferencesui/SAKPreferencesUi.cc b/src/preferences/preferencesui/SAKPreferencesUi.cc index 47e0eea6..37a5c5c4 100644 --- a/src/preferences/preferencesui/SAKPreferencesUi.cc +++ b/src/preferences/preferencesui/SAKPreferencesUi.cc @@ -10,9 +10,9 @@ #include "SAKPreferencesUi.hh" #include "ui_SAKPreferencesUi.h" -SAKPreferencesUi::SAKPreferencesUi(QWidget *parent) : - QWidget(parent), - ui(new Ui::SAKPreferencesUi) +SAKPreferencesUi::SAKPreferencesUi(QWidget *parent) + : QWidget(parent) + , ui(new Ui::SAKPreferencesUi) { ui->setupUi(this); } diff --git a/src/sakapplication.cc b/src/sakapplication.cc index ad20a3fa..e2b3aafe 100644 --- a/src/sakapplication.cc +++ b/src/sakapplication.cc @@ -35,102 +35,109 @@ #include "saksystemtrayicon.h" #include "saktranslator.h" -QDate buildDate = - QLocale(QLocale::English) - .toDate(QString(__DATE__).replace(" ", " 0"), "MMM dd yyyy"); +QDate buildDate = QLocale(QLocale::English) + .toDate(QString(__DATE__).replace(" ", " 0"), "MMM dd yyyy"); QTime buildTime = QTime::fromString(__TIME__, "hh:mm:ss"); SAKApplication::SAKApplication(int argc, char** argv) - : QApplication(argc, argv) { - // It can avoid app crash in this way to show a splashScreen. - // If you new a QSplashScreen and show it in the main function, - // app will crash(test on Ubuntu 16.04). - // Of course, it is because that I use a wrong way, - // also, it could be a bug of Qt. - QPixmap pixmap(":/resources/images/StartUi.jpg"); - mSplashScreen = new QSplashScreen(pixmap); - showSplashScreenMessage(tr("Initializing...")); - mSplashScreen->show(); - processEvents(); + : QApplication(argc, argv) +{ + // It can avoid app crash in this way to show a splashScreen. + // If you new a QSplashScreen and show it in the main function, + // app will crash(test on Ubuntu 16.04). + // Of course, it is because that I use a wrong way, + // also, it could be a bug of Qt. + QPixmap pixmap(":/resources/images/StartUi.jpg"); + mSplashScreen = new QSplashScreen(pixmap); + showSplashScreenMessage(tr("Initializing...")); + mSplashScreen->show(); + processEvents(); - // Palete - int ret = SAKSettings::instance()->palette(); - if ((ret == SAKDataStructure::PaletteDark) || - (ret == SAKDataStructure::PaletteLight)) { - QString fileName = (ret == SAKDataStructure::PaletteLight - ? ":/resources/palette/SAKAppPaletteLight" - : ":/resources/palette/SAKAppPaletteDark"); - setupPalette(fileName); - } else { - QString customPalette = SAKSettings::instance()->customPalette(); - if (customPalette.isEmpty()) { - qCInfo(mLoggingCategory) << "current palete: system"; + // Palete + int ret = SAKSettings::instance()->palette(); + if ((ret == SAKDataStructure::PaletteDark) || (ret == SAKDataStructure::PaletteLight)) { + QString fileName = (ret == SAKDataStructure::PaletteLight + ? ":/resources/palette/SAKAppPaletteLight" + : ":/resources/palette/SAKAppPaletteDark"); + setupPalette(fileName); } else { - setupPalette(customPalette); + QString customPalette = SAKSettings::instance()->customPalette(); + if (customPalette.isEmpty()) { + qCInfo(mLoggingCategory) << "current palete: system"; + } else { + setupPalette(customPalette); + } } - } - // Setup ui language. - QString language = SAKSettings::instance()->language(); - SAKTranslator::instance()->setupLanguage(language); - showSplashScreenMessage(tr("Initializing main window...")); + // Setup ui language. + QString language = SAKSettings::instance()->language(); + SAKTranslator::instance()->setupLanguage(language); + showSplashScreenMessage(tr("Initializing main window...")); - SAKMainWindow* mainWindow = new SAKMainWindow(); - mSplashScreen->finish(mainWindow); - QObject::connect(this, &SAKApplication::activeMainWindow, mainWindow, - &SAKMainWindow::activateWindow); - mainWindow->show(); + SAKMainWindow* mainWindow = new SAKMainWindow(); + mSplashScreen->finish(mainWindow); + QObject::connect(this, + &SAKApplication::activeMainWindow, + mainWindow, + &SAKMainWindow::activateWindow); + mainWindow->show(); #ifdef Q_OS_WIN - // Setup system tray icon. - SAKSystemTrayIcon* systemTrayIcon = new SAKSystemTrayIcon(qApp); - QObject::connect(systemTrayIcon, &SAKSystemTrayIcon::invokeExit, qApp, - [=]() { mainWindow->close(); }); - QObject::connect(systemTrayIcon, &SAKSystemTrayIcon::invokeShowMainWindow, - qApp, [=]() { mainWindow->show(); }); - systemTrayIcon->show(); + // Setup system tray icon. + SAKSystemTrayIcon* systemTrayIcon = new SAKSystemTrayIcon(qApp); + QObject::connect(systemTrayIcon, &SAKSystemTrayIcon::invokeExit, qApp, [=]() { + mainWindow->close(); + }); + QObject::connect(systemTrayIcon, &SAKSystemTrayIcon::invokeShowMainWindow, qApp, [=]() { + mainWindow->show(); + }); + systemTrayIcon->show(); #endif - // Move the window to the screen central. + // Move the window to the screen central. #ifndef Q_OS_ANDROID - mainWindow->resize(mainWindow->height() * 1.732, mainWindow->height()); + mainWindow->resize(mainWindow->height() * 1.732, mainWindow->height()); #endif - QRect screenRect = QGuiApplication::primaryScreen()->geometry(); - bool tooWidth = (mainWindow->width() > screenRect.width()); - bool tooHeight = (mainWindow->height() > screenRect.height()); - if (tooWidth || tooHeight) { - mainWindow->showMaximized(); - qCInfo(mLoggingCategory) << "too small screen"; - } else { - mainWindow->move((screenRect.width() - mainWindow->width()) / 2, - (screenRect.height() - mainWindow->height()) / 2); - } - showSplashScreenMessage(tr("Finished...")); + QRect screenRect = QGuiApplication::primaryScreen()->geometry(); + bool tooWidth = (mainWindow->width() > screenRect.width()); + bool tooHeight = (mainWindow->height() > screenRect.height()); + if (tooWidth || tooHeight) { + mainWindow->showMaximized(); + qCInfo(mLoggingCategory) << "too small screen"; + } else { + mainWindow->move((screenRect.width() - mainWindow->width()) / 2, + (screenRect.height() - mainWindow->height()) / 2); + } + showSplashScreenMessage(tr("Finished...")); - QString msg = QString("the size of main window is: %1x%2") - .arg(mainWindow->width()) - .arg(mainWindow->height()); - qCInfo(mLoggingCategory) << qPrintable(msg); + QString msg = QString("the size of main window is: %1x%2") + .arg(mainWindow->width()) + .arg(mainWindow->height()); + qCInfo(mLoggingCategory) << qPrintable(msg); } SAKApplication::~SAKApplication() {} -QSplashScreen* SAKApplication::splashScreen() { return mSplashScreen; } - -void SAKApplication::showSplashScreenMessage(QString msg) { - mSplashScreen->showMessage(msg, Qt::AlignBottom, QColor(255, 255, 255)); +QSplashScreen* SAKApplication::splashScreen() +{ + return mSplashScreen; } -void SAKApplication::setupPalette(const QString& fileName) { - QFile file(fileName); - if (file.open(QFile::ReadOnly)) { - QDataStream out(&file); - QPalette p; - out >> p; - file.close(); - setPalette(p); - qCInfo(mLoggingCategory) << "current palete:" << fileName; - } else { - qCWarning(mLoggingCategory) - << "open palette file error:" << file.errorString(); - } +void SAKApplication::showSplashScreenMessage(QString msg) +{ + mSplashScreen->showMessage(msg, Qt::AlignBottom, QColor(255, 255, 255)); +} + +void SAKApplication::setupPalette(const QString& fileName) +{ + QFile file(fileName); + if (file.open(QFile::ReadOnly)) { + QDataStream out(&file); + QPalette p; + out >> p; + file.close(); + setPalette(p); + qCInfo(mLoggingCategory) << "current palete:" << fileName; + } else { + qCWarning(mLoggingCategory) << "open palette file error:" << file.errorString(); + } } diff --git a/src/sakapplication.h b/src/sakapplication.h index 403f4a5a..54cae61f 100644 --- a/src/sakapplication.h +++ b/src/sakapplication.h @@ -11,12 +11,12 @@ #define SAKAPPLICATION_H #include -#include #include +#include #define sakApp (static_cast(QCoreApplication::instance())) -class SAKApplication:public QApplication +class SAKApplication : public QApplication { Q_OBJECT public: diff --git a/src/sakmainwindow.h b/src/sakmainwindow.h index bd50993c..7481bf59 100644 --- a/src/sakmainwindow.h +++ b/src/sakmainwindow.h @@ -28,57 +28,59 @@ namespace Ui { class SAKMainWindow; } -class SAKMainWindow : public QMainWindow { - Q_OBJECT - public: - explicit SAKMainWindow(QWidget* parent = Q_NULLPTR); - ~SAKMainWindow(); +class SAKMainWindow : public QMainWindow +{ + Q_OBJECT +public: + explicit SAKMainWindow(QWidget* parent = Q_NULLPTR); + ~SAKMainWindow(); #ifdef Q_OS_WIN - protected: - void closeEvent(QCloseEvent* event); +protected: + void closeEvent(QCloseEvent* event); #endif - private: - struct SettingsKeyContext { - const QString exitToSystemTray{"MainWindow/exitToSystemTray"}; - } mSettingsKey; - const QLoggingCategory mLoggingCategory{"sak.mainwindow"}; - Ui::SAKMainWindow* ui; +private: + struct SettingsKeyContext + { + const QString exitToSystemTray{"MainWindow/exitToSystemTray"}; + } mSettingsKey; + const QLoggingCategory mLoggingCategory{"sak.mainwindow"}; + Ui::SAKMainWindow* ui; - private: - void initMenuBar(); - void initFileMenu(); - void initToolMenu(); - void initOptionMenu(); - void initOptionMenuAppStyleMenu(QMenu* optionMenu); - void initOptionMenuMainWindowMenu(QMenu* optionMenu); - void initOptionMenuSettingsMenu(QMenu* optionMenu); +private: + void initMenuBar(); + void initFileMenu(); + void initToolMenu(); + void initOptionMenu(); + void initOptionMenuAppStyleMenu(QMenu* optionMenu); + void initOptionMenuMainWindowMenu(QMenu* optionMenu); + void initOptionMenuSettingsMenu(QMenu* optionMenu); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - void initOptionMenuHdpiPolicy(QMenu* optionMenu); + void initOptionMenuHdpiPolicy(QMenu* optionMenu); #endif - void initOptionMenuPalette(QMenu* optionMenu); - void initWindowMenu(); - void initLanguageMenu(); - void initHelpMenu(); - void initLinksMenu(); - void initDemoMenu(); - void initNav(); - void initNav(QButtonGroup* bg, const QIcon& icon, const QString& name, - QWidget* page, QToolBar* tb); - void initStatusBar(); + void initOptionMenuPalette(QMenu* optionMenu); + void initWindowMenu(); + void initLanguageMenu(); + void initHelpMenu(); + void initLinksMenu(); + void initDemoMenu(); + void initNav(); + void initNav( + QButtonGroup* bg, const QIcon& icon, const QString& name, QWidget* page, QToolBar* tb); + void initStatusBar(); - void aboutSoftware(); - void clearConfiguration(); - void rebootRequestion(); - void showHistory(); - void showQrCode(); - void showDonation(); - void createQtConf(); + void aboutSoftware(); + void clearConfiguration(); + void rebootRequestion(); + void showHistory(); + void showQrCode(); + void showDonation(); + void createQtConf(); - private slots: - void onImportActionTriggered(); - void onExportActionTriggered(); +private slots: + void onImportActionTriggered(); + void onExportActionTriggered(); }; -#endif // MAINWINDOW_H +#endif // MAINWINDOW_H diff --git a/src/saksystemtrayicon.cc b/src/saksystemtrayicon.cc index 6403450a..9d95482b 100644 --- a/src/saksystemtrayicon.cc +++ b/src/saksystemtrayicon.cc @@ -7,10 +7,10 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ +#include "saksystemtrayicon.h" +#include #include #include -#include -#include "saksystemtrayicon.h" SAKSystemTrayIcon::SAKSystemTrayIcon(QObject *parent) : QSystemTrayIcon(parent) @@ -19,10 +19,9 @@ SAKSystemTrayIcon::SAKSystemTrayIcon(QObject *parent) setToolTip(tr("Qt Swiss Army Knife")); QMenu *menu = new QMenu(); - menu->addAction(tr("Open main window"), this, - [=](){emit invokeShowMainWindow();}); + menu->addAction(tr("Open main window"), this, [=]() { emit invokeShowMainWindow(); }); menu->addSeparator(); - menu->addAction(tr("Exit program"), this, [=](){emit invokeExit();}); + menu->addAction(tr("Exit program"), this, [=]() { emit invokeExit(); }); setContextMenu(menu); } diff --git a/src/toolbox/toolbox/saktoolbox.cc b/src/toolbox/toolbox/saktoolbox.cc index 2192e3f2..8c35f22e 100644 --- a/src/toolbox/toolbox/saktoolbox.cc +++ b/src/toolbox/toolbox/saktoolbox.cc @@ -11,308 +11,405 @@ #include "saktoolfactory.h" -SAKToolBox::SAKToolBox(QObject* parent) : QObject{parent} { - auto createTool = [](int type) -> SAKBaseTool* { +SAKToolBox::SAKToolBox(QObject* parent) + : QObject{parent} +{ + auto createTool = [](int type) -> SAKBaseTool* { + auto toolFactory = SAKToolFactory::instance(); + return toolFactory->createTool(type); + }; + + SAKBaseTool* tool = createTool(SAKToolFactory::MaskerTool); + mTxMaskerTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::MaskerTool); + mRxMaskerTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::AnalyzerTool); + mTxAnalyzerTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::AnalyzerTool); + mRxAnalyzerTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::EmitterTool); + mEmitterTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::ResponserTool); + mResponserTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::StorerTool); + mStorerTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::PrestoreTool); + mPrestorerTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::VelometerTool); + mRxVelometerTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::VelometerTool); + mTxVelometerTool = qobject_cast(tool); + + tool = createTool(SAKToolFactory::StatistiticianTool); + mRxStatisticianTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::StatistiticianTool); + mTxStatisticianTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::UdpTransmitterTool); + mUdpTransmitterTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::TcpTransmitterTool); + mTcpTransmitterTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::WebSocketTransmitterTool); + mWebSocketTransmitterTool = qobject_cast(tool); + tool = createTool(SAKToolFactory::SerialPortTransmitterTool); + mSerialPortTransmitterTool = qobject_cast(tool); + + mToolList << mTxMaskerTool << mRxMaskerTool << mTxAnalyzerTool << mRxAnalyzerTool + << mEmitterTool << mResponserTool << mStorerTool << mPrestorerTool << mRxVelometerTool + << mTxVelometerTool << mRxStatisticianTool << mTxStatisticianTool + << mUdpTransmitterTool << mTcpTransmitterTool << mWebSocketTransmitterTool + << mSerialPortTransmitterTool; + + int flag = Qt::AutoConnection | Qt::UniqueConnection; + for (auto tool : mToolList) { + connect(tool, + &SAKBaseTool::errorOccured, + this, + &SAKToolBox::errorOccurred, + Qt::ConnectionType(flag)); + } + + connect(this, &SAKToolBox::errorOccurred, this, [=]() { this->close(); }); +} + +SAKToolBox::~SAKToolBox() +{ + if (mComunicationTool) { + mComunicationTool->exit(); + mComunicationTool->wait(); + mComunicationTool->deleteLater(); + } + + for (auto tool : mToolList) { + tool->exit(); + tool->wait(); + tool->deleteLater(); + } +} + +void SAKToolBox::initialize(int type) +{ + if (mComunicationTool) { + mComunicationTool->exit(); + mComunicationTool->wait(); + mComunicationTool->deleteLater(); + mComunicationTool = nullptr; + } + auto toolFactory = SAKToolFactory::instance(); - return toolFactory->createTool(type); - }; - - SAKBaseTool* tool = createTool(SAKToolFactory::MaskerTool); - mTxMaskerTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::MaskerTool); - mRxMaskerTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::AnalyzerTool); - mTxAnalyzerTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::AnalyzerTool); - mRxAnalyzerTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::EmitterTool); - mEmitterTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::ResponserTool); - mResponserTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::StorerTool); - mStorerTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::PrestoreTool); - mPrestorerTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::VelometerTool); - mRxVelometerTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::VelometerTool); - mTxVelometerTool = qobject_cast(tool); - - tool = createTool(SAKToolFactory::StatistiticianTool); - mRxStatisticianTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::StatistiticianTool); - mTxStatisticianTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::UdpTransmitterTool); - mUdpTransmitterTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::TcpTransmitterTool); - mTcpTransmitterTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::WebSocketTransmitterTool); - mWebSocketTransmitterTool = qobject_cast(tool); - tool = createTool(SAKToolFactory::SerialPortTransmitterTool); - mSerialPortTransmitterTool = - qobject_cast(tool); - - mToolList << mTxMaskerTool << mRxMaskerTool << mTxAnalyzerTool - << mRxAnalyzerTool << mEmitterTool << mResponserTool << mStorerTool - << mPrestorerTool << mRxVelometerTool << mTxVelometerTool - << mRxStatisticianTool << mTxStatisticianTool << mUdpTransmitterTool - << mTcpTransmitterTool << mWebSocketTransmitterTool - << mSerialPortTransmitterTool; - - int flag = Qt::AutoConnection | Qt::UniqueConnection; - for (auto tool : mToolList) { - connect(tool, &SAKBaseTool::errorOccured, this, &SAKToolBox::errorOccurred, - Qt::ConnectionType(flag)); - } - - connect(this, &SAKToolBox::errorOccurred, this, [=]() { this->close(); }); -} - -SAKToolBox::~SAKToolBox() { - if (mComunicationTool) { - mComunicationTool->exit(); - mComunicationTool->wait(); - mComunicationTool->deleteLater(); - } - - for (auto tool : mToolList) { - tool->exit(); - tool->wait(); - tool->deleteLater(); - } -} - -void SAKToolBox::initialize(int type) { - if (mComunicationTool) { - mComunicationTool->exit(); - mComunicationTool->wait(); - mComunicationTool->deleteLater(); - mComunicationTool = nullptr; - } - - auto toolFactory = SAKToolFactory::instance(); - auto tool = toolFactory->createTool(type); - mComunicationTool = qobject_cast(tool); - if (!mComunicationTool) { - qCWarning(mLoggingCategory) - << "mComunicationTool is nullptr, type:" << type; - return; - } - - // rx->output_masker->output_analyzer->emmitter,responser - connect(mComunicationTool, &SAKBaseTool::bytesOutputted, mRxMaskerTool, - &SAKBaseTool::inputBytes); - connect(mRxMaskerTool, &SAKBaseTool::bytesOutputted, mRxAnalyzerTool, - &SAKBaseTool::inputBytes); - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mEmitterTool, - &SAKBaseTool::inputBytes); - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mResponserTool, - &SAKBaseTool::inputBytes); - - // emiiter,responser,prestorer->input_analyzer->input_masker->tx - connect(mEmitterTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, - &SAKBaseTool::inputBytes); - connect(mResponserTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, - &SAKBaseTool::inputBytes); - connect(mPrestorerTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, - &SAKBaseTool::inputBytes); - connect(mTxAnalyzerTool, &SAKBaseTool::bytesOutputted, mTxMaskerTool, - &SAKBaseTool::inputBytes); - connect(mTxMaskerTool, &SAKBaseTool::bytesOutputted, mComunicationTool, - &SAKBaseTool::inputBytes); - - // rx->storer; tx->storer - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mStorerTool, - &SAKBaseTool::inputBytes); - connect(mTxMaskerTool, &SAKBaseTool::bytesInputted, mStorerTool, - &SAKBaseTool::inputBytes); - - // rx->velometer; tx->velometer - connect(mComunicationTool, &SAKBaseTool::bytesOutputted, mRxVelometerTool, - &SAKBaseTool::inputBytes); - connect(mComunicationTool, &SAKBaseTool::bytesInputted, mTxVelometerTool, - &SAKBaseTool::inputBytes); - - // rx->statistician; tx->statistician - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mRxStatisticianTool, - &SAKBaseTool::inputBytes); - connect(mComunicationTool, &SAKBaseTool::bytesInputted, mTxStatisticianTool, - &SAKBaseTool::inputBytes); - - // rx->serialport transmition; serialport transmition->Tx analyzer - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, - mSerialPortTransmitterTool, &SAKBaseTool::inputBytes); - connect(mSerialPortTransmitterTool, &SAKBaseTool::bytesOutputted, - mTxAnalyzerTool, &SAKBaseTool::inputBytes); - - // rx->udp transmition; udp transmition->Tx analyzer - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mUdpTransmitterTool, - &SAKBaseTool::inputBytes); - connect(mUdpTransmitterTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, - &SAKBaseTool::inputBytes); - - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mTcpTransmitterTool, - &SAKBaseTool::inputBytes); - connect(mTcpTransmitterTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, - &SAKBaseTool::inputBytes); - - connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, - mWebSocketTransmitterTool, &SAKBaseTool::inputBytes); - connect(mWebSocketTransmitterTool, &SAKBaseTool::bytesOutputted, - mTxAnalyzerTool, &SAKBaseTool::inputBytes); - - connect(mComunicationTool, &SAKCommunicationTool::errorOccured, this, - &SAKToolBox::errorOccurred); - - emit communicatonChanged(); -} - -void SAKToolBox::open() { - if (mComunicationTool) { - for (auto tool : mToolList) { - tool->start(); + auto tool = toolFactory->createTool(type); + mComunicationTool = qobject_cast(tool); + if (!mComunicationTool) { + qCWarning(mLoggingCategory) << "mComunicationTool is nullptr, type:" << type; + return; } - mIsWorking = true; - emit isWorkingChanged(); - mComunicationTool->start(); - } else { - uninitializedTips(); - } + // rx->output_masker->output_analyzer->emmitter,responser + connect(mComunicationTool, + &SAKBaseTool::bytesOutputted, + mRxMaskerTool, + &SAKBaseTool::inputBytes); + connect(mRxMaskerTool, &SAKBaseTool::bytesOutputted, mRxAnalyzerTool, &SAKBaseTool::inputBytes); + connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mEmitterTool, &SAKBaseTool::inputBytes); + connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mResponserTool, &SAKBaseTool::inputBytes); + + // emiiter,responser,prestorer->input_analyzer->input_masker->tx + connect(mEmitterTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, &SAKBaseTool::inputBytes); + connect(mResponserTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, &SAKBaseTool::inputBytes); + connect(mPrestorerTool, &SAKBaseTool::bytesOutputted, mTxAnalyzerTool, &SAKBaseTool::inputBytes); + connect(mTxAnalyzerTool, &SAKBaseTool::bytesOutputted, mTxMaskerTool, &SAKBaseTool::inputBytes); + connect(mTxMaskerTool, + &SAKBaseTool::bytesOutputted, + mComunicationTool, + &SAKBaseTool::inputBytes); + + // rx->storer; tx->storer + connect(mRxAnalyzerTool, &SAKBaseTool::bytesOutputted, mStorerTool, &SAKBaseTool::inputBytes); + connect(mTxMaskerTool, &SAKBaseTool::bytesInputted, mStorerTool, &SAKBaseTool::inputBytes); + + // rx->velometer; tx->velometer + connect(mComunicationTool, + &SAKBaseTool::bytesOutputted, + mRxVelometerTool, + &SAKBaseTool::inputBytes); + connect(mComunicationTool, + &SAKBaseTool::bytesInputted, + mTxVelometerTool, + &SAKBaseTool::inputBytes); + + // rx->statistician; tx->statistician + connect(mRxAnalyzerTool, + &SAKBaseTool::bytesOutputted, + mRxStatisticianTool, + &SAKBaseTool::inputBytes); + connect(mComunicationTool, + &SAKBaseTool::bytesInputted, + mTxStatisticianTool, + &SAKBaseTool::inputBytes); + + // rx->serialport transmition; serialport transmition->Tx analyzer + connect(mRxAnalyzerTool, + &SAKBaseTool::bytesOutputted, + mSerialPortTransmitterTool, + &SAKBaseTool::inputBytes); + connect(mSerialPortTransmitterTool, + &SAKBaseTool::bytesOutputted, + mTxAnalyzerTool, + &SAKBaseTool::inputBytes); + + // rx->udp transmition; udp transmition->Tx analyzer + connect(mRxAnalyzerTool, + &SAKBaseTool::bytesOutputted, + mUdpTransmitterTool, + &SAKBaseTool::inputBytes); + connect(mUdpTransmitterTool, + &SAKBaseTool::bytesOutputted, + mTxAnalyzerTool, + &SAKBaseTool::inputBytes); + + connect(mRxAnalyzerTool, + &SAKBaseTool::bytesOutputted, + mTcpTransmitterTool, + &SAKBaseTool::inputBytes); + connect(mTcpTransmitterTool, + &SAKBaseTool::bytesOutputted, + mTxAnalyzerTool, + &SAKBaseTool::inputBytes); + + connect(mRxAnalyzerTool, + &SAKBaseTool::bytesOutputted, + mWebSocketTransmitterTool, + &SAKBaseTool::inputBytes); + connect(mWebSocketTransmitterTool, + &SAKBaseTool::bytesOutputted, + mTxAnalyzerTool, + &SAKBaseTool::inputBytes); + + connect(mComunicationTool, + &SAKCommunicationTool::errorOccured, + this, + &SAKToolBox::errorOccurred); + + emit communicatonChanged(); } -void SAKToolBox::close() { - if (mComunicationTool) { - mComunicationTool->exit(); - mComunicationTool->wait(); +void SAKToolBox::open() +{ + if (mComunicationTool) { + for (auto tool : mToolList) { + tool->start(); + } - for (auto tool : mToolList) { - tool->exit(); - tool->wait(); + mIsWorking = true; + emit isWorkingChanged(); + mComunicationTool->start(); + } else { + uninitializedTips(); } - - mIsWorking = false; - emit isWorkingChanged(); - } else { - uninitializedTips(); - } } -void SAKToolBox::send(const QByteArray& bytes, const QVariant& context) { - mTxAnalyzerTool->inputBytes(bytes, context); +void SAKToolBox::close() +{ + if (mComunicationTool) { + mComunicationTool->exit(); + mComunicationTool->wait(); + + for (auto tool : mToolList) { + tool->exit(); + tool->wait(); + } + + mIsWorking = false; + emit isWorkingChanged(); + } else { + uninitializedTips(); + } } -bool SAKToolBox::isWorking() { return mIsWorking; } - -SAKCommunicationTool* SAKToolBox::getCommunicationTool() { - return mComunicationTool; +void SAKToolBox::send(const QByteArray& bytes, const QVariant& context) +{ + mTxAnalyzerTool->inputBytes(bytes, context); } -SAKMaskerTool* SAKToolBox::getTxMaskerTool() { return mTxMaskerTool; } - -SAKMaskerTool* SAKToolBox::getRxMaskerTool() { return mRxMaskerTool; } - -SAKAnalyzerTool* SAKToolBox::getTxAnalyzerTool() { return mTxAnalyzerTool; } - -SAKAnalyzerTool* SAKToolBox::getRxAnalyzerTool() { return mRxAnalyzerTool; } - -SAKEmitterTool* SAKToolBox::getEmitterTool() { return mEmitterTool; } - -SAKResponserTool* SAKToolBox::getResponserTool() { return mResponserTool; } - -SAKStorerTool* SAKToolBox::getStorerTool() { return mStorerTool; } - -SAKPrestorerTool* SAKToolBox::getPrestorerTool() { return mPrestorerTool; } - -SAKVelometerTool* SAKToolBox::getRxVelometerTool() { return mRxVelometerTool; } - -SAKVelometerTool* SAKToolBox::getTxVelometerTool() { return mTxVelometerTool; } - -SAKStatisticianTool* SAKToolBox::getRxStatisticianTool() { - return mRxStatisticianTool; +bool SAKToolBox::isWorking() +{ + return mIsWorking; } -SAKStatisticianTool* SAKToolBox::getTxStatisticianTool() { - return mTxStatisticianTool; +SAKCommunicationTool* SAKToolBox::getCommunicationTool() +{ + return mComunicationTool; } -SAKUdpTransmitterTool* SAKToolBox::getUdpTransmitterTool() { - return mUdpTransmitterTool; +SAKMaskerTool* SAKToolBox::getTxMaskerTool() +{ + return mTxMaskerTool; } -SAKTcpTransmitterTool* SAKToolBox::getTcpTransmitterTool() { - return mTcpTransmitterTool; +SAKMaskerTool* SAKToolBox::getRxMaskerTool() +{ + return mRxMaskerTool; } -SAKWebSocketTransmitterTool* SAKToolBox::getWebSocketTransmitterTool() { - return mWebSocketTransmitterTool; +SAKAnalyzerTool* SAKToolBox::getTxAnalyzerTool() +{ + return mTxAnalyzerTool; } -SAKSerialPortTransmitterTool* SAKToolBox::getSerialPortTransmitterTool() { - return mSerialPortTransmitterTool; +SAKAnalyzerTool* SAKToolBox::getRxAnalyzerTool() +{ + return mRxAnalyzerTool; } -void SAKToolBox::uninitializedTips() { - static QByteArray tips( - "You must call the interface name initialize()" - " before using the object."); - Q_ASSERT_X(false, __FUNCTION__, tips.constData()); - - emit errorOccurred(QString::fromLatin1(tips)); +SAKEmitterTool* SAKToolBox::getEmitterTool() +{ + return mEmitterTool; } -QVariant SAKToolBox::communicaton() { - return QVariant::fromValue(mComunicationTool); +SAKResponserTool* SAKToolBox::getResponserTool() +{ + return mResponserTool; } -QVariant SAKToolBox::txMasker() { return QVariant::fromValue(mTxMaskerTool); } - -QVariant SAKToolBox::rxMasker() { return QVariant::fromValue(mRxMaskerTool); } - -QVariant SAKToolBox::txAnalyzer() { - return QVariant::fromValue(mTxAnalyzerTool); +SAKStorerTool* SAKToolBox::getStorerTool() +{ + return mStorerTool; } -QVariant SAKToolBox::rxAnalyzer() { - return QVariant::fromValue(mRxAnalyzerTool); +SAKPrestorerTool* SAKToolBox::getPrestorerTool() +{ + return mPrestorerTool; } -QVariant SAKToolBox::emitter() { return QVariant::fromValue(mEmitterTool); } - -QVariant SAKToolBox::responser() { return QVariant::fromValue(mResponserTool); } - -QVariant SAKToolBox::storer() { return QVariant::fromValue(mStorerTool); } - -QVariant SAKToolBox::prestorer() { return QVariant::fromValue(mPrestorerTool); } - -QVariant SAKToolBox::rxVelometer() { - return QVariant::fromValue(mRxVelometerTool); +SAKVelometerTool* SAKToolBox::getRxVelometerTool() +{ + return mRxVelometerTool; } -QVariant SAKToolBox::txVelometer() { - return QVariant::fromValue(mTxVelometerTool); +SAKVelometerTool* SAKToolBox::getTxVelometerTool() +{ + return mTxVelometerTool; } -QVariant SAKToolBox::rxStatistician() { - return QVariant::fromValue(mRxStatisticianTool); +SAKStatisticianTool* SAKToolBox::getRxStatisticianTool() +{ + return mRxStatisticianTool; } -QVariant SAKToolBox::txStatistician() { - return QVariant::fromValue(mTxStatisticianTool); +SAKStatisticianTool* SAKToolBox::getTxStatisticianTool() +{ + return mTxStatisticianTool; } -QVariant SAKToolBox::udpTransmitter() { - return QVariant::fromValue(mUdpTransmitterTool); +SAKUdpTransmitterTool* SAKToolBox::getUdpTransmitterTool() +{ + return mUdpTransmitterTool; } -QVariant SAKToolBox::tcpTransmitter() { - return QVariant::fromValue(mTcpTransmitterTool); +SAKTcpTransmitterTool* SAKToolBox::getTcpTransmitterTool() +{ + return mTcpTransmitterTool; } -QVariant SAKToolBox::webSocketTransmitter() { - return QVariant::fromValue(mWebSocketTransmitterTool); +SAKWebSocketTransmitterTool* SAKToolBox::getWebSocketTransmitterTool() +{ + return mWebSocketTransmitterTool; } -QVariant SAKToolBox::serialPortTransmitter() { - return QVariant::fromValue(mSerialPortTransmitterTool); +SAKSerialPortTransmitterTool* SAKToolBox::getSerialPortTransmitterTool() +{ + return mSerialPortTransmitterTool; +} + +void SAKToolBox::uninitializedTips() +{ + static QByteArray tips("You must call the interface name initialize()" + " before using the object."); + Q_ASSERT_X(false, __FUNCTION__, tips.constData()); + + emit errorOccurred(QString::fromLatin1(tips)); +} + +QVariant SAKToolBox::communicaton() +{ + return QVariant::fromValue(mComunicationTool); +} + +QVariant SAKToolBox::txMasker() +{ + return QVariant::fromValue(mTxMaskerTool); +} + +QVariant SAKToolBox::rxMasker() +{ + return QVariant::fromValue(mRxMaskerTool); +} + +QVariant SAKToolBox::txAnalyzer() +{ + return QVariant::fromValue(mTxAnalyzerTool); +} + +QVariant SAKToolBox::rxAnalyzer() +{ + return QVariant::fromValue(mRxAnalyzerTool); +} + +QVariant SAKToolBox::emitter() +{ + return QVariant::fromValue(mEmitterTool); +} + +QVariant SAKToolBox::responser() +{ + return QVariant::fromValue(mResponserTool); +} + +QVariant SAKToolBox::storer() +{ + return QVariant::fromValue(mStorerTool); +} + +QVariant SAKToolBox::prestorer() +{ + return QVariant::fromValue(mPrestorerTool); +} + +QVariant SAKToolBox::rxVelometer() +{ + return QVariant::fromValue(mRxVelometerTool); +} + +QVariant SAKToolBox::txVelometer() +{ + return QVariant::fromValue(mTxVelometerTool); +} + +QVariant SAKToolBox::rxStatistician() +{ + return QVariant::fromValue(mRxStatisticianTool); +} + +QVariant SAKToolBox::txStatistician() +{ + return QVariant::fromValue(mTxStatisticianTool); +} + +QVariant SAKToolBox::udpTransmitter() +{ + return QVariant::fromValue(mUdpTransmitterTool); +} + +QVariant SAKToolBox::tcpTransmitter() +{ + return QVariant::fromValue(mTcpTransmitterTool); +} + +QVariant SAKToolBox::webSocketTransmitter() +{ + return QVariant::fromValue(mWebSocketTransmitterTool); +} + +QVariant SAKToolBox::serialPortTransmitter() +{ + return QVariant::fromValue(mSerialPortTransmitterTool); } diff --git a/src/toolbox/toolbox/saktoolbox.h b/src/toolbox/toolbox/saktoolbox.h index 61545b61..6c9a1e2b 100644 --- a/src/toolbox/toolbox/saktoolbox.h +++ b/src/toolbox/toolbox/saktoolbox.h @@ -13,26 +13,25 @@ #include #include -#include "sakbasetool.h" -#include "sakmaskertool.h" -#include "sakstorertool.h" -#include "sakemittertool.h" #include "sakanalyzertool.h" +#include "sakbasetool.h" +#include "sakcommunicationtool.h" +#include "sakemittertool.h" +#include "sakmaskertool.h" #include "sakprestorertool.h" #include "sakresponsertool.h" -#include "sakvelometertool.h" -#include "sakstatisticiantool.h" -#include "sakcommunicationtool.h" -#include "sakudptransmittertool.h" -#include "saktcptransmittertool.h" -#include "sakwebsockettransmittertool.h" #include "sakserialporttransmittertool.h" +#include "sakstatisticiantool.h" +#include "sakstorertool.h" +#include "saktcptransmittertool.h" +#include "sakudptransmittertool.h" +#include "sakvelometertool.h" +#include "sakwebsockettransmittertool.h" class SAKToolBox : public QObject { Q_OBJECT - Q_PROPERTY(QVariant communicaton READ communicaton - NOTIFY communicatonChanged) + Q_PROPERTY(QVariant communicaton READ communicaton NOTIFY communicatonChanged) Q_PROPERTY(QVariant txMasker READ txMasker CONSTANT) Q_PROPERTY(QVariant rxMasker READ rxMasker CONSTANT) Q_PROPERTY(QVariant txAnalyzer READ txAnalyzer CONSTANT) @@ -48,14 +47,12 @@ class SAKToolBox : public QObject Q_PROPERTY(QVariant udpTransmitter READ udpTransmitter CONSTANT) Q_PROPERTY(QVariant tcpTransmitter READ tcpTransmitter CONSTANT) - Q_PROPERTY(QVariant webSocketTransmitter READ webSocketTransmitter - CONSTANT) - Q_PROPERTY(QVariant serialPortTransmitter READ serialPortTransmitter - CONSTANT) + Q_PROPERTY(QVariant webSocketTransmitter READ webSocketTransmitter CONSTANT) + Q_PROPERTY(QVariant serialPortTransmitter READ serialPortTransmitter CONSTANT) Q_PROPERTY(bool isWorking READ isWorking NOTIFY isWorkingChanged) public: - explicit SAKToolBox(QObject *parent = nullptr); + explicit SAKToolBox(QObject* parent = nullptr); ~SAKToolBox(); /// You must call the interface before useing. @@ -63,8 +60,7 @@ public: Q_INVOKABLE void open(); Q_INVOKABLE void close(); - Q_INVOKABLE void send(const QByteArray &bytes, - const QVariant &context = QJsonObject()); + Q_INVOKABLE void send(const QByteArray& bytes, const QVariant& context = QJsonObject()); bool isWorking(); SAKCommunicationTool* getCommunicationTool(); @@ -80,22 +76,22 @@ public: SAKVelometerTool* getTxVelometerTool(); SAKStatisticianTool* getRxStatisticianTool(); SAKStatisticianTool* getTxStatisticianTool(); - SAKUdpTransmitterTool * getUdpTransmitterTool(); - SAKTcpTransmitterTool * getTcpTransmitterTool(); + SAKUdpTransmitterTool* getUdpTransmitterTool(); + SAKTcpTransmitterTool* getTcpTransmitterTool(); SAKWebSocketTransmitterTool* getWebSocketTransmitterTool(); SAKSerialPortTransmitterTool* getSerialPortTransmitterTool(); signals: - void errorOccurred(const QString &errorString); + void errorOccurred(const QString& errorString); -private: +private: QList mToolList; const QLoggingCategory mLoggingCategory{"sak.toolbox"}; private: void uninitializedTips(); -// Properties ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ + // Properties ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ private: SAKCommunicationTool* mComunicationTool{nullptr}; SAKMaskerTool* mTxMaskerTool{nullptr}; diff --git a/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.cc b/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.cc index ae227f51..cd7e9234 100644 --- a/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.cc +++ b/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.cc @@ -15,38 +15,43 @@ #include "ui_saktoolboxuicommunicationmenu.h" SAKToolBoxUiCommunicationMenu::SAKToolBoxUiCommunicationMenu(QWidget* parent) - : QMenu(parent), ui(new Ui::SAKToolBoxUiCommunicationMenu) { - QWidget* w = new QWidget(this); - ui->setupUi(w); - QWidgetAction* action = new QWidgetAction(this); - action->setDefaultWidget(w); - addAction(action); + : QMenu(parent) + , ui(new Ui::SAKToolBoxUiCommunicationMenu) +{ + QWidget* w = new QWidget(this); + ui->setupUi(w); + QWidgetAction* action = new QWidgetAction(this); + action->setDefaultWidget(w); + addAction(action); - ui->widgetTxMasker->setToolName("Tx masker"); - ui->widgetRxMasker->setToolName("Rx masker"); - ui->widgetTxAnanyzer->setToolName(tr("Tx analyzer")); - ui->widgetRxAnanlyzer->setToolName(tr("Rx analyzer")); + ui->widgetTxMasker->setToolName("Tx masker"); + ui->widgetRxMasker->setToolName("Rx masker"); + ui->widgetTxAnanyzer->setToolName(tr("Tx analyzer")); + ui->widgetRxAnanlyzer->setToolName(tr("Rx analyzer")); } -SAKToolBoxUiCommunicationMenu::~SAKToolBoxUiCommunicationMenu() { delete ui; } - -void SAKToolBoxUiCommunicationMenu::initialize(SAKToolBox* toolBox, - const QString& settingsGroup) { - auto txM = toolBox->getTxMaskerTool(); - auto rxM = toolBox->getRxMaskerTool(); - auto txA = toolBox->getTxAnalyzerTool(); - auto rxA = toolBox->getRxAnalyzerTool(); - auto storer = toolBox->getStorerTool(); - - auto txMGroup = settingsGroup + "/txMasker"; - auto rxMGroup = settingsGroup + "/rxMasker"; - auto txAGroup = settingsGroup + "/txAnalyzer"; - auto rxAGroup = settingsGroup + "/rxAnalyzer"; - auto storerGroup = settingsGroup + "/storer"; - - ui->widgetRxMasker->initialize(rxM, rxMGroup); - ui->widgetTxMasker->initialize(txM, txMGroup); - ui->widgetTxAnanyzer->initialize(txA, txAGroup); - ui->widgetRxAnanlyzer->initialize(rxA, rxAGroup); - ui->widgetStorer->initialize(storer, storerGroup); +SAKToolBoxUiCommunicationMenu::~SAKToolBoxUiCommunicationMenu() +{ + delete ui; +} + +void SAKToolBoxUiCommunicationMenu::initialize(SAKToolBox* toolBox, const QString& settingsGroup) +{ + auto txM = toolBox->getTxMaskerTool(); + auto rxM = toolBox->getRxMaskerTool(); + auto txA = toolBox->getTxAnalyzerTool(); + auto rxA = toolBox->getRxAnalyzerTool(); + auto storer = toolBox->getStorerTool(); + + auto txMGroup = settingsGroup + "/txMasker"; + auto rxMGroup = settingsGroup + "/rxMasker"; + auto txAGroup = settingsGroup + "/txAnalyzer"; + auto rxAGroup = settingsGroup + "/rxAnalyzer"; + auto storerGroup = settingsGroup + "/storer"; + + ui->widgetRxMasker->initialize(rxM, rxMGroup); + ui->widgetTxMasker->initialize(txM, txMGroup); + ui->widgetTxAnanyzer->initialize(txA, txAGroup); + ui->widgetRxAnanlyzer->initialize(rxA, rxAGroup); + ui->widgetStorer->initialize(storer, storerGroup); } diff --git a/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.h b/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.h index 38cb1252..4f5830c9 100644 --- a/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.h +++ b/src/toolbox/toolboxui/saktoolboxuicommunicationmenu.h @@ -10,9 +10,9 @@ #ifndef SAKTOOLBOXUICOMMUNICATIONMENU_H #define SAKTOOLBOXUICOMMUNICATIONMENU_H +#include #include #include -#include namespace Ui { class SAKToolBoxUiCommunicationMenu; diff --git a/src/toolbox/toolboxui/saktoolboxuifactory.cc b/src/toolbox/toolboxui/saktoolboxuifactory.cc index 8f0ae676..1b9ff11c 100644 --- a/src/toolbox/toolboxui/saktoolboxuifactory.cc +++ b/src/toolbox/toolboxui/saktoolboxuifactory.cc @@ -22,24 +22,29 @@ #include "SAKWebSocketServerToolBoxUi.h" #endif -SAKToolBoxUiFactory::SAKToolBoxUiFactory(QObject* parent) : QObject{parent} {} +SAKToolBoxUiFactory::SAKToolBoxUiFactory(QObject* parent) + : QObject{parent} +{} -SAKToolBoxUiFactory* SAKToolBoxUiFactory::instance() { - static SAKToolBoxUiFactory factory; - return &factory; +SAKToolBoxUiFactory* SAKToolBoxUiFactory::instance() +{ + static SAKToolBoxUiFactory factory; + return &factory; } -QList SAKToolBoxUiFactory::supportedTools() { - QList list; - list << SAKToolFactory::SerialportTool << SAKToolFactory::UdpClientTool - << SAKToolFactory::UdpServerTool << SAKToolFactory::TcpClientTool - << SAKToolFactory::TcpServerTool << SAKToolFactory::WebSocketClientTool - << SAKToolFactory::WebSocketServerTool << SAKToolFactory::BleCentralTool - << SAKToolFactory::BlePeriheral; - return list; +QList SAKToolBoxUiFactory::supportedTools() +{ + QList list; + list << SAKToolFactory::SerialportTool << SAKToolFactory::UdpClientTool + << SAKToolFactory::UdpServerTool << SAKToolFactory::TcpClientTool + << SAKToolFactory::TcpServerTool << SAKToolFactory::WebSocketClientTool + << SAKToolFactory::WebSocketServerTool << SAKToolFactory::BleCentralTool + << SAKToolFactory::BlePeriheral; + return list; } -SAKToolBoxUi* SAKToolBoxUiFactory::createToolBoxUi(int type) { +SAKToolBoxUi* SAKToolBoxUiFactory::createToolBoxUi(int type) +{ #if 0 if (type == SAKToolFactory::SerialportTool) { return new SAKSerialPortToolBoxUi(); @@ -62,5 +67,5 @@ SAKToolBoxUi* SAKToolBoxUiFactory::createToolBoxUi(int type) { } #endif - return Q_NULLPTR; + return Q_NULLPTR; } diff --git a/src/toolbox/toolboxui/saktoolboxuifactory.h b/src/toolbox/toolboxui/saktoolboxuifactory.h index 28f68e1c..0a0084d7 100644 --- a/src/toolbox/toolboxui/saktoolboxuifactory.h +++ b/src/toolbox/toolboxui/saktoolboxuifactory.h @@ -25,7 +25,6 @@ public: SAKToolBoxUi *createToolBoxUi(int type); private: - }; #endif // SAKTOOLBOXUIFACTORY_H diff --git a/src/toolbox/toolboxui/saktoolboxuiinputmenu.cc b/src/toolbox/toolboxui/saktoolboxuiinputmenu.cc index 72cd5447..471cca1d 100644 --- a/src/toolbox/toolboxui/saktoolboxuiinputmenu.cc +++ b/src/toolbox/toolboxui/saktoolboxuiinputmenu.cc @@ -13,86 +13,88 @@ #include "ui_saktoolboxuiinputmenu.h" -#define SAK_CB_ACTIVATED \ - static_cast(&QComboBox::activated) +#define SAK_CB_ACTIVATED static_cast(&QComboBox::activated) -SAKToolBoxUiInputMenu::SAKToolBoxUiInputMenu(const QString& settingsGroup, - QWidget* parent) - : QMenu{parent}, ui(new Ui::SAKToolBoxUiInputMenu) { - QWidget* w = new QWidget(this); - ui->setupUi(w); - QWidgetAction* action = new QWidgetAction(w); - action->setDefaultWidget(w); - addAction(action); +SAKToolBoxUiInputMenu::SAKToolBoxUiInputMenu(const QString& settingsGroup, QWidget* parent) + : QMenu{parent} + , ui(new Ui::SAKToolBoxUiInputMenu) +{ + QWidget* w = new QWidget(this); + ui->setupUi(w); + QWidgetAction* action = new QWidgetAction(w); + action->setDefaultWidget(w); + addAction(action); - ui->comboBoxPrefix->setGroupKey(settingsGroup + "/input", "prefix", false); - mParameters.prefix = ui->comboBoxPrefix->currentData().toInt(); - connect(ui->comboBoxPrefix, SAK_CB_ACTIVATED, this, [=]() { - int ret = ui->comboBoxPrefix->currentData().toInt(); - this->mParameters.prefix = ret; - emit parametersChanged(); - }); + ui->comboBoxPrefix->setGroupKey(settingsGroup + "/input", "prefix", false); + mParameters.prefix = ui->comboBoxPrefix->currentData().toInt(); + connect(ui->comboBoxPrefix, SAK_CB_ACTIVATED, this, [=]() { + int ret = ui->comboBoxPrefix->currentData().toInt(); + this->mParameters.prefix = ret; + emit parametersChanged(); + }); - ui->comboBoxSuffix->setGroupKey(settingsGroup + "/input", "suffix"); - mParameters.suffix = ui->comboBoxSuffix->currentData().toInt(); - connect(ui->comboBoxSuffix, SAK_CB_ACTIVATED, this, [=]() { - int ret = ui->comboBoxSuffix->currentData().toInt(); - this->mParameters.suffix = ret; - emit parametersChanged(); - }); + ui->comboBoxSuffix->setGroupKey(settingsGroup + "/input", "suffix"); + mParameters.suffix = ui->comboBoxSuffix->currentData().toInt(); + connect(ui->comboBoxSuffix, SAK_CB_ACTIVATED, this, [=]() { + int ret = ui->comboBoxSuffix->currentData().toInt(); + this->mParameters.suffix = ret; + emit parametersChanged(); + }); - ui->comboBoxEscape->setGroupKey(settingsGroup + "/input", "escape"); - mParameters.escapeCharacter = ui->comboBoxEscape->currentData().toInt(); - connect(ui->comboBoxEscape, SAK_CB_ACTIVATED, this, [=]() { - int ret = ui->comboBoxEscape->currentData().toInt(); - this->mParameters.escapeCharacter = ret; - emit parametersChanged(); - }); + ui->comboBoxEscape->setGroupKey(settingsGroup + "/input", "escape"); + mParameters.escapeCharacter = ui->comboBoxEscape->currentData().toInt(); + connect(ui->comboBoxEscape, SAK_CB_ACTIVATED, this, [=]() { + int ret = ui->comboBoxEscape->currentData().toInt(); + this->mParameters.escapeCharacter = ret; + emit parametersChanged(); + }); - ui->checkBoxAppendCrc->setGroupKey(settingsGroup + "/input", "crcAppend"); - mParameters.appendCrc = ui->checkBoxAppendCrc->isChecked(); - connect(ui->checkBoxAppendCrc, &QCheckBox::clicked, this, [=]() { - this->mParameters.appendCrc = ui->checkBoxAppendCrc->isChecked(); - emit parametersChanged(); - }); + ui->checkBoxAppendCrc->setGroupKey(settingsGroup + "/input", "crcAppend"); + mParameters.appendCrc = ui->checkBoxAppendCrc->isChecked(); + connect(ui->checkBoxAppendCrc, &QCheckBox::clicked, this, [=]() { + this->mParameters.appendCrc = ui->checkBoxAppendCrc->isChecked(); + emit parametersChanged(); + }); - ui->checkBoxBigEndian->setGroupKey(settingsGroup + "/input", "crcBigEndian"); - mParameters.bigEndian = ui->checkBoxBigEndian->isChecked(); - connect(ui->checkBoxBigEndian, &QCheckBox::clicked, this, [=]() { - this->mParameters.bigEndian = ui->checkBoxBigEndian->isChecked(); - emit parametersChanged(); - }); + ui->checkBoxBigEndian->setGroupKey(settingsGroup + "/input", "crcBigEndian"); + mParameters.bigEndian = ui->checkBoxBigEndian->isChecked(); + connect(ui->checkBoxBigEndian, &QCheckBox::clicked, this, [=]() { + this->mParameters.bigEndian = ui->checkBoxBigEndian->isChecked(); + emit parametersChanged(); + }); - ui->spinBoxStartIndex->setGroupKey(settingsGroup + "/input", "startIndex"); - mParameters.startIndex = ui->spinBoxStartIndex->value(); - connect(ui->spinBoxStartIndex, QOverload::of(&QSpinBox::valueChanged), - this, [=](int) { - this->mParameters.startIndex = ui->spinBoxStartIndex->value(); - emit parametersChanged(); - }); + ui->spinBoxStartIndex->setGroupKey(settingsGroup + "/input", "startIndex"); + mParameters.startIndex = ui->spinBoxStartIndex->value(); + connect(ui->spinBoxStartIndex, QOverload::of(&QSpinBox::valueChanged), this, [=](int) { + this->mParameters.startIndex = ui->spinBoxStartIndex->value(); + emit parametersChanged(); + }); - ui->spinBoxEndIndex->setGroupKey(settingsGroup + "/input", "endIndex"); - mParameters.endIndex = ui->spinBoxEndIndex->value(); - connect(ui->spinBoxEndIndex, QOverload::of(&QSpinBox::valueChanged), - this, [=]() { - this->mParameters.endIndex = ui->spinBoxEndIndex->value(); - emit parametersChanged(); - }); + ui->spinBoxEndIndex->setGroupKey(settingsGroup + "/input", "endIndex"); + mParameters.endIndex = ui->spinBoxEndIndex->value(); + connect(ui->spinBoxEndIndex, QOverload::of(&QSpinBox::valueChanged), this, [=]() { + this->mParameters.endIndex = ui->spinBoxEndIndex->value(); + emit parametersChanged(); + }); - ui->comboBoxAglorithm->setGroupKey(settingsGroup + "/input", "algorithm"); - mParameters.algorithm = ui->comboBoxAglorithm->currentData().toInt(); - mParameters.algorithmName = ui->comboBoxAglorithm->currentText(); - connect(ui->comboBoxAglorithm, SAK_CB_ACTIVATED, this, [=]() { - int ret = ui->comboBoxAglorithm->currentData().toInt(); - QString name = ui->comboBoxAglorithm->currentText(); - this->mParameters.algorithm = ret; - this->mParameters.algorithmName = name; - emit parametersChanged(); - }); + ui->comboBoxAglorithm->setGroupKey(settingsGroup + "/input", "algorithm"); + mParameters.algorithm = ui->comboBoxAglorithm->currentData().toInt(); + mParameters.algorithmName = ui->comboBoxAglorithm->currentText(); + connect(ui->comboBoxAglorithm, SAK_CB_ACTIVATED, this, [=]() { + int ret = ui->comboBoxAglorithm->currentData().toInt(); + QString name = ui->comboBoxAglorithm->currentText(); + this->mParameters.algorithm = ret; + this->mParameters.algorithmName = name; + emit parametersChanged(); + }); } -SAKToolBoxUiInputMenu::~SAKToolBoxUiInputMenu() { delete ui; } - -SAKToolBoxUiInputMenu::Parameters SAKToolBoxUiInputMenu::parameters() { - return mParameters; +SAKToolBoxUiInputMenu::~SAKToolBoxUiInputMenu() +{ + delete ui; +} + +SAKToolBoxUiInputMenu::Parameters SAKToolBoxUiInputMenu::parameters() +{ + return mParameters; } diff --git a/src/toolbox/toolboxui/saktoolboxuiinputmenu.h b/src/toolbox/toolboxui/saktoolboxuiinputmenu.h index 40deb491..661adeeb 100644 --- a/src/toolbox/toolboxui/saktoolboxuiinputmenu.h +++ b/src/toolbox/toolboxui/saktoolboxuiinputmenu.h @@ -20,11 +20,11 @@ class SAKToolBoxUiInputMenu : public QMenu { Q_OBJECT public: - explicit SAKToolBoxUiInputMenu(const QString &settingsGroup, - QWidget *parent = nullptr); + explicit SAKToolBoxUiInputMenu(const QString &settingsGroup, QWidget *parent = nullptr); ~SAKToolBoxUiInputMenu(); - struct Parameters { + struct Parameters + { int prefix; int suffix; int escapeCharacter; diff --git a/src/toolbox/toolboxui/saktoolboxuioutputmenu.cc b/src/toolbox/toolboxui/saktoolboxuioutputmenu.cc index 03194252..e2213896 100644 --- a/src/toolbox/toolboxui/saktoolboxuioutputmenu.cc +++ b/src/toolbox/toolboxui/saktoolboxuioutputmenu.cc @@ -58,7 +58,7 @@ SAKToolBoxUiOutputMenu::SAKToolBoxUiOutputMenu(const QString& settingsGroup, const QString fillterKey = settingsGroup + "/fillter"; txt = SAKSettings::instance()->value(fillterKey).toString(); ui->filter->setText(txt); - connect(ui->filter, &QLineEdit::editingFinished, this, [=](){ + connect(ui->filter, &QLineEdit::editingFinished, this, [=]() { SAKSettings::instance()->setValue(fillterKey, ui->filter->text().trimmed()); }); } diff --git a/src/tools/tools/sakanalyzertool.cc b/src/tools/tools/sakanalyzertool.cc index bb0e091b..4c5b3534 100644 --- a/src/tools/tools/sakanalyzertool.cc +++ b/src/tools/tools/sakanalyzertool.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakinterface.h" #include "sakanalyzertool.h" +#include "sakinterface.h" SAKAnalyzerTool::SAKAnalyzerTool(QObject *parent) : SAKBaseTool{"sak.analyzertool", parent} @@ -44,12 +44,12 @@ void SAKAnalyzerTool::setMaxTempBytes(int maxBytes) mParametersMutex.unlock(); } -void SAKAnalyzerTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKAnalyzerTool::inputBytes(const QByteArray &bytes, const QVariant &context) { if (bytes.isEmpty()) { - outputMessage(QtInfoMsg, "Empty input bytes, " - "the operation will be ignored!"); + outputMessage(QtInfoMsg, + "Empty input bytes, " + "the operation will be ignored!"); return; } @@ -77,7 +77,7 @@ void SAKAnalyzerTool::run() QTimer *handleTimer = new QTimer(); handleTimer->setInterval(5); handleTimer->setSingleShot(true); - connect(handleTimer, &QTimer::timeout, handleTimer, [=](){ + connect(handleTimer, &QTimer::timeout, handleTimer, [=]() { if (mEnable) { mInputtedBytesMutex.lock(); analyze(); @@ -126,8 +126,7 @@ void SAKAnalyzerTool::analyzeFixed() mParametersMutex.unlock(); while (mInputtedBytes.length() >= ctx.frameBytes) { - QByteArray frame(mInputtedBytes.data(), - ctx.frameBytes); + QByteArray frame(mInputtedBytes.data(), ctx.frameBytes); mInputtedBytes.remove(0, ctx.frameBytes); QByteArray ba = SAKInterface::arrayToHex(frame, ' '); diff --git a/src/tools/tools/sakanalyzertool.h b/src/tools/tools/sakanalyzertool.h index 690d0670..56f81ba9 100644 --- a/src/tools/tools/sakanalyzertool.h +++ b/src/tools/tools/sakanalyzertool.h @@ -10,8 +10,8 @@ #ifndef SAKANALYZERTOOL_H #define SAKANALYZERTOOL_H -#include #include +#include #include "sakbasetool.h" @@ -26,14 +26,14 @@ public: Q_INVOKABLE void setSeparationMark(const QByteArray &mark); Q_INVOKABLE void setMaxTempBytes(int maxBytes); - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; protected: virtual void run() final; private: - struct Parameters { + struct Parameters + { bool fixed; int frameBytes; QByteArray separationMark; diff --git a/src/tools/tools/sakbasetool.cc b/src/tools/tools/sakbasetool.cc index 7bf49d72..29820d71 100644 --- a/src/tools/tools/sakbasetool.cc +++ b/src/tools/tools/sakbasetool.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include #include +#include #include "sakbasetool.h" @@ -16,17 +16,15 @@ SAKBaseTool::SAKBaseTool(const char *logCategory, QObject *parent) : QThread{parent} , mLoggingCategory(logCategory) { - connect(this, &SAKBaseTool::started, this, [=](){ + connect(this, &SAKBaseTool::started, this, [=]() { this->mIsWorking = true; emit this->isWorkingChanged(); }); - connect(this, &SAKBaseTool::finished, this, [=](){ + connect(this, &SAKBaseTool::finished, this, [=]() { this->mIsWorking = false; emit this->isWorkingChanged(); }); - connect(this, &SAKBaseTool::errorOccured, this, [=](){ - exit(); - }); + connect(this, &SAKBaseTool::errorOccured, this, [=]() { exit(); }); } SAKBaseTool::~SAKBaseTool() diff --git a/src/tools/tools/sakbasetool.h b/src/tools/tools/sakbasetool.h index fb53d8b3..576bb04c 100644 --- a/src/tools/tools/sakbasetool.h +++ b/src/tools/tools/sakbasetool.h @@ -11,9 +11,9 @@ #define SAKBASETOOL_H #include -#include #include #include +#include class SAKBaseTool : public QThread { @@ -23,16 +23,15 @@ class SAKBaseTool : public QThread public: explicit SAKBaseTool(const char *logCategory, QObject *parent = Q_NULLPTR); virtual ~SAKBaseTool(); - QString toolName(){return mToolName;} - void setToolName(const QString &name){mToolName = name;} + QString toolName() { return mToolName; } + void setToolName(const QString &name) { mToolName = name; } /** * @brief inputBytes: The entrance of data. * @param bytes: The bytes input. * @param context: The extension parameters. */ - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()); + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()); signals: void bytesInputted(const QByteArray &bytes, const QVariant &context); @@ -47,9 +46,13 @@ protected: void outputMessage(int type, const QString &info) const; public: - bool isWorking(){return mIsWorking;} - bool enable(){return mEnable;} - void setEnable(bool enable){mEnable = enable; emit enableChanged();} + bool isWorking() { return mIsWorking; } + bool enable() { return mEnable; } + void setEnable(bool enable) + { + mEnable = enable; + emit enableChanged(); + } protected: std::atomic_bool mIsWorking{false}; diff --git a/src/tools/tools/sakblecentraltool.cc b/src/tools/tools/sakblecentraltool.cc index bfc614dc..5ac64770 100644 --- a/src/tools/tools/sakblecentraltool.cc +++ b/src/tools/tools/sakblecentraltool.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include #include +#include #include "sakblecentraltool.h" @@ -16,19 +16,14 @@ SAKBleCentralTool::SAKBleCentralTool(QObject *parent) : SAKCommunicationTool("sak.blecentral", parent) -{ +{} -} - -SAKBleCentralTool::~SAKBleCentralTool() -{ - -} +SAKBleCentralTool::~SAKBleCentralTool() {} QString SAKBleCentralTool::serviceName(QVariant service) { - QObject *obj = service.value(); - auto cookedService = qobject_cast(obj); + QObject *obj = service.value(); + auto cookedService = qobject_cast(obj); if (cookedService) { return cookedService->serviceName(); } else { @@ -41,11 +36,11 @@ QString SAKBleCentralTool::serviceName(QVariant service) QVariantList SAKBleCentralTool::characteristics(QVariant service) { QVariantList list; - if (service.canConvert()) { + if (service.canConvert()) { return list; } #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) - auto cookedService = service.value(); + auto cookedService = service.value(); if (cookedService) { auto characteristics = cookedService->characteristics(); for (auto &characteristic : characteristics) { @@ -90,15 +85,13 @@ void SAKBleCentralTool::readCharacteristic() void SAKBleCentralTool::changeNotify() { - if (!((mServiceIndex >= 0) - && (mServiceIndex < mServices.length()))) { + if (!((mServiceIndex >= 0) && (mServiceIndex < mServices.length()))) { return; } auto service = mServices.at(mServiceIndex); auto characteristics = service->characteristics(); - if (!((mCharacteristicIndex >= 0) - && (mCharacteristicIndex < characteristics.length()))) { + if (!((mCharacteristicIndex >= 0) && (mCharacteristicIndex < characteristics.length()))) { return; } @@ -160,12 +153,11 @@ bool SAKBleCentralTool::initialize(QString &errStr) #if QT_VERSION >= QT_VERSION_CHECK(5, 7, 0) mServices.clear(); mBleCentral = QLowEnergyController::createCentral(mBluetoothDeviceInfo); - connect(mBleCentral, &QLowEnergyController::serviceDiscovered, mBleCentral, - [=](const QBluetoothUuid &newService){ - onServiceDiscovered(newService); - }); - connect(mBleCentral, &QLowEnergyController::discoveryFinished, - mBleCentral, [=](){ + connect(mBleCentral, + &QLowEnergyController::serviceDiscovered, + mBleCentral, + [=](const QBluetoothUuid &newService) { onServiceDiscovered(newService); }); + connect(mBleCentral, &QLowEnergyController::discoveryFinished, mBleCentral, [=]() { onServiceDiscoveryFinished(); }); connect(mBleCentral, @@ -175,13 +167,13 @@ bool SAKBleCentralTool::initialize(QString &errStr) QOverload::of(&QLowEnergyController::error), #endif mBleCentral, - [=](QLowEnergyController::Error err){ - onBleCentralErrorOccuured(err); + [=](QLowEnergyController::Error err) { onBleCentralErrorOccuured(err); }); + connect(mBleCentral, &QLowEnergyController::connected, mBleCentral, [=]() { + onBleCentralConnected(); + }); + connect(mBleCentral, &QLowEnergyController::disconnected, mBleCentral, [=]() { + onBleCentralDisconnected(); }); - connect(mBleCentral, &QLowEnergyController::connected, - mBleCentral, [=](){onBleCentralConnected();}); - connect(mBleCentral, &QLowEnergyController::disconnected, - mBleCentral, [=](){onBleCentralDisconnected();}); mBleCentral->connectToDevice(); emit serviceDiscoveryStarted(); @@ -193,8 +185,7 @@ bool SAKBleCentralTool::initialize(QString &errStr) void SAKBleCentralTool::readBytes() { - if (!((mServiceIndex >= 0) - && (mServiceIndex < mServices.length()))) { + if (!((mServiceIndex >= 0) && (mServiceIndex < mServices.length()))) { return; } @@ -204,8 +195,7 @@ void SAKBleCentralTool::readBytes() service->readCharacteristic(characteristic); } -void SAKBleCentralTool::writeBytes(const QByteArray &bytes, - const QVariant &context) +void SAKBleCentralTool::writeBytes(const QByteArray &bytes, const QVariant &context) { Q_UNUSED(context); if (!((mServiceIndex >= 0) && (mServiceIndex < mServices.length()))) { @@ -217,15 +207,13 @@ void SAKBleCentralTool::writeBytes(const QByteArray &bytes, auto characteristics = service->characteristics(); auto characteristic = characteristics.at(mCharacteristicIndex); if (mWriteModel == 0) { - if (!hasFlag(QVariant::fromValue(characteristic), - QLowEnergyCharacteristic::Write)) { + if (!hasFlag(QVariant::fromValue(characteristic), QLowEnergyCharacteristic::Write)) { QString str = "QLowEnergyService::WriteWithResponse"; qCWarning(mLoggingCategory) << "unsupported write model: " + str; return; } - qCInfo(mLoggingCategory) << "try to write bytes:" - << QString::fromLatin1(bytes.toHex()); + qCInfo(mLoggingCategory) << "try to write bytes:" << QString::fromLatin1(bytes.toHex()); service->writeCharacteristic(characteristic, bytes); } else { if (!hasFlag(QVariant::fromValue(characteristic), @@ -251,16 +239,14 @@ void SAKBleCentralTool::uninitialize() void SAKBleCentralTool::onServiceDiscovered(const QBluetoothUuid &newService) { - outputMessage(QtInfoMsg, "new ble service discovered:" - + newService.toString()); + outputMessage(QtInfoMsg, "new ble service discovered:" + newService.toString()); } void SAKBleCentralTool::onServiceDiscoveryFinished() { outputMessage(QtInfoMsg, "ble service discovery finished."); QList uuids = mBleCentral->services(); - outputMessage(QtInfoMsg, "service count:" - + QString::number(uuids.length())); + outputMessage(QtInfoMsg, "service count:" + QString::number(uuids.length())); for (auto &uuid : uuids) { auto service = mBleCentral->createServiceObject(uuid); @@ -268,30 +254,37 @@ void SAKBleCentralTool::onServiceDiscoveryFinished() continue; } - connect(service, &QLowEnergyService::characteristicChanged, service, - [=](const QLowEnergyCharacteristic &info, - const QByteArray &value){ - emit bytesOutputted(value, QVariant()); - Q_UNUSED(info); - }); - connect(service, &QLowEnergyService::characteristicRead, service, - [=](const QLowEnergyCharacteristic &info, - const QByteArray &value){ - emit bytesOutputted(value, QVariant()); - Q_UNUSED(info); - }); - connect(service, &QLowEnergyService::characteristicWritten, service, - [=](const QLowEnergyCharacteristic &info, - const QByteArray &value){ - emit bytesInputted(value, QVariant()); - Q_UNUSED(info); - }); - connect(service, &QLowEnergyService::stateChanged, service, - [=](QLowEnergyService::ServiceState newState){ + connect(service, + &QLowEnergyService::characteristicChanged, + service, + [=](const QLowEnergyCharacteristic &info, const QByteArray &value) { + emit bytesOutputted(value, QVariant()); + Q_UNUSED(info); + }); + connect(service, + &QLowEnergyService::characteristicRead, + service, + [=](const QLowEnergyCharacteristic &info, const QByteArray &value) { + emit bytesOutputted(value, QVariant()); + Q_UNUSED(info); + }); + connect(service, + &QLowEnergyService::characteristicWritten, + service, + [=](const QLowEnergyCharacteristic &info, const QByteArray &value) { + emit bytesInputted(value, QVariant()); + Q_UNUSED(info); + }); + connect(service, + &QLowEnergyService::stateChanged, + service, + [=](QLowEnergyService::ServiceState newState) { onServiceObjectStateChanged(service, newState); - }); - connect(service, &QLowEnergyService::descriptorWritten, - this, &SAKBleCentralTool::descriptorWritten); + }); + connect(service, + &QLowEnergyService::descriptorWritten, + this, + &SAKBleCentralTool::descriptorWritten); mServices.append(service); service->discoverDetails(); @@ -300,15 +293,13 @@ void SAKBleCentralTool::onServiceDiscoveryFinished() emit serviceDiscoveryFinished(); } -void SAKBleCentralTool::onBleCentralErrorOccuured( - QLowEnergyController::Error err) +void SAKBleCentralTool::onBleCentralErrorOccuured(QLowEnergyController::Error err) { if (err == QLowEnergyController::UnknownError) { - return ; + return; } - outputMessage(QtWarningMsg, "new ble service error:" - + mBleCentral->errorString()); + outputMessage(QtWarningMsg, "new ble service error:" + mBleCentral->errorString()); exit(); } @@ -325,8 +316,8 @@ void SAKBleCentralTool::onBleCentralDisconnected() emit errorOccured(msg); } -void SAKBleCentralTool::onServiceObjectStateChanged( - QLowEnergyService *service, QLowEnergyService::ServiceState newState) +void SAKBleCentralTool::onServiceObjectStateChanged(QLowEnergyService *service, + QLowEnergyService::ServiceState newState) { Q_UNUSED(service); #if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) diff --git a/src/tools/tools/sakblecentraltool.h b/src/tools/tools/sakblecentraltool.h index 1ceafbda..220b7008 100644 --- a/src/tools/tools/sakblecentraltool.h +++ b/src/tools/tools/sakblecentraltool.h @@ -10,11 +10,11 @@ #ifndef EDBLECENTRAL_HH #define EDBLECENTRAL_HH -#include -#include -#include -#include #include +#include +#include +#include +#include #include "sakcommunicationtool.h" @@ -23,13 +23,10 @@ class SAKBleCentralTool : public SAKCommunicationTool Q_OBJECT Q_PROPERTY(QVariant info READ info WRITE setInfo NOTIFY infoChanged) Q_PROPERTY(QVariantList services READ services NOTIFY servicesChanged) - Q_PROPERTY(int serviceIndex READ serviceIndex WRITE setServiceIndex - NOTIFY serviceIndexChanged) - Q_PROPERTY(int characteristicIndex READ characteristicIndex - WRITE setCharacteristicIndex - NOTIFY characteristicIndexChanged) - Q_PROPERTY(int writeModel READ writeModel WRITE setWriteModel - NOTIFY writeModelChanged) + Q_PROPERTY(int serviceIndex READ serviceIndex WRITE setServiceIndex NOTIFY serviceIndexChanged) + Q_PROPERTY(int characteristicIndex READ characteristicIndex WRITE setCharacteristicIndex NOTIFY + characteristicIndexChanged) + Q_PROPERTY(int writeModel READ writeModel WRITE setWriteModel NOTIFY writeModelChanged) public: SAKBleCentralTool(QObject *parent = nullptr); ~SAKBleCentralTool(); @@ -44,15 +41,13 @@ public: Q_INVOKABLE bool isNotified(QVariant characteristic); signals: - void descriptorWritten(const QLowEnergyDescriptor &descriptor, - const QByteArray &newValue); + void descriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue); void serviceDiscoveryStarted(); void serviceDiscoveryFinished(); protected: virtual bool initialize(QString &errStr) final; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; virtual void readBytes() final; virtual void uninitialize() final; @@ -68,8 +63,8 @@ private: void onServiceObjectStateChanged(QLowEnergyService *service, QLowEnergyService::ServiceState newState); -//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ -//Properties + //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ + //Properties public: Q_INVOKABLE QVariant info(); Q_INVOKABLE void setInfo(QVariant info); @@ -91,7 +86,7 @@ signals: private: QBluetoothDeviceInfo mBluetoothDeviceInfo; - QVector mServices; + QVector mServices; int mServiceIndex{-1}; int mCharacteristicIndex{-1}; int mWriteModel; diff --git a/src/tools/tools/sakcommunicationtool.cc b/src/tools/tools/sakcommunicationtool.cc index 6a9a3e44..ab6fb66e 100644 --- a/src/tools/tools/sakcommunicationtool.cc +++ b/src/tools/tools/sakcommunicationtool.cc @@ -7,18 +7,14 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include #include "sakcommunicationtool.h" +#include -SAKCommunicationTool::SAKCommunicationTool(const char *logCategory, - QObject *parent) +SAKCommunicationTool::SAKCommunicationTool(const char *logCategory, QObject *parent) : SAKBaseTool{logCategory, parent} -{ +{} -} - -void SAKCommunicationTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKCommunicationTool::inputBytes(const QByteArray &bytes, const QVariant &context) { if (!enable()) { return; @@ -59,7 +55,7 @@ void SAKCommunicationTool::run() QTimer *txTimer = new QTimer(); txTimer->setInterval(5); txTimer->setSingleShot(true); - connect(txTimer, &QTimer::timeout, txTimer, [=](){ + connect(txTimer, &QTimer::timeout, txTimer, [=]() { this->mInputDataMutex.lock(); if (!mInputDataList.isEmpty()) { InputDataContext dataCtx = mInputDataList.takeFirst(); diff --git a/src/tools/tools/sakcommunicationtool.h b/src/tools/tools/sakcommunicationtool.h index 01c8031f..dae032fb 100644 --- a/src/tools/tools/sakcommunicationtool.h +++ b/src/tools/tools/sakcommunicationtool.h @@ -10,21 +10,20 @@ #ifndef SAKCOMMUNICATIONTOOL_H #define SAKCOMMUNICATIONTOOL_H +#include "sakbasetool.h" #include #include -#include "sakbasetool.h" class SAKCommunicationTool : public SAKBaseTool { Q_OBJECT public: - explicit SAKCommunicationTool(const char *logCategory, - QObject *parent = nullptr); - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + explicit SAKCommunicationTool(const char *logCategory, QObject *parent = nullptr); + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; protected: - struct InputDataContext { + struct InputDataContext + { QByteArray bytes; QVariant context; }; @@ -33,8 +32,7 @@ protected: virtual void run() final; virtual bool initialize(QString &errStr) = 0; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) = 0; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) = 0; virtual void uninitialize() = 0; QJsonObject rxJsonObject() const; diff --git a/src/tools/tools/sakemittertool.cc b/src/tools/tools/sakemittertool.cc index 7c149647..8c0aa454 100644 --- a/src/tools/tools/sakemittertool.cc +++ b/src/tools/tools/sakemittertool.cc @@ -7,23 +7,20 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include #include +#include #include "sakemittertool.h" #include "sakcrcinterface.h" -#include "sakinterface.h" #include "sakdatastructure.h" +#include "sakinterface.h" SAKEmitterTool::SAKEmitterTool(QObject *parent) : SAKTableModelTool{"sak.emittertool", parent} -{ +{} -} - -void SAKEmitterTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKEmitterTool::inputBytes(const QByteArray &bytes, const QVariant &context) { Q_UNUSED(bytes) Q_UNUSED(context) @@ -52,8 +49,7 @@ QVariant SAKEmitterTool::itemContext(int index) ctx.insert(itemEnable(), true); ctx.insert(itemDescription(), "Demo"); ctx.insert(itemTextFormat(), SAKDataStructure::TextFormatAscii); - ctx.insert(itemEscapeCharacter(), - SAKDataStructure::EscapeCharacterOptionNone); + ctx.insert(itemEscapeCharacter(), SAKDataStructure::EscapeCharacterOptionNone); ctx.insert(itemInterval(), 1000); ctx.insert(itemPrefix(), SAKDataStructure::AffixesNone); ctx.insert(itemSuffix(), SAKDataStructure::AffixesNone); @@ -129,9 +125,7 @@ QVariant SAKEmitterTool::data(const QModelIndex &index, int role) const return QVariant(); } -bool SAKEmitterTool::setData(const QModelIndex &index, - const QVariant &value, - int role) +bool SAKEmitterTool::setData(const QModelIndex &index, const QVariant &value, int role) { Q_UNUSED(role); int row = index.row(); @@ -177,9 +171,7 @@ bool SAKEmitterTool::setData(const QModelIndex &index, return true; } -bool SAKEmitterTool::insertRows(int row, - int count, - const QModelIndex &parent) +bool SAKEmitterTool::insertRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); Data ctx; @@ -200,27 +192,39 @@ bool SAKEmitterTool::removeRows(int row, int count, const QModelIndex &parent) return true; } -QVariant SAKEmitterTool::headerData(int section, - Qt::Orientation orientation, - int role) const +QVariant SAKEmitterTool::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(role); if (orientation == Qt::Horizontal) { switch (section) { - case 0: return mDataKeys.itemEnable; - case 1: return mDataKeys.itemDescription; - case 2: return mDataKeys.itemTextFormat; - case 3: return mDataKeys.itemEscapeCharacter; - case 4: return mDataKeys.itemInterval; - case 5: return mDataKeys.itemPrefix; - case 6: return mDataKeys.itemSuffix; - case 7: return mDataKeys.itemCrcEnable; - case 8: return mDataKeys.itemCrcBigEndian; - case 9: return mDataKeys.itemCrcAlgorithm; - case 10: return mDataKeys.itemCrcStartIndex; - case 11: return mDataKeys.itemCrcEndIndex; - case 12: return mDataKeys.itemText; - default: return ""; + case 0: + return mDataKeys.itemEnable; + case 1: + return mDataKeys.itemDescription; + case 2: + return mDataKeys.itemTextFormat; + case 3: + return mDataKeys.itemEscapeCharacter; + case 4: + return mDataKeys.itemInterval; + case 5: + return mDataKeys.itemPrefix; + case 6: + return mDataKeys.itemSuffix; + case 7: + return mDataKeys.itemCrcEnable; + case 8: + return mDataKeys.itemCrcBigEndian; + case 9: + return mDataKeys.itemCrcAlgorithm; + case 10: + return mDataKeys.itemCrcStartIndex; + case 11: + return mDataKeys.itemCrcEndIndex; + case 12: + return mDataKeys.itemText; + default: + return ""; } } @@ -232,9 +236,7 @@ void SAKEmitterTool::run() mEmittingTimer = new QTimer(); mEmittingTimer->setInterval(mScanInterval); mEmittingTimer->setSingleShot(true); - connect(mEmittingTimer, &QTimer::timeout, mEmittingTimer, [=](){ - try2emit(); - }); + connect(mEmittingTimer, &QTimer::timeout, mEmittingTimer, [=]() { try2emit(); }); mEmittingTimer->start(); exec(); @@ -285,11 +287,11 @@ QByteArray SAKEmitterTool::itemBytes(const SAKEmitterTool::Data &item) return bytes; } -QVariant SAKEmitterTool::columnDisplayRoleData( - const SAKEmitterTool::EmiterItem &item, int column) const +QVariant SAKEmitterTool::columnDisplayRoleData(const SAKEmitterTool::EmiterItem &item, + int column) const { DataKeys keys; - QStringList hs = const_cast(this)->headers(); + QStringList hs = const_cast(this)->headers(); if (column >= 0 && column < hs.count()) { const QString dataKey = hs.at(column); if (dataKey == mDataKeys.itemEnable) { diff --git a/src/tools/tools/sakemittertool.h b/src/tools/tools/sakemittertool.h index 6d2ef5de..eaf5d6b5 100644 --- a/src/tools/tools/sakemittertool.h +++ b/src/tools/tools/sakemittertool.h @@ -10,10 +10,10 @@ #ifndef SAKEMITTERTOOL_H #define SAKEMITTERTOOL_H -#include -#include -#include #include +#include +#include +#include #include "saktablemodeltool.h" @@ -34,7 +34,8 @@ class SAKEmitterTool : public SAKTableModelTool Q_PROPERTY(QString itemCrcEndIndex READ itemCrcEndIndex CONSTANT) Q_PROPERTY(QString itemText READ itemText CONSTANT) public: - struct DataKeys { + struct DataKeys + { const QString itemEnable{"Enable"}; const QString itemDescription{"Description"}; const QString itemTextFormat{"Format"}; @@ -51,7 +52,8 @@ public: }; public: - struct Data { + struct Data + { bool itemEnable; QString itemDescription{"Demo"}; int itemTextFormat; @@ -68,36 +70,29 @@ public: int itemCrcEndIndex; }; - struct EmiterItem { + struct EmiterItem + { Data data; int elapsedTime{0}; }; public: explicit SAKEmitterTool(QObject *parent = Q_NULLPTR); - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; public: virtual QString cookHeaderString(const QString &str) override; virtual QVariant itemContext(int index) final; protected: - virtual int rowCount(const QModelIndex &parent - = QModelIndex()) const override; - virtual int columnCount(const QModelIndex &parent - = QModelIndex()) const override; - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const override; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; - virtual bool insertRows(int row, int count, - const QModelIndex &parent - = QModelIndex()) override; - virtual bool removeRows(int row, int count, - const QModelIndex &parent - = QModelIndex()) override; + virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; diff --git a/src/tools/tools/sakmaskertool.cc b/src/tools/tools/sakmaskertool.cc index 0cf66f1b..e81afebd 100644 --- a/src/tools/tools/sakmaskertool.cc +++ b/src/tools/tools/sakmaskertool.cc @@ -28,8 +28,7 @@ void SAKMaskerTool::setMaskCode(qint8 maskCode) mMask = maskCode; } -void SAKMaskerTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKMaskerTool::inputBytes(const QByteArray &bytes, const QVariant &context) { emit bytesInputted(bytes, context); @@ -46,7 +45,7 @@ void SAKMaskerTool::run() QTimer *timer = new QTimer(); timer->setInterval(5); timer->setSingleShot(true); - connect(timer, &QTimer::timeout, timer, [=](){ + connect(timer, &QTimer::timeout, timer, [=]() { QByteArray bytes; QVariant context; this->mInputParametersListMutex.lock(); @@ -60,27 +59,24 @@ void SAKMaskerTool::run() if (!bytes.isEmpty()) { QByteArray ba = SAKInterface::arrayToHex(bytes, ' '); QString hex = QString::fromLatin1(ba); - outputMessage(QtInfoMsg, - QString("%1<-%2").arg(mToolName, hex)); + outputMessage(QtInfoMsg, QString("%1<-%2").arg(mToolName, hex)); if (this->enable()) { QByteArray cookedBytes; for (int i = 0; i < bytes.length(); i++) { quint8 value = quint8(bytes.at(i)); value ^= mMask; - cookedBytes.append(reinterpret_cast(&value), 1); + cookedBytes.append(reinterpret_cast(&value), 1); } ba = SAKInterface::arrayToHex(cookedBytes, ' '); QString hex = QString::fromLatin1(ba); - outputMessage(QtInfoMsg, - QString("%1->%2").arg(mToolName, hex)); + outputMessage(QtInfoMsg, QString("%1->%2").arg(mToolName, hex)); emit bytesOutputted(cookedBytes, context); } else { ba = SAKInterface::arrayToHex(bytes, ' '); QString hex = QString::fromLatin1(ba); - outputMessage(QtInfoMsg, - QString("%1->%2").arg(mToolName, hex)); + outputMessage(QtInfoMsg, QString("%1->%2").arg(mToolName, hex)); emit bytesOutputted(bytes, context); } } diff --git a/src/tools/tools/sakmaskertool.h b/src/tools/tools/sakmaskertool.h index 220cd900..5e18b03d 100644 --- a/src/tools/tools/sakmaskertool.h +++ b/src/tools/tools/sakmaskertool.h @@ -24,14 +24,14 @@ public: Q_INVOKABLE void setMaskCode(qint8 maskCode); - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; protected: void run(); private: - struct InputParameters { + struct InputParameters + { QByteArray bytes; QVariant context; }; diff --git a/src/tools/tools/sakprestorertool.cc b/src/tools/tools/sakprestorertool.cc index 12f94a13..bc7a2fe7 100644 --- a/src/tools/tools/sakprestorertool.cc +++ b/src/tools/tools/sakprestorertool.cc @@ -7,20 +7,18 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include -#include #include +#include +#include -#include "sakinterface.h" #include "sakcrcinterface.h" -#include "sakprestorertool.h" #include "sakdatastructure.h" +#include "sakinterface.h" +#include "sakprestorertool.h" SAKPrestorerTool::SAKPrestorerTool(QObject *parent) : SAKTableModelTool{"sak.prestorertool", parent} -{ - -} +{} int SAKPrestorerTool::rowCount(const QModelIndex &parent) const { @@ -48,9 +46,7 @@ QVariant SAKPrestorerTool::data(const QModelIndex &index, int role) const return QVariant(); } -bool SAKPrestorerTool::setData(const QModelIndex &index, - const QVariant &value, - int role) +bool SAKPrestorerTool::setData(const QModelIndex &index, const QVariant &value, int role) { Q_UNUSED(role); int row = index.row(); @@ -73,7 +69,7 @@ bool SAKPrestorerTool::setData(const QModelIndex &index, item.itemCrcEnable = value.toBool(); } else if (dataKey == mDataKeys.itemCrcBigEndian) { item.itemCrxBigEndian = value.toBool(); - } else if (dataKey == mDataKeys.itemCrcAlgorithm) { + } else if (dataKey == mDataKeys.itemCrcAlgorithm) { item.itemCrcAlgorithm = value.toInt(); } else if (dataKey == mDataKeys.itemCrcStartIndex) { item.itemCrcStartIndex = value.toInt(); @@ -82,7 +78,6 @@ bool SAKPrestorerTool::setData(const QModelIndex &index, } else if (dataKey == mDataKeys.itemText) { item.itemText = value.toString(); } else { - } mItems.replace(row, item); @@ -92,8 +87,7 @@ bool SAKPrestorerTool::setData(const QModelIndex &index, return true; } -bool SAKPrestorerTool::insertRows(int row, int count, - const QModelIndex &parent) +bool SAKPrestorerTool::insertRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); Item item{}; @@ -111,25 +105,35 @@ bool SAKPrestorerTool::removeRows(int row, int count, const QModelIndex &parent) return true; } -QVariant SAKPrestorerTool::headerData(int section, - Qt::Orientation orientation, - int role) const +QVariant SAKPrestorerTool::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(role); if (orientation == Qt::Horizontal) { switch (section) { - case 0: return mDataKeys.itemDescription; - case 1: return mDataKeys.itemTextFormat; - case 2: return mDataKeys.itemEscapeCharacter; - case 3: return mDataKeys.itemPrefix; - case 4: return mDataKeys.itemSuffix; - case 5: return mDataKeys.itemCrcEnable; - case 6: return mDataKeys.itemCrcBigEndian; - case 7: return mDataKeys.itemCrcAlgorithm; - case 8: return mDataKeys.itemCrcStartIndex; - case 9: return mDataKeys.itemCrcEndIndex; - case 10: return mDataKeys.itemText; - default: return ""; + case 0: + return mDataKeys.itemDescription; + case 1: + return mDataKeys.itemTextFormat; + case 2: + return mDataKeys.itemEscapeCharacter; + case 3: + return mDataKeys.itemPrefix; + case 4: + return mDataKeys.itemSuffix; + case 5: + return mDataKeys.itemCrcEnable; + case 6: + return mDataKeys.itemCrcBigEndian; + case 7: + return mDataKeys.itemCrcAlgorithm; + case 8: + return mDataKeys.itemCrcStartIndex; + case 9: + return mDataKeys.itemCrcEndIndex; + case 10: + return mDataKeys.itemText; + default: + return ""; } } @@ -180,7 +184,7 @@ QVariant SAKPrestorerTool::columnDisplayRoleData(const Item &item, int column) c return item.itemCrcEnable; } else if (dataKey == mDataKeys.itemCrcBigEndian) { return item.itemCrxBigEndian; - } else if (dataKey == mDataKeys.itemCrcAlgorithm) { + } else if (dataKey == mDataKeys.itemCrcAlgorithm) { return item.itemCrcAlgorithm; } else if (dataKey == mDataKeys.itemCrcStartIndex) { return item.itemCrcStartIndex; @@ -231,7 +235,7 @@ QVariant SAKPrestorerTool::itemContext(int index) QJsonObject ctx; mItemsMutex.lock(); if (index >= 0 && index < mItems.count()) { - auto item = mItems.at(index); + auto item = mItems.at(index); ctx.insert(itemDescription(), item.itemDescription); ctx.insert(itemTextFormat(), item.itemTextFormat); ctx.insert(itemEscapeCharacter(), item.itemEscapeCharacter); @@ -246,8 +250,7 @@ QVariant SAKPrestorerTool::itemContext(int index) } else { ctx.insert(itemDescription(), "Demo"); ctx.insert(itemTextFormat(), SAKDataStructure::TextFormatAscii); - ctx.insert(itemEscapeCharacter(), - SAKDataStructure::EscapeCharacterOptionNone); + ctx.insert(itemEscapeCharacter(), SAKDataStructure::EscapeCharacterOptionNone); ctx.insert(itemPrefix(), SAKDataStructure::AffixesNone); ctx.insert(itemSuffix(), SAKDataStructure::AffixesNone); ctx.insert(itemCrcEnable(), false); @@ -278,8 +281,7 @@ void SAKPrestorerTool::send(int index) } } -void SAKPrestorerTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKPrestorerTool::inputBytes(const QByteArray &bytes, const QVariant &context) { Q_UNUSED(bytes); Q_UNUSED(context); @@ -290,7 +292,7 @@ void SAKPrestorerTool::run() QTimer *sendTimer = new QTimer(); sendTimer->setInterval(mScanInterval); sendTimer->setSingleShot(true); - connect(sendTimer, &QTimer::timeout, sendTimer, [=](){ + connect(sendTimer, &QTimer::timeout, sendTimer, [=]() { try2send(); sendTimer->start(); }); @@ -387,4 +389,3 @@ QStringList SAKPrestorerTool::descriptions() return list; } - diff --git a/src/tools/tools/sakprestorertool.h b/src/tools/tools/sakprestorertool.h index 7f9ab4a4..eac03fa2 100644 --- a/src/tools/tools/sakprestorertool.h +++ b/src/tools/tools/sakprestorertool.h @@ -10,10 +10,10 @@ #ifndef SAKPRESTORERTOOL_H #define SAKPRESTORERTOOL_H -#include -#include -#include #include +#include +#include +#include #include "saktablemodeltool.h" @@ -37,7 +37,8 @@ class SAKPrestorerTool : public SAKTableModelTool Q_PROPERTY(QStringList descriptions READ descriptions NOTIFY descriptionsChanged) public: - struct Item { + struct Item + { QString itemDescription{"Demo"}; int itemTextFormat; int itemEscapeCharacter; @@ -52,7 +53,8 @@ public: int itemCrcEndIndex; }; - struct ItemKeys { + struct ItemKeys + { const QString itemDescription{"Description"}; const QString itemTextFormat{"Format"}; const QString itemEscapeCharacter{"Escape"}; @@ -75,23 +77,19 @@ public: Q_INVOKABLE void send(int index); protected: - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context) final; void run() final; - virtual int rowCount(const QModelIndex &parent - = QModelIndex()) const override; - virtual int columnCount(const QModelIndex &parent - = QModelIndex()) const override; - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const override; - virtual bool setData(const QModelIndex &index, const QVariant &value, + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + virtual bool setData(const QModelIndex &index, + const QVariant &value, int role = Qt::EditRole) override; - virtual bool insertRows(int row, int count, - const QModelIndex &parent = QModelIndex()) override; - virtual bool removeRows(int row, int count, - const QModelIndex &parent = QModelIndex()) override; - virtual QVariant headerData(int section, Qt::Orientation orientation, + virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + virtual QVariant headerData(int section, + Qt::Orientation orientation, int role = Qt::DisplayRole) const override; private: @@ -101,6 +99,7 @@ private: const int mScanInterval{5}; QList mIndexs; QMutex mIndexsMutex; + private: QVector mItems; QMutex mItemsMutex; diff --git a/src/tools/tools/sakresponsertool.cc b/src/tools/tools/sakresponsertool.cc index 8fbeca28..a23ce53a 100644 --- a/src/tools/tools/sakresponsertool.cc +++ b/src/tools/tools/sakresponsertool.cc @@ -8,23 +8,21 @@ * the file LICENCE in the root of the source code directory. ******************************************************************************/ #include -#include -#include -#include #include +#include #include #include +#include +#include -#include "sakinterface.h" #include "sakcrcinterface.h" #include "sakdatastructure.h" +#include "sakinterface.h" #include "sakresponsertool.h" SAKResponserTool::SAKResponserTool(QObject *parent) : SAKTableModelTool{"sak.responsertool", parent} -{ - -} +{} int SAKResponserTool::rowCount(const QModelIndex &parent) const { @@ -52,9 +50,7 @@ QVariant SAKResponserTool::data(const QModelIndex &index, int role) const return QVariant(); } -bool SAKResponserTool::setData(const QModelIndex &index, - const QVariant &value, - int role) +bool SAKResponserTool::setData(const QModelIndex &index, const QVariant &value, int role) { Q_UNUSED(role); int row = index.row(); @@ -143,46 +139,68 @@ bool SAKResponserTool::removeRows(int row, int count, const QModelIndex &parent) return true; } -QVariant SAKResponserTool::headerData(int section, - Qt::Orientation orientation, - int role) const +QVariant SAKResponserTool::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(role); if (orientation == Qt::Horizontal) { switch (section) { - case 0: return mDataKeys.itemEnable; - case 1: return mDataKeys.itemDescription; - case 2: return mDataKeys.itemOption; - case 3: return mDataKeys.itemReferenceTextFormat; - case 4: return mDataKeys.itemReferenceEscapeCharacter; - case 5: return mDataKeys.itemReferencePrefix; - case 6: return mDataKeys.itemReferenceSuffix; - case 7: return mDataKeys.itemReferenceCrcEnable; - case 8: return mDataKeys.itemReferenceCrcBigEndian; - case 9: return mDataKeys.itemReferenceCrcAlgorithm; - case 10: return mDataKeys.itemReferenceCrcStartIndex; - case 11: return mDataKeys.itemReferenceCrcEndIndex; - case 12: return mDataKeys.itemReferenceText; - case 13: return mDataKeys.itemResponseTextFormat; - case 14: return mDataKeys.itemResponseEscapeCharacter; - case 15: return mDataKeys.itemResponsePrefix; - case 16: return mDataKeys.itemResponseSuffix; - case 17: return mDataKeys.itemResponseCrcEnable; - case 18: return mDataKeys.itemResponseCrcBigEndian; - case 19: return mDataKeys.itemResponseCrcAlgorithm; - case 20: return mDataKeys.itemResponseCrcStartIndex; - case 21: return mDataKeys.itemResponseCrcEndIndex; - case 22: return mDataKeys.itemResponseDelay; - case 23: return mDataKeys.itemResponseText; - default: return ""; + case 0: + return mDataKeys.itemEnable; + case 1: + return mDataKeys.itemDescription; + case 2: + return mDataKeys.itemOption; + case 3: + return mDataKeys.itemReferenceTextFormat; + case 4: + return mDataKeys.itemReferenceEscapeCharacter; + case 5: + return mDataKeys.itemReferencePrefix; + case 6: + return mDataKeys.itemReferenceSuffix; + case 7: + return mDataKeys.itemReferenceCrcEnable; + case 8: + return mDataKeys.itemReferenceCrcBigEndian; + case 9: + return mDataKeys.itemReferenceCrcAlgorithm; + case 10: + return mDataKeys.itemReferenceCrcStartIndex; + case 11: + return mDataKeys.itemReferenceCrcEndIndex; + case 12: + return mDataKeys.itemReferenceText; + case 13: + return mDataKeys.itemResponseTextFormat; + case 14: + return mDataKeys.itemResponseEscapeCharacter; + case 15: + return mDataKeys.itemResponsePrefix; + case 16: + return mDataKeys.itemResponseSuffix; + case 17: + return mDataKeys.itemResponseCrcEnable; + case 18: + return mDataKeys.itemResponseCrcBigEndian; + case 19: + return mDataKeys.itemResponseCrcAlgorithm; + case 20: + return mDataKeys.itemResponseCrcStartIndex; + case 21: + return mDataKeys.itemResponseCrcEndIndex; + case 22: + return mDataKeys.itemResponseDelay; + case 23: + return mDataKeys.itemResponseText; + default: + return ""; } } return QVariant(""); } -QVariant SAKResponserTool::columnDisplayRoleData( - const ResponserData &item, int column) const +QVariant SAKResponserTool::columnDisplayRoleData(const ResponserData &item, int column) const { if (column >= 0 && column < headers().count()) { const QString dataKey = headers().at(column); @@ -245,9 +263,8 @@ QVariant SAKResponserTool::columnDisplayRoleData( QByteArray SAKResponserTool::referenceBytes(const ResponserItem &item) const { QByteArray bytes; - QString text = item.itemReferenceText ; - text = SAKDataStructure::cookedString(item.itemReferenceEscapeCharacter, - text); + QString text = item.itemReferenceText; + text = SAKDataStructure::cookedString(item.itemReferenceEscapeCharacter, text); bytes = SAKInterface::string2array(text, item.itemReferenceTextFormat); QByteArray prefix = SAKDataStructure::affixesData(item.itemReferencePrefix); QByteArray suffix = SAKDataStructure::affixesData(item.itemReferenceSuffix); @@ -255,10 +272,11 @@ QByteArray SAKResponserTool::referenceBytes(const ResponserItem &item) const bytes.prepend(prefix); if (item.itemReferenceCrcEnable) { SAKCrcInterface sakCrc; - QByteArray crcBytes = sakCrc.calculateBytes( - bytes, item.itemReferenceCrcAlgorithm, - item.itemReferenceCrcStartIndex, item.itemReferenceCrcEndIndex, - item.itemReferenceCrcBigEndian); + QByteArray crcBytes = sakCrc.calculateBytes(bytes, + item.itemReferenceCrcAlgorithm, + item.itemReferenceCrcStartIndex, + item.itemReferenceCrcEndIndex, + item.itemReferenceCrcBigEndian); bytes.append(crcBytes); } bytes.append(suffix); @@ -270,8 +288,7 @@ QByteArray SAKResponserTool::responseBytes(const ResponserItem &item) const { QByteArray bytes; QString text = item.itemResponseText; - text = SAKDataStructure::cookedString(item.itemResponseEscapeCharacter, - text); + text = SAKDataStructure::cookedString(item.itemResponseEscapeCharacter, text); bytes = SAKInterface::string2array(text, item.itemResponseTextFormat); QByteArray prefix = SAKDataStructure::affixesData(item.itemResponsePrefix); QByteArray suffix = SAKDataStructure::affixesData(item.itemResponseSuffix); @@ -279,10 +296,11 @@ QByteArray SAKResponserTool::responseBytes(const ResponserItem &item) const bytes.prepend(prefix); if (item.itemResponseCrcEnable) { SAKCrcInterface sakCrc; - QByteArray crcBytes = sakCrc.calculateBytes( - bytes, item.itemResponseCrcAlgorithm, - item.itemResponseCrcStartIndex, item.itemResponseCrcEndIndex, - item.itemResponseCrcBigEndian); + QByteArray crcBytes = sakCrc.calculateBytes(bytes, + item.itemResponseCrcAlgorithm, + item.itemResponseCrcStartIndex, + item.itemResponseCrcEndIndex, + item.itemResponseCrcBigEndian); bytes.append(crcBytes); } bytes.append(suffix); @@ -292,7 +310,7 @@ QByteArray SAKResponserTool::responseBytes(const ResponserItem &item) const QVariant SAKResponserTool::itemContext(int index) { - auto itemCtx = [=](int index)->QJsonObject { + auto itemCtx = [=](int index) -> QJsonObject { QJsonObject ctx; if (index >= 0 && index < mItems.count()) { auto item = mItems.at(index); @@ -300,59 +318,36 @@ QVariant SAKResponserTool::itemContext(int index) ctx.insert(itemDescription(), item.data.itemDescription); ctx.insert(itemOption(), item.data.itemOption); - ctx.insert(itemReferenceTextFormat(), - item.data.itemReferenceTextFormat); - ctx.insert(itemReferenceEscapeCharacter(), - item.data.itemReferenceEscapeCharacter); - ctx.insert(itemReferencePrefix(), - item.data.itemReferencePrefix); - ctx.insert(itemReferenceSuffix(), - item.data.itemReferenceSuffix); - ctx.insert(itemReferenceCrcEnable(), - item.data.itemReferenceCrcEnable); - ctx.insert(itemReferenceCrcBigEndian(), - item.data.itemReferenceCrcBigEndian); - ctx.insert(itemReferenceCrcAlgorithm(), - item.data.itemReferenceCrcAlgorithm); - ctx.insert(itemReferenceCrcStartIndex(), - item.data.itemReferenceCrcStartIndex); - ctx.insert(itemReferenceCrcEndIndex(), - item.data.itemReferenceCrcEndIndex); - ctx.insert(itemReferenceText(), - item.data.itemReferenceText); + ctx.insert(itemReferenceTextFormat(), item.data.itemReferenceTextFormat); + ctx.insert(itemReferenceEscapeCharacter(), item.data.itemReferenceEscapeCharacter); + ctx.insert(itemReferencePrefix(), item.data.itemReferencePrefix); + ctx.insert(itemReferenceSuffix(), item.data.itemReferenceSuffix); + ctx.insert(itemReferenceCrcEnable(), item.data.itemReferenceCrcEnable); + ctx.insert(itemReferenceCrcBigEndian(), item.data.itemReferenceCrcBigEndian); + ctx.insert(itemReferenceCrcAlgorithm(), item.data.itemReferenceCrcAlgorithm); + ctx.insert(itemReferenceCrcStartIndex(), item.data.itemReferenceCrcStartIndex); + ctx.insert(itemReferenceCrcEndIndex(), item.data.itemReferenceCrcEndIndex); + ctx.insert(itemReferenceText(), item.data.itemReferenceText); - ctx.insert(itemResponseTextFormat(), - item.data.itemResponseTextFormat); - ctx.insert(itemResponseEscapeCharacter(), - item.data.itemResponseEscapeCharacter); - ctx.insert(itemResponsePrefix(), - item.data.itemResponsePrefix); - ctx.insert(itemResponseSuffix(), - item.data.itemResponseSuffix); - ctx.insert(itemResponseCrcEnable(), - item.data.itemResponseCrcEnable); - ctx.insert(itemResponseCrcBigEndian(), - item.data.itemResponseCrcBigEndian); - ctx.insert(itemResponseCrcAlgorithm(), - item.data.itemResponseCrcAlgorithm); - ctx.insert(itemResponseCrcStartIndex(), - item.data.itemResponseCrcStartIndex); - ctx.insert(itemResponseCrcEndIndex(), - item.data.itemResponseCrcEndIndex); - ctx.insert(itemResponseDelay(), - item.data.itemResponseDelay); - ctx.insert(itemResponseText(), - item.data.itemResponseText); + ctx.insert(itemResponseTextFormat(), item.data.itemResponseTextFormat); + ctx.insert(itemResponseEscapeCharacter(), item.data.itemResponseEscapeCharacter); + ctx.insert(itemResponsePrefix(), item.data.itemResponsePrefix); + ctx.insert(itemResponseSuffix(), item.data.itemResponseSuffix); + ctx.insert(itemResponseCrcEnable(), item.data.itemResponseCrcEnable); + ctx.insert(itemResponseCrcBigEndian(), item.data.itemResponseCrcBigEndian); + ctx.insert(itemResponseCrcAlgorithm(), item.data.itemResponseCrcAlgorithm); + ctx.insert(itemResponseCrcStartIndex(), item.data.itemResponseCrcStartIndex); + ctx.insert(itemResponseCrcEndIndex(), item.data.itemResponseCrcEndIndex); + ctx.insert(itemResponseDelay(), item.data.itemResponseDelay); + ctx.insert(itemResponseText(), item.data.itemResponseText); } else { // If index is out of range, return the default values. ctx.insert(itemEnable(), true); ctx.insert(itemDescription(), "Demo"); ctx.insert(itemOption(), 0); - ctx.insert(itemReferenceTextFormat(), - SAKDataStructure::TextFormatAscii); - ctx.insert(itemReferenceEscapeCharacter(), - SAKDataStructure::EscapeCharacterOptionNone); + ctx.insert(itemReferenceTextFormat(), SAKDataStructure::TextFormatAscii); + ctx.insert(itemReferenceEscapeCharacter(), SAKDataStructure::EscapeCharacterOptionNone); ctx.insert(itemReferencePrefix(), SAKDataStructure::AffixesNone); ctx.insert(itemReferenceSuffix(), SAKDataStructure::AffixesNone); ctx.insert(itemReferenceCrcEnable(), false); @@ -362,10 +357,8 @@ QVariant SAKResponserTool::itemContext(int index) ctx.insert(itemReferenceCrcEndIndex(), 0); ctx.insert(itemReferenceText(), "Reference data."); - ctx.insert(itemResponseTextFormat(), - SAKDataStructure::TextFormatAscii); - ctx.insert(itemResponseEscapeCharacter(), - SAKDataStructure::EscapeCharacterOptionNone); + ctx.insert(itemResponseTextFormat(), SAKDataStructure::TextFormatAscii); + ctx.insert(itemResponseEscapeCharacter(), SAKDataStructure::EscapeCharacterOptionNone); ctx.insert(itemResponsePrefix(), SAKDataStructure::AffixesNone); ctx.insert(itemResponseSuffix(), SAKDataStructure::AffixesNone); ctx.insert(itemResponseCrcEnable(), false); @@ -443,12 +436,12 @@ QString SAKResponserTool::cookHeaderString(const QString &str) return "--"; } -void SAKResponserTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKResponserTool::inputBytes(const QByteArray &bytes, const QVariant &context) { mInputContextListMutex.lock(); mInputContextList.append({bytes, context}); - mInputContextListMutex.unlock();; + mInputContextListMutex.unlock(); + ; } void SAKResponserTool::run() @@ -457,7 +450,7 @@ void SAKResponserTool::run() outputTimer->setInterval(5); outputTimer->setSingleShot(true); - connect(outputTimer, &QTimer::timeout, outputTimer, [=](){ + connect(outputTimer, &QTimer::timeout, outputTimer, [=]() { mInputContextListMutex.lock(); while (!mInputContextList.isEmpty()) { auto ctx = mInputContextList.takeFirst(); @@ -478,8 +471,7 @@ void SAKResponserTool::run() outputTimer = nullptr; } -void SAKResponserTool::try2output(const SAKResponserTool::InputContext &ctx, - QObject *receiver) +void SAKResponserTool::try2output(const SAKResponserTool::InputContext &ctx, QObject *receiver) { mItemsMutex.lock(); auto items = mItems; @@ -521,9 +513,8 @@ void SAKResponserTool::try2output(const SAKResponserTool::InputContext &ctx, continue; } - QTimer::singleShot(item.data.itemResponseDelay, receiver, [=](){ - emit bytesOutputted(item.data.itemResponseText.toUtf8(), - ctx.context); + QTimer::singleShot(item.data.itemResponseDelay, receiver, [=]() { + emit bytesOutputted(item.data.itemResponseText.toUtf8(), ctx.context); }); } } diff --git a/src/tools/tools/sakresponsertool.h b/src/tools/tools/sakresponsertool.h index 9421c11c..48a0be6b 100644 --- a/src/tools/tools/sakresponsertool.h +++ b/src/tools/tools/sakresponsertool.h @@ -10,9 +10,9 @@ #ifndef SAKRESPONSERTOOL_H #define SAKRESPONSERTOOL_H +#include #include #include -#include #include "saktablemodeltool.h" @@ -51,7 +51,8 @@ class SAKResponserTool : public SAKTableModelTool SAK_STR_PROPERTY(itemResponseDelay) SAK_STR_PROPERTY(itemResponseText) public: - struct ResponserItem { + struct ResponserItem + { bool itemEnable; QString itemDescription{"Demo"}; int itemOption; @@ -80,12 +81,14 @@ public: int itemResponseDelay; }; - struct ResponserData { + struct ResponserData + { ResponserItem data; int elapsedTime{0}; }; - struct ResponserItemKeys { + struct ResponserItemKeys + { const QString itemEnable{"Enable"}; const QString itemDescription{"Description"}; const QString itemOption{"Option"}; @@ -116,31 +119,26 @@ public: explicit SAKResponserTool(QObject *parent = nullptr); Q_INVOKABLE virtual QVariant itemContext(int index) final; virtual QString cookHeaderString(const QString &str) override; - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; protected: virtual void run() final; - virtual int rowCount(const QModelIndex &parent - = QModelIndex()) const final; - virtual int columnCount(const QModelIndex &parent - = QModelIndex()) const final; - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const final; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const final; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const final; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const final; virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) final; - virtual bool insertRows(int row, int count, - const QModelIndex &parent = QModelIndex()) final; - virtual bool removeRows(int row, int count, - const QModelIndex &parent = QModelIndex()) final; + virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) final; + virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) final; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const final; private: - struct InputContext { + struct InputContext + { QByteArray bytes; QVariant context; }; diff --git a/src/tools/tools/sakserialporttool.cc b/src/tools/tools/sakserialporttool.cc index c3d55417..e81bc7c2 100644 --- a/src/tools/tools/sakserialporttool.cc +++ b/src/tools/tools/sakserialporttool.cc @@ -7,14 +7,12 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakinterface.h" #include "sakserialporttool.h" +#include "sakinterface.h" SAKSerialPortTool::SAKSerialPortTool(QObject *parent) : SAKCommunicationTool("sak.serialporttool", parent) -{ - -} +{} QString SAKSerialPortTool::portName() { @@ -91,12 +89,12 @@ bool SAKSerialPortTool::initialize(QString &errStr) QString info = QString("portName:%1, baudRate:%2, dataBits:%3, " "stopBits:%4, parity:%5, flowControl: %6") - .arg(mParameters.portName, - QString::number(mParameters.baudRate), - QString::number(mParameters.dataBits), - QString::number(mParameters.stopBits), - QString::number(mParameters.parity), - QString::number(mParameters.flowControl)); + .arg(mParameters.portName, + QString::number(mParameters.baudRate), + QString::number(mParameters.dataBits), + QString::number(mParameters.stopBits), + QString::number(mParameters.parity), + QString::number(mParameters.flowControl)); outputMessage(QtInfoMsg, info); if (!mSerialPort->open(QSerialPort::ReadWrite)) { @@ -107,15 +105,12 @@ bool SAKSerialPortTool::initialize(QString &errStr) return false; } - connect(mSerialPort, &QSerialPort::readyRead, mSerialPort, [=](){ - readBytes(); - }); + connect(mSerialPort, &QSerialPort::readyRead, mSerialPort, [=]() { readBytes(); }); return true; } -void SAKSerialPortTool::writeBytes(const QByteArray &bytes, - const QVariant &context) +void SAKSerialPortTool::writeBytes(const QByteArray &bytes, const QVariant &context) { if (mSerialPort && mSerialPort->isOpen()) { qint64 ret = mSerialPort->write(bytes); diff --git a/src/tools/tools/sakserialporttool.h b/src/tools/tools/sakserialporttool.h index e2394533..a8720114 100644 --- a/src/tools/tools/sakserialporttool.h +++ b/src/tools/tools/sakserialporttool.h @@ -56,13 +56,13 @@ signals: protected: virtual bool initialize(QString &errStr) final; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; virtual void readBytes() final; virtual void uninitialize() final; private: - struct { + struct + { QString portName{""}; int baudRate{9600}; int dataBits{QSerialPort::Data8}; diff --git a/src/tools/tools/sakserialporttransmittertool.cc b/src/tools/tools/sakserialporttransmittertool.cc index 0754d399..173ff347 100644 --- a/src/tools/tools/sakserialporttransmittertool.cc +++ b/src/tools/tools/sakserialporttransmittertool.cc @@ -7,22 +7,20 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ +#include "sakserialporttransmittertool.h" #include "sakinterface.h" #include "sakserialporttool.h" -#include "sakserialporttransmittertool.h" SAKSerialPortTransmitterTool::SAKSerialPortTransmitterTool(QObject *parent) : SAKTransmitterTool{"sak.serialporttransmittertool", parent} -{ - -} +{} QString SAKSerialPortTransmitterTool::cookHeaderString(const QString &str) { ItemContextKey keys; if (str == keys.enable) { return tr("enable"); - } else if (str == keys.portName) { + } else if (str == keys.portName) { return tr("portName"); } else if (str == keys.baudRate) { return tr("baudRate"); @@ -46,8 +44,7 @@ QVariant SAKSerialPortTransmitterTool::itemContext(int index) QJsonObject obj; ItemContextKey ctx; if (index >= 0 && index < mToolVector.count()) { - SAKSerialPortTool *tool = - qobject_cast(mToolVector.value(index)); + SAKSerialPortTool *tool = qobject_cast(mToolVector.value(index)); obj.insert(ctx.baudRate, tool->baudRate()); obj.insert(ctx.dataBits, tool->dataBits()); obj.insert(ctx.enable, tool->enable()); @@ -69,8 +66,7 @@ QVariant SAKSerialPortTransmitterTool::itemContext(int index) return obj; } -void SAKSerialPortTransmitterTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKSerialPortTransmitterTool::inputBytes(const QByteArray &bytes, const QVariant &context) { QByteArray ba = SAKInterface::arrayToHex(bytes, ' '); QString hex = QString::fromLatin1(ba); @@ -89,14 +85,13 @@ int SAKSerialPortTransmitterTool::columnCount(const QModelIndex &parent) const return 7; } -QVariant SAKSerialPortTransmitterTool::data(const QModelIndex &index, - int role) const +QVariant SAKSerialPortTransmitterTool::data(const QModelIndex &index, int role) const { if (role != Qt::DisplayRole) { return QVariant(); } - auto ret = qobject_cast(mToolVector.value(index.row())); + auto ret = qobject_cast(mToolVector.value(index.row())); QString key = headerData(index.column(), Qt::Horizontal).toString(); ItemContextKey ctx; if (key == ctx.enable) { @@ -122,15 +117,13 @@ QVariant SAKSerialPortTransmitterTool::data(const QModelIndex &index, return true; } -bool SAKSerialPortTransmitterTool::setData(const QModelIndex &index, - const QVariant &value, - int role) +bool SAKSerialPortTransmitterTool::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::EditRole) { return false; } - auto ret = qobject_cast(mToolVector.value(index.row())); + auto ret = qobject_cast(mToolVector.value(index.row())); QString key = headerData(index.column(), Qt::Horizontal).toString(); ItemContextKey ctx; if (key == ctx.enable) { diff --git a/src/tools/tools/sakserialporttransmittertool.h b/src/tools/tools/sakserialporttransmittertool.h index d7142e02..e855e6ee 100644 --- a/src/tools/tools/sakserialporttransmittertool.h +++ b/src/tools/tools/sakserialporttransmittertool.h @@ -19,7 +19,8 @@ class SAKSerialPortTransmitterTool : public SAKTransmitterTool { Q_OBJECT public: - struct ItemContextKey { + struct ItemContextKey + { const QString enable{"enable"}; const QString portName{"portName"}; const QString baudRate{"baudRate"}; @@ -29,6 +30,7 @@ public: const QString flowControl{"flowControl"}; const QString description{"description"}; }; + public: explicit SAKSerialPortTransmitterTool(QObject *parent = nullptr); virtual QString cookHeaderString(const QString &str) override; @@ -37,10 +39,8 @@ public: const QVariant &context = QJsonObject()) override; protected: - virtual int columnCount(const QModelIndex &parent - = QModelIndex()) const override; - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const override; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; diff --git a/src/tools/tools/saksocketclienttool.cc b/src/tools/tools/saksocketclienttool.cc index 8500105d..c004e030 100644 --- a/src/tools/tools/saksocketclienttool.cc +++ b/src/tools/tools/saksocketclienttool.cc @@ -11,9 +11,7 @@ SAKSocketClientTool::SAKSocketClientTool(const char *lg, QObject *parent) : SAKCommunicationTool{lg, parent} -{ - -} +{} QString SAKSocketClientTool::clientIp() { @@ -22,7 +20,8 @@ QString SAKSocketClientTool::clientIp() void SAKSocketClientTool::setClientIp(const QString &ip) { - mClientIp = ip; emit clientIpChanged(); + mClientIp = ip; + emit clientIpChanged(); } int SAKSocketClientTool::clientPort() @@ -32,7 +31,8 @@ int SAKSocketClientTool::clientPort() void SAKSocketClientTool::setClientPort(int port) { - mClientPort = port; emit clientPortChanged(); + mClientPort = port; + emit clientPortChanged(); } bool SAKSocketClientTool::specifyClientIpPort() @@ -63,7 +63,8 @@ int SAKSocketClientTool::serverPort() void SAKSocketClientTool::setServerPort(int port) { - mServerPort = port; emit serverPortChanged(); + mServerPort = port; + emit serverPortChanged(); } QString SAKSocketClientTool::bindingIpPort() @@ -78,5 +79,6 @@ int SAKSocketClientTool::messageType() void SAKSocketClientTool::setMessageType(int type) { - mMessageType = type; emit messageTypeChanged(); + mMessageType = type; + emit messageTypeChanged(); } diff --git a/src/tools/tools/saksocketclienttool.h b/src/tools/tools/saksocketclienttool.h index 2c02ec79..6b288368 100644 --- a/src/tools/tools/saksocketclienttool.h +++ b/src/tools/tools/saksocketclienttool.h @@ -17,7 +17,8 @@ class SAKSocketClientTool : public SAKCommunicationTool Q_OBJECT Q_PROPERTY(QString clientIp READ clientIp WRITE setClientIp NOTIFY clientIpChanged) Q_PROPERTY(int clientPort READ clientPort WRITE setClientPort NOTIFY clientPortChanged) - Q_PROPERTY(bool specifyClientIpPort READ specifyClientIpPort WRITE setSpecifyClientIpPort NOTIFY specifyClientIpPortChanged) + Q_PROPERTY(bool specifyClientIpPort READ specifyClientIpPort WRITE setSpecifyClientIpPort NOTIFY + specifyClientIpPortChanged) Q_PROPERTY(QString serverIp READ serverIp WRITE setServerIp NOTIFY serverIpChanged) Q_PROPERTY(int serverPort READ serverPort WRITE setServerPort NOTIFY serverPortChanged) Q_PROPERTY(QString bindingIpPort READ bindingIpPort NOTIFY bindingIpPortChanged) diff --git a/src/tools/tools/saksocketclienttransmittertool.cc b/src/tools/tools/saksocketclienttransmittertool.cc index 507113bf..f7f43466 100644 --- a/src/tools/tools/saksocketclienttransmittertool.cc +++ b/src/tools/tools/saksocketclienttransmittertool.cc @@ -7,15 +7,13 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "saksocketclienttool.h" #include "saksocketclienttransmittertool.h" +#include "saksocketclienttool.h" -SAKSocketClientTransmitterTool::SAKSocketClientTransmitterTool( - const char *logCategory, QObject *parent) +SAKSocketClientTransmitterTool::SAKSocketClientTransmitterTool(const char *logCategory, + QObject *parent) : SAKTransmitterTool{logCategory, parent} -{ - -} +{} QString SAKSocketClientTransmitterTool::cookHeaderString(const QString &str) { @@ -44,8 +42,7 @@ QVariant SAKSocketClientTransmitterTool::itemContext(int index) QJsonObject obj; ItemContextKeys keys; if (index >= 0 && index < mToolVector.count()) { - SAKSocketClientTool *tool = - qobject_cast(mToolVector.value(index)); + SAKSocketClientTool *tool = qobject_cast(mToolVector.value(index)); obj.insert(keys.enable, tool->enable()); obj.insert(keys.clientIp, tool->clientIp()); obj.insert(keys.clientPort, tool->clientPort()); @@ -66,22 +63,19 @@ QVariant SAKSocketClientTransmitterTool::itemContext(int index) return obj; } -int SAKSocketClientTransmitterTool::columnCount( - const QModelIndex &parent) const +int SAKSocketClientTransmitterTool::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 7; } -QVariant SAKSocketClientTransmitterTool::data(const QModelIndex &index, - int role) const +QVariant SAKSocketClientTransmitterTool::data(const QModelIndex &index, int role) const { if (role != Qt::DisplayRole) { return QVariant(); } - auto tool = - qobject_cast(mToolVector.value(index.row())); + auto tool = qobject_cast(mToolVector.value(index.row())); QString key = headerData(index.column(), Qt::Horizontal).toString(); ItemContextKeys keys; if (key == keys.enable) { @@ -108,14 +102,15 @@ QVariant SAKSocketClientTransmitterTool::data(const QModelIndex &index, } bool SAKSocketClientTransmitterTool::setData(const QModelIndex &index, - const QVariant &value, int role) + const QVariant &value, + int role) { if (role != Qt::EditRole) { return false; } auto baseTool = mToolVector.value(index.row()); - auto tool = qobject_cast(baseTool); + auto tool = qobject_cast(baseTool); QString key = headerData(index.column(), Qt::Horizontal).toString(); ItemContextKeys keys; if (key == keys.enable) { @@ -141,8 +136,8 @@ bool SAKSocketClientTransmitterTool::setData(const QModelIndex &index, } QVariant SAKSocketClientTransmitterTool::headerData(int section, - Qt::Orientation orientation, - int role) const + Qt::Orientation orientation, + int role) const { if (role != Qt::DisplayRole || orientation != Qt::Horizontal) { return "--"; diff --git a/src/tools/tools/saksocketclienttransmittertool.h b/src/tools/tools/saksocketclienttransmittertool.h index a6a520ab..451e983b 100644 --- a/src/tools/tools/saksocketclienttransmittertool.h +++ b/src/tools/tools/saksocketclienttransmittertool.h @@ -16,13 +16,13 @@ class SAKSocketClientTransmitterTool : public SAKTransmitterTool { Q_OBJECT public: - explicit SAKSocketClientTransmitterTool(const char *logCategory, - QObject *parent = nullptr); + explicit SAKSocketClientTransmitterTool(const char *logCategory, QObject *parent = nullptr); virtual QString cookHeaderString(const QString &str) override; Q_INVOKABLE virtual QVariant itemContext(int index) override; public: - struct ItemContextKeys { + struct ItemContextKeys + { const QString enable{"Enable"}; const QString clientIp{"ClientIp"}; const QString clientPort{"ClientPort"}; @@ -34,10 +34,8 @@ public: }; protected: - virtual int columnCount(const QModelIndex &parent - = QModelIndex()) const override; - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const override; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; diff --git a/src/tools/tools/saksocketservertool.cc b/src/tools/tools/saksocketservertool.cc index 582a2438..76467aba 100644 --- a/src/tools/tools/saksocketservertool.cc +++ b/src/tools/tools/saksocketservertool.cc @@ -11,9 +11,7 @@ SAKSocketServerTool::SAKSocketServerTool(const char *log, QObject *parent) : SAKCommunicationTool{log, parent} -{ - -} +{} QString SAKSocketServerTool::serverIp() { @@ -33,7 +31,8 @@ int SAKSocketServerTool::serverPort() void SAKSocketServerTool::setServerPort(int port) { - mServerPort = port; emit serverPortChanged(); + mServerPort = port; + emit serverPortChanged(); } bool SAKSocketServerTool::specifyIpAndPort() @@ -75,5 +74,6 @@ int SAKSocketServerTool::messageType() void SAKSocketServerTool::setMessageType(int type) { - mMessageType = type; emit messageTypeChanged(); + mMessageType = type; + emit messageTypeChanged(); } diff --git a/src/tools/tools/saksocketservertool.h b/src/tools/tools/saksocketservertool.h index 245184cf..8499b887 100644 --- a/src/tools/tools/saksocketservertool.h +++ b/src/tools/tools/saksocketservertool.h @@ -17,7 +17,8 @@ class SAKSocketServerTool : public SAKCommunicationTool Q_OBJECT Q_PROPERTY(QString serverIp READ serverIp WRITE setServerIp NOTIFY serverIpChanged) Q_PROPERTY(int serverPort READ serverPort WRITE setServerPort NOTIFY serverPortChanged) - Q_PROPERTY(bool specifyIpAndPort READ specifyIpAndPort WRITE setSpecifyIpAndPort NOTIFY specifyIpAndPortChanged) + Q_PROPERTY(bool specifyIpAndPort READ specifyIpAndPort WRITE setSpecifyIpAndPort NOTIFY + specifyIpAndPortChanged) Q_PROPERTY(QStringList clients READ clients NOTIFY clientsChanged) Q_PROPERTY(int clientIndex READ clientIndex WRITE setClientIndex NOTIFY clientIndexChanged) Q_PROPERTY(QString bindingIpPort READ bindingIpPort NOTIFY bindingIpPortChanged) diff --git a/src/tools/tools/sakstatisticiantool.cc b/src/tools/tools/sakstatisticiantool.cc index de7b0f0a..80755400 100644 --- a/src/tools/tools/sakstatisticiantool.cc +++ b/src/tools/tools/sakstatisticiantool.cc @@ -12,7 +12,7 @@ SAKStatisticianTool::SAKStatisticianTool(QObject *parent) : SAKBaseTool{"sak.statisticiantool", parent} { - connect(this, &SAKStatisticianTool::started, this, [=](){ + connect(this, &SAKStatisticianTool::started, this, [=]() { this->mFrames = 0; this->mBytes = 0; @@ -21,8 +21,7 @@ SAKStatisticianTool::SAKStatisticianTool(QObject *parent) }); } -void SAKStatisticianTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKStatisticianTool::inputBytes(const QByteArray &bytes, const QVariant &context) { Q_UNUSED(context) diff --git a/src/tools/tools/sakstatisticiantool.h b/src/tools/tools/sakstatisticiantool.h index 45e0767c..73525430 100644 --- a/src/tools/tools/sakstatisticiantool.h +++ b/src/tools/tools/sakstatisticiantool.h @@ -20,8 +20,7 @@ class SAKStatisticianTool : public SAKBaseTool public: explicit SAKStatisticianTool(QObject *parent = nullptr); - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; protected: virtual void run() final; @@ -31,8 +30,8 @@ private: int mBytes{0}; private: - int frames(){return mFrames;} - int bytes(){return mBytes;} + int frames() { return mFrames; } + int bytes() { return mBytes; } signals: void framesChanged(int frames); diff --git a/src/tools/tools/sakstorertool.cc b/src/tools/tools/sakstorertool.cc index a7a533ca..8c09bf99 100644 --- a/src/tools/tools/sakstorertool.cc +++ b/src/tools/tools/sakstorertool.cc @@ -7,21 +7,18 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include +#include #include #include -#include -#include #include +#include #include "sakinterface.h" #include "sakstorertool.h" SAKStorerTool::SAKStorerTool(QObject *parent) : SAKBaseTool{"sak.storertool", parent} -{ - -} +{} SAKStorerTool::~SAKStorerTool() { @@ -30,8 +27,7 @@ SAKStorerTool::~SAKStorerTool() mInputContextListMutex.unlock(); } -void SAKStorerTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKStorerTool::inputBytes(const QByteArray &bytes, const QVariant &context) { if (enable()) { mInputContextListMutex.lock(); @@ -122,7 +118,7 @@ void SAKStorerTool::run() QTimer *writeTimer = new QTimer(); writeTimer->setInterval(2000); writeTimer->setSingleShot(true); - connect(writeTimer, &QTimer::timeout, writeTimer, [=](){ + connect(writeTimer, &QTimer::timeout, writeTimer, [=]() { this->write2file(); writeTimer->start(); }); @@ -145,9 +141,9 @@ void SAKStorerTool::write2file() } QString path = mParameters.file; - QFile file (path); + QFile file(path); if (file.exists()) { - if (file.size() > 1024*1024) { + if (file.size() > 1024 * 1024) { const QString format = QString("yyyy-MM-dd-hh-mm-ss_"); auto dt = QDateTime::currentDateTime().toString(format); QDir dir(path); @@ -156,15 +152,14 @@ void SAKStorerTool::write2file() pathTemp = pathTemp.remove(fileNameTemp); QString newFileName = pathTemp + dt + fileNameTemp; file.copy(newFileName); - file.open(QFile::WriteOnly|QFile::Truncate); + file.open(QFile::WriteOnly | QFile::Truncate); file.close(); } } else { - outputMessage(QtWarningMsg, - QString("the file(%1) is not exist").arg(path)); + outputMessage(QtWarningMsg, QString("the file(%1) is not exist").arg(path)); } - if (file.open(QFile::WriteOnly|QFile::Text|QFile::Append)) { + if (file.open(QFile::WriteOnly | QFile::Text | QFile::Append)) { QTextStream outStream(&file); while (!mInputContextList.isEmpty()) { auto ctx = mInputContextList.takeFirst(); diff --git a/src/tools/tools/sakstorertool.h b/src/tools/tools/sakstorertool.h index 2dcd58d9..b6e647ff 100644 --- a/src/tools/tools/sakstorertool.h +++ b/src/tools/tools/sakstorertool.h @@ -10,8 +10,8 @@ #ifndef SAKSTORERTOOL_H #define SAKSTORERTOOL_H -#include #include +#include #include "sakbasetool.h" @@ -29,8 +29,7 @@ public: explicit SAKStorerTool(QObject *parent = nullptr); ~SAKStorerTool(); - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; public: int saveFormat(); @@ -61,7 +60,8 @@ protected: virtual void run() final; private: - struct Parameters { + struct Parameters + { QString file; int format; bool saveRx; @@ -72,7 +72,8 @@ private: } mParameters; QMutex mParametersMutex; - struct InputContext { + struct InputContext + { QByteArray bytes; QVariant context; }; diff --git a/src/tools/tools/saktablemodeltool.cc b/src/tools/tools/saktablemodeltool.cc index c21c19d1..5a60251f 100644 --- a/src/tools/tools/saktablemodeltool.cc +++ b/src/tools/tools/saktablemodeltool.cc @@ -7,35 +7,49 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ +#include "saktablemodeltool.h" #include #include -#include "saktablemodeltool.h" SAKTableModelTool::SAKTableModelTool(const char *logCategory, QObject *parent) : SAKBaseTool{logCategory, parent} { mTableModel = new SAKTableModel(this); - connect(mTableModel, &SAKTableModel::invokeGetRowCount, - this, &SAKTableModelTool::onInvokeGetRowCount, + connect(mTableModel, + &SAKTableModel::invokeGetRowCount, + this, + &SAKTableModelTool::onInvokeGetRowCount, Qt::DirectConnection); - connect(mTableModel, &SAKTableModel::invokeGetColumnCount, - this, &SAKTableModelTool::onInvokeGetColumnCount, + connect(mTableModel, + &SAKTableModel::invokeGetColumnCount, + this, + &SAKTableModelTool::onInvokeGetColumnCount, Qt::DirectConnection); - connect(mTableModel, &SAKTableModel::invokeGetData, - this, &SAKTableModelTool::onInvokeGetData, + connect(mTableModel, + &SAKTableModel::invokeGetData, + this, + &SAKTableModelTool::onInvokeGetData, Qt::DirectConnection); - connect(mTableModel, &SAKTableModel::invokeSetData, - this, &SAKTableModelTool::onInvokeSetData, + connect(mTableModel, + &SAKTableModel::invokeSetData, + this, + &SAKTableModelTool::onInvokeSetData, Qt::DirectConnection); - connect(mTableModel, &SAKTableModel::invokeInsertRows, - this, &SAKTableModelTool::onInvokeInsertRows, + connect(mTableModel, + &SAKTableModel::invokeInsertRows, + this, + &SAKTableModelTool::onInvokeInsertRows, Qt::DirectConnection); - connect(mTableModel, &SAKTableModel::invokeRemoveRows, - this, &SAKTableModelTool::onInvokeRemoveRows, + connect(mTableModel, + &SAKTableModel::invokeRemoveRows, + this, + &SAKTableModelTool::onInvokeRemoveRows, Qt::DirectConnection); - connect(mTableModel, &SAKTableModel::invokeGetHeaderData, - this, &SAKTableModelTool::onInvokeGetHeaderData, + connect(mTableModel, + &SAKTableModel::invokeGetHeaderData, + this, + &SAKTableModelTool::onInvokeGetHeaderData, Qt::DirectConnection); } @@ -74,8 +88,7 @@ void SAKTableModelTool::addItem(const QString &jsonCtx, int index) auto key = headers().at(i); auto modelIndex = mTableModel->index(index, i); mTableModel->setData(modelIndex, jsonObj.value(key), Qt::EditRole); - qCInfo(mLoggingCategory) << qPrintable(QString("set %1 as").arg(key)) - << jsonObj.value(key); + qCInfo(mLoggingCategory) << qPrintable(QString("set %1 as").arg(key)) << jsonObj.value(key); } } @@ -105,9 +118,7 @@ void SAKTableModelTool::onInvokeGetColumnCount(int &count) count = columnCount(); } -void SAKTableModelTool::onInvokeGetData(QVariant &data, - const QModelIndex &index, - int role) +void SAKTableModelTool::onInvokeGetData(QVariant &data, const QModelIndex &index, int role) { data = this->data(index, role); } @@ -115,7 +126,7 @@ void SAKTableModelTool::onInvokeGetData(QVariant &data, void SAKTableModelTool::onInvokeSetData(bool &result, const QModelIndex &index, const QVariant &value, - int role ) + int role) { result = setData(index, value, role); } diff --git a/src/tools/tools/saktablemodeltool.h b/src/tools/tools/saktablemodeltool.h index 750e5de1..5fe746d4 100644 --- a/src/tools/tools/saktablemodeltool.h +++ b/src/tools/tools/saktablemodeltool.h @@ -19,8 +19,7 @@ class SAKTableModelTool : public SAKBaseTool Q_PROPERTY(QVariant tableModel READ tableModel CONSTANT) Q_PROPERTY(QStringList headers READ headers CONSTANT) public: - explicit SAKTableModelTool(const char *logCategory, - QObject *parent = nullptr); + explicit SAKTableModelTool(const char *logCategory, QObject *parent = nullptr); QVariant tableModel(); QStringList headers() const; @@ -31,22 +30,16 @@ public: protected: virtual int rowCount(const QModelIndex &parent = QModelIndex()) const = 0; - virtual int columnCount(const QModelIndex &parent - = QModelIndex()) const = 0; - virtual QVariant data(const QModelIndex &index, - int role = Qt::DisplayRole) const = 0; - virtual bool setData(const QModelIndex &index, - const QVariant &value, - int role = Qt::EditRole) = 0; - virtual bool insertRows(int row, - int count, - const QModelIndex &parent = QModelIndex()) = 0; - virtual bool removeRows(int row, - int count, - const QModelIndex &parent = QModelIndex()) = 0; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const = 0; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0; + virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) + = 0; + virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) = 0; + virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) = 0; virtual QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const = 0; + int role = Qt::DisplayRole) const + = 0; protected: SAKTableModel *mTableModel; @@ -54,9 +47,7 @@ protected: private: void onInvokeGetRowCount(int &count); void onInvokeGetColumnCount(int &count); - void onInvokeGetData(QVariant &data, - const QModelIndex &index, - int role = Qt::DisplayRole); + void onInvokeGetData(QVariant &data, const QModelIndex &index, int role = Qt::DisplayRole); void onInvokeSetData(bool &result, const QModelIndex &index, const QVariant &value, diff --git a/src/tools/tools/saktcpclienttool.cc b/src/tools/tools/saktcpclienttool.cc index cae17e07..94a954f1 100644 --- a/src/tools/tools/saktcpclienttool.cc +++ b/src/tools/tools/saktcpclienttool.cc @@ -15,71 +15,74 @@ #include "sakinterface.h" SAKTcpClientTool::SAKTcpClientTool(QObject* parent) - : SAKSocketClientTool{"sak.tcpclienttool", parent} {} + : SAKSocketClientTool{"sak.tcpclienttool", parent} +{} -bool SAKTcpClientTool::initialize(QString& errStr) { - mTcpSocket = new QTcpSocket(); - if (mSpecifyClientIpPort) { - if (!mTcpSocket->bind(QHostAddress(mClientIp), mClientPort)) { - errStr = "Binding error: " + mTcpSocket->errorString(); - return false; +bool SAKTcpClientTool::initialize(QString& errStr) +{ + mTcpSocket = new QTcpSocket(); + if (mSpecifyClientIpPort) { + if (!mTcpSocket->bind(QHostAddress(mClientIp), mClientPort)) { + errStr = "Binding error: " + mTcpSocket->errorString(); + return false; + } } - } - mTcpSocket->connectToHost(QHostAddress(mServerIp), mServerPort); - if (!mTcpSocket->waitForConnected()) { - errStr = "Connect to host error: " + mTcpSocket->errorString(); - return false; - } + mTcpSocket->connectToHost(QHostAddress(mServerIp), mServerPort); + if (!mTcpSocket->waitForConnected()) { + errStr = "Connect to host error: " + mTcpSocket->errorString(); + return false; + } - QString ip = mTcpSocket->localAddress().toString(); - QString port = QString::number(mTcpSocket->localPort()); - mBindingIpPort = ip + ":" + port; - outputMessage(QtInfoMsg, "Client address and port: " + mBindingIpPort); - emit bindingIpPortChanged(); + QString ip = mTcpSocket->localAddress().toString(); + QString port = QString::number(mTcpSocket->localPort()); + mBindingIpPort = ip + ":" + port; + outputMessage(QtInfoMsg, "Client address and port: " + mBindingIpPort); + emit bindingIpPortChanged(); - connect(mTcpSocket, SAK_SIG_SOCKETERROROCCURRED, mTcpSocket, [=]() { - QString info = "Error occurred: " + mTcpSocket->errorString(); - outputMessage(QtWarningMsg, info); - emit errorOccured(mTcpSocket->errorString()); - }); + connect(mTcpSocket, SAK_SIG_SOCKETERROROCCURRED, mTcpSocket, [=]() { + QString info = "Error occurred: " + mTcpSocket->errorString(); + outputMessage(QtWarningMsg, info); + emit errorOccured(mTcpSocket->errorString()); + }); - connect(mTcpSocket, &QTcpSocket::disconnected, mTcpSocket, [=]() { exit(); }); + connect(mTcpSocket, &QTcpSocket::disconnected, mTcpSocket, [=]() { exit(); }); - connect(mTcpSocket, &QTcpSocket::readyRead, mTcpSocket, - [=]() { readBytes(); }); + connect(mTcpSocket, &QTcpSocket::readyRead, mTcpSocket, [=]() { readBytes(); }); - return true; + return true; } -void SAKTcpClientTool::writeBytes(const QByteArray& bytes, - const QVariant& context) { - Q_UNUSED(context); - qint64 ret = mTcpSocket->write(bytes); - if (ret == -1) { - outputMessage(QtWarningMsg, mTcpSocket->errorString()); - } else { - emit bytesInputted(bytes, QVariant()); - } +void SAKTcpClientTool::writeBytes(const QByteArray& bytes, const QVariant& context) +{ + Q_UNUSED(context); + qint64 ret = mTcpSocket->write(bytes); + if (ret == -1) { + outputMessage(QtWarningMsg, mTcpSocket->errorString()); + } else { + emit bytesInputted(bytes, QVariant()); + } } -void SAKTcpClientTool::uninitialize() { - mTcpSocket->disconnectFromHost(); - mTcpSocket->close(); - mTcpSocket->deleteLater(); - mTcpSocket = nullptr; +void SAKTcpClientTool::uninitialize() +{ + mTcpSocket->disconnectFromHost(); + mTcpSocket->close(); + mTcpSocket->deleteLater(); + mTcpSocket = nullptr; } -void SAKTcpClientTool::readBytes() { - QHostAddress address = mTcpSocket->peerAddress(); - quint16 port = mTcpSocket->peerPort(); - QByteArray bytes = mTcpSocket->readAll(); - if (!bytes.isEmpty()) { - QByteArray ba = SAKInterface::arrayToHex(bytes, ' '); - QString ipport = address.toString() + ":" + QString::number(port); - QString info = mBindingIpPort + "<-" + ipport + ":"; - info += QString::fromLatin1(ba); - outputMessage(QtDebugMsg, info); - emit bytesOutputted(bytes, rxJsonObject()); - } +void SAKTcpClientTool::readBytes() +{ + QHostAddress address = mTcpSocket->peerAddress(); + quint16 port = mTcpSocket->peerPort(); + QByteArray bytes = mTcpSocket->readAll(); + if (!bytes.isEmpty()) { + QByteArray ba = SAKInterface::arrayToHex(bytes, ' '); + QString ipport = address.toString() + ":" + QString::number(port); + QString info = mBindingIpPort + "<-" + ipport + ":"; + info += QString::fromLatin1(ba); + outputMessage(QtDebugMsg, info); + emit bytesOutputted(bytes, rxJsonObject()); + } } diff --git a/src/tools/tools/saktcpclienttool.h b/src/tools/tools/saktcpclienttool.h index 9c050260..36174b38 100644 --- a/src/tools/tools/saktcpclienttool.h +++ b/src/tools/tools/saktcpclienttool.h @@ -10,8 +10,8 @@ #ifndef SAKTCPCLIENTTOOL_H #define SAKTCPCLIENTTOOL_H -#include #include "saksocketclienttool.h" +#include class SAKTcpClientTool : public SAKSocketClientTool { @@ -21,8 +21,7 @@ public: protected: virtual bool initialize(QString &errStr) final; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; void readBytes(); virtual void uninitialize() final; diff --git a/src/tools/tools/saktcpservertool.cc b/src/tools/tools/saktcpservertool.cc index 6f02c0e3..77704a4f 100644 --- a/src/tools/tools/saktcpservertool.cc +++ b/src/tools/tools/saktcpservertool.cc @@ -14,9 +14,7 @@ SAKTcpServerTool::SAKTcpServerTool(QObject *parent) : SAKSocketServerTool{"sak.tcpservertool", parent} -{ - -} +{} bool SAKTcpServerTool::initialize(QString &errStr) { @@ -29,7 +27,7 @@ bool SAKTcpServerTool::initialize(QString &errStr) mBindingIpPort = QString("%1:%2").arg(mServerIp).arg(mServerPort); outputMessage(QtInfoMsg, "Server ip and port: " + mBindingIpPort); - connect(mTcpServer, &QTcpServer::newConnection, mTcpServer, [=](){ + connect(mTcpServer, &QTcpServer::newConnection, mTcpServer, [=]() { QTcpSocket *client = mTcpServer->nextPendingConnection(); this->mTcpSocketListMutex.lock(); this->mTcpSocketList.append(client); @@ -42,16 +40,14 @@ bool SAKTcpServerTool::initialize(QString &errStr) outputMessage(QtInfoMsg, "New connection:" + ipPort); emit clientsChanged(); - connect(client, &QTcpSocket::readyRead, client, [=](){ + connect(client, &QTcpSocket::readyRead, client, [=]() { QByteArray bytes = client->readAll(); QString hex = bytes.toHex(); - outputMessage(QtInfoMsg, QString("%1<-%2:%3").arg(mBindingIpPort, - ipPort, - hex)); + outputMessage(QtInfoMsg, QString("%1<-%2:%3").arg(mBindingIpPort, ipPort, hex)); emit bytesOutputted(bytes, QVariant()); }); - connect(client, &QTcpSocket::disconnected, client, [=](){ + connect(client, &QTcpSocket::disconnected, client, [=]() { client->deleteLater(); this->mTcpSocketListMutex.lock(); this->mTcpSocketList.removeOne(client); @@ -68,8 +64,7 @@ bool SAKTcpServerTool::initialize(QString &errStr) this->mTcpSocketList.removeOne(client); this->mTcpSocketListMutex.unlock(); this->mClients.removeOne(ipPort); - outputMessage(QtInfoMsg, QString("Error occurred: %1") - .arg(client->errorString())); + outputMessage(QtInfoMsg, QString("Error occurred: %1").arg(client->errorString())); emit clientsChanged(); }); }); @@ -77,8 +72,7 @@ bool SAKTcpServerTool::initialize(QString &errStr) return true; } -void SAKTcpServerTool::writeBytes(const QByteArray &bytes, - const QVariant &context) +void SAKTcpServerTool::writeBytes(const QByteArray &bytes, const QVariant &context) { Q_UNUSED(context); if (mClientIndex >= 0 && mClientIndex < mTcpSocketList.length()) { @@ -110,9 +104,7 @@ void SAKTcpServerTool::writeBytesInner(QTcpSocket *client, quint16 port = client->peerPort(); QString ipPort = QString("%1:%2").arg(ip).arg(port); QString hex = bytes.toHex(); - outputMessage(QtInfoMsg, QString("%1->%2:%3").arg(mBindingIpPort, - ipPort, - hex)); + outputMessage(QtInfoMsg, QString("%1->%2:%3").arg(mBindingIpPort, ipPort, hex)); emit bytesInputted(bytes, context); } } diff --git a/src/tools/tools/saktcpservertool.h b/src/tools/tools/saktcpservertool.h index c1d6fc99..b94e8cfd 100644 --- a/src/tools/tools/saktcpservertool.h +++ b/src/tools/tools/saktcpservertool.h @@ -10,9 +10,9 @@ #ifndef SAKTCPSERVERTOOL_H #define SAKTCPSERVERTOOL_H +#include "saksocketservertool.h" #include #include -#include "saksocketservertool.h" class SAKTcpServerTool : public SAKSocketServerTool { @@ -22,17 +22,17 @@ public: protected: virtual bool initialize(QString &errStr) final; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; virtual void uninitialize() final; private: - void writeBytesInner(QTcpSocket *client, const QByteArray &bytes, + void writeBytesInner(QTcpSocket *client, + const QByteArray &bytes, const QVariant &context = QJsonObject()); private: QTcpServer *mTcpServer{nullptr}; - QList mTcpSocketList; + QList mTcpSocketList; QMutex mTcpSocketListMutex; }; diff --git a/src/tools/tools/saktcptransmittertool.cc b/src/tools/tools/saktcptransmittertool.cc index 22705904..30203c28 100644 --- a/src/tools/tools/saktcptransmittertool.cc +++ b/src/tools/tools/saktcptransmittertool.cc @@ -7,14 +7,12 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "saktcpclienttool.h" #include "saktcptransmittertool.h" +#include "saktcpclienttool.h" SAKTcpTransmitterTool::SAKTcpTransmitterTool(QObject *parent) : SAKSocketClientTransmitterTool{"sak.tcptransmittertool", parent} -{ - -} +{} SAKCommunicationTool *SAKTcpTransmitterTool::createTool() { diff --git a/src/tools/tools/saktoolfactory.cc b/src/tools/tools/saktoolfactory.cc index 6b57098c..3918a34f 100644 --- a/src/tools/tools/saktoolfactory.cc +++ b/src/tools/tools/saktoolfactory.cc @@ -7,34 +7,32 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include -#include "sakmaskertool.h" -#include "sakstorertool.h" #include "saktoolfactory.h" -#include "sakemittertool.h" #include "sakanalyzertool.h" +#include "sakblecentraltool.h" +#include "sakemittertool.h" +#include "sakmaskertool.h" #include "sakprestorertool.h" #include "sakresponsertool.h" -#include "sakudpclienttool.h" -#include "sakudpservertool.h" +#include "sakserialporttool.h" +#include "sakserialporttransmittertool.h" +#include "sakstatisticiantool.h" +#include "sakstorertool.h" #include "saktcpclienttool.h" #include "saktcpservertool.h" -#include "sakvelometertool.h" -#include "sakblecentraltool.h" -#include "sakserialporttool.h" -#include "sakstatisticiantool.h" #include "saktcptransmittertool.h" +#include "sakudpclienttool.h" +#include "sakudpservertool.h" #include "sakudptransmittertool.h" +#include "sakvelometertool.h" #include "sakwebsocketclienttool.h" #include "sakwebsocketservertool.h" #include "sakwebsockettransmittertool.h" -#include "sakserialporttransmittertool.h" +#include SAKToolFactory::SAKToolFactory(QObject *parent) : QObject{parent} -{ - -} +{} SAKToolFactory *SAKToolFactory::instance() { @@ -98,6 +96,5 @@ SAKBaseTool *SAKToolFactory::createTool(int type) Q_ASSERT_X(false, __FUNCTION__, msg.toLatin1().data()); } - return tool; } diff --git a/src/tools/tools/saktoolfactory.h b/src/tools/tools/saktoolfactory.h index 1555453c..106a525a 100644 --- a/src/tools/tools/saktoolfactory.h +++ b/src/tools/tools/saktoolfactory.h @@ -49,7 +49,6 @@ private: public: static SAKToolFactory *instance(); SAKBaseTool *createTool(int type); - }; #endif // SAKTOOLFACTORY_H diff --git a/src/tools/tools/saktransmittertool.cc b/src/tools/tools/saktransmittertool.cc index fb34d842..599ccdd9 100644 --- a/src/tools/tools/saktransmittertool.cc +++ b/src/tools/tools/saktransmittertool.cc @@ -7,14 +7,16 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include #include "saktransmittertool.h" +#include SAKTransmitterTool::SAKTransmitterTool(const char *logCategory, QObject *parent) : SAKTableModelTool{logCategory, parent} { - connect(mTableModel, &QAbstractTableModel::dataChanged, - this, &SAKTransmitterTool::onDataChanged); + connect(mTableModel, + &QAbstractTableModel::dataChanged, + this, + &SAKTransmitterTool::onDataChanged); } SAKCommunicationTool *SAKTransmitterTool::communicationTool(int index) @@ -36,8 +38,7 @@ int SAKTransmitterTool::rowCount(const QModelIndex &parent) const return ret; } -bool SAKTransmitterTool::removeRows(int row, int count, - const QModelIndex &parent) +bool SAKTransmitterTool::removeRows(int row, int count, const QModelIndex &parent) { if (mToolVector.isEmpty()) { return true; @@ -65,27 +66,24 @@ bool SAKTransmitterTool::removeRows(int row, int count, return true; } - -bool SAKTransmitterTool::insertRows(int row, int count, - const QModelIndex &parent) +bool SAKTransmitterTool::insertRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent) - auto initTool = [=](SAKCommunicationTool* tool){ + auto initTool = [=](SAKCommunicationTool *tool) { tool->setParent(this); - connect(this, &SAKCommunicationTool::bytesInputted, - tool, &SAKCommunicationTool::inputBytes); - connect(tool, &SAKCommunicationTool::bytesOutputted, - this, &SAKCommunicationTool::bytesOutputted); - connect(this, &SAKCommunicationTool::started, - tool, [=](){tool->start();}); - connect(this, &SAKCommunicationTool::finished, - tool, [=](){tool->exit();}); + connect(this, &SAKCommunicationTool::bytesInputted, tool, &SAKCommunicationTool::inputBytes); + connect(tool, + &SAKCommunicationTool::bytesOutputted, + this, + &SAKCommunicationTool::bytesOutputted); + connect(this, &SAKCommunicationTool::started, tool, [=]() { tool->start(); }); + connect(this, &SAKCommunicationTool::finished, tool, [=]() { tool->exit(); }); - connect(tool, &SAKCommunicationTool::finished, this, [=](){ + connect(tool, &SAKCommunicationTool::finished, this, [=]() { // Reboot the transmitter thread if tool box is wroking. if (this->isRunning()) { - QTimer::singleShot(1*1000, tool, [=](){ + QTimer::singleShot(1 * 1000, tool, [=]() { qCDebug(mLoggingCategory) << "reboot..."; tool->start(); }); diff --git a/src/tools/tools/saktransmittertool.h b/src/tools/tools/saktransmittertool.h index c822b1f4..33a6d248 100644 --- a/src/tools/tools/saktransmittertool.h +++ b/src/tools/tools/saktransmittertool.h @@ -12,35 +12,27 @@ #include -#include "saktablemodeltool.h" #include "sakcommunicationtool.h" +#include "saktablemodeltool.h" class SAKTransmitterTool : public SAKTableModelTool { Q_OBJECT public: - explicit SAKTransmitterTool(const char *logCategory, - QObject *parent = nullptr); + explicit SAKTransmitterTool(const char *logCategory, QObject *parent = nullptr); SAKCommunicationTool *communicationTool(int index); protected: - virtual void run() override {exec();} + virtual void run() override { exec(); } protected: - virtual int rowCount(const QModelIndex &parent - = QModelIndex()) const override; - virtual bool removeRows(int row, - int count, - const QModelIndex &parent - = QModelIndex()) override; - virtual bool insertRows(int row, - int count, - const QModelIndex &parent - = QModelIndex()) override; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override; + virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; virtual SAKCommunicationTool *createTool() = 0; protected: - QVector mToolVector; + QVector mToolVector; QMutex mToolVectorMutex; private: diff --git a/src/tools/tools/sakudpclienttool.cc b/src/tools/tools/sakudpclienttool.cc index 890e3f4f..858766ec 100644 --- a/src/tools/tools/sakudpclienttool.cc +++ b/src/tools/tools/sakudpclienttool.cc @@ -9,15 +9,13 @@ ******************************************************************************/ #include -#include "sakinterface.h" #include "sakcompatibility.h" +#include "sakinterface.h" #include "sakudpclienttool.h" SAKUdpClientTool::SAKUdpClientTool(QObject *parent) : SAKSocketClientTool{"sak.udpclienttool", parent} -{ - -} +{} bool SAKUdpClientTool::initialize(QString &errStr) { @@ -43,8 +41,7 @@ bool SAKUdpClientTool::initialize(QString &errStr) outputMessage(QtInfoMsg, info); emit bindingIpPortChanged(); - connect(mUdpSocket, &QUdpSocket::readyRead, - mUdpSocket, [=](){readBytes();}); + connect(mUdpSocket, &QUdpSocket::readyRead, mUdpSocket, [=]() { readBytes(); }); connect(mUdpSocket, SAK_SIG_SOCKETERROROCCURRED, this, [=]() { emit errorOccured(mUdpSocket->errorString()); }); @@ -52,16 +49,13 @@ bool SAKUdpClientTool::initialize(QString &errStr) return true; } -void SAKUdpClientTool::writeBytes(const QByteArray &bytes, - const QVariant &context) +void SAKUdpClientTool::writeBytes(const QByteArray &bytes, const QVariant &context) { if (mServerIp.isEmpty()) { return; } - qint64 ret = mUdpSocket->writeDatagram(bytes, - QHostAddress(mServerIp), - mServerPort); + qint64 ret = mUdpSocket->writeDatagram(bytes, QHostAddress(mServerIp), mServerPort); if (ret == -1) { QString ipport = mServerIp + ":" + QString::number(mServerPort); QString str = mUdpSocket->errorString(); @@ -95,9 +89,7 @@ void SAKUdpClientTool::readBytes() QByteArray bytes(len, 0); QHostAddress address; quint16 port; - qint64 ret = mUdpSocket->readDatagram(bytes.data(), - bytes.length(), - &address, &port); + qint64 ret = mUdpSocket->readDatagram(bytes.data(), bytes.length(), &address, &port); if (ret == -1) { outputMessage(QtWarningMsg, mUdpSocket->errorString()); } else { diff --git a/src/tools/tools/sakudpclienttool.h b/src/tools/tools/sakudpclienttool.h index 93a4308f..813f83d1 100644 --- a/src/tools/tools/sakudpclienttool.h +++ b/src/tools/tools/sakudpclienttool.h @@ -10,8 +10,8 @@ #ifndef SAKUDPCLIENTTOOL_H #define SAKUDPCLIENTTOOL_H -#include #include "saksocketclienttool.h" +#include class SAKUdpClientTool : public SAKSocketClientTool { @@ -21,8 +21,7 @@ public: protected: virtual bool initialize(QString &errStr) final; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; virtual void uninitialize() final; void readBytes(); diff --git a/src/tools/tools/sakudpservertool.cc b/src/tools/tools/sakudpservertool.cc index ccb2524b..3cd393eb 100644 --- a/src/tools/tools/sakudpservertool.cc +++ b/src/tools/tools/sakudpservertool.cc @@ -14,9 +14,7 @@ SAKUdpServerTool::SAKUdpServerTool(QObject *parent) : SAKSocketServerTool{"sak.udpservertool", parent} -{ - -} +{} bool SAKUdpServerTool::initialize(QString &errStr) { @@ -40,8 +38,7 @@ bool SAKUdpServerTool::initialize(QString &errStr) outputMessage(QtInfoMsg, mBindingIpPort); emit bindingIpPortChanged(); - connect(mUdpSocket, &QUdpSocket::readyRead, - mUdpSocket, [=](){readBytes();}); + connect(mUdpSocket, &QUdpSocket::readyRead, mUdpSocket, [=]() { readBytes(); }); connect(mUdpSocket, SAK_SIG_SOCKETERROROCCURRED, this, [=]() { emit errorOccured(mUdpSocket->errorString()); }); @@ -49,8 +46,7 @@ bool SAKUdpServerTool::initialize(QString &errStr) return true; } -void SAKUdpServerTool::writeBytes(const QByteArray &bytes, - const QVariant &context) +void SAKUdpServerTool::writeBytes(const QByteArray &bytes, const QVariant &context) { if (mClientIndex >= 0 && mClientIndex < mClients.length()) { QString ipPort = mClients.at(mClientIndex); @@ -85,8 +81,7 @@ void SAKUdpServerTool::readBytes() QByteArray bytes(len, 0); QHostAddress address; quint16 port; - qint64 ret = mUdpSocket->readDatagram(bytes.data(), bytes.length(), - &address, &port); + qint64 ret = mUdpSocket->readDatagram(bytes.data(), bytes.length(), &address, &port); if (ret == -1) { outputMessage(QtWarningMsg, mUdpSocket->errorString()); break; @@ -94,10 +89,8 @@ void SAKUdpServerTool::readBytes() QByteArray ba = SAKInterface::arrayToHex(bytes, ' '); QString hex = QString::fromLatin1(ba); - QString info = - QString("%1:%2").arg(address.toString()).arg(port); - QString msg = - QString("%1<-%2:%3").arg(mBindingIpPort, info, hex); + QString info = QString("%1:%2").arg(address.toString()).arg(port); + QString msg = QString("%1<-%2:%3").arg(mBindingIpPort, info, hex); outputMessage(QtInfoMsg, msg); if (!mClients.contains(info)) { @@ -111,15 +104,15 @@ void SAKUdpServerTool::readBytes() void SAKUdpServerTool::writeDatagram(const QByteArray &bytes, const QVariant &context, - const QString &ip, quint16 port) + const QString &ip, + quint16 port) { qint64 ret = mUdpSocket->writeDatagram(bytes, QHostAddress(ip), port); if (ret == -1) { outputMessage(QtWarningMsg, mUdpSocket->errorString()); } else { QString hex = QString::fromLatin1(SAKInterface::arrayToHex(bytes, ' ')); - outputMessage(QtInfoMsg, - QString("%1<-%2").arg(mBindingIpPort, hex)); + outputMessage(QtInfoMsg, QString("%1<-%2").arg(mBindingIpPort, hex)); emit bytesInputted(bytes, context); } } diff --git a/src/tools/tools/sakudpservertool.h b/src/tools/tools/sakudpservertool.h index 28955052..c96bc3c0 100644 --- a/src/tools/tools/sakudpservertool.h +++ b/src/tools/tools/sakudpservertool.h @@ -10,8 +10,8 @@ #ifndef SAKUDPSERVERTOOL_H #define SAKUDPSERVERTOOL_H -#include #include "saksocketservertool.h" +#include class SAKUdpServerTool : public SAKSocketServerTool { @@ -21,8 +21,7 @@ public: protected: virtual bool initialize(QString &errStr) final; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; virtual void uninitialize() final; void readBytes(); @@ -30,8 +29,10 @@ private: QUdpSocket *mUdpSocket{nullptr}; private: - void writeDatagram(const QByteArray &bytes, const QVariant &context, - const QString &ip, quint16 port); + void writeDatagram(const QByteArray &bytes, + const QVariant &context, + const QString &ip, + quint16 port); }; #endif // SAKUDPSERVERTOOL_H diff --git a/src/tools/tools/sakudptransmittertool.cc b/src/tools/tools/sakudptransmittertool.cc index 730cbc27..3b076eb8 100644 --- a/src/tools/tools/sakudptransmittertool.cc +++ b/src/tools/tools/sakudptransmittertool.cc @@ -14,9 +14,7 @@ SAKUdpTransmitterTool::SAKUdpTransmitterTool(QObject *parent) : SAKSocketClientTransmitterTool{"sak.udptransmittertool", parent} -{ - -} +{} SAKCommunicationTool *SAKUdpTransmitterTool::createTool() { diff --git a/src/tools/tools/sakvelometertool.cc b/src/tools/tools/sakvelometertool.cc index c5510869..54369535 100644 --- a/src/tools/tools/sakvelometertool.cc +++ b/src/tools/tools/sakvelometertool.cc @@ -7,17 +7,14 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include #include "sakvelometertool.h" +#include SAKVelometerTool::SAKVelometerTool(QObject *parent) : SAKBaseTool{"sak.velometertool", parent} -{ +{} -} - -void SAKVelometerTool::inputBytes(const QByteArray &bytes, - const QVariant &context) +void SAKVelometerTool::inputBytes(const QByteArray &bytes, const QVariant &context) { if (isRunning()) { InputBytesContext ctx; @@ -35,7 +32,7 @@ void SAKVelometerTool::run() QTimer *timer = new QTimer(); timer->setInterval(1000); timer->setSingleShot(true); - connect(timer, &QTimer::timeout, timer, [=](){ + connect(timer, &QTimer::timeout, timer, [=]() { this->mInputBytesContextListMutex.lock(); auto list = this->mInputBytesContextList; this->mInputBytesContextList.clear(); @@ -49,10 +46,10 @@ void SAKVelometerTool::run() QString cookedVelocity; if (v < 1024) { cookedVelocity = QString("%1Bytes/s").arg(v); - } else if (v < 1024*1024) { - cookedVelocity = QString("%1KB/s").arg(v/1024); + } else if (v < 1024 * 1024) { + cookedVelocity = QString("%1KB/s").arg(v / 1024); } else { - cookedVelocity = QString("%1MB/s").arg(v/(1024*1024)); + cookedVelocity = QString("%1MB/s").arg(v / (1024 * 1024)); } this->mVelocityMutex.lock(); diff --git a/src/tools/tools/sakvelometertool.h b/src/tools/tools/sakvelometertool.h index ad500842..bb9b5773 100644 --- a/src/tools/tools/sakvelometertool.h +++ b/src/tools/tools/sakvelometertool.h @@ -10,9 +10,9 @@ #ifndef SAKVELOMETERTOOL_H #define SAKVELOMETERTOOL_H +#include "sakbasetool.h" #include #include -#include "sakbasetool.h" class SAKVelometerTool : public SAKBaseTool { @@ -21,14 +21,14 @@ class SAKVelometerTool : public SAKBaseTool public: explicit SAKVelometerTool(QObject *parent = nullptr); - virtual void inputBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void inputBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; protected: void run(); private: - struct InputBytesContext { + struct InputBytesContext + { QByteArray bytes; QVariant context; }; diff --git a/src/tools/tools/sakwebsocketservertool.cc b/src/tools/tools/sakwebsocketservertool.cc index 3d143ea6..04c777ab 100644 --- a/src/tools/tools/sakwebsocketservertool.cc +++ b/src/tools/tools/sakwebsocketservertool.cc @@ -16,33 +16,35 @@ #define WS_ERR_SIGNAL void (QWebSocket::*)(QAbstractSocket::SocketError) SAKWebSocketServerTool::SAKWebSocketServerTool(QObject *parent) - : SAKSocketServerTool{"sak.websocketservertool", parent} {} + : SAKSocketServerTool{"sak.websocketservertool", parent} +{} -bool SAKWebSocketServerTool::initialize(QString &errStr) { - QString serverName = QString("%1:%2").arg(mServerIp).arg(mServerPort); - mWebSocketServer = - new QWebSocketServer(serverName, QWebSocketServer::NonSecureMode); - if (!mWebSocketServer->listen(QHostAddress(mServerIp), mServerPort)) { - errStr = mWebSocketServer->errorString(); - outputMessage(QtWarningMsg, errStr); - return false; - } +bool SAKWebSocketServerTool::initialize(QString &errStr) +{ + QString serverName = QString("%1:%2").arg(mServerIp).arg(mServerPort); + mWebSocketServer = new QWebSocketServer(serverName, QWebSocketServer::NonSecureMode); + if (!mWebSocketServer->listen(QHostAddress(mServerIp), mServerPort)) { + errStr = mWebSocketServer->errorString(); + outputMessage(QtWarningMsg, errStr); + return false; + } - QString mBindingIpPort = QString("%1:%2").arg(mServerIp).arg(mServerPort); - outputMessage(QtInfoMsg, "Server url: " + mBindingIpPort); + QString mBindingIpPort = QString("%1:%2").arg(mServerIp).arg(mServerPort); + outputMessage(QtInfoMsg, "Server url: " + mBindingIpPort); - connect(mWebSocketServer, &QWebSocketServer::serverError, mWebSocketServer, - [=](QWebSocketProtocol::CloseCode closeCode) { - Q_UNUSED(closeCode) - emit errorOccured(mWebSocketServer->errorString()); - }); + connect(mWebSocketServer, + &QWebSocketServer::serverError, + mWebSocketServer, + [=](QWebSocketProtocol::CloseCode closeCode) { + Q_UNUSED(closeCode) + emit errorOccured(mWebSocketServer->errorString()); + }); - connect(mWebSocketServer, &QWebSocketServer::acceptError, mWebSocketServer, - [=]() { emit errorOccured(mWebSocketServer->errorString()); }); + connect(mWebSocketServer, &QWebSocketServer::acceptError, mWebSocketServer, [=]() { + emit errorOccured(mWebSocketServer->errorString()); + }); - connect( - mWebSocketServer, &QWebSocketServer::newConnection, mWebSocketServer, - [=]() { + connect(mWebSocketServer, &QWebSocketServer::newConnection, mWebSocketServer, [=]() { QWebSocket *client = mWebSocketServer->nextPendingConnection(); mWebSocketList.append(client); @@ -52,100 +54,94 @@ bool SAKWebSocketServerTool::initialize(QString &errStr) { mClients.append(ipPort); emit clientsChanged(); - connect(client, &QWebSocket::textMessageReceived, client, - [=](const QString &message) { - QByteArray bytes = message.toUtf8(); - QString ip = client->peerAddress().toString(); - quint16 port = client->peerPort(); - QString ipport = - QString("%1:%2").arg(ip, QString::number(port)); - QString hex = QString::fromUtf8(bytes); - outputMessage( - QtInfoMsg, - QString("%1<-%2:%3").arg(mBindingIpPort, ipport, hex)); - emit bytesOutputted(bytes, QVariant()); - }); + connect(client, &QWebSocket::textMessageReceived, client, [=](const QString &message) { + QByteArray bytes = message.toUtf8(); + QString ip = client->peerAddress().toString(); + quint16 port = client->peerPort(); + QString ipport = QString("%1:%2").arg(ip, QString::number(port)); + QString hex = QString::fromUtf8(bytes); + outputMessage(QtInfoMsg, QString("%1<-%2:%3").arg(mBindingIpPort, ipport, hex)); + emit bytesOutputted(bytes, QVariant()); + }); - connect(client, &QWebSocket::binaryMessageReceived, client, - [=](const QByteArray &message) { - QString ip = client->peerAddress().toString(); - quint16 port = client->peerPort(); - QString ipport = - QString("%1:%2").arg(ip, QString::number(port)); - QString hex = QString::fromUtf8(message); - outputMessage( - QtInfoMsg, - QString("%1<-%2:%3").arg(mBindingIpPort, ipport, hex)); - emit bytesOutputted(message, QVariant()); - }); + connect(client, &QWebSocket::binaryMessageReceived, client, [=](const QByteArray &message) { + QString ip = client->peerAddress().toString(); + quint16 port = client->peerPort(); + QString ipport = QString("%1:%2").arg(ip, QString::number(port)); + QString hex = QString::fromUtf8(message); + outputMessage(QtInfoMsg, QString("%1<-%2:%3").arg(mBindingIpPort, ipport, hex)); + emit bytesOutputted(message, QVariant()); + }); connect(client, &QWebSocket::disconnected, client, [=]() { - this->mWebSocketList.removeOne(client); - this->mClients.removeOne(ipPort); - outputMessage(QtInfoMsg, - QString("Connection(%1) has been disconnected: %2") - .arg(mBindingIpPort, client->errorString())); - emit clientsChanged(); + this->mWebSocketList.removeOne(client); + this->mClients.removeOne(ipPort); + outputMessage(QtInfoMsg, + QString("Connection(%1) has been disconnected: %2") + .arg(mBindingIpPort, client->errorString())); + emit clientsChanged(); }); #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) - connect(client, static_cast(&QWebSocket::errorOccurred), + connect(client, + static_cast(&QWebSocket::errorOccurred), #else connect(client, static_cast(&QWebSocket::error), #endif - client, [=](QAbstractSocket::SocketError err) { - Q_UNUSED(err); - this->mWebSocketList.removeOne(client); - this->mClients.removeOne(ipPort); - outputMessage( - QtInfoMsg, - QString("Error occurred: %1").arg(client->errorString())); - emit clientsChanged(); + client, + [=](QAbstractSocket::SocketError err) { + Q_UNUSED(err); + this->mWebSocketList.removeOne(client); + this->mClients.removeOne(ipPort); + outputMessage(QtInfoMsg, + QString("Error occurred: %1").arg(client->errorString())); + emit clientsChanged(); }); - }); + }); - return true; + return true; } -void SAKWebSocketServerTool::writeBytes(const QByteArray &bytes, - const QVariant &context) { - Q_UNUSED(context); - if (mClientIndex >= 0 && mClientIndex < mWebSocketList.length()) { - QWebSocket *client = mWebSocketList.at(mClientIndex); - writeBytesInner(client, bytes, context); - } else { - for (auto &client : mWebSocketList) { - writeBytesInner(client, bytes, context); +void SAKWebSocketServerTool::writeBytes(const QByteArray &bytes, const QVariant &context) +{ + Q_UNUSED(context); + if (mClientIndex >= 0 && mClientIndex < mWebSocketList.length()) { + QWebSocket *client = mWebSocketList.at(mClientIndex); + writeBytesInner(client, bytes, context); + } else { + for (auto &client : mWebSocketList) { + writeBytesInner(client, bytes, context); + } } - } } -void SAKWebSocketServerTool::uninitialize() { - mWebSocketServer->close(); - mWebSocketServer->deleteLater(); - mWebSocketServer = nullptr; +void SAKWebSocketServerTool::uninitialize() +{ + mWebSocketServer->close(); + mWebSocketServer->deleteLater(); + mWebSocketServer = nullptr; } void SAKWebSocketServerTool::writeBytesInner(QWebSocket *client, const QByteArray &bytes, - const QVariant &context) { - qint64 ret = -1; - QString hex; - if (mMessageType == 0) { - hex = QString::fromLatin1(SAKInterface::arrayToHex(bytes, ' ')); - ret = client->sendBinaryMessage(bytes); - } else { - hex = QString::fromUtf8(bytes); - ret = client->sendTextMessage(QString::fromUtf8(bytes)); - } + const QVariant &context) +{ + qint64 ret = -1; + QString hex; + if (mMessageType == 0) { + hex = QString::fromLatin1(SAKInterface::arrayToHex(bytes, ' ')); + ret = client->sendBinaryMessage(bytes); + } else { + hex = QString::fromUtf8(bytes); + ret = client->sendTextMessage(QString::fromUtf8(bytes)); + } - if (ret == -1) { - outputMessage(QtWarningMsg, client->errorString()); - } else { - QString ip = client->peerAddress().toString(); - quint16 port = client->peerPort(); - QString ipport = QString("%1:%2").arg(ip, QString::number(port)); - outputMessage(QtInfoMsg, - QString("%1->%2:%3").arg(this->mBindingIpPort, ipport, hex)); - emit bytesInputted(bytes, context); - } + if (ret == -1) { + outputMessage(QtWarningMsg, client->errorString()); + } else { + QString ip = client->peerAddress().toString(); + quint16 port = client->peerPort(); + QString ipport = QString("%1:%2").arg(ip, QString::number(port)); + outputMessage(QtInfoMsg, QString("%1->%2:%3").arg(this->mBindingIpPort, ipport, hex)); + emit bytesInputted(bytes, context); + } } diff --git a/src/tools/tools/sakwebsocketservertool.h b/src/tools/tools/sakwebsocketservertool.h index 40afb322..a75285ae 100644 --- a/src/tools/tools/sakwebsocketservertool.h +++ b/src/tools/tools/sakwebsocketservertool.h @@ -10,8 +10,8 @@ #ifndef SAKWEBSOCKETSERVERTOOL_H #define SAKWEBSOCKETSERVERTOOL_H -#include #include "saksocketservertool.h" +#include class SAKWebSocketServerTool : public SAKSocketServerTool { @@ -21,17 +21,17 @@ public: protected: virtual bool initialize(QString &errStr) final; - virtual void writeBytes(const QByteArray &bytes, - const QVariant &context = QJsonObject()) final; + virtual void writeBytes(const QByteArray &bytes, const QVariant &context = QJsonObject()) final; virtual void uninitialize() final; private: - void writeBytesInner(QWebSocket *client, const QByteArray &bytes, + void writeBytesInner(QWebSocket *client, + const QByteArray &bytes, const QVariant &context = QJsonObject()); private: QWebSocketServer *mWebSocketServer{nullptr}; - QList mWebSocketList; + QList mWebSocketList; }; #endif // SAKWEBSOCKETSERVERTOOL_H diff --git a/src/tools/tools/sakwebsockettransmittertool.cc b/src/tools/tools/sakwebsockettransmittertool.cc index f860c255..9551e4f3 100644 --- a/src/tools/tools/sakwebsockettransmittertool.cc +++ b/src/tools/tools/sakwebsockettransmittertool.cc @@ -7,14 +7,12 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakwebsocketclienttool.h" #include "sakwebsockettransmittertool.h" +#include "sakwebsocketclienttool.h" SAKWebSocketTransmitterTool::SAKWebSocketTransmitterTool(QObject *parent) : SAKSocketClientTransmitterTool{"sak.websockettransmittertool", parent} -{ - -} +{} SAKCommunicationTool *SAKWebSocketTransmitterTool::createTool() { diff --git a/src/tools/toolsui/sakanalyzertoolui.cc b/src/tools/toolsui/sakanalyzertoolui.cc index 3d40afa1..fc70ea2d 100644 --- a/src/tools/toolsui/sakanalyzertoolui.cc +++ b/src/tools/toolsui/sakanalyzertoolui.cc @@ -16,77 +16,82 @@ #include "ui_sakanalyzertoolui.h" SAKAnalyzerToolUi::SAKAnalyzerToolUi(QWidget *parent) - : SAKBaseToolUi{parent}, ui(new Ui::SAKAnalyzerToolUi) { - ui->setupUi(this); + : SAKBaseToolUi{parent} + , ui(new Ui::SAKAnalyzerToolUi) +{ + ui->setupUi(this); } -void SAKAnalyzerToolUi::setToolName(const QString &name) { - ui->groupBox->setTitle(name); +void SAKAnalyzerToolUi::setToolName(const QString &name) +{ + ui->groupBox->setTitle(name); } -void SAKAnalyzerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) { - int format = SAKDataStructure::TextFormatHex; - SAKUiInterface::setValidator(ui->lineEditSeparationMark, format); +void SAKAnalyzerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) +{ + int format = SAKDataStructure::TextFormatHex; + SAKUiInterface::setValidator(ui->lineEditSeparationMark, format); - ui->checkBoxEnable->setGroupKey(settingsGroup, "analyzerEnable"); - ui->checkBoxFixedLength->setGroupKey(settingsGroup, "fxiedLength"); - ui->spinBoxFrameLength->setGroupKey(settingsGroup, "frameLength"); - ui->spinBoxMaxTempBytes->setGroupKey(settingsGroup, "maxTempBytes"); - ui->lineEditSeparationMark->setGroupKey(settingsGroup, "separationMark"); + ui->checkBoxEnable->setGroupKey(settingsGroup, "analyzerEnable"); + ui->checkBoxFixedLength->setGroupKey(settingsGroup, "fxiedLength"); + ui->spinBoxFrameLength->setGroupKey(settingsGroup, "frameLength"); + ui->spinBoxMaxTempBytes->setGroupKey(settingsGroup, "maxTempBytes"); + ui->lineEditSeparationMark->setGroupKey(settingsGroup, "separationMark"); - auto cookedTool = qobject_cast(tool); - static QByteArray tips("invalid SAKAnalyzerTool"); - Q_ASSERT_X(cookedTool, __FUNCTION__, tips.constData()); - if (!cookedTool) { - qCWarning((*mLoggingCategory)) << QString::fromLatin1(tips); - return; - } + auto cookedTool = qobject_cast(tool); + static QByteArray tips("invalid SAKAnalyzerTool"); + Q_ASSERT_X(cookedTool, __FUNCTION__, tips.constData()); + if (!cookedTool) { + qCWarning((*mLoggingCategory)) << QString::fromLatin1(tips); + return; + } - bool enable = ui->checkBoxEnable->isChecked(); - bool fixed = ui->checkBoxFixedLength->isChecked(); - int len = ui->spinBoxFrameLength->value(); - int maxBytes = ui->spinBoxMaxTempBytes->value(); - QString txt = ui->lineEditSeparationMark->text().trimmed(); - QByteArray flag = SAKInterface::string2array(txt, format); - - cookedTool->setEnable(enable); - cookedTool->setFixed(fixed); - cookedTool->setFrameBytes(len); - cookedTool->setMaxTempBytes(maxBytes); - cookedTool->setSeparationMark(flag); - - connect(ui->checkBoxEnable, &QCheckBox::clicked, this, [=]() { bool enable = ui->checkBoxEnable->isChecked(); - cookedTool->setEnable(enable); - }); - connect(ui->checkBoxFixedLength, &QCheckBox::clicked, this, [=]() { bool fixed = ui->checkBoxFixedLength->isChecked(); + int len = ui->spinBoxFrameLength->value(); + int maxBytes = ui->spinBoxMaxTempBytes->value(); + QString txt = ui->lineEditSeparationMark->text().trimmed(); + QByteArray flag = SAKInterface::string2array(txt, format); + + cookedTool->setEnable(enable); cookedTool->setFixed(fixed); - }); - connect(ui->spinBoxFrameLength, + cookedTool->setFrameBytes(len); + cookedTool->setMaxTempBytes(maxBytes); + cookedTool->setSeparationMark(flag); + + connect(ui->checkBoxEnable, &QCheckBox::clicked, this, [=]() { + bool enable = ui->checkBoxEnable->isChecked(); + cookedTool->setEnable(enable); + }); + connect(ui->checkBoxFixedLength, &QCheckBox::clicked, this, [=]() { + bool fixed = ui->checkBoxFixedLength->isChecked(); + cookedTool->setFixed(fixed); + }); + connect(ui->spinBoxFrameLength, #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QOverload::of(&QSpinBox::valueChanged), + QOverload::of(&QSpinBox::valueChanged), #else &QSpinBox::valueChanged, #endif - this, [=]() { - int len = ui->spinBoxFrameLength->value(); - cookedTool->setFrameBytes(len); - }); - connect(ui->spinBoxMaxTempBytes, + this, + [=]() { + int len = ui->spinBoxFrameLength->value(); + cookedTool->setFrameBytes(len); + }); + connect(ui->spinBoxMaxTempBytes, #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QOverload::of(&QSpinBox::valueChanged), + QOverload::of(&QSpinBox::valueChanged), #else &QSpinBox::valueChanged, #endif - this, [=]() { - int maxBytes = ui->spinBoxMaxTempBytes->value(); - cookedTool->setMaxTempBytes(maxBytes); - }); - connect(ui->lineEditSeparationMark, &QLineEdit::textChanged, this, [=]() { - QString txt = ui->lineEditSeparationMark->text().trimmed(); - QByteArray flag = SAKInterface::string2array(txt, format); - cookedTool->setSeparationMark(flag); - }); + this, + [=]() { + int maxBytes = ui->spinBoxMaxTempBytes->value(); + cookedTool->setMaxTempBytes(maxBytes); + }); + connect(ui->lineEditSeparationMark, &QLineEdit::textChanged, this, [=]() { + QString txt = ui->lineEditSeparationMark->text().trimmed(); + QByteArray flag = SAKInterface::string2array(txt, format); + cookedTool->setSeparationMark(flag); + }); } diff --git a/src/tools/toolsui/sakanalyzertoolui.h b/src/tools/toolsui/sakanalyzertoolui.h index 4ee755a2..02c54844 100644 --- a/src/tools/toolsui/sakanalyzertoolui.h +++ b/src/tools/toolsui/sakanalyzertoolui.h @@ -23,8 +23,7 @@ class SAKAnalyzerToolUi : public SAKBaseToolUi public: explicit SAKAnalyzerToolUi(QWidget *parent = nullptr); void setToolName(const QString &name); - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: Ui::SAKAnalyzerToolUi *ui; diff --git a/src/tools/toolsui/sakbasetoolui.cc b/src/tools/toolsui/sakbasetoolui.cc index 2b65e01d..629d0db1 100644 --- a/src/tools/toolsui/sakbasetoolui.cc +++ b/src/tools/toolsui/sakbasetoolui.cc @@ -7,14 +7,12 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakbasetool.h" #include "sakbasetoolui.h" +#include "sakbasetool.h" SAKBaseToolUi::SAKBaseToolUi(QWidget *parent) : QWidget{parent} -{ - -} +{} void SAKBaseToolUi::initialize(SAKBaseTool *tool, const QString &settingsGroup, @@ -33,7 +31,7 @@ void SAKBaseToolUi::initialize(SAKBaseTool *tool, return; } - connect(tool, &SAKBaseTool::isWorkingChanged, this, [=](){ + connect(tool, &SAKBaseTool::isWorkingChanged, this, [=]() { onIsWorkingChanged(tool->isWorking()); }); @@ -45,8 +43,7 @@ void SAKBaseToolUi::onIsWorkingChanged(bool isWorking) Q_UNUSED(isWorking) } -void SAKBaseToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) +void SAKBaseToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { Q_UNUSED(tool) Q_UNUSED(settingsGroup) diff --git a/src/tools/toolsui/sakbasetoolui.h b/src/tools/toolsui/sakbasetoolui.h index 15cacf45..ccf173b0 100644 --- a/src/tools/toolsui/sakbasetoolui.h +++ b/src/tools/toolsui/sakbasetoolui.h @@ -10,8 +10,8 @@ #ifndef SAKBASETOOLUI_H #define SAKBASETOOLUI_H -#include #include +#include class SAKBaseTool; class SAKBaseToolUi : public QWidget @@ -26,8 +26,7 @@ public: protected: virtual void onIsWorkingChanged(bool isWorking); - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup); + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup); protected: QLoggingCategory *mLoggingCategory{nullptr}; diff --git a/src/tools/toolsui/sakblecentraltoolui.cc b/src/tools/toolsui/sakblecentraltoolui.cc index 4927ecfa..a634a94c 100644 --- a/src/tools/toolsui/sakblecentraltoolui.cc +++ b/src/tools/toolsui/sakblecentraltoolui.cc @@ -23,225 +23,256 @@ #define SAK_CB_I_C &QComboBox::currentIndexChanged SAKBleCentralToolUi::SAKBleCentralToolUi(QWidget* parent) - : SAKCommunicationToolUi{parent}, - ui(new Ui::SAKBleCentralToolUi), - mBleTool(Q_NULLPTR) { - ui->setupUi(this); - ui->progressBar->hide(); - connect(ui->pushButtonScan, &QPushButton::clicked, this, - &SAKBleCentralToolUi::onPushButtonScanClicked); - connect(ui->comboBoxDevices, - static_cast(SAK_CB_I_C), this, - &SAKBleCentralToolUi::onComboBoxDevicesActived); - connect(ui->comboBoxServices, - static_cast(SAK_CB_I_C), this, - &SAKBleCentralToolUi::onComboBoxServicesCurrentIndexChanged); - connect(ui->comboBoxCharacteristics, - static_cast(SAK_CB_I_C), this, - &SAKBleCentralToolUi::onComboBoxCharacteristicsActived); - connect(ui->comboBoxWriteWay, - static_cast(SAK_CB_I_C), this, - &SAKBleCentralToolUi::onComboBoxWriteWayCurrentIndexChanged); - connect(ui->pushButtonNotify, &QPushButton::clicked, this, - &SAKBleCentralToolUi::onPushButtonNotifyClicked); - connect(ui->pushButtonRead, &QPushButton::clicked, this, - &SAKBleCentralToolUi::onPushButtonReadClicked); - connect(ui->comboBoxDevices, &SAKBluetoothDeviceInfoComboBox::finished, this, - [=]() { - ui->pushButtonScan->setText(tr("Scan")); - ui->pushButtonScan->setEnabled(true); - }); - connect(ui->comboBoxDevices, &SAKBluetoothDeviceInfoComboBox::started, this, - [=]() { - ui->pushButtonScan->setText(tr("Stop")); - ui->pushButtonScan->setEnabled(true); - }); - - ui->labelWriteWay->setVisible(false); - ui->comboBoxWriteWay->setVisible(false); - ui->pushButtonNotify->setVisible(false); - ui->pushButtonRead->setVisible(false); - ui->labelUnsupported->setVisible(false); - ui->labelUnsupported->setStyleSheet("QLabel{color:red}"); -} - -SAKBleCentralToolUi::~SAKBleCentralToolUi() { - delete ui; -} - -void SAKBleCentralToolUi::onBaseToolUiInitialized( - SAKBaseTool* tool, const QString& settingsGroup) { - SAKCommunicationToolUi::onBaseToolUiInitialized(tool, settingsGroup); - - mBleTool = qobject_cast(mTool); - if (!mBleTool) { - QByteArray msg("invalid SAKBleCentralTool tool"); - qCWarning(mLoggingCategory) << QString::fromLatin1(msg); - Q_ASSERT_X(false, __FUNCTION__, msg.data()); - return; - } - - onComboBoxWriteWayCurrentIndexChanged(); - connect(mBleTool, &SAKBleCentralTool::descriptorWritten, this, - &SAKBleCentralToolUi::onDescriptorWritten); - - initSettingsMenu(settingsGroup); -} - -void SAKBleCentralToolUi::onIsWorkingChanged(bool isWorking) { - if (!isWorking) { + : SAKCommunicationToolUi{parent} + , ui(new Ui::SAKBleCentralToolUi) + , mBleTool(Q_NULLPTR) +{ + ui->setupUi(this); ui->progressBar->hide(); - } + connect(ui->pushButtonScan, + &QPushButton::clicked, + this, + &SAKBleCentralToolUi::onPushButtonScanClicked); + connect(ui->comboBoxDevices, + static_cast(SAK_CB_I_C), + this, + &SAKBleCentralToolUi::onComboBoxDevicesActived); + connect(ui->comboBoxServices, + static_cast(SAK_CB_I_C), + this, + &SAKBleCentralToolUi::onComboBoxServicesCurrentIndexChanged); + connect(ui->comboBoxCharacteristics, + static_cast(SAK_CB_I_C), + this, + &SAKBleCentralToolUi::onComboBoxCharacteristicsActived); + connect(ui->comboBoxWriteWay, + static_cast(SAK_CB_I_C), + this, + &SAKBleCentralToolUi::onComboBoxWriteWayCurrentIndexChanged); + connect(ui->pushButtonNotify, + &QPushButton::clicked, + this, + &SAKBleCentralToolUi::onPushButtonNotifyClicked); + connect(ui->pushButtonRead, + &QPushButton::clicked, + this, + &SAKBleCentralToolUi::onPushButtonReadClicked); + connect(ui->comboBoxDevices, &SAKBluetoothDeviceInfoComboBox::finished, this, [=]() { + ui->pushButtonScan->setText(tr("Scan")); + ui->pushButtonScan->setEnabled(true); + }); + connect(ui->comboBoxDevices, &SAKBluetoothDeviceInfoComboBox::started, this, [=]() { + ui->pushButtonScan->setText(tr("Stop")); + ui->pushButtonScan->setEnabled(true); + }); + + ui->labelWriteWay->setVisible(false); + ui->comboBoxWriteWay->setVisible(false); + ui->pushButtonNotify->setVisible(false); + ui->pushButtonRead->setVisible(false); + ui->labelUnsupported->setVisible(false); + ui->labelUnsupported->setStyleSheet("QLabel{color:red}"); } -void SAKBleCentralToolUi::initSettingsMenu(const QString& settingsGroup) { - QWidget* w = new QWidget(this); - QGridLayout* gl = new QGridLayout(); - w->setLayout(gl); +SAKBleCentralToolUi::~SAKBleCentralToolUi() +{ + delete ui; +} - int rowIndex = 0; - gl->addWidget(new QLabel(tr("Timeout interval(S)"), w), rowIndex, 0, 1, 1); - SAKSpinBox* sp = new SAKSpinBox(w); - sp->setMinimum(10); - sp->setMaximum(120); - sp->setValue(120); - sp->setGroupKey(settingsGroup, "timeoutInterval"); - gl->addWidget(sp, rowIndex, 1, 1, 1); - connect(sp, +void SAKBleCentralToolUi::onBaseToolUiInitialized(SAKBaseTool* tool, const QString& settingsGroup) +{ + SAKCommunicationToolUi::onBaseToolUiInitialized(tool, settingsGroup); + + mBleTool = qobject_cast(mTool); + if (!mBleTool) { + QByteArray msg("invalid SAKBleCentralTool tool"); + qCWarning(mLoggingCategory) << QString::fromLatin1(msg); + Q_ASSERT_X(false, __FUNCTION__, msg.data()); + return; + } + + onComboBoxWriteWayCurrentIndexChanged(); + connect(mBleTool, + &SAKBleCentralTool::descriptorWritten, + this, + &SAKBleCentralToolUi::onDescriptorWritten); + + initSettingsMenu(settingsGroup); +} + +void SAKBleCentralToolUi::onIsWorkingChanged(bool isWorking) +{ + if (!isWorking) { + ui->progressBar->hide(); + } +} + +void SAKBleCentralToolUi::initSettingsMenu(const QString& settingsGroup) +{ + QWidget* w = new QWidget(this); + QGridLayout* gl = new QGridLayout(); + w->setLayout(gl); + + int rowIndex = 0; + gl->addWidget(new QLabel(tr("Timeout interval(S)"), w), rowIndex, 0, 1, 1); + SAKSpinBox* sp = new SAKSpinBox(w); + sp->setMinimum(10); + sp->setMaximum(120); + sp->setValue(120); + sp->setGroupKey(settingsGroup, "timeoutInterval"); + gl->addWidget(sp, rowIndex, 1, 1, 1); + connect(sp, #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - QOverload::of(&QSpinBox::valueChanged), + QOverload::of(&QSpinBox::valueChanged), #else &QSpinBox::valueChanged, #endif - this, [=](int v) { ui->comboBoxDevices->setTimeoutInterval(v); }); + this, + [=](int v) { ui->comboBoxDevices->setTimeoutInterval(v); }); - rowIndex += 1; - gl->addWidget(new QLabel(tr("Name filtter"), w), rowIndex, 0, 1, 1); - SAKLineEdit* le = new SAKLineEdit(w); - le->setGroupKey(settingsGroup, "nameFiltter"); - gl->addWidget(le, rowIndex, 1, 1, 1); - connect(le, &SAKLineEdit::textChanged, this, [=](const QString& text) { - ui->comboBoxDevices->setNameFiltter(text); - }); + rowIndex += 1; + gl->addWidget(new QLabel(tr("Name filtter"), w), rowIndex, 0, 1, 1); + SAKLineEdit* le = new SAKLineEdit(w); + le->setGroupKey(settingsGroup, "nameFiltter"); + gl->addWidget(le, rowIndex, 1, 1, 1); + connect(le, &SAKLineEdit::textChanged, this, [=](const QString& text) { + ui->comboBoxDevices->setNameFiltter(text); + }); - rowIndex += 1; - QMenu* menu = new QMenu(this); - QPushButton* bt = new QPushButton(tr("OK")); - connect(bt, &QPushButton::clicked, menu, &QMenu::close); - gl->addWidget(bt, rowIndex, 1, 1, 1); + rowIndex += 1; + QMenu* menu = new QMenu(this); + QPushButton* bt = new QPushButton(tr("OK")); + connect(bt, &QPushButton::clicked, menu, &QMenu::close); + gl->addWidget(bt, rowIndex, 1, 1, 1); - QWidgetAction* a = new QWidgetAction(this); - a->setDefaultWidget(w); + QWidgetAction* a = new QWidgetAction(this); + a->setDefaultWidget(w); - menu->addAction(a); - ui->pushButtonSettings->setMenu(menu); + menu->addAction(a); + ui->pushButtonSettings->setMenu(menu); - connect(mBleTool, &SAKBleCentralTool::serviceDiscoveryStarted, this, - &SAKBleCentralToolUi::onServiceDiscoveryStarted); - connect(mBleTool, &SAKBleCentralTool::serviceDiscoveryFinished, this, - &SAKBleCentralToolUi::onServiceDiscoveryFinished); + connect(mBleTool, + &SAKBleCentralTool::serviceDiscoveryStarted, + this, + &SAKBleCentralToolUi::onServiceDiscoveryStarted); + connect(mBleTool, + &SAKBleCentralTool::serviceDiscoveryFinished, + this, + &SAKBleCentralToolUi::onServiceDiscoveryFinished); - int timeoutInterval = sp->value(); - QString nameFiltter = le->text().trimmed(); - ui->comboBoxDevices->setTimeoutInterval(timeoutInterval); - ui->comboBoxDevices->setNameFiltter(nameFiltter); + int timeoutInterval = sp->value(); + QString nameFiltter = le->text().trimmed(); + ui->comboBoxDevices->setTimeoutInterval(timeoutInterval); + ui->comboBoxDevices->setNameFiltter(nameFiltter); - onComboBoxDevicesActived(); + onComboBoxDevicesActived(); } -void SAKBleCentralToolUi::onServiceDiscoveryStarted() { - ui->progressBar->show(); +void SAKBleCentralToolUi::onServiceDiscoveryStarted() +{ + ui->progressBar->show(); } -void SAKBleCentralToolUi::onServiceDiscoveryFinished() { - ui->comboBoxServices->clear(); - auto services = mBleTool->services(); - for (auto& service : services) { - auto cookedSerivce = service.value(); - ui->comboBoxServices->addItem(cookedSerivce->serviceName(), service); +void SAKBleCentralToolUi::onServiceDiscoveryFinished() +{ + ui->comboBoxServices->clear(); + auto services = mBleTool->services(); + for (auto& service : services) { + auto cookedSerivce = service.value(); + ui->comboBoxServices->addItem(cookedSerivce->serviceName(), service); #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) - connect(cookedSerivce, &QLowEnergyService::stateChanged, this, - [=](QLowEnergyService::ServiceState state) { - if (state == QLowEnergyService::RemoteServiceDiscovered) { - onComboBoxServicesCurrentIndexChanged(); - } - }); + connect(cookedSerivce, + &QLowEnergyService::stateChanged, + this, + [=](QLowEnergyService::ServiceState state) { + if (state == QLowEnergyService::RemoteServiceDiscovered) { + onComboBoxServicesCurrentIndexChanged(); + } + }); #endif - } - ui->progressBar->hide(); + } + ui->progressBar->hide(); } -void SAKBleCentralToolUi::onDescriptorWritten( - const QLowEnergyDescriptor& descriptor, const QByteArray& newValue) { - Q_UNUSED(descriptor) - Q_UNUSED(newValue) - onComboBoxCharacteristicsActived(); +void SAKBleCentralToolUi::onDescriptorWritten(const QLowEnergyDescriptor& descriptor, + const QByteArray& newValue) +{ + Q_UNUSED(descriptor) + Q_UNUSED(newValue) + onComboBoxCharacteristicsActived(); } -void SAKBleCentralToolUi::onPushButtonScanClicked() { - ui->pushButtonScan->setEnabled(false); - if (ui->comboBoxDevices->isActive()) { - ui->comboBoxDevices->stopDiscover(); - } else { - ui->comboBoxDevices->startDiscover(); - } +void SAKBleCentralToolUi::onPushButtonScanClicked() +{ + ui->pushButtonScan->setEnabled(false); + if (ui->comboBoxDevices->isActive()) { + ui->comboBoxDevices->stopDiscover(); + } else { + ui->comboBoxDevices->startDiscover(); + } } -void SAKBleCentralToolUi::onComboBoxDevicesActived() { - QVariant data = ui->comboBoxDevices->currentData(); - mBleTool->setInfo(data); +void SAKBleCentralToolUi::onComboBoxDevicesActived() +{ + QVariant data = ui->comboBoxDevices->currentData(); + mBleTool->setInfo(data); } -void SAKBleCentralToolUi::onComboBoxServicesCurrentIndexChanged() { - mBleTool->setServiceIndex(ui->comboBoxServices->currentIndex()); - auto service = ui->comboBoxServices->currentData(); - auto cookedSerivce = service.value(); - auto chs = cookedSerivce->characteristics(); - ui->comboBoxCharacteristics->clear(); - for (int i = 0; i < chs.count(); i++) { - auto ch = chs.at(i); - QVariant var = QVariant::fromValue(ch); - QString name = ch.name(); - name = name.isEmpty() ? tr("Characteristics%1").arg(i + 1) : name; - ui->comboBoxCharacteristics->addItem(name, var); - } +void SAKBleCentralToolUi::onComboBoxServicesCurrentIndexChanged() +{ + mBleTool->setServiceIndex(ui->comboBoxServices->currentIndex()); + auto service = ui->comboBoxServices->currentData(); + auto cookedSerivce = service.value(); + auto chs = cookedSerivce->characteristics(); + ui->comboBoxCharacteristics->clear(); + for (int i = 0; i < chs.count(); i++) { + auto ch = chs.at(i); + QVariant var = QVariant::fromValue(ch); + QString name = ch.name(); + name = name.isEmpty() ? tr("Characteristics%1").arg(i + 1) : name; + ui->comboBoxCharacteristics->addItem(name, var); + } } -void SAKBleCentralToolUi::onComboBoxCharacteristicsActived() { - int index = ui->comboBoxCharacteristics->currentIndex(); - mBleTool->setCharacteristicIndex(index); +void SAKBleCentralToolUi::onComboBoxCharacteristicsActived() +{ + int index = ui->comboBoxCharacteristics->currentIndex(); + mBleTool->setCharacteristicIndex(index); - QVariant ch = ui->comboBoxCharacteristics->currentData(); - bool writeFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Write); - int writeNoResponse = QLowEnergyCharacteristic::WriteNoResponse; - bool writeNoResponseFlag = mBleTool->hasFlag(ch, writeNoResponse); - ui->labelWriteWay->setVisible(writeFlag); - ui->comboBoxWriteWay->setVisible(writeNoResponseFlag); + QVariant ch = ui->comboBoxCharacteristics->currentData(); + bool writeFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Write); + int writeNoResponse = QLowEnergyCharacteristic::WriteNoResponse; + bool writeNoResponseFlag = mBleTool->hasFlag(ch, writeNoResponse); + ui->labelWriteWay->setVisible(writeFlag); + ui->comboBoxWriteWay->setVisible(writeNoResponseFlag); - bool readFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Read); - bool notifyFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Notify); - ui->pushButtonNotify->setVisible(notifyFlag); - ui->pushButtonRead->setVisible(readFlag); - bool supported = writeFlag || writeNoResponseFlag || readFlag || notifyFlag; - ui->labelUnsupported->setVisible(!supported); + bool readFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Read); + bool notifyFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Notify); + ui->pushButtonNotify->setVisible(notifyFlag); + ui->pushButtonRead->setVisible(readFlag); + bool supported = writeFlag || writeNoResponseFlag || readFlag || notifyFlag; + ui->labelUnsupported->setVisible(!supported); - if (notifyFlag) { - bool isNotified = mBleTool->isNotified(ch); - QString txt = isNotified ? tr("Disnotify") : tr("Notify"); - ui->pushButtonNotify->setText(txt); - } + if (notifyFlag) { + bool isNotified = mBleTool->isNotified(ch); + QString txt = isNotified ? tr("Disnotify") : tr("Notify"); + ui->pushButtonNotify->setText(txt); + } } -void SAKBleCentralToolUi::onComboBoxWriteWayCurrentIndexChanged() { - int index = ui->comboBoxWriteWay->currentIndex(); - mBleTool->setWriteModel(index); - qCInfo(mLoggingCategory) << "set write model to:" << index; +void SAKBleCentralToolUi::onComboBoxWriteWayCurrentIndexChanged() +{ + int index = ui->comboBoxWriteWay->currentIndex(); + mBleTool->setWriteModel(index); + qCInfo(mLoggingCategory) << "set write model to:" << index; } -void SAKBleCentralToolUi::onPushButtonNotifyClicked() { - mBleTool->changeNotify(); +void SAKBleCentralToolUi::onPushButtonNotifyClicked() +{ + mBleTool->changeNotify(); } -void SAKBleCentralToolUi::onPushButtonReadClicked() { - mBleTool->readCharacteristic(); +void SAKBleCentralToolUi::onPushButtonReadClicked() +{ + mBleTool->readCharacteristic(); } diff --git a/src/tools/toolsui/sakblecentraltoolui.h b/src/tools/toolsui/sakblecentraltoolui.h index 562eb39c..c06ff653 100644 --- a/src/tools/toolsui/sakblecentraltoolui.h +++ b/src/tools/toolsui/sakblecentraltoolui.h @@ -26,8 +26,7 @@ public: ~SAKBleCentralToolUi(); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) override; virtual void onIsWorkingChanged(bool isWorking) final; @@ -42,8 +41,7 @@ private: private slots: void onServiceDiscoveryStarted(); void onServiceDiscoveryFinished(); - void onDescriptorWritten(const QLowEnergyDescriptor &descriptor, - const QByteArray &newValue); + void onDescriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue); void onPushButtonScanClicked(); void onComboBoxDevicesActived(); diff --git a/src/tools/toolsui/sakcommunicationtoolui.cc b/src/tools/toolsui/sakcommunicationtoolui.cc index 41800549..4ac15d43 100644 --- a/src/tools/toolsui/sakcommunicationtoolui.cc +++ b/src/tools/toolsui/sakcommunicationtoolui.cc @@ -11,9 +11,7 @@ SAKCommunicationToolUi::SAKCommunicationToolUi(QWidget *parent) : SAKBaseToolUi{parent} -{ - -} +{} void SAKCommunicationToolUi::onIsWorkingChanged(bool isWorking) { diff --git a/src/tools/toolsui/sakemittertoolui.cc b/src/tools/toolsui/sakemittertoolui.cc index 3edafca0..c580108c 100644 --- a/src/tools/toolsui/sakemittertoolui.cc +++ b/src/tools/toolsui/sakemittertoolui.cc @@ -16,13 +16,9 @@ SAKEmitterToolUi::SAKEmitterToolUi(QWidget *parent) mEditor = new SAKEmitterToolUiEditor(this); } -SAKEmitterToolUi::~SAKEmitterToolUi() -{ +SAKEmitterToolUi::~SAKEmitterToolUi() {} -} - -void SAKEmitterToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) +void SAKEmitterToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) { SAKTableModelToolUi::onBaseToolUiInitialized(tool, settingGroup); @@ -34,7 +30,7 @@ void SAKEmitterToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, QList SAKEmitterToolUi::defaultHideColumns() { QList list; - auto tb = mTableModelTool->tableModel().value(); + auto tb = mTableModelTool->tableModel().value(); for (int i = 0; i < tb->columnCount(); i++) { list.append(i); } diff --git a/src/tools/toolsui/sakemittertoolui.h b/src/tools/toolsui/sakemittertoolui.h index 45fb42d1..b364204e 100644 --- a/src/tools/toolsui/sakemittertoolui.h +++ b/src/tools/toolsui/sakemittertoolui.h @@ -21,8 +21,7 @@ public: ~SAKEmitterToolUi(); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) override; virtual QList defaultHideColumns() override; virtual QDialog *itemEditor() override; diff --git a/src/tools/toolsui/sakemittertooluieditor.cc b/src/tools/toolsui/sakemittertooluieditor.cc index 89cddb4e..907d3e83 100644 --- a/src/tools/toolsui/sakemittertooluieditor.cc +++ b/src/tools/toolsui/sakemittertooluieditor.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakemittertool.h" #include "sakemittertooluieditor.h" +#include "sakemittertool.h" #include "ui_sakemittertooluieditor.h" SAKEmitterToolUiEditor::SAKEmitterToolUiEditor(QWidget *parent) @@ -19,10 +19,8 @@ SAKEmitterToolUiEditor::SAKEmitterToolUiEditor(QWidget *parent) setModal(true); setWindowTitle(tr("Emitter Item Editor")); - connect(ui->pushButtonApply, &QPushButton::clicked, - this, &SAKEmitterToolUiEditor::accept); - connect(ui->pushButtonCancel, &QPushButton::clicked, - this, &SAKEmitterToolUiEditor::reject); + connect(ui->pushButtonApply, &QPushButton::clicked, this, &SAKEmitterToolUiEditor::accept); + connect(ui->pushButtonCancel, &QPushButton::clicked, this, &SAKEmitterToolUiEditor::reject); } SAKEmitterToolUiEditor::~SAKEmitterToolUiEditor() diff --git a/src/tools/toolsui/sakmaskertoolui.cc b/src/tools/toolsui/sakmaskertoolui.cc index 046478ac..a69d7319 100644 --- a/src/tools/toolsui/sakmaskertoolui.cc +++ b/src/tools/toolsui/sakmaskertoolui.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakmaskertool.h" #include "sakmaskertoolui.h" +#include "sakmaskertool.h" #include "ui_sakmaskertoolui.h" SAKMaskerToolUi::SAKMaskerToolUi(QWidget *parent) @@ -28,28 +28,26 @@ void SAKMaskerToolUi::setToolName(const QString &name) ui->groupBox->setTitle(name); } -void SAKMaskerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) +void SAKMaskerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { #if 0 ui->checkBoxEnable->setGroupKey(settingsGroup, "maskerEnable"); #endif ui->spinBoxMaskCode->setGroupKey(settingsGroup, "maskCode"); - SAKMaskerTool *cookedTool = qobject_cast(tool); + SAKMaskerTool *cookedTool = qobject_cast(tool); if (!cookedTool) { qCWarning((*mLoggingCategory)) << "Invalid tool type!"; return; } - connect(ui->checkBoxEnable, &QCheckBox::clicked, this, [=](){ + connect(ui->checkBoxEnable, &QCheckBox::clicked, this, [=]() { cookedTool->setEnable(ui->checkBoxEnable->isChecked()); }); connect(ui->spinBoxMaskCode, - static_cast(&QSpinBox::valueChanged), - this, [=](int code){ - cookedTool->setMaskCode(code); - }); + static_cast(&QSpinBox::valueChanged), + this, + [=](int code) { cookedTool->setMaskCode(code); }); cookedTool->setEnable(ui->checkBoxEnable->isChecked()); cookedTool->setMaskCode(ui->spinBoxMaskCode->value()); diff --git a/src/tools/toolsui/sakmaskertoolui.h b/src/tools/toolsui/sakmaskertoolui.h index 2ef52031..8e8627ef 100644 --- a/src/tools/toolsui/sakmaskertoolui.h +++ b/src/tools/toolsui/sakmaskertoolui.h @@ -25,8 +25,7 @@ public: void setToolName(const QString &name); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: Ui::SAKMaskerToolUi *ui; diff --git a/src/tools/toolsui/sakprestorertoolui.cc b/src/tools/toolsui/sakprestorertoolui.cc index aeb73416..b85087f9 100644 --- a/src/tools/toolsui/sakprestorertoolui.cc +++ b/src/tools/toolsui/sakprestorertoolui.cc @@ -8,11 +8,11 @@ * the file LICENCE in the root of the source code directory. ******************************************************************************/ #include -#include -#include #include +#include #include #include +#include #include "sakmenu.h" #include "sakprestorertool.h" @@ -26,18 +26,14 @@ SAKPrestorerToolUi::SAKPrestorerToolUi(QWidget *parent) mMenu = new SAKMenu(); } -SAKPrestorerToolUi::~SAKPrestorerToolUi() -{ - -} +SAKPrestorerToolUi::~SAKPrestorerToolUi() {} QMenu *SAKPrestorerToolUi::menu() { return mMenu; } -void SAKPrestorerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) +void SAKPrestorerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) { SAKTableModelToolUi::onBaseToolUiInitialized(tool, settingGroup); @@ -45,14 +41,11 @@ void SAKPrestorerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, columns << 9; setStretchSections(columns); - SAKPrestorerTool *cookedTool = qobject_cast(tool); - auto *model = cookedTool->tableModel().value(); - connect(model, &QAbstractTableModel::rowsRemoved, - this, &SAKPrestorerToolUi::updateMenu); - connect(model, &QAbstractTableModel::rowsInserted, - this, &SAKPrestorerToolUi::updateMenu); - connect(model, &QAbstractTableModel::dataChanged, - this, &SAKPrestorerToolUi::updateMenu); + SAKPrestorerTool *cookedTool = qobject_cast(tool); + auto *model = cookedTool->tableModel().value(); + connect(model, &QAbstractTableModel::rowsRemoved, this, &SAKPrestorerToolUi::updateMenu); + connect(model, &QAbstractTableModel::rowsInserted, this, &SAKPrestorerToolUi::updateMenu); + connect(model, &QAbstractTableModel::dataChanged, this, &SAKPrestorerToolUi::updateMenu); updateMenu(); QList list; @@ -63,7 +56,7 @@ void SAKPrestorerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, QList SAKPrestorerToolUi::defaultHideColumns() { QList list; - auto tb = mTableModelTool->tableModel().value(); + auto tb = mTableModelTool->tableModel().value(); for (int i = 0; i < tb->columnCount(); i++) { list.append(i); } @@ -85,8 +78,8 @@ QDialog *SAKPrestorerToolUi::itemEditor() void SAKPrestorerToolUi::updateMenu() { - auto *cookedTool = qobject_cast(mTableModelTool); - auto *model = cookedTool->tableModel().value(); + auto *cookedTool = qobject_cast(mTableModelTool); + auto *model = cookedTool->tableModel().value(); mMenu->clear(); @@ -94,8 +87,6 @@ void SAKPrestorerToolUi::updateMenu() QString desc = cookedTool->description(i); QAction *a = new QAction(desc, mMenu); mMenu->addAction(a); - connect(a, &QAction::triggered, this, [=](){ - cookedTool->send(i); - }); + connect(a, &QAction::triggered, this, [=]() { cookedTool->send(i); }); } } diff --git a/src/tools/toolsui/sakprestorertoolui.h b/src/tools/toolsui/sakprestorertoolui.h index 67d50a5a..ce52e5a8 100644 --- a/src/tools/toolsui/sakprestorertoolui.h +++ b/src/tools/toolsui/sakprestorertoolui.h @@ -10,8 +10,8 @@ #ifndef SAKPRESTORERTOOLUI_H #define SAKPRESTORERTOOLUI_H -#include #include "saktablemodeltoolui.h" +#include class SAKPrestorerTool; class SAKPrestorerToolUiEditor; @@ -24,8 +24,7 @@ public: QMenu *menu(); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) override; virtual QList defaultHideColumns() override; virtual QDialog *itemEditor() override; diff --git a/src/tools/toolsui/sakprestorertooluieditor.cc b/src/tools/toolsui/sakprestorertooluieditor.cc index ae5bf964..3c3c84b0 100644 --- a/src/tools/toolsui/sakprestorertooluieditor.cc +++ b/src/tools/toolsui/sakprestorertooluieditor.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakprestorertool.h" #include "sakprestorertooluieditor.h" +#include "sakprestorertool.h" #include "ui_sakprestorertooluieditor.h" SAKPrestorerToolUiEditor::SAKPrestorerToolUiEditor(QWidget *parent) @@ -19,10 +19,8 @@ SAKPrestorerToolUiEditor::SAKPrestorerToolUiEditor(QWidget *parent) setModal(true); setWindowTitle(tr("Prestorer Item Editor")); - connect(ui->pushButtonOk, &QPushButton::clicked, - this, &SAKPrestorerToolUiEditor::accept); - connect(ui->pushButtonCancel, &QPushButton::clicked, - this, &SAKPrestorerToolUiEditor::reject); + connect(ui->pushButtonOk, &QPushButton::clicked, this, &SAKPrestorerToolUiEditor::accept); + connect(ui->pushButtonCancel, &QPushButton::clicked, this, &SAKPrestorerToolUiEditor::reject); } SAKPrestorerToolUiEditor::~SAKPrestorerToolUiEditor() diff --git a/src/tools/toolsui/sakresponsertoolui.cc b/src/tools/toolsui/sakresponsertoolui.cc index b439f66d..45f06104 100644 --- a/src/tools/toolsui/sakresponsertoolui.cc +++ b/src/tools/toolsui/sakresponsertoolui.cc @@ -7,16 +7,16 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ +#include #include -#include -#include -#include #include #include -#include +#include +#include +#include -#include "saktablemodeltool.h" #include "sakresponsertoolui.h" +#include "saktablemodeltool.h" SAKResponserToolUi::SAKResponserToolUi(QWidget *parent) : SAKTableModelToolUi{"sak.responsertoolui", parent} @@ -24,13 +24,9 @@ SAKResponserToolUi::SAKResponserToolUi(QWidget *parent) mEditor = new SAKResponserToolUiEditor(this); } -SAKResponserToolUi::~SAKResponserToolUi() -{ +SAKResponserToolUi::~SAKResponserToolUi() {} -} - -void SAKResponserToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) +void SAKResponserToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) { SAKTableModelToolUi::onBaseToolUiInitialized(tool, settingGroup); QList columns; @@ -41,7 +37,7 @@ void SAKResponserToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, QList SAKResponserToolUi::defaultHideColumns() { QList list; - auto tb = mTableModelTool->tableModel().value(); + auto tb = mTableModelTool->tableModel().value(); for (int i = 0; i < tb->columnCount(); i++) { list.append(i); } diff --git a/src/tools/toolsui/sakresponsertoolui.h b/src/tools/toolsui/sakresponsertoolui.h index 94c9a189..0019027d 100644 --- a/src/tools/toolsui/sakresponsertoolui.h +++ b/src/tools/toolsui/sakresponsertoolui.h @@ -12,8 +12,8 @@ #include -#include "saktablemodeltoolui.h" #include "sakresponsertooluieditor.h" +#include "saktablemodeltoolui.h" class SAKResponserToolUi : public SAKTableModelToolUi { @@ -23,8 +23,7 @@ public: ~SAKResponserToolUi(); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) override; virtual QList defaultHideColumns() override; virtual QDialog *itemEditor() override; diff --git a/src/tools/toolsui/sakresponsertooluieditor.cc b/src/tools/toolsui/sakresponsertooluieditor.cc index 3c748dcd..1a074356 100644 --- a/src/tools/toolsui/sakresponsertooluieditor.cc +++ b/src/tools/toolsui/sakresponsertooluieditor.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakresponsertool.h" #include "sakresponsertooluieditor.h" +#include "sakresponsertool.h" #include "ui_sakresponsertooluieditor.h" SAKResponserToolUiEditor::SAKResponserToolUiEditor(QWidget *parent) @@ -19,10 +19,8 @@ SAKResponserToolUiEditor::SAKResponserToolUiEditor(QWidget *parent) setModal(true); setWindowTitle(tr("Responser Item Editor")); - connect(ui->pushButtonOk, &QPushButton::clicked, - this, &SAKResponserToolUiEditor::accept); - connect(ui->pushButtonCancel, &QPushButton::clicked, - this, &SAKResponserToolUiEditor::reject); + connect(ui->pushButtonOk, &QPushButton::clicked, this, &SAKResponserToolUiEditor::accept); + connect(ui->pushButtonCancel, &QPushButton::clicked, this, &SAKResponserToolUiEditor::reject); } SAKResponserToolUiEditor::~SAKResponserToolUiEditor() @@ -36,28 +34,28 @@ QJsonObject SAKResponserToolUiEditor::parameters() QString description = ui->lineEditDescription->text().trimmed(); int option = ui->comboBoxOption->currentData().toInt(); - int refFormat = ui->comboBoxRefFormat->currentData().toInt(); - int refEscape = ui->comboBoxRefEscape->currentData().toInt(); - int refPrefix = ui->comboBoxRefPrefix->currentData().toInt(); - int refSuffix = ui->comboBoxRefSuffix->currentData().toInt(); - bool refCrcEnable = ui->checkBoxRefCrcEnable->isChecked(); - bool refCrcBigEndian = ui->checkBoxRefCrcBigEndian->isChecked(); - int refAlgorithm = ui->comboBoxRefAlgorithm->currentData().toInt(); - int refStart = ui->spinBoxRefStart->value(); - int refEnd = ui->spinBoxRefEnd->value(); - QString refData = ui->lineEditRefData->text(); + int refFormat = ui->comboBoxRefFormat->currentData().toInt(); + int refEscape = ui->comboBoxRefEscape->currentData().toInt(); + int refPrefix = ui->comboBoxRefPrefix->currentData().toInt(); + int refSuffix = ui->comboBoxRefSuffix->currentData().toInt(); + bool refCrcEnable = ui->checkBoxRefCrcEnable->isChecked(); + bool refCrcBigEndian = ui->checkBoxRefCrcBigEndian->isChecked(); + int refAlgorithm = ui->comboBoxRefAlgorithm->currentData().toInt(); + int refStart = ui->spinBoxRefStart->value(); + int refEnd = ui->spinBoxRefEnd->value(); + QString refData = ui->lineEditRefData->text(); - int resFormat = ui->comboBoxResFormat->currentData().toInt(); - int resEscape = ui->comboBoxResEscape->currentData().toInt(); - int resPrefix = ui->comboBoxResPrefix->currentData().toInt(); - int resSuffix = ui->comboBoxResSuffix->currentData().toInt(); - bool resCrcEnable = ui->checkBoxResCrcEnable->isChecked(); - bool resCrcBigEndian = ui->checkBoxResCrcBigEndian->isChecked(); - int resAlgorithm = ui->comboBoxResAlgorithm->currentData().toInt(); - int resStart = ui->spinBoxResStart->value(); - int resEnd = ui->spinBoxResEnd->value(); - int resDelay = ui->spinBoxResDelay->value(); - QString resData = ui->lineEditResData->text(); + int resFormat = ui->comboBoxResFormat->currentData().toInt(); + int resEscape = ui->comboBoxResEscape->currentData().toInt(); + int resPrefix = ui->comboBoxResPrefix->currentData().toInt(); + int resSuffix = ui->comboBoxResSuffix->currentData().toInt(); + bool resCrcEnable = ui->checkBoxResCrcEnable->isChecked(); + bool resCrcBigEndian = ui->checkBoxResCrcBigEndian->isChecked(); + int resAlgorithm = ui->comboBoxResAlgorithm->currentData().toInt(); + int resStart = ui->spinBoxResStart->value(); + int resEnd = ui->spinBoxResEnd->value(); + int resDelay = ui->spinBoxResDelay->value(); + QString resData = ui->lineEditResData->text(); SAKResponserTool::ResponserItemKeys keys; QJsonObject jsonObj; @@ -103,8 +101,7 @@ void SAKResponserToolUiEditor::setParameters(const QJsonObject ¶ms) int refPrefix = params.value(keys.itemReferencePrefix).toInt(); int refSuffix = params.value(keys.itemReferenceSuffix).toInt(); bool refCrcEnable = params.value(keys.itemReferenceCrcEnable).toBool(); - bool refCrcBigEndian = - params.value(keys.itemReferenceCrcBigEndian).toBool(); + bool refCrcBigEndian = params.value(keys.itemReferenceCrcBigEndian).toBool(); int refAlgorithm = params.value(keys.itemReferenceCrcAlgorithm).toInt(); int refStart = params.value(keys.itemReferenceCrcStartIndex).toInt(); int refEnd = params.value(keys.itemReferenceCrcEndIndex).toInt(); @@ -115,8 +112,7 @@ void SAKResponserToolUiEditor::setParameters(const QJsonObject ¶ms) int resPrefix = params.value(keys.itemResponsePrefix).toInt(); int resSuffix = params.value(keys.itemResponseSuffix).toInt(); bool resCrcEnable = params.value(keys.itemResponseCrcEnable).toBool(); - bool resCrcBigEndian = - params.value(keys.itemResponseCrcBigEndian).toBool(); + bool resCrcBigEndian = params.value(keys.itemResponseCrcBigEndian).toBool(); int resAlgorithm = params.value(keys.itemResponseCrcAlgorithm).toInt(); int resStart = params.value(keys.itemResponseCrcStartIndex).toInt(); int resEnd = params.value(keys.itemResponseCrcEndIndex).toInt(); diff --git a/src/tools/toolsui/sakserialporttoolui.cc b/src/tools/toolsui/sakserialporttoolui.cc index aa467986..3fd304bd 100644 --- a/src/tools/toolsui/sakserialporttoolui.cc +++ b/src/tools/toolsui/sakserialporttoolui.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakserialporttool.h" #include "sakserialporttoolui.h" +#include "sakserialporttool.h" #include "ui_sakserialporttoolui.h" SAKSerialPortToolUi::SAKSerialPortToolUi(QWidget *parent) @@ -23,15 +23,14 @@ SAKSerialPortToolUi::~SAKSerialPortToolUi() delete ui; } -void SAKSerialPortToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) +void SAKSerialPortToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { if (!(tool && tool->inherits("SAKSerialPortTool"))) { qCWarning(mLoggingCategory) << "Invalid type of communication tool!"; return; } - mTool = qobject_cast(tool); + mTool = qobject_cast(tool); mTool->setPortName(ui->comboBoxPortNames->currentText()); mTool->setBaudRate(ui->comboBoxBaudRate->currentData().toInt()); mTool->setDataBits(ui->comboBoxDataBits->currentData().toInt()); @@ -39,23 +38,30 @@ void SAKSerialPortToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, mTool->setParity(ui->comboBoxParity->currentData().toInt()); mTool->setFlowControl(ui->comboBoxFlowControl->currentData().toInt()); - connect(ui->comboBoxPortNames, &QComboBox::currentTextChanged, - this, &SAKSerialPortToolUi::onComboBoxPortNamesCurrentTextChanged); + connect(ui->comboBoxPortNames, + &QComboBox::currentTextChanged, + this, + &SAKSerialPortToolUi::onComboBoxPortNamesCurrentTextChanged); connect(ui->comboBoxBaudRate, - static_cast(&QComboBox::currentIndexChanged), - this, &SAKSerialPortToolUi::onComboBoxBaudRateCurrentIndexChanged); + static_cast(&QComboBox::currentIndexChanged), + this, + &SAKSerialPortToolUi::onComboBoxBaudRateCurrentIndexChanged); connect(ui->comboBoxDataBits, - static_cast(&QComboBox::currentIndexChanged), - this, &SAKSerialPortToolUi::onComboBoxDataBitsCurrentIndexChanged); + static_cast(&QComboBox::currentIndexChanged), + this, + &SAKSerialPortToolUi::onComboBoxDataBitsCurrentIndexChanged); connect(ui->comboBoxStopBits, - static_cast(&QComboBox::currentIndexChanged), - this, &SAKSerialPortToolUi::onComboBoxStopBitsCurrentIndexChanged); + static_cast(&QComboBox::currentIndexChanged), + this, + &SAKSerialPortToolUi::onComboBoxStopBitsCurrentIndexChanged); connect(ui->comboBoxParity, - static_cast(&QComboBox::currentIndexChanged), - this, &SAKSerialPortToolUi::onComboBoxParityCurrentIndexChanged); + static_cast(&QComboBox::currentIndexChanged), + this, + &SAKSerialPortToolUi::onComboBoxParityCurrentIndexChanged); connect(ui->comboBoxFlowControl, - static_cast(&QComboBox::currentIndexChanged), - this, &SAKSerialPortToolUi::onComboBoxFlowControlCurrentIndexChanged); + static_cast(&QComboBox::currentIndexChanged), + this, + &SAKSerialPortToolUi::onComboBoxFlowControlCurrentIndexChanged); ui->comboBoxPortNames->setGroupKey(settingsGroup, "portName"); ui->comboBoxBaudRate->setGroupKey(settingsGroup, "baudRate", false); diff --git a/src/tools/toolsui/sakserialporttoolui.h b/src/tools/toolsui/sakserialporttoolui.h index b84ee4ec..547f530b 100644 --- a/src/tools/toolsui/sakserialporttoolui.h +++ b/src/tools/toolsui/sakserialporttoolui.h @@ -10,8 +10,8 @@ #ifndef SAKSERIALPORTTOOLBOXUI_HH #define SAKSERIALPORTTOOLBOXUI_HH -#include #include "sakcommunicationtoolui.h" +#include namespace Ui { class SAKSerialPortToolUi; @@ -24,8 +24,7 @@ class SAKSerialPortToolUi : public SAKCommunicationToolUi public: explicit SAKSerialPortToolUi(QWidget *parent = nullptr); ~SAKSerialPortToolUi(); - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: SAKSerialPortTool *mTool{nullptr}; diff --git a/src/tools/toolsui/sakserialporttransmittertoolui.cc b/src/tools/toolsui/sakserialporttransmittertoolui.cc index 6330d4e1..aa8655c1 100644 --- a/src/tools/toolsui/sakserialporttransmittertoolui.cc +++ b/src/tools/toolsui/sakserialporttransmittertoolui.cc @@ -15,8 +15,8 @@ SAKSerialPortTransmitterToolUi::SAKSerialPortTransmitterToolUi(QWidget *parent) mEditor = new SAKSerialPortTransmitterToolUiEditor(this); } -void SAKSerialPortTransmitterToolUi::onBaseToolUiInitialized( - SAKBaseTool *tool, const QString &settingGroup) +void SAKSerialPortTransmitterToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, + const QString &settingGroup) { SAKTransmitterToolUi::SAKTransmitterToolUi::onBaseToolUiInitialized(tool, settingGroup); setSectionResizeModeToStretch(); diff --git a/src/tools/toolsui/sakserialporttransmittertoolui.h b/src/tools/toolsui/sakserialporttransmittertoolui.h index b596e48d..2d4791bd 100644 --- a/src/tools/toolsui/sakserialporttransmittertoolui.h +++ b/src/tools/toolsui/sakserialporttransmittertoolui.h @@ -10,8 +10,8 @@ #ifndef SAKSERIALPORTTRANSMITTERTOOLUI_H #define SAKSERIALPORTTRANSMITTERTOOLUI_H -#include "saktransmittertoolui.h" #include "sakserialporttransmittertooluieditor.h" +#include "saktransmittertoolui.h" class SAKSerialPortTransmitterToolUi : public SAKTransmitterToolUi { @@ -20,8 +20,7 @@ public: SAKSerialPortTransmitterToolUi(QWidget *parent = nullptr); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) override; virtual QDialog *itemEditor() override; private: diff --git a/src/tools/toolsui/sakserialporttransmittertooluieditor.cc b/src/tools/toolsui/sakserialporttransmittertooluieditor.cc index 010bde24..4572d61c 100644 --- a/src/tools/toolsui/sakserialporttransmittertooluieditor.cc +++ b/src/tools/toolsui/sakserialporttransmittertooluieditor.cc @@ -13,16 +13,19 @@ #include "sakserialporttransmittertooluieditor.h" #include "ui_sakserialporttransmittertooluieditor.h" -SAKSerialPortTransmitterToolUiEditor:: - SAKSerialPortTransmitterToolUiEditor(QWidget *parent) +SAKSerialPortTransmitterToolUiEditor::SAKSerialPortTransmitterToolUiEditor(QWidget *parent) : QDialog(parent) , ui(new Ui::SAKSerialPortTransmitterToolUiEditor) { ui->setupUi(this); - connect(ui->pushButtonApply, &QPushButton::clicked, - this, &SAKSerialPortTransmitterToolUiEditor::accept); - connect(ui->pushButtonCancel, &QPushButton::clicked, - this, &SAKSerialPortTransmitterToolUiEditor::reject); + connect(ui->pushButtonApply, + &QPushButton::clicked, + this, + &SAKSerialPortTransmitterToolUiEditor::accept); + connect(ui->pushButtonCancel, + &QPushButton::clicked, + this, + &SAKSerialPortTransmitterToolUiEditor::reject); } SAKSerialPortTransmitterToolUiEditor::~SAKSerialPortTransmitterToolUiEditor() @@ -52,7 +55,6 @@ QJsonObject SAKSerialPortTransmitterToolUiEditor::parameters() obj.insert(keys.flowControl, flowControl); return obj; - } void SAKSerialPortTransmitterToolUiEditor::setParameters(const QJsonObject ¶ms) diff --git a/src/tools/toolsui/saksocketclienttoolui.cc b/src/tools/toolsui/saksocketclienttoolui.cc index 15f77d36..df0ade3d 100644 --- a/src/tools/toolsui/saksocketclienttoolui.cc +++ b/src/tools/toolsui/saksocketclienttoolui.cc @@ -20,19 +20,25 @@ SAKSocketClientToolUi::SAKSocketClientToolUi(QWidget *parent) ui->setupUi(this); connect(ui->comboBoxClientAddress, - static_cast(&QComboBox::activated), - this, &SAKSocketClientToolUi::onComboBoxServerAddressCurrentTextChanged); + static_cast(&QComboBox::activated), + this, + &SAKSocketClientToolUi::onComboBoxServerAddressCurrentTextChanged); connect(ui->spinBoxClientPort, - static_cast(&QSpinBox::valueChanged), - this, &SAKSocketClientToolUi::onSpinBoxClientPortValueChanged); + static_cast(&QSpinBox::valueChanged), + this, + &SAKSocketClientToolUi::onSpinBoxClientPortValueChanged); connect(ui->comboBoxServerAddress, - static_cast(&QComboBox::currentTextChanged), - this, &SAKSocketClientToolUi::onComboBoxServerAddressCurrentTextChanged); + static_cast(&QComboBox::currentTextChanged), + this, + &SAKSocketClientToolUi::onComboBoxServerAddressCurrentTextChanged); connect(ui->spinBoxServerPort, - static_cast(&QSpinBox::valueChanged), - this, &SAKSocketClientToolUi::onSpinBoxServerPortValueChanged); - connect(ui->checkBoxSpecifyIpAndPort, &QCheckBox::clicked, - this, &SAKSocketClientToolUi::onCheckBoxSpecifyIpAndPortClicked); + static_cast(&QSpinBox::valueChanged), + this, + &SAKSocketClientToolUi::onSpinBoxServerPortValueChanged); + connect(ui->checkBoxSpecifyIpAndPort, + &QCheckBox::clicked, + this, + &SAKSocketClientToolUi::onCheckBoxSpecifyIpAndPortClicked); } SAKSocketClientToolUi::~SAKSocketClientToolUi() @@ -47,8 +53,7 @@ void SAKSocketClientToolUi::onIsWorkingChanged(bool isWorking) ui->checkBoxSpecifyIpAndPort->setEnabled(!isWorking); } -void SAKSocketClientToolUi::onBaseToolUiInitialized( - SAKBaseTool *tool, const QString &settingsGroup) +void SAKSocketClientToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { if (!tool) { return; @@ -65,7 +70,7 @@ void SAKSocketClientToolUi::onBaseToolUiInitialized( ui->comboBoxMessageType->hide(); } - mTool = qobject_cast(tool); + mTool = qobject_cast(tool); if (!mTool) { qCWarning(mLoggingCategory) << "qobject_cast<>() return nullptr"; return; @@ -73,8 +78,7 @@ void SAKSocketClientToolUi::onBaseToolUiInitialized( ui->comboBoxClientAddress->setGroupKey(settingsGroup, "clientAddress"); ui->spinBoxClientPort->setGroupKey(settingsGroup, "clientPort"); - ui->checkBoxSpecifyIpAndPort->setGroupKey(settingsGroup, - "specifyIpAndPort"); + ui->checkBoxSpecifyIpAndPort->setGroupKey(settingsGroup, "specifyIpAndPort"); ui->comboBoxServerAddress->setGroupKey(settingsGroup, "serverAddress"); ui->spinBoxServerPort->setGroupKey(settingsGroup, "serverPort"); ui->comboBoxMessageType->setGroupKey(settingsGroup, "messageType"); @@ -85,11 +89,11 @@ void SAKSocketClientToolUi::onBaseToolUiInitialized( mTool->setServerPort(ui->spinBoxServerPort->value()); mTool->setSpecifyClientIpPort(ui->checkBoxSpecifyIpAndPort->isChecked()); - connect(mTool, &SAKSocketClientTool::bindingIpPortChanged, this, [=](){ + connect(mTool, &SAKSocketClientTool::bindingIpPortChanged, this, [=]() { QString ipport = mTool->bindingIpPort(); ui->labelContext->setText(ipport); }); - connect(mTool, &SAKSocketClientTool::finished, this, [=](){ + connect(mTool, &SAKSocketClientTool::finished, this, [=]() { ui->labelContext->setText(tr("Closed")); }); } diff --git a/src/tools/toolsui/saksocketclienttoolui.h b/src/tools/toolsui/saksocketclienttoolui.h index 106fbbf7..68d14b79 100644 --- a/src/tools/toolsui/saksocketclienttoolui.h +++ b/src/tools/toolsui/saksocketclienttoolui.h @@ -10,8 +10,8 @@ #ifndef SAKSOCKETCLIENTTOOLUI_H #define SAKSOCKETCLIENTTOOLUI_H -#include #include "sakcommunicationtoolui.h" +#include namespace Ui { class SAKSocketClientToolUi; @@ -25,8 +25,7 @@ public: explicit SAKSocketClientToolUi(QWidget *parent = nullptr); ~SAKSocketClientToolUi(); virtual void onIsWorkingChanged(bool isWorking) final; - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: const QLoggingCategory mLoggingCategory{"sak.socketclienttoolui"}; diff --git a/src/tools/toolsui/saksocketclienttransmittertoolui.cc b/src/tools/toolsui/saksocketclienttransmittertoolui.cc index 8e171309..a6b09ca9 100644 --- a/src/tools/toolsui/saksocketclienttransmittertoolui.cc +++ b/src/tools/toolsui/saksocketclienttransmittertoolui.cc @@ -9,8 +9,7 @@ ******************************************************************************/ #include "saksocketclienttransmittertoolui.h" -SAKSocketClientTransmitterToolUi::SAKSocketClientTransmitterToolUi( - const char *lg, QWidget *parent) +SAKSocketClientTransmitterToolUi::SAKSocketClientTransmitterToolUi(const char *lg, QWidget *parent) : SAKTransmitterToolUi(lg, parent) { mEditor = new SAKSocketClientTransmitterToolUiEditor(this); @@ -21,8 +20,8 @@ QDialog *SAKSocketClientTransmitterToolUi::itemEditor() return mEditor; } -void SAKSocketClientTransmitterToolUi::onBaseToolUiInitialized( - SAKBaseTool *tool, const QString &settingGroup) +void SAKSocketClientTransmitterToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, + const QString &settingGroup) { SAKTransmitterToolUi::onBaseToolUiInitialized(tool, settingGroup); setColumnVisible(4, false); diff --git a/src/tools/toolsui/saksocketclienttransmittertoolui.h b/src/tools/toolsui/saksocketclienttransmittertoolui.h index 8abcd9b1..58211d0a 100644 --- a/src/tools/toolsui/saksocketclienttransmittertoolui.h +++ b/src/tools/toolsui/saksocketclienttransmittertoolui.h @@ -10,8 +10,8 @@ #ifndef SAKSOCKETCLIENTTRANSMITTERTOOLUI_H #define SAKSOCKETCLIENTTRANSMITTERTOOLUI_H -#include "saktransmittertoolui.h" #include "saksocketclienttransmittertooluieditor.h" +#include "saktransmittertoolui.h" class SAKSocketClientTransmitterToolUi : public SAKTransmitterToolUi { @@ -20,8 +20,7 @@ public: virtual QDialog *itemEditor() override; protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) override; protected: SAKSocketClientTransmitterToolUiEditor *mEditor{nullptr}; diff --git a/src/tools/toolsui/saksocketclienttransmittertooluieditor.cc b/src/tools/toolsui/saksocketclienttransmittertooluieditor.cc index 363eccb0..ced1b4f3 100644 --- a/src/tools/toolsui/saksocketclienttransmittertooluieditor.cc +++ b/src/tools/toolsui/saksocketclienttransmittertooluieditor.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "saksocketclienttransmittertool.h" #include "saksocketclienttransmittertooluieditor.h" +#include "saksocketclienttransmittertool.h" #include "ui_saksocketclienttransmittertooluieditor.h" SAKSocketClientTransmitterToolUiEditor::SAKSocketClientTransmitterToolUiEditor(QWidget *parent) @@ -16,10 +16,14 @@ SAKSocketClientTransmitterToolUiEditor::SAKSocketClientTransmitterToolUiEditor(Q , ui(new Ui::SAKSocketClientTransmitterToolUiEditor) { ui->setupUi(this); - connect(ui->pushButtonApply, &QPushButton::clicked, - this, &SAKSocketClientTransmitterToolUiEditor::accept); - connect(ui->pushButtonCancel, &QPushButton::clicked, - this, &SAKSocketClientTransmitterToolUiEditor::reject); + connect(ui->pushButtonApply, + &QPushButton::clicked, + this, + &SAKSocketClientTransmitterToolUiEditor::accept); + connect(ui->pushButtonCancel, + &QPushButton::clicked, + this, + &SAKSocketClientTransmitterToolUiEditor::reject); } SAKSocketClientTransmitterToolUiEditor::~SAKSocketClientTransmitterToolUiEditor() @@ -43,8 +47,7 @@ QJsonObject SAKSocketClientTransmitterToolUiEditor::parameters() bool enable = ui->checkBoxEnable->isChecked(); QString clientIp = ui->comboBoxClientIp->currentText(); int clientPort = ui->spinBoxClientPort->value(); - bool specifiedClientIpPort = - ui->checkBoxSpecifiedClientIpAndPort->isChecked(); + bool specifiedClientIpPort = ui->checkBoxSpecifiedClientIpAndPort->isChecked(); QString serverIp = ui->comboBoxServerIp->currentText(); int serverPort = ui->spinBoxServerPort->value(); int messageType = ui->comboBoxMessageType->currentData().toInt(); @@ -67,8 +70,7 @@ void SAKSocketClientTransmitterToolUiEditor::setParameters(const QJsonObject &pa bool enable = params.value(keys.enable).toBool(); QString clientIp = params.value(keys.clientIp).toString(); int clientPort = params.value(keys.clientPort).toInt(); - bool specifiedClientIpPort = - params.value(keys.specifiedClientIpPort).toBool(); + bool specifiedClientIpPort = params.value(keys.specifiedClientIpPort).toBool(); QString serverIp = params.value(keys.serverIp).toString(); int serverPort = params.value(keys.serverPort).toInt(); int messageType = params.value(keys.messageType).toInt(); diff --git a/src/tools/toolsui/saksocketservertoolui.cc b/src/tools/toolsui/saksocketservertoolui.cc index 3d5c326d..4fa2d241 100644 --- a/src/tools/toolsui/saksocketservertoolui.cc +++ b/src/tools/toolsui/saksocketservertoolui.cc @@ -7,10 +7,10 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include -#include "saksocketservertool.h" #include "saksocketservertoolui.h" +#include "saksocketservertool.h" #include "ui_saksocketservertoolui.h" +#include SAKSocketServerToolUi::SAKSocketServerToolUi(QWidget *parent) : SAKCommunicationToolUi{parent} @@ -18,19 +18,25 @@ SAKSocketServerToolUi::SAKSocketServerToolUi(QWidget *parent) { ui->setupUi(this); connect(ui->comboBoxServerIp, - static_cast(&QComboBox::activated), - this, &SAKSocketServerToolUi::onComboBoxServerIpActived); + static_cast(&QComboBox::activated), + this, + &SAKSocketServerToolUi::onComboBoxServerIpActived); connect(ui->spinBoxServerPort, - static_cast(&QSpinBox::valueChanged), - this, &SAKSocketServerToolUi::onSpinBoxServerPortValueChanged); + static_cast(&QSpinBox::valueChanged), + this, + &SAKSocketServerToolUi::onSpinBoxServerPortValueChanged); connect(ui->comboBoxClientList, - static_cast(&QComboBox::currentIndexChanged), - this, &SAKSocketServerToolUi::onComboBoxClientsIndexChanged); + static_cast(&QComboBox::currentIndexChanged), + this, + &SAKSocketServerToolUi::onComboBoxClientsIndexChanged); connect(ui->comboBoxMessageType, - static_cast(&QComboBox::currentIndexChanged), - this, &SAKSocketServerToolUi::onComboBoxMessageTypeIndexChanged); - connect(ui->checkBoxSpecifyIpAndPort, &QCheckBox::clicked, - this, &SAKSocketServerToolUi::onCheckBoxSpecifyIpAndPortClicked); + static_cast(&QComboBox::currentIndexChanged), + this, + &SAKSocketServerToolUi::onComboBoxMessageTypeIndexChanged); + connect(ui->checkBoxSpecifyIpAndPort, + &QCheckBox::clicked, + this, + &SAKSocketServerToolUi::onCheckBoxSpecifyIpAndPortClicked); ui->pushButtonClear->hide(); } @@ -46,8 +52,7 @@ void SAKSocketServerToolUi::onIsWorkingChanged(bool isWorking) ui->checkBoxSpecifyIpAndPort->setEnabled(!isWorking); } -void SAKSocketServerToolUi::onBaseToolUiInitialized( - SAKBaseTool *tool, const QString &settingsGroup) +void SAKSocketServerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { if (!tool) { return; @@ -70,7 +75,7 @@ void SAKSocketServerToolUi::onBaseToolUiInitialized( ui->checkBoxSpecifyIpAndPort->hide(); } - mTool = qobject_cast(tool); + mTool = qobject_cast(tool); if (!mTool) { qCWarning(mLoggingCategory) << "qobject_cast<>() return nullptr"; return; @@ -79,26 +84,26 @@ void SAKSocketServerToolUi::onBaseToolUiInitialized( ui->comboBoxServerIp->setGroupKey(settingsGroup, "serverIp"); ui->spinBoxServerPort->setGroupKey(settingsGroup, "port"); ui->comboBoxMessageType->setGroupKey(settingsGroup, "messageType"); - ui->checkBoxSpecifyIpAndPort->setGroupKey(settingsGroup, - "specifiedIpAndPort"); + ui->checkBoxSpecifyIpAndPort->setGroupKey(settingsGroup, "specifiedIpAndPort"); QString ip = ui->comboBoxServerIp->currentText(); int port = ui->spinBoxServerPort->value(); bool specified = ui->checkBoxSpecifyIpAndPort->isChecked(); int messageType = ui->comboBoxMessageType->currentData().toInt(); - mTool->setServerIp(ip);; + mTool->setServerIp(ip); + ; mTool->setServerPort(port); mTool->setSpecifyIpAndPort(specified); mTool->setMessageType(messageType); - connect(mTool, &SAKSocketServerTool::bindingIpPortChanged, this, [=](){ + connect(mTool, &SAKSocketServerTool::bindingIpPortChanged, this, [=]() { QString ipport = mTool->bindingIpPort(); ui->labelBindingInfo->setText(ipport); }); - connect(mTool, &SAKSocketServerTool::finished, this, [=](){ + connect(mTool, &SAKSocketServerTool::finished, this, [=]() { ui->labelBindingInfo->setText(tr("Closed")); }); - connect(mTool, &SAKSocketServerTool::clientsChanged, this, [=](){ + connect(mTool, &SAKSocketServerTool::clientsChanged, this, [=]() { int index = ui->comboBoxClientList->currentIndex(); QString first = ui->comboBoxClientList->itemText(0); QStringList clients = mTool->clients(); diff --git a/src/tools/toolsui/saksocketservertoolui.h b/src/tools/toolsui/saksocketservertoolui.h index 3cc05f7a..00dc1582 100644 --- a/src/tools/toolsui/saksocketservertoolui.h +++ b/src/tools/toolsui/saksocketservertoolui.h @@ -10,8 +10,8 @@ #ifndef SAKSOCKETSERVERTOOLUI_H #define SAKSOCKETSERVERTOOLUI_H -#include #include "sakcommunicationtoolui.h" +#include namespace Ui { class SAKSocketServerToolUi; @@ -25,9 +25,7 @@ public: explicit SAKSocketServerToolUi(QWidget *parent = nullptr); ~SAKSocketServerToolUi(); virtual void onIsWorkingChanged(bool isWorking) final; - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; - + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: SAKSocketServerTool *mTool{nullptr}; diff --git a/src/tools/toolsui/sakstatisticiantoolui.cc b/src/tools/toolsui/sakstatisticiantoolui.cc index 6eebeb2f..1d12e260 100644 --- a/src/tools/toolsui/sakstatisticiantoolui.cc +++ b/src/tools/toolsui/sakstatisticiantoolui.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakstatisticiantool.h" #include "sakstatisticiantoolui.h" +#include "sakstatisticiantool.h" #include "ui_sakstatisticiantoolui.h" SAKStatisticianToolUi::SAKStatisticianToolUi(QWidget *parent) @@ -23,8 +23,7 @@ SAKStatisticianToolUi::~SAKStatisticianToolUi() delete ui; } -void SAKStatisticianToolUi::onBaseToolUiInitialized( - SAKBaseTool *tool, const QString &settingsGroup) +void SAKStatisticianToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { Q_UNUSED(settingsGroup) @@ -36,20 +35,18 @@ void SAKStatisticianToolUi::onBaseToolUiInitialized( return; } - auto cookedTool = qobject_cast(tool); + auto cookedTool = qobject_cast(tool); if (!cookedTool) { return; } - connect(cookedTool, &SAKStatisticianTool::bytesChanged, - this, [=](int bytes){ + connect(cookedTool, &SAKStatisticianTool::bytesChanged, this, [=](int bytes) { ui->labelBytes->setText(QString::number(bytes)); }); - connect(cookedTool, &SAKStatisticianTool::framesChanged, - this, [=](int frames){ + connect(cookedTool, &SAKStatisticianTool::framesChanged, this, [=](int frames) { ui->labelFrames->setText(QString::number(frames)); }); - connect(cookedTool, &SAKStatisticianTool::started, this, [=](){ + connect(cookedTool, &SAKStatisticianTool::started, this, [=]() { ui->labelBytes->setText(QString::number(0)); ui->labelFrames->setText(QString::number(0)); }); diff --git a/src/tools/toolsui/sakstatisticiantoolui.h b/src/tools/toolsui/sakstatisticiantoolui.h index 6d563a59..eb2e61c8 100644 --- a/src/tools/toolsui/sakstatisticiantoolui.h +++ b/src/tools/toolsui/sakstatisticiantoolui.h @@ -24,8 +24,7 @@ public: ~SAKStatisticianToolUi(); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: Ui::SAKStatisticianToolUi *ui; diff --git a/src/tools/toolsui/sakstorertoolui.cc b/src/tools/toolsui/sakstorertoolui.cc index ef8b19a6..ecba34d6 100644 --- a/src/tools/toolsui/sakstorertoolui.cc +++ b/src/tools/toolsui/sakstorertoolui.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include #include +#include #include "sakstorertool.h" #include "sakstorertoolui.h" @@ -19,8 +19,10 @@ SAKStorerToolUi::SAKStorerToolUi(QWidget *parent) , ui(new Ui::SAKStorerToolUi) { ui->setupUi(this); - connect(ui->pushButtonSelectFile, &QPushButton::clicked, - this, &SAKStorerToolUi::onPushButtonSelectFileClicked); + connect(ui->pushButtonSelectFile, + &QPushButton::clicked, + this, + &SAKStorerToolUi::onPushButtonSelectFileClicked); } SAKStorerToolUi::~SAKStorerToolUi() @@ -28,45 +30,45 @@ SAKStorerToolUi::~SAKStorerToolUi() delete ui; } -void SAKStorerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) +void SAKStorerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { if (!tool) { qCWarning((*mLoggingCategory)) << "The tool value is nullptr!"; return; } - SAKStorerTool *cookedTool = qobject_cast(tool); + SAKStorerTool *cookedTool = qobject_cast(tool); if (!cookedTool) { qCWarning((*mLoggingCategory)) << "The cookedTool value is nullptr!"; return; } - connect(ui->checkBoxEnable, &QCheckBox::clicked, this, [=](){ + connect(ui->checkBoxEnable, &QCheckBox::clicked, this, [=]() { cookedTool->setEnable(ui->checkBoxEnable->isChecked()); }); - connect(ui->checkBoxRx, &QCheckBox::clicked, this, [=](){ + connect(ui->checkBoxRx, &QCheckBox::clicked, this, [=]() { cookedTool->setSaveRx(ui->checkBoxRx->isChecked()); }); - connect(ui->checkBoxTx, &QCheckBox::clicked, this, [=](){ + connect(ui->checkBoxTx, &QCheckBox::clicked, this, [=]() { cookedTool->setSaveTx(ui->checkBoxTx->isChecked()); }); - connect(ui->checkBoxDate, &QCheckBox::clicked, this, [=](){ + connect(ui->checkBoxDate, &QCheckBox::clicked, this, [=]() { cookedTool->setSaveDate(ui->checkBoxDate->isChecked()); }); - connect(ui->checkBoxDate, &QCheckBox::clicked, this, [=](){ + connect(ui->checkBoxDate, &QCheckBox::clicked, this, [=]() { cookedTool->setSaveTime(ui->checkBoxTime->isChecked()); }); - connect(ui->checkBoxMs, &QCheckBox::clicked, this, [=](){ + connect(ui->checkBoxMs, &QCheckBox::clicked, this, [=]() { cookedTool->setSaveMs(ui->checkBoxMs->isChecked()); }); connect(ui->comboBoxFormat, - static_cast(&QComboBox::activated), - this, [=](){ - int format = ui->comboBoxFormat->currentData().toInt(); - cookedTool->setSaveFormat(format); - }); - connect(ui->lineEditStorerPath, &SAKLineEdit::textChanged, this, [=](){ + static_cast(&QComboBox::activated), + this, + [=]() { + int format = ui->comboBoxFormat->currentData().toInt(); + cookedTool->setSaveFormat(format); + }); + connect(ui->lineEditStorerPath, &SAKLineEdit::textChanged, this, [=]() { cookedTool->setFileName(ui->lineEditStorerPath->text()); }); @@ -91,8 +93,10 @@ void SAKStorerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, void SAKStorerToolUi::onPushButtonSelectFileClicked() { - auto str = QFileDialog::getSaveFileName(Q_NULLPTR, tr("Save file"), - ".", tr("txt (*.txt);;All (*)")); + auto str = QFileDialog::getSaveFileName(Q_NULLPTR, + tr("Save file"), + ".", + tr("txt (*.txt);;All (*)")); if (!str.isEmpty()) { ui->lineEditStorerPath->setText(str); } diff --git a/src/tools/toolsui/sakstorertoolui.h b/src/tools/toolsui/sakstorertoolui.h index 28d9a069..015c5400 100644 --- a/src/tools/toolsui/sakstorertoolui.h +++ b/src/tools/toolsui/sakstorertoolui.h @@ -23,8 +23,7 @@ class SAKStorerToolUi : public SAKBaseToolUi public: explicit SAKStorerToolUi(QWidget *parent = nullptr); ~SAKStorerToolUi(); - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: Ui::SAKStorerToolUi *ui{nullptr}; diff --git a/src/tools/toolsui/saktablemodeltoolui.cc b/src/tools/toolsui/saktablemodeltoolui.cc index 1e51c9ec..3ba0f73b 100644 --- a/src/tools/toolsui/saktablemodeltoolui.cc +++ b/src/tools/toolsui/saktablemodeltoolui.cc @@ -8,10 +8,10 @@ * the file LICENCE in the root of the source code directory. ******************************************************************************/ #include -#include -#include #include +#include #include +#include #include #include "sakmenu.h" @@ -29,21 +29,32 @@ SAKTableModelToolUi::SAKTableModelToolUi(const char *lg, QWidget *parent) QHeaderView *vHeaderView = ui->tableView->verticalHeader(); vHeaderView->hide(); - connect(ui->pushButtonEdit, &QPushButton::clicked, - this, &SAKTableModelToolUi::onPushButtonEditClicked); - connect(ui->pushButtonClear, &QPushButton::clicked, - this, &SAKTableModelToolUi::onPushButtonClearClicked); - connect(ui->pushButtonDelete, &QPushButton::clicked, - this, &SAKTableModelToolUi::onPushButtonDeleteClicked); - connect(ui->pushButtonImport, &QPushButton::clicked, - this, &SAKTableModelToolUi::onPushButtonImportClicked); - connect(ui->pushButtonExport, &QPushButton::clicked, - this, &SAKTableModelToolUi::onPushButtonExportClicked); - connect(ui->pushButtonAppend, &QPushButton::clicked, - this, &SAKTableModelToolUi::onPushButtonAppendClicked); + connect(ui->pushButtonEdit, + &QPushButton::clicked, + this, + &SAKTableModelToolUi::onPushButtonEditClicked); + connect(ui->pushButtonClear, + &QPushButton::clicked, + this, + &SAKTableModelToolUi::onPushButtonClearClicked); + connect(ui->pushButtonDelete, + &QPushButton::clicked, + this, + &SAKTableModelToolUi::onPushButtonDeleteClicked); + connect(ui->pushButtonImport, + &QPushButton::clicked, + this, + &SAKTableModelToolUi::onPushButtonImportClicked); + connect(ui->pushButtonExport, + &QPushButton::clicked, + this, + &SAKTableModelToolUi::onPushButtonExportClicked); + connect(ui->pushButtonAppend, + &QPushButton::clicked, + this, + &SAKTableModelToolUi::onPushButtonAppendClicked); - connect(ui->tableView, &QTableView::doubleClicked, - this, [=](const QModelIndex &index){ + connect(ui->tableView, &QTableView::doubleClicked, this, [=](const QModelIndex &index) { Q_UNUSED(index) onPushButtonEditClicked(); }); @@ -54,7 +65,7 @@ SAKTableModelToolUi::~SAKTableModelToolUi() delete ui; } -void SAKTableModelToolUi::setStretchSections(QListcolumns) +void SAKTableModelToolUi::setStretchSections(QList columns) { QTableView *tableView = ui->tableView; QHeaderView *headerView = tableView->horizontalHeader(); @@ -80,8 +91,7 @@ void SAKTableModelToolUi::setColumnVisible(int column, bool visible) } } -void SAKTableModelToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) +void SAKTableModelToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) { if (!tool) { qCWarning(mLoggingCategory) << "The value of tool is nullptr!"; @@ -89,19 +99,17 @@ void SAKTableModelToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, } if (!tool->inherits("SAKTableModelTool")) { - qCWarning(mLoggingCategory) - << "The tool does not inherits SAKTableModelTool!"; + qCWarning(mLoggingCategory) << "The tool does not inherits SAKTableModelTool!"; return; } - mTableModelTool = qobject_cast(tool); + mTableModelTool = qobject_cast(tool); if (!mTableModelTool) { - qCWarning(mLoggingCategory) - << "The value of mTableModelTool is nullptr!"; + qCWarning(mLoggingCategory) << "The value of mTableModelTool is nullptr!"; return; } - mTableModel = mTableModelTool->tableModel().value(); + mTableModel = mTableModelTool->tableModel().value(); QTableView *tableView = ui->tableView; QHeaderView *headerView = tableView->horizontalHeader(); int columnCount = mTableModel->columnCount(); @@ -131,15 +139,13 @@ void SAKTableModelToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, auto hideColumns = defaultHideColumns(); for (int i = 0; i < headers.count(); i++) { QAction *ret = mMenu->addAction(headers.at(i)); - connect(ret, &QAction::triggered, this, [=](){ + connect(ret, &QAction::triggered, this, [=]() { if (ret->isChecked()) { tableView->showColumn(i); } else { tableView->hideColumn(i); } - settings->setValue(settingGroup + "/" + rawHeaders.at(i), - ret->isChecked()); - + settings->setValue(settingGroup + "/" + rawHeaders.at(i), ret->isChecked()); }); ret->setCheckable(true); @@ -223,8 +229,7 @@ void SAKTableModelToolUi::edit(const QModelIndex &index) Qt::DirectConnection, ret, Q_ARG(QJsonObject, jsonObj)); - qCInfo(mLoggingCategory) << "the parameter of setParameters() is:" - << jsonObj; + qCInfo(mLoggingCategory) << "the parameter of setParameters() is:" << jsonObj; Q_UNUSED(ret); editor->show(); @@ -234,8 +239,7 @@ void SAKTableModelToolUi::edit(const QModelIndex &index) "parameters", Qt::DirectConnection, Q_RETURN_ARG(QJsonObject, params)); - qCInfo(mLoggingCategory) << "the parameter of parameters() is:" - << params; + qCInfo(mLoggingCategory) << "the parameter of parameters() is:" << params; QJsonDocument jsonDoc; jsonDoc.setObject(params); QString str = QString::fromUtf8(jsonDoc.toJson()); @@ -255,8 +259,7 @@ bool SAKTableModelToolUi::append() Qt::DirectConnection, ret, Q_ARG(QJsonObject, jsonObj)); - qCInfo(mLoggingCategory) << "the parameter of setParameters() is:" - << jsonObj; + qCInfo(mLoggingCategory) << "the parameter of setParameters() is:" << jsonObj; Q_UNUSED(ret); editor->show(); @@ -268,8 +271,7 @@ bool SAKTableModelToolUi::append() "parameters", Qt::DirectConnection, Q_RETURN_ARG(QJsonObject, jsonObj)); - qCInfo(mLoggingCategory) << "the parameter of parameters() is:" - << jsonObj; + qCInfo(mLoggingCategory) << "the parameter of parameters() is:" << jsonObj; QJsonDocument jsonDoc; jsonDoc.setObject(jsonObj); QString str = QString::fromUtf8(jsonDoc.toJson()); @@ -292,8 +294,7 @@ QModelIndex SAKTableModelToolUi::currentIndex() void SAKTableModelToolUi::writeToSettingsFile() { QByteArray json = exportAsJson(); - SAKSettings::instance()->setValue(mItemsKey, - QString::fromLatin1(json.toHex())); + SAKSettings::instance()->setValue(mItemsKey, QString::fromLatin1(json.toHex())); } bool SAKTableModelToolUi::isInitialized() @@ -332,7 +333,7 @@ void SAKTableModelToolUi::onPushButtonClearClicked() tr("Clear Data"), tr("The data will be empty from settings file, " "please confrim the operation!"), - QMessageBox::Cancel|QMessageBox::Ok); + QMessageBox::Cancel | QMessageBox::Ok); if (ret == QMessageBox::Ok) { clear(); writeToSettingsFile(); @@ -349,7 +350,7 @@ void SAKTableModelToolUi::onPushButtonDeleteClicked() tr("Delete Data"), tr("The data will be delete from settings file, " "please confrim the operation!"), - QMessageBox::Cancel|QMessageBox::Ok); + QMessageBox::Cancel | QMessageBox::Ok); if (ret != QMessageBox::Ok) { return; @@ -379,13 +380,13 @@ void SAKTableModelToolUi::onPushButtonImportClicked() QFile file(fileName); if (file.open(QFile::ReadOnly)) { QByteArray json = file.readAll(); - file.close();; + file.close(); + ; importFromJson(json); writeToSettingsFile(); } else { - qCWarning(mLoggingCategory) << "Can not open file:" - << file.errorString(); + qCWarning(mLoggingCategory) << "Can not open file:" << file.errorString(); } } @@ -409,8 +410,7 @@ void SAKTableModelToolUi::onPushButtonExportClicked() out << exportAsJson(); file.close(); } else { - qCWarning(mLoggingCategory) << "Can not open file:" - << file.errorString(); + qCWarning(mLoggingCategory) << "Can not open file:" << file.errorString(); } } diff --git a/src/tools/toolsui/saktablemodeltoolui.h b/src/tools/toolsui/saktablemodeltoolui.h index 70b8e494..4c610903 100644 --- a/src/tools/toolsui/saktablemodeltoolui.h +++ b/src/tools/toolsui/saktablemodeltoolui.h @@ -10,13 +10,13 @@ #ifndef SAKTABLEMODELTOOLUI_H #define SAKTABLEMODELTOOLUI_H -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include #include "sakbasetoolui.h" @@ -31,13 +31,12 @@ class SAKTableModelToolUi : public SAKBaseToolUi public: explicit SAKTableModelToolUi(const char *lg, QWidget *parent = nullptr); ~SAKTableModelToolUi(); - void setStretchSections(QListcolumns); + void setStretchSections(QList columns); void setSectionResizeModeToStretch(); void setColumnVisible(int column, bool visible); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) override; virtual QList defaultHideColumns(); virtual void afterRowEdited(int row); virtual QDialog *itemEditor() = 0; diff --git a/src/tools/toolsui/saktableviewtoolui.cc b/src/tools/toolsui/saktableviewtoolui.cc index e2245afd..18fd8f59 100644 --- a/src/tools/toolsui/saktableviewtoolui.cc +++ b/src/tools/toolsui/saktableviewtoolui.cc @@ -11,6 +11,4 @@ SAKTableViewToolUi::SAKTableViewToolUi(QWidget *parent) : SAKBaseToolUi(parent) -{ - -} +{} diff --git a/src/tools/toolsui/saktcptransmittertoolti.cc b/src/tools/toolsui/saktcptransmittertoolti.cc index 23decaa6..2bc56001 100644 --- a/src/tools/toolsui/saktcptransmittertoolti.cc +++ b/src/tools/toolsui/saktcptransmittertoolti.cc @@ -11,6 +11,4 @@ SAKTcpTransmitterToolUi::SAKTcpTransmitterToolUi(QWidget *parent) : SAKSocketClientTransmitterToolUi{"SAK.TcpTransmitterToolUi", parent} -{ - -} +{} diff --git a/src/tools/toolsui/saktransmittertoolui.cc b/src/tools/toolsui/saktransmittertoolui.cc index be968542..eae8a4a2 100644 --- a/src/tools/toolsui/saktransmittertoolui.cc +++ b/src/tools/toolsui/saktransmittertoolui.cc @@ -7,19 +7,17 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "saktransmittertool.h" #include "saktransmittertoolui.h" +#include "saktransmittertool.h" SAKTransmitterToolUi::SAKTransmitterToolUi(const char *lg, QWidget *parent) : SAKTableModelToolUi{lg, parent} -{ - -} +{} void SAKTransmitterToolUi::afterRowEdited(int row) { SAKTransmitterTool *cookedTool = Q_NULLPTR; - cookedTool = qobject_cast(mTool); + cookedTool = qobject_cast(mTool); if (!cookedTool) { return; } diff --git a/src/tools/toolsui/sakudptransmittertoolui.cc b/src/tools/toolsui/sakudptransmittertoolui.cc index 70c8fc58..0990e8b4 100644 --- a/src/tools/toolsui/sakudptransmittertoolui.cc +++ b/src/tools/toolsui/sakudptransmittertoolui.cc @@ -11,6 +11,4 @@ SAKUdpTransmitterToolUi::SAKUdpTransmitterToolUi(QWidget *parent) : SAKSocketClientTransmitterToolUi("SAK.SocketClientTransmitterToolUi", parent) -{ - -} +{} diff --git a/src/tools/toolsui/sakvelometertoolui.cc b/src/tools/toolsui/sakvelometertoolui.cc index 363c541a..91ffe11b 100644 --- a/src/tools/toolsui/sakvelometertoolui.cc +++ b/src/tools/toolsui/sakvelometertoolui.cc @@ -7,8 +7,8 @@ * QtSwissArmyKnife is licensed according to the terms in * the file LICENCE in the root of the source code directory. ******************************************************************************/ -#include "sakvelometertool.h" #include "sakvelometertoolui.h" +#include "sakvelometertool.h" #include "ui_sakvelometertoolui.h" SAKVelometerToolUi::SAKVelometerToolUi(QWidget *parent) @@ -23,8 +23,7 @@ SAKVelometerToolUi::~SAKVelometerToolUi() delete ui; } -void SAKVelometerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) +void SAKVelometerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) { Q_UNUSED(settingsGroup) @@ -39,14 +38,13 @@ void SAKVelometerToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, return; } - auto cookedTool = qobject_cast(tool); + auto cookedTool = qobject_cast(tool); if (!cookedTool) { qCWarning(mLoggingCategory) << "Invalid tool!"; return; } - connect(cookedTool, &SAKVelometerTool::velocityChanged, - this, [=](const QString &v){ + connect(cookedTool, &SAKVelometerTool::velocityChanged, this, [=](const QString &v) { ui->labelVelocity->setText(v); }); } diff --git a/src/tools/toolsui/sakvelometertoolui.h b/src/tools/toolsui/sakvelometertoolui.h index 545ef9bc..6a638914 100644 --- a/src/tools/toolsui/sakvelometertoolui.h +++ b/src/tools/toolsui/sakvelometertoolui.h @@ -10,8 +10,8 @@ #ifndef SAKVELOMETERTOOLUI_H #define SAKVELOMETERTOOLUI_H -#include #include "sakbasetoolui.h" +#include namespace Ui { class SAKVelometerToolUi; @@ -25,8 +25,7 @@ public: ~SAKVelometerToolUi(); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingsGroup) final; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingsGroup) final; private: const QLoggingCategory mLoggingCategory{"sak.velometertoolui"}; diff --git a/src/tools/toolsui/sakwebsockettransmittertoolui.cc b/src/tools/toolsui/sakwebsockettransmittertoolui.cc index 2069dbbc..9570ec76 100644 --- a/src/tools/toolsui/sakwebsockettransmittertoolui.cc +++ b/src/tools/toolsui/sakwebsockettransmittertoolui.cc @@ -11,15 +11,12 @@ SAKWebSocketTransmitterToolUi::SAKWebSocketTransmitterToolUi(QWidget *parent) : SAKSocketClientTransmitterToolUi("SAK.WebSocketTransmitterToolUi", parent) -{ +{} -} - -void SAKWebSocketTransmitterToolUi::onBaseToolUiInitialized( - SAKBaseTool *tool, const QString &settingGroup) +void SAKWebSocketTransmitterToolUi::onBaseToolUiInitialized(SAKBaseTool *tool, + const QString &settingGroup) { - SAKSocketClientTransmitterToolUi::onBaseToolUiInitialized(tool, - settingGroup); + SAKSocketClientTransmitterToolUi::onBaseToolUiInitialized(tool, settingGroup); setColumnVisible(4, true); mEditor->setWebSocketContextVisible(true); diff --git a/src/tools/toolsui/sakwebsockettransmittertoolui.h b/src/tools/toolsui/sakwebsockettransmittertoolui.h index 824c6365..a681eed3 100644 --- a/src/tools/toolsui/sakwebsockettransmittertoolui.h +++ b/src/tools/toolsui/sakwebsockettransmittertoolui.h @@ -19,8 +19,7 @@ public: SAKWebSocketTransmitterToolUi(QWidget *parent = nullptr); protected: - virtual void onBaseToolUiInitialized(SAKBaseTool *tool, - const QString &settingGroup) override; + virtual void onBaseToolUiInitialized(SAKBaseTool *tool, const QString &settingGroup) override; }; #endif // SAKWEBSOCKETTRANSMITTERTOOLUI_H