chore: format the file

This commit is contained in:
wuhai 2023-11-21 14:25:42 +08:00
parent 3a0b1b7a6f
commit ec480d10e9
204 changed files with 6984 additions and 6594 deletions

View File

@ -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()

View File

@ -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})

View File

@ -12,11 +12,15 @@
#include "sakasciiassistant.h"
#include "sakcommonmainwindow.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKAsciiAssistant>(
argc, argv, QObject::tr("Ascii Assistant"), "SAK.AsciiAssistant");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app = CreateCommonMainWindowApplication<SAKAsciiAssistant>(argc,
argv,
QObject::tr(
"Ascii Assistant"),
"SAK.AsciiAssistant");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -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_;
}

View File

@ -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

View File

@ -12,11 +12,15 @@
#include "sakbase64assistant.h"
#include "sakcommonmainwindow.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKBase64Assisatnt>(
argc, argv, QObject::tr("Base64 Assisatnt"), "SAK.Base64Assisatnt");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app
= CreateCommonMainWindowApplication<SAKBase64Assisatnt>(argc,
argv,
QObject::tr("Base64 Assisatnt"),
"SAK.Base64Assisatnt");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -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);
}

View File

@ -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

View File

@ -12,11 +12,12 @@
#include "sakbroadcastassistant.h"
#include "sakcommonmainwindow.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKBroadcastAssistant>(
argc, argv, QObject::tr("Broadcast Assistant"), "SAK.BroadcastAssistant");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app = CreateCommonMainWindowApplication<SAKBroadcastAssistant>(
argc, argv, QObject::tr("Broadcast Assistant"), "SAK.BroadcastAssistant");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -13,157 +13,166 @@
#include <QNetworkAddressEntry>
#include <QNetworkInterface>
#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("<font color=silver>%1</font>").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("<font color=silver>%1</font>").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();
}
}

View File

@ -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

View File

@ -12,60 +12,67 @@
#include <QTimer>
#include <QUdpSocket>
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;
}

View File

@ -13,31 +13,35 @@
#include <QMutex>
#include <QThread>
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

View File

@ -9,14 +9,18 @@
******************************************************************************/
#include <QApplication>
#include "sakcrcassistant.h"
#include "sakcommonmainwindow.h"
#include "sakcrcassistant.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKCRCAssistant>(
argc, argv, QObject::tr("CRC Assistant"), "SAK.CRCAssistant");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app = CreateCommonMainWindowApplication<SAKCRCAssistant>(argc,
argv,
QObject::tr(
"CRC Assistant"),
"SAK.CRCAssistant");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -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<SAKCommonCrcInterface::SAKEnumCrcModel>();
bool ok = false;
int ret = models.keyToValue(
mParameterComboBox->currentText().toLatin1().constData(), &ok);
SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8;
if (ok) {
model = static_cast<SAKCommonCrcInterface::SAKEnumCrcModel>(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<char>(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<SAKCommonCrcInterface::SAKEnumCrcModel>();
bool ok = false;
int ret = models.keyToValue(
mParameterComboBox->currentText().toLatin1().constData(), &ok);
SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8;
if (ok) {
model = static_cast<SAKCommonCrcInterface::SAKEnumCrcModel>(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<uint8_t>(
reinterpret_cast<uint8_t*>(inputArray.data()),
static_cast<uint64_t>(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<uint16_t>(
reinterpret_cast<uint8_t*>(inputArray.data()),
static_cast<uint64_t>(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<uint32_t>(
reinterpret_cast<uint8_t*>(inputArray.data()),
static_cast<uint64_t>(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<SAKCommonCrcInterface::SAKEnumCrcModel>();
bool ok = false;
SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8;
int ret = models.keyToValue(
mParameterComboBox->currentText().toLatin1().constData(), &ok);
if (ok) {
model = static_cast<SAKCommonCrcInterface::SAKEnumCrcModel>(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<int>(crc_interface_->poly(model)), 16),
bitsWidth / 4, '0'));
mInitLineEdit->setText(QString("0x%1").arg(
QString::number(static_cast<int>(crc_interface_->initialValue(model)),
16),
bitsWidth / 4, '0'));
mXorLineEdit->setText(QString("0x%1").arg(
QString::number(static_cast<int>(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<SAKCommonCrcInterface::SAKEnumCrcModel>();
bool ok = false;
int ret = models.keyToValue(mParameterComboBox->currentText().toLatin1().constData(), &ok);
SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8;
if (ok) {
model = static_cast<SAKCommonCrcInterface::SAKEnumCrcModel>(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<char>(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<SAKCommonCrcInterface::SAKEnumCrcModel>();
bool ok = false;
int ret = models.keyToValue(mParameterComboBox->currentText().toLatin1().constData(), &ok);
SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8;
if (ok) {
model = static_cast<SAKCommonCrcInterface::SAKEnumCrcModel>(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<uint8_t>(reinterpret_cast<uint8_t*>(inputArray.data()),
static_cast<uint64_t>(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<uint16_t>(reinterpret_cast<uint8_t*>(inputArray.data()),
static_cast<uint64_t>(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<uint32_t>(reinterpret_cast<uint8_t*>(inputArray.data()),
static_cast<uint64_t>(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<SAKCommonCrcInterface::SAKEnumCrcModel>();
bool ok = false;
SAKCommonCrcInterface::SAKEnumCrcModel model = SAKCommonCrcInterface::CRC_8;
int ret = models.keyToValue(mParameterComboBox->currentText().toLatin1().constData(), &ok);
if (ok) {
model = static_cast<SAKCommonCrcInterface::SAKEnumCrcModel>(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<int>(crc_interface_->poly(model)), 16),
bitsWidth / 4,
'0'));
mInitLineEdit->setText(
QString("0x%1").arg(QString::number(static_cast<int>(crc_interface_->initialValue(model)),
16),
bitsWidth / 4,
'0'));
mXorLineEdit->setText(
QString("0x%1").arg(QString::number(static_cast<int>(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);
}

View File

@ -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

View File

@ -12,12 +12,12 @@
#include "sakcommonmainwindow.h"
#include "sakfilecheckassistant.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKFileCheckAssistant>(
argc, argv, QObject::tr("File Check Assistant"),
"SAK.FileCheckAssistant");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app = CreateCommonMainWindowApplication<SAKFileCheckAssistant>(
argc, argv, QObject::tr("File Check Assistant"), "SAK.FileCheckAssistant");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -15,124 +15,132 @@
#include <QFile>
#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);
}
}

View File

@ -13,24 +13,24 @@
#include <QThread>
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<qint64> consumeTimeList;
private:
SAKFileCheckAssistant* mCryptographicHashController;
QList<qint64> 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

View File

@ -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<SAKToolFileCheckAssistant::Algorithm>();
QMetaEnum algorithms = QMetaEnum::fromType<SAKToolFileCheckAssistant::Algorithm>();
#else
QMetaEnum algorithms = QMetaEnum::fromType<QCryptographicHash::Algorithm>();
QMetaEnum algorithms = QMetaEnum::fromType<QCryptographicHash::Algorithm>();
#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("<font color=red>%1</font>").arg(msg);
} else {
msg = QString("<font color=blue>%1</font>").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("<font color=red>%1</font>").arg(msg);
} else {
msg = QString("<font color=blue>%1</font>").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<SAKToolFileCheckAssistant::Algorithm>();
QMetaEnum algorithms = QMetaEnum::fromType<SAKToolFileCheckAssistant::Algorithm>();
#else
QMetaEnum algorithms = QMetaEnum::fromType<QCryptographicHash::Algorithm>();
QMetaEnum algorithms = QMetaEnum::fromType<QCryptographicHash::Algorithm>();
#endif
mAlgorithm =
static_cast<QCryptographicHash::Algorithm>(algorithms.value(index));
mResultLineEdit->clear();
mCalculatorProgressBar->setValue(0);
mAlgorithm = static_cast<QCryptographicHash::Algorithm>(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());
}
}

View File

@ -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

View File

@ -12,11 +12,15 @@
#include "sakcommonmainwindow.h"
#include "saknumberassistant.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKNumberAssistant>(
argc, argv, QObject::tr("Number Assistant"), "SAK.NumberAssistant");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app
= CreateCommonMainWindowApplication<SAKNumberAssistant>(argc,
argv,
QObject::tr("Number Assistant"),
"SAK.NumberAssistant");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -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<char*>(&value), 1);
}
if (ui_->floatRadioButton->isChecked()) {
float* f = reinterpret_cast<float*>(data.data());
ui_->friendlyCookedDataLineEdit->setText(QString("%1").arg(*f));
data = SAKInterface::arrayToHex(data, ' ');
ui_->hexCookedDataLineEdit->setText(QString(data));
} else {
double* d = reinterpret_cast<double*>(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<quint8*>(&value);
for (int i = 0; i < int(sizeof(value)); i++) {
ptr[i] = reinterpret_cast<quint8*>(&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<char*>(&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<quint8*>(&value);
for (int i = 0; i < int(sizeof(value)); i++) {
ptr[i] = reinterpret_cast<quint8*>(&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<char*>(&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<char*>(&value), 1);
}
if (ui_->floatRadioButton->isChecked()) {
float* f = reinterpret_cast<float*>(data.data());
ui_->friendlyCookedDataLineEdit->setText(QString("%1").arg(*f));
data = SAKInterface::arrayToHex(data, ' ');
ui_->hexCookedDataLineEdit->setText(QString(data));
} else {
double* d = reinterpret_cast<double*>(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<quint8*>(&value);
for (int i = 0; i < int(sizeof(value)); i++) {
ptr[i] = reinterpret_cast<quint8*>(&temp)[int(sizeof(value)) - 1 - i];
}
}
data.append(reinterpret_cast<char*>(&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<quint8*>(&value);
for (int i = 0; i < int(sizeof(value)); i++) {
ptr[i] = reinterpret_cast<quint8*>(&temp)[int(sizeof(value)) - 1 - i];
}
}
data.append(reinterpret_cast<char*>(&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();
}

View File

@ -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

View File

@ -10,8 +10,8 @@
#include "sakassistantsfactory.h"
#include <QWidget>
#include <QCoreApplication>
#include <QWidget>
#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<SAKCRCAssistant>(kCrcAssistant,
tr("CRC Assistant"));
RegisterAssistantMetaType<SAKCRCAssistant>(kCrcAssistant, tr("CRC Assistant"));
#endif
#ifdef SAK_IMPORT_MODULE_CRCASSISTANT
RegisterAssistantMetaType<SAKFileCheckAssistant>(kFileCheckAssistant,
tr("File Check Assistant"));
RegisterAssistantMetaType<SAKFileCheckAssistant>(kFileCheckAssistant,
tr("File Check Assistant"));
#endif
#ifdef SAK_IMPORT_MODULE_ASCIIASSISTANT
RegisterAssistantMetaType<SAKAsciiAssistant>(kAsciiAssistant,
tr("ASCII Assistant"));
RegisterAssistantMetaType<SAKAsciiAssistant>(kAsciiAssistant, tr("ASCII Assistant"));
#endif
#ifdef SAK_IMPORT_MODULE_FLOATASSISTANT
RegisterAssistantMetaType<SAKNumberAssistant>(kFileCheckAssistant,
tr("Number Assistant"));
RegisterAssistantMetaType<SAKNumberAssistant>(kFileCheckAssistant, tr("Number Assistant"));
#endif
#ifdef SAK_IMPORT_MODULE_STRINGASSISTANT
RegisterAssistantMetaType<SAKStringAssistant>(kStringAssistant,
tr("String Assistant"));
RegisterAssistantMetaType<SAKStringAssistant>(kStringAssistant, tr("String Assistant"));
#endif
#ifdef SAK_IMPORT_MODULE_BROADCASTASSISTANT
RegisterAssistantMetaType<SAKBroadcastAssistant>(kBroadcastAssistant,
tr("Broadcast Assistant"));
RegisterAssistantMetaType<SAKBroadcastAssistant>(kBroadcastAssistant, tr("Broadcast Assistant"));
#endif
#ifdef SAK_IMPORT_MODULE_BASE64ASSISTANT
RegisterAssistantMetaType<SAKBase64Assisatnt>(kBase64Assistant,
tr("Base64 Assistant"));
RegisterAssistantMetaType<SAKBase64Assisatnt>(kBase64Assistant, tr("Base64 Assistant"));
#endif
}
QList<int> SAKAssistantsFactory::SupportedAssistants() {
return type_name_map_.keys();
QList<int> 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<QWidget*>(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<QWidget*>(obj);
}
return Q_NULLPTR;
return Q_NULLPTR;
}

View File

@ -13,39 +13,41 @@
#include <QMap>
#include <QObject>
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<int> SupportedAssistants();
QString GetAssistantName(int type) const;
QWidget* NewAssistant(int type);
QList<int> SupportedAssistants();
QString GetAssistantName(int type) const;
QWidget* NewAssistant(int type);
private:
QMap<int, QString> type_name_map_;
QMap<int, QMetaObject> meta_object_map_;
private:
QMap<int, QString> type_name_map_;
QMap<int, QMetaObject> meta_object_map_;
private:
template <typename T>
void RegisterAssistantMetaType(int type, const QString& assistant_name) {
type_name_map_.insert(type, assistant_name);
meta_object_map_.insert(type, T::staticMetaObject);
}
private:
template<typename T>
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

View File

@ -12,11 +12,15 @@
#include "sakcommonmainwindow.h"
#include "sakstringassistant.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKStringAssistant>(
argc, argv, QObject::tr("String Assistant"), "SAK.StringAssistant");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app
= CreateCommonMainWindowApplication<SAKStringAssistant>(argc,
argv,
QObject::tr("String Assistant"),
"SAK.StringAssistant");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -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<int>::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<int>::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<SAKCommonDataStructure::SAKEnumTextFormatInput>(
void SAKStringAssistant::OnTextEditTextChanged()
{
if (!ui_->textEdit->blockSignals(true)) {
QString inputString = ui_->textEdit->toPlainText();
auto inputFormat = static_cast<SAKCommonDataStructure::SAKEnumTextFormatInput>(
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<SAKCommonDataStructure::SAKEnumTextFormatInput>(
ui_->inputFormatComboBox->currentData().toInt());
QByteArray inputArray = SAKCommonDataStructure::stringToByteArray(inputString, inputFormat);
auto outputFormat = static_cast<SAKCommonDataStructure::SAKEnumTextFormatOutput>(
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<SAKCommonDataStructure::SAKEnumTextFormatInput>(
ui_->inputFormatComboBox->currentData().toInt());
QByteArray inputArray =
SAKCommonDataStructure::stringToByteArray(inputString, inputFormat);
auto outputFormat =
static_cast<SAKCommonDataStructure::SAKEnumTextFormatOutput>(
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();
}

View File

@ -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

View File

@ -9,6 +9,8 @@
******************************************************************************/
#include "sakcanbus.h"
SAKCanBus::SAKCanBus(QObject* parent) : QThread(parent) {}
SAKCanBus::SAKCanBus(QObject* parent)
: QThread(parent)
{}
SAKCanBus::~SAKCanBus() {}

View File

@ -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<int>::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<int>::of(&QComboBox::currentIndexChanged), this,
&SAKCanBusUi::onLoopbackIndexChanged);
connect(ui->receivOwnComboBox,
QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&SAKCanBusUi::onReceiveOwnIndexChanged);
connect(ui->canFdComboBox,
QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&SAKCanBusUi::onCanFdIndexChanged);
connect(ui->bitrateComboBox,
QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&SAKCanBusUi::onBitrateChanged);
connect(ui->dataBitrateComboBox,
QOverload<int>::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<int>::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<int>::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<int>::of(&QComboBox::currentIndexChanged),
this,
&SAKCanBusUi::onLoopbackIndexChanged);
connect(ui->receivOwnComboBox,
QOverload<int>::of(&QComboBox::currentIndexChanged),
this,
&SAKCanBusUi::onReceiveOwnIndexChanged);
connect(ui->canFdComboBox,
QOverload<int>::of(&QComboBox::currentIndexChanged),
this,
&SAKCanBusUi::onCanFdIndexChanged);
connect(ui->bitrateComboBox,
QOverload<int>::of(&QComboBox::currentIndexChanged),
this,
&SAKCanBusUi::onBitrateChanged);
connect(ui->dataBitrateComboBox,
QOverload<int>::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<int>::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("<font color=green>[Tx] </font>");
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("<font color=green>[Tx] </font>");
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("<font color=blue>[Rx] </font>");
outputMessage(flag + view);
}
QString flag = QString("<font color=blue>[Rx] </font>");
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("<font color=silver>%1 </font>").arg(datetimeString);
cookedMsg += msg;
QString cookedMsg;
cookedMsg = QString("<font color=silver>%1 </font>").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::ConfigurationItem> SAKCanBusUi::configurationItems() {
QVector<SAKCanBusUi::ConfigurationItem> 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::ConfigurationItem> SAKCanBusUi::configurationItems()
{
QVector<SAKCanBusUi::ConfigurationItem> items;
ConfigurationItem item;
const QVector<int> rates = {10000, 20000, 50000, 100000, 125000,
250000, 500000, 800000, 1000000};
const QVector<int> 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<int> rates = {10000, 20000, 50000, 100000, 125000, 250000, 500000, 800000, 1000000};
const QVector<int> 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);
}
}
}
}

View File

@ -10,27 +10,32 @@
#ifndef SAKCANBUSSTUDIOUI_H
#define SAKCANBUSSTUDIOUI_H
#include <QWidget>
#include <QVector>
#include <QSettings>
#include <QComboBox>
#include <QCheckBox>
#include <QCanBusFrame>
#include <QCanBusDevice>
#include <QCanBusFrame>
#include <QCheckBox>
#include <QComboBox>
#include <QSettings>
#include <QVector>
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class SAKCanBusUi; }
namespace Ui {
class SAKCanBusUi;
}
QT_END_NAMESPACE
class SAKCanBusUi : public QWidget
{
Q_OBJECT
typedef QPair<QCanBusDevice::ConfigurationKey, QVariant> 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);

View File

@ -12,11 +12,15 @@
#include "sakcanbusstudioui.h"
#include "sakcommonmainwindow.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKCanBusUi>(
argc, argv, QObject::tr("CAN Bus Studio"), "SAK.CanBusStudio");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app = CreateCommonMainWindowApplication<SAKCanBusUi>(argc,
argv,
QObject::tr(
"CAN Bus Studio"),
"SAK.CanBusStudio");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -13,119 +13,148 @@
#include <QDebug>
#include <QtGlobal>
#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<QBluetoothDeviceInfo>(info);
}
mDeviceInfoListMutex.unlock();
return QVariant();
void SAKBleScanner::startDiscover()
{
start();
}
QString SAKBleScanner::deviceName(const QVariant& deviceInfo) {
auto cookedInfo = deviceInfo.value<QBluetoothDeviceInfo>();
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<QBluetoothDeviceInfo>(info);
}
mDeviceInfoListMutex.unlock();
return QVariant();
}
QString SAKBleScanner::deviceName(const QVariant& deviceInfo)
{
auto cookedInfo = deviceInfo.value<QBluetoothDeviceInfo>();
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<BLE_ERR_SIG>(&QBluetoothDeviceDiscoveryAgent::error),
this, &SAKBleScanner::onDiscoveryErrorOccurred);
connect(mDiscover,
static_cast<BLE_ERR_SIG>(&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();
}

View File

@ -10,23 +10,20 @@
#ifndef SAKBLESCANNER_H
#define SAKBLESCANNER_H
#include <QBluetoothDeviceDiscoveryAgent>
#include <QBluetoothDeviceInfo>
#include <QLoggingCategory>
#include <QMutex>
#include <QThread>
#include <QVariant>
#include <QLoggingCategory>
#include <QBluetoothDeviceInfo>
#include <QBluetoothDeviceDiscoveryAgent>
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();

View File

@ -14,146 +14,148 @@
#include "sakcommoncrcinterface.h"
SAKCommonCrcInterface::SAKCommonCrcInterface(QObject* parent)
: QObject(parent) {}
: QObject(parent)
{}
QStringList SAKCommonCrcInterface::supportedParameterModels() {
modelStrings.clear();
QMetaEnum models = QMetaEnum::fromType<SAKEnumCrcModel>();
QStringList SAKCommonCrcInterface::supportedParameterModels()
{
modelStrings.clear();
QMetaEnum models = QMetaEnum::fromType<SAKEnumCrcModel>();
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<SAKCommonCrcInterface::SAKEnumCrcModel>();
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<SAKCommonCrcInterface::SAKEnumCrcModel>();
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

View File

@ -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<typename T>
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<T>(initialValue(model));
T rawPoly = static_cast<T>(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<T>((byte << 8*(sizeof (T)-1)));
for(int i = 0;i < 8;i++){
if(crcReg & (temp << (sizeof (T)*8-1))){
crcReg ^= static_cast<T>((byte << 8 * (sizeof(T) - 1)));
for (int i = 0; i < 8; i++) {
if (crcReg & (temp << (sizeof(T) * 8 - 1))) {
crcReg = static_cast<T>((crcReg << 1) ^ rawPoly);
}else {
} else {
crcReg = static_cast<T>(crcReg << 1);
}
}
}
if (isOutputReversal(model)){
reverseInt(crcReg,crcReg);
if (isOutputReversal(model)) {
reverseInt(crcReg, crcReg);
}
T crc = (crcReg ^ static_cast<T>(xorValue(model))) ;
T crc = (crcReg ^ static_cast<T>(xorValue(model)));
return crc;
}
private:
QStringList modelStrings;
private:
template<typename T>
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;

View File

@ -16,380 +16,390 @@
#include <QStandardItemModel>
SAKCommonDataStructure::SAKCommonDataStructure(QObject *parent)
: QObject(parent) {}
: QObject(parent)
{}
SAKCommonDataStructure::~SAKCommonDataStructure() {}
void SAKCommonDataStructure::setComboBoxTextOutputFormat(QComboBox *comboBox) {
if (comboBox) {
QMap<int, QString> 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<int, QString> 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<int, QString> 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<int, QString> 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<char *>(&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<char *>(&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<char *>(&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<char *>(&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<SAKCommonDataStructure::SAKEnumTextFormatInput>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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<const char16_t *>(origingData.constData()),
origingData.length() / sizeof(char16_t)));
} else if (format == SAKCommonDataStructure::OutputFormatUcs4) {
str.append(QString::fromUcs4(
reinterpret_cast<const char32_t *>(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<int, QRegularExpressionValidator *> 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<char *>(&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<char *>(&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<char *>(&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<char *>(&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<SAKCommonDataStructure::SAKEnumTextFormatInput>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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<const char16_t *>(origingData.constData()),
origingData.length() / sizeof(char16_t)));
} else if (format == SAKCommonDataStructure::OutputFormatUcs4) {
str.append(QString::fromUcs4(reinterpret_cast<const char32_t *>(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<SAKEnumTextFormatInput>(format);
SAKCommonDataStructure::setLineEditTextFormat(lineEdit, cookedFormat);
}
SAKEnumTextFormatInput format)
{
QMap<int, QRegularExpressionValidator *> 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<int, QString> 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<SAKCommonDataStructure::SAKEnumTextFormatInput>(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<SAKEnumTextFormatInput>(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<int, QString> 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<SAKCommonDataStructure::SAKEnumTextFormatInput>(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<int, QString> &formatMap,
int currentData) {
if (comboBox) {
comboBox->clear();
QMapIterator<int, QString> 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<int, QString> 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);
}
}
}
}
}

View File

@ -10,10 +10,10 @@
#ifndef SAKCOMMONDATASTRUCTURE_H
#define SAKCOMMONDATASTRUCTURE_H
#include <QComboBox>
#include <QMap>
#include <QObject>
#include <QTextEdit>
#include <QComboBox>
#ifdef SAK_IMPORT_MODULE_SERIALPORT
#include <QSerialPort>
@ -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<int, QString> &formatMap,

View File

@ -7,57 +7,48 @@
* QtSwissArmyKnife is licensed according to the terms in
* the file LICENCE in the root of the source code directory.
******************************************************************************/
#include <QMap>
#include <QMetaEnum>
#include <QComboBox>
#include <QHostAddress>
#include <QMap>
#include <QMetaEnum>
#include <QNetworkInterface>
#include <QStandardItemModel>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QStandardItemModel>
#ifdef SAK_IMPORT_MODULE_SERIALPORT
#include <QSerialPort>
#include <QSerialPortInfo>
#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<int, QRegularExpression> 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<QSerialPortInfo> 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<qint32> 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<QHostAddress> 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);

View File

@ -10,38 +10,48 @@
#ifndef SAKCOMMONINTERFACE_H
#define SAKCOMMONINTERFACE_H
#include <QObject>
#include <QCheckBox>
#include <QSettings>
#include <QLineEdit>
#include <QComboBox>
#include <QLineEdit>
#include <QObject>
#include <QSettings>
#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);
};

View File

@ -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<uint8_t>(
reinterpret_cast<uint8_t*>(temp.data()) + startIndex,
len, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char*>(&ret), sizeof(ret));
uint8_t ret = crcCalculate<uint8_t>(reinterpret_cast<uint8_t *>(temp.data())
+ startIndex,
len,
SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char *>(&ret), sizeof(ret));
} else if (bw == 16) {
uint16_t ret = crcCalculate<uint16_t>(
reinterpret_cast<uint8_t*>(temp.data()) + startIndex,
len, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char*>(&ret), sizeof(ret));
uint16_t ret = crcCalculate<uint16_t>(reinterpret_cast<uint8_t *>(temp.data())
+ startIndex,
len,
SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char *>(&ret), sizeof(ret));
} else if (bw == 32) {
uint32_t ret = crcCalculate<uint32_t>(
reinterpret_cast<uint8_t*>(temp.data()) + startIndex,
len, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char*>(&ret), sizeof(ret));
uint32_t ret = crcCalculate<uint32_t>(reinterpret_cast<uint8_t *>(temp.data())
+ startIndex,
len,
SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char *>(&ret), sizeof(ret));
}
} else {
if (bw == 8) {
uint8_t ret = crcCalculate<uint8_t>(
nullptr, 0, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char*>(&ret), sizeof(ret));
uint8_t ret = crcCalculate<uint8_t>(nullptr, 0, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char *>(&ret), sizeof(ret));
} else if (bw == 16) {
uint16_t ret = crcCalculate<uint8_t>(
nullptr, 0, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char*>(&ret), sizeof(ret));
uint16_t ret = crcCalculate<uint8_t>(nullptr, 0, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char *>(&ret), sizeof(ret));
} else if (bw == 32) {
uint32_t ret = crcCalculate<uint8_t>(
nullptr, 0, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char*>(&ret), sizeof(ret));
uint32_t ret = crcCalculate<uint8_t>(nullptr, 0, SAKEnumCrcAlgorithm(arithmetic));
retBytes = QByteArray(reinterpret_cast<char *>(&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;

View File

@ -10,15 +10,15 @@
#ifndef SAKCRCINTERFACE_H
#define SAKCRCINTERFACE_H
#include <QLoggingCategory>
#include <QObject>
#include <QStringList>
#include <QLoggingCategory>
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<typename T>
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<T>(initialValue(model));
T rawPoly = static_cast<T>(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<T>((byte << 8*(sizeof (T)-1)));
for(int i = 0;i < 8;i++){
if(crcReg & (temp << (sizeof (T)*8-1))){
crcReg ^= static_cast<T>((byte << 8 * (sizeof(T) - 1)));
for (int i = 0; i < 8; i++) {
if (crcReg & (temp << (sizeof(T) * 8 - 1))) {
crcReg = static_cast<T>((crcReg << 1) ^ rawPoly);
}else {
} else {
crcReg = static_cast<T>(crcReg << 1);
}
}
}
if (isOutputReversal(model)){
reverseInt(crcReg,crcReg);
if (isOutputReversal(model)) {
reverseInt(crcReg, crcReg);
}
T crc = (crcReg ^ static_cast<T>(xorValue(model))) ;
T crc = (crcReg ^ static_cast<T>(xorValue(model)));
return crc;
}
@ -98,13 +97,14 @@ private:
private:
template<typename T>
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;

View File

@ -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;
}

View File

@ -13,85 +13,79 @@
#include <QObject>
#include <Qt>
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

View File

@ -2,8 +2,8 @@
* Copyright 2023 wuuhaii(qsaker@foxmail.com). All rights reserved.
******************************************************************************/
#include <QDebug>
#include <QTextDocument>
#include <QRegularExpression>
#include <QTextDocument>
#ifdef SAK_IMPORT_MODULE_QML
#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
#include <QQuickTextDocument>
@ -14,23 +14,21 @@
SAKHighlighter::SAKHighlighter(QObject *parent)
: QSyntaxHighlighter(parent)
{
}
{}
void SAKHighlighter::setDoc(QVariant doc)
{
auto obj = doc.value<QObject*>();
auto obj = doc.value<QObject *>();
#ifdef SAK_IMPORT_MODULE_QML
#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
if (obj->inherits("QQuickTextDocument")) {
setDocument(doc.value<QQuickTextDocument*>()->textDocument());
setDocument(doc.value<QQuickTextDocument *>()->textDocument());
return;
}
#endif
#endif
if (obj->inherits("QTextDocument")) {
setDocument(doc.value<QTextDocument*>());
setDocument(doc.value<QTextDocument *>());
}
}

View File

@ -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<QObject*>();
if (obj) {
void SAKInterface::setMaximumBlockCount(QVariant doc, int maximum)
{
auto obj = doc.value<QObject*>();
if (obj) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
#ifdef SAK_IMPORT_MODULE_QML
auto quickTextDoc = qobject_cast<QQuickTextDocument*>(obj);
if (quickTextDoc) {
auto textDoc = quickTextDoc->textDocument();
textDoc->setMaximumBlockCount(maximum);
auto quickTextDoc = qobject_cast<QQuickTextDocument*>(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<int> 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<int> 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<char*>(&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<char*>(&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<char*>(&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<char*>(&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<char*>(&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<char*>(&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<char*>(&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<char*>(&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<const uchar*>(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<const uchar*>(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;
}

View File

@ -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

View File

@ -13,45 +13,47 @@
#include <QNetworkInterface>
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();
}
}
}
}

View File

@ -4,8 +4,8 @@
#ifndef SAKNETWORKINTERFACESCANNER_H
#define SAKNETWORKINTERFACESCANNER_H
#include <QTimer>
#include <QObject>
#include <QTimer>
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();
};

View File

@ -1,9 +1,9 @@
/*******************************************************************************
* Copyright 2023 wuuhaii(qsaker@foxmail.com). All rights reserved.
******************************************************************************/
#include "sakserialportscanner.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#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;
}

View File

@ -4,8 +4,8 @@
#ifndef SAKSERIALPORTSCANNER_H
#define SAKSERIALPORTSCANNER_H
#include <QTimer>
#include <QObject>
#include <QTimer>
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();
};

View File

@ -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<SAKTableModel*>(this)->invokeGetRowCount(count);
emit const_cast<SAKTableModel *>(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<SAKTableModel*>(this)->invokeGetColumnCount(column);
emit const_cast<SAKTableModel *>(this)->invokeGetColumnCount(column);
return column;
}
QVariant SAKTableModel::data(const QModelIndex &index, int role) const
{
QVariant d;
emit const_cast<SAKTableModel*>(this)->invokeGetData(d, index, role);
emit const_cast<SAKTableModel *>(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<SAKTableModel*>(this)->invokeGetHeaderData(d,
section,
orientation,
role);
emit const_cast<SAKTableModel *>(this)->invokeGetHeaderData(d, section, orientation, role);
return d;
}

View File

@ -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,

View File

@ -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;
}
}

View File

@ -10,13 +10,13 @@
#ifndef SAKTRANSLATOR_H
#define SAKTRANSLATOR_H
#include <QMap>
#include <QObject>
#include <QJsonArray>
#include <QJsonObject>
#include <QLoggingCategory>
#include <QMap>
#include <QObject>
#include <QTranslator>
#include <QVariantList>
#include <QLoggingCategory>
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);

View File

@ -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)

View File

@ -17,7 +17,7 @@ SAKBaudRateComboBox::SAKBaudRateComboBox(QWidget *parent)
{
clear();
QList<qint32> bd = QSerialPortInfo::standardBaudRates();
for (auto &var:bd) {
for (auto &var : bd) {
addItem(QString::number(var), QVariant::fromValue(var));
}

View File

@ -13,7 +13,9 @@
#include <QMessageBox>
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);
}

View File

@ -12,8 +12,8 @@
#include <QEvent>
#include "sakcombobox.h"
#include "sakblescanner.h"
#include "sakcombobox.h"
class SAKBluetoothDeviceInfoComboBox : public SAKComboBox
{

View File

@ -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());
}

View File

@ -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;

View File

@ -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());
}
}
}
}

View File

@ -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;

View File

@ -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<QAction*> actions = app_style_action_group_->actions();
for (auto action : actions) {
app_style_action_group_->removeAction(action);
}
void SAKCommonMainWindow::InitOptionMenuAppStyleMenu()
{
QList<QAction*> 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<QPair<int, QString>> policy_list;
typedef QPair<int, QString> 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<QPair<int, QString>> policy_list;
typedef QPair<int, QString> 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";
}

View File

@ -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 <typename T>
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<typename T>
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

View File

@ -14,10 +14,10 @@
#include "sakcrcinterface.h"
SAKCrcAlgorithmComboBox::SAKCrcAlgorithmComboBox(QWidget* parent)
: SAKComboBox(parent) {
QMetaEnum metaEnum =
QMetaEnum::fromType<SAKCrcInterface::SAKEnumCrcAlgorithm>();
for (int i = 0; i < metaEnum.keyCount(); i++) {
addItem(metaEnum.key(i), metaEnum.value(i));
}
: SAKComboBox(parent)
{
QMetaEnum metaEnum = QMetaEnum::fromType<SAKCrcInterface::SAKEnumCrcAlgorithm>();
for (int i = 0; i < metaEnum.keyCount(); i++) {
addItem(metaEnum.key(i), metaEnum.value(i));
}
}

View File

@ -12,9 +12,10 @@
#include <QSerialPort>
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);
}

View File

@ -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);
}

View File

@ -12,8 +12,9 @@
#include <QSerialPort>
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);
}

View File

@ -12,11 +12,13 @@
#include <QNetworkAddressEntry>
#include <QNetworkInterface>
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());
}
}
}
}

View File

@ -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());
}

View File

@ -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;

View File

@ -12,19 +12,23 @@
#include <QMouseEvent>
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);
}

View File

@ -11,10 +11,12 @@
#include <QSerialPort>
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);
}

View File

@ -14,19 +14,21 @@
#include <QStandardItemModel>
SAKPortNameComboBox::SAKPortNameComboBox(QWidget* parent)
: SAKComboBox(parent) {
refresh();
: SAKComboBox(parent)
{
refresh();
}
void SAKPortNameComboBox::refresh() {
clear();
QList<QSerialPortInfo> 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<QSerialPortInfo> 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);
}

View File

@ -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);
}

View File

@ -11,29 +11,36 @@
#include "saksettings.h"
SAKSpinBox::SAKSpinBox(QWidget* parent) : QSpinBox(parent) {
connect(this, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
this, &SAKSpinBox::writeToSettingsFile);
SAKSpinBox::SAKSpinBox(QWidget* parent)
: QSpinBox(parent)
{
connect(this,
static_cast<void (QSpinBox::*)(int)>(&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());
}

View File

@ -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;

View File

@ -12,10 +12,11 @@
#include <QSerialPort>
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);
}

View File

@ -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);
}

View File

@ -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<int, QRegularExpression> 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<int, QRegularExpression> 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;
}

View File

@ -10,8 +10,8 @@
#ifndef SAKUIINTERFACE_H
#define SAKUIINTERFACE_H
#include <QObject>
#include <QLineEdit>
#include <QObject>
class SAKUiInterface : public QObject
{

View File

@ -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);
}

View File

@ -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();
}

View File

@ -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<SAKToolBox>("SAK.Custom", 1, 0, "SAKDevice");
qmlRegisterType<SAKSettings>("SAK.Custom", 1, 0, "SAKSettings");
qmlRegisterType<SAKBleScanner>("SAK.Custom", 1, 0, "SAKBleScanner");
qmlRegisterType<SAKHighlighter>("SAK.Custom", 1, 0, "SAKHighlighter");
qmlRegisterType<SAKCrcInterface>("SAK.Custom", 1, 0, "SAKCrcInterface");
qmlRegisterType<SAKSerialPortScanner>("SAK.Custom", 1, 0,
"SAKSerialPortScanner");
qmlRegisterType<SAKNetworkInterfaceScanner>("SAK.Custom", 1, 0,
"SAKNetworkInterfaceScanner");
const QString reason = "Uncreatable type!";
qmlRegisterType<SAKToolBox>("SAK.Custom", 1, 0, "SAKDevice");
qmlRegisterType<SAKSettings>("SAK.Custom", 1, 0, "SAKSettings");
qmlRegisterType<SAKBleScanner>("SAK.Custom", 1, 0, "SAKBleScanner");
qmlRegisterType<SAKHighlighter>("SAK.Custom", 1, 0, "SAKHighlighter");
qmlRegisterType<SAKCrcInterface>("SAK.Custom", 1, 0, "SAKCrcInterface");
qmlRegisterType<SAKSerialPortScanner>("SAK.Custom", 1, 0, "SAKSerialPortScanner");
qmlRegisterType<SAKNetworkInterfaceScanner>("SAK.Custom", 1, 0, "SAKNetworkInterfaceScanner");
qmlRegisterUncreatableType<SAKBaseTool>("SAK.Custom", 1, 0, "SAKBaseTool",
reason);
qmlRegisterUncreatableType<SAKMaskerTool>("SAK.Custom", 1, 0, "SAKMaskerTool",
reason);
qmlRegisterUncreatableType<SAKStorerTool>("SAK.Custom", 1, 0, "SAKStorerTool",
reason);
qmlRegisterUncreatableType<SAKEmitterTool>("SAK.Custom", 1, 0,
"SAKEmitterTool", reason);
qmlRegisterUncreatableType<SAKToolFactory>("SAK.Custom", 1, 0,
"SAKToolsFactory", reason);
qmlRegisterUncreatableType<SAKAnalyzerTool>("SAK.Custom", 1, 0,
"SAKAnalyzerTool", reason);
qmlRegisterUncreatableType<SAKPrestorerTool>("SAK.Custom", 1, 0,
"SAKPrestorerTool", reason);
qmlRegisterUncreatableType<SAKResponserTool>("SAK.Custom", 1, 0,
"SAKResponserTool", reason);
qmlRegisterUncreatableType<SAKUdpClientTool>("SAK.Custom", 1, 0,
"SAKUdpClientTool", reason);
qmlRegisterUncreatableType<SAKUdpServerTool>("SAK.Custom", 1, 0,
"SAKUdpServerTool", reason);
qmlRegisterUncreatableType<SAKTcpClientTool>("SAK.Custom", 1, 0,
"SAKTcpClientTool", reason);
qmlRegisterUncreatableType<SAKTcpServerTool>("SAK.Custom", 1, 0,
"SAKTcpServerTool", reason);
qmlRegisterUncreatableType<SAKBleCentralTool>("SAK.Custom", 1, 0,
"SAKBleCentralTool", reason);
qmlRegisterUncreatableType<SAKSerialPortTool>("SAK.Custom", 1, 0,
"SAKSerialportTool", reason);
qmlRegisterUncreatableType<SAKTableModelTool>("SAK.Custom", 1, 0,
"SAKTabelModelTool", reason);
qmlRegisterUncreatableType<SAKCommunicationTool>(
"SAK.Custom", 1, 0, "SAKCommunicationTool", reason);
qmlRegisterUncreatableType<SAKWebSocketServerTool>(
"SAK.Custom", 1, 0, "SAKWebSocketServerTool", reason);
qmlRegisterUncreatableType<SAKWebSocketClientTool>(
"SAK.Custom", 1, 0, "SAKWebSocketClientTool", reason);
qmlRegisterUncreatableType<SAKBaseTool>("SAK.Custom", 1, 0, "SAKBaseTool", reason);
qmlRegisterUncreatableType<SAKMaskerTool>("SAK.Custom", 1, 0, "SAKMaskerTool", reason);
qmlRegisterUncreatableType<SAKStorerTool>("SAK.Custom", 1, 0, "SAKStorerTool", reason);
qmlRegisterUncreatableType<SAKEmitterTool>("SAK.Custom", 1, 0, "SAKEmitterTool", reason);
qmlRegisterUncreatableType<SAKToolFactory>("SAK.Custom", 1, 0, "SAKToolsFactory", reason);
qmlRegisterUncreatableType<SAKAnalyzerTool>("SAK.Custom", 1, 0, "SAKAnalyzerTool", reason);
qmlRegisterUncreatableType<SAKPrestorerTool>("SAK.Custom", 1, 0, "SAKPrestorerTool", reason);
qmlRegisterUncreatableType<SAKResponserTool>("SAK.Custom", 1, 0, "SAKResponserTool", reason);
qmlRegisterUncreatableType<SAKUdpClientTool>("SAK.Custom", 1, 0, "SAKUdpClientTool", reason);
qmlRegisterUncreatableType<SAKUdpServerTool>("SAK.Custom", 1, 0, "SAKUdpServerTool", reason);
qmlRegisterUncreatableType<SAKTcpClientTool>("SAK.Custom", 1, 0, "SAKTcpClientTool", reason);
qmlRegisterUncreatableType<SAKTcpServerTool>("SAK.Custom", 1, 0, "SAKTcpServerTool", reason);
qmlRegisterUncreatableType<SAKBleCentralTool>("SAK.Custom", 1, 0, "SAKBleCentralTool", reason);
qmlRegisterUncreatableType<SAKSerialPortTool>("SAK.Custom", 1, 0, "SAKSerialportTool", reason);
qmlRegisterUncreatableType<SAKTableModelTool>("SAK.Custom", 1, 0, "SAKTabelModelTool", reason);
qmlRegisterUncreatableType<SAKCommunicationTool>("SAK.Custom",
1,
0,
"SAKCommunicationTool",
reason);
qmlRegisterUncreatableType<SAKWebSocketServerTool>("SAK.Custom",
1,
0,
"SAKWebSocketServerTool",
reason);
qmlRegisterUncreatableType<SAKWebSocketClientTool>("SAK.Custom",
1,
0,
"SAKWebSocketClientTool",
reason);
qmlRegisterUncreatableType<SAKInterface>("SAK.Custom", 1, 0, "SAKInterface",
reason);
qmlRegisterUncreatableType<SAKDataStructure>("SAK.Custom", 1, 0,
"SAKDataStructure", reason);
qmlRegisterUncreatableType<SAKInterface>("SAK.Custom", 1, 0, "SAKInterface", reason);
qmlRegisterUncreatableType<SAKDataStructure>("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;
}

View File

@ -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);
}

View File

@ -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]);

View File

@ -12,11 +12,14 @@
#include "sakcommonmainwindow.h"
#include "sakmodbusui.h"
int main(int argc, char* argv[]) {
QApplication* app = CreateCommonMainWindowApplication<SAKModbusUi>(
argc, argv, QObject::tr("Modbus Studio"), "SAK.ModbusStudio");
int ret = app->exec();
app->deleteLater();
int main(int argc, char* argv[])
{
QApplication* app = CreateCommonMainWindowApplication<SAKModbusUi>(argc,
argv,
QObject::tr("Modbus Studio"),
"SAK.ModbusStudio");
int ret = app->exec();
app->deleteLater();
return ret;
return ret;
}

View File

@ -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<QModbusTcpClient *>(modbus_device)) {
return true;
} else if (qobject_cast<QModbusTcpServer *>(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<QModbusTcpClient *>(modbus_device)) {
return true;
} else if (qobject_cast<QModbusTcpServer *>(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<QModbusRtuSerialClient *>(modbus_device)) {
if (qobject_cast<QModbusRtuSerialClient *>(modbus_device)) {
#else
if (qobject_cast<QModbusRtuSerialMaster *>(modbus_device)) {
if (qobject_cast<QModbusRtuSerialMaster *>(modbus_device)) {
#endif
return true;
return true;
#if QT_VERSION >= QT_VERSION_CHECK(6, 2, 0)
} else if (qobject_cast<QModbusRtuSerialServer *>(modbus_device)) {
} else if (qobject_cast<QModbusRtuSerialServer *>(modbus_device)) {
#else
} else if (qobject_cast<QModbusRtuSerialSlave *>(modbus_device)) {
} else if (qobject_cast<QModbusRtuSerialSlave *>(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<QModbusServer *>(modbus_device)) {
return true;
}
return false;
}
bool SAKModbusFactory::IsClientDevice(QModbusDevice *modbus_device) {
if (modbus_device && qobject_cast<QModbusClient *>(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<QModbusServer *>(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<QModbusClient *>(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<QModbusServer *>(server)) {
QModbusServer *modbusServer = qobject_cast<QModbusServer *>(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<QModbusServer *>(server)) {
QModbusServer *modbusServer = qobject_cast<QModbusServer *>(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<quint16> SAKModbusFactory::GetServerData(
QModbusDevice *server, QModbusDataUnit::RegisterType table, int address,
int quantity) {
QList<quint16> values;
if (server && qobject_cast<QModbusServer *>(server)) {
QModbusServer *cooked_server = qobject_cast<QModbusServer *>(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<quint16> SAKModbusFactory::GetServerData(QModbusDevice *server,
QModbusDataUnit::RegisterType table,
int address,
int quantity)
{
QList<quint16> values;
if (server && qobject_cast<QModbusServer *>(server)) {
QModbusServer *cooked_server = qobject_cast<QModbusServer *>(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<QModbusServer *>(*modbus_device);
if (server) {
server->disconnect();
}
void SAKModbusFactory::DeleteModbusDevuce(QModbusDevice **modbus_device)
{
if (*modbus_device) {
QModbusServer *server = qobject_cast<QModbusServer *>(*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<QModbusClient *>(client);
cooked_client->setTimeout(timeout);
cooked_client->setNumberOfRetries(number_of_retries);
}
QModbusClient *cooked_client = qobject_cast<QModbusClient *>(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<QModbusServer *>(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<QModbusServer *>(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<quint16> 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<QModbusClient *>(modbus_device);
QModbusReply *reply = client->sendWriteRequest(dataUnit, server_address);
return reply;
} else {
qCWarning(kLoggingCategory) << "Unvalid data unit!";
auto *client = qobject_cast<QModbusClient *>(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<QModbusClient *>(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<QModbusClient *>(modbus_device);
return client->sendRawRequest(request, server_address);
}
return Q_NULLPTR;
return Q_NULLPTR;
}

View File

@ -16,64 +16,72 @@
#include <QModbusReply>
#include <QObject>
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<quint16> 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<quint16> 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<quint16> values,
QVector<quint16> values,
#else
QList<quint16> values,
QList<quint16> 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

File diff suppressed because it is too large Load Diff

View File

@ -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<quint16> &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<quint16> &values);
void UpdateClientReadWriteButtonState();
void UpdateClientParameters();
void UpdateClientTableViewAddress(QTableView *view, int start_address);
void UpdateServerParameters();
bool UpdateServerMap(QModbusDevice *server);
void UpdateServerRegistersData();
quint8 GetClientFunctionCode();
QList<quint16> GetClientRegisterValue();
QByteArray GetClientPdu();
QTableView *GetTableView(QModbusDataUnit::RegisterType table);
QList<quint16> GetTableValues(QTableView *table_view, int row, int count);
quint8 GetClientFunctionCode();
QList<quint16> GetClientRegisterValue();
QByteArray GetClientPdu();
QTableView *GetTableView(QModbusDataUnit::RegisterType table);
QList<quint16> 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

View File

@ -11,6 +11,4 @@
SAKPreferences::SAKPreferences(QObject *parent)
: QObject{parent}
{
}
{}

View File

@ -19,7 +19,6 @@ public:
explicit SAKPreferences(QObject *parent = nullptr);
signals:
};
#endif // SAKPREFERENCES_HH

View File

@ -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);
}

View File

@ -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();
}
}

View File

@ -11,12 +11,12 @@
#define SAKAPPLICATION_H
#include <QApplication>
#include <QSplashScreen>
#include <QLoggingCategory>
#include <QSplashScreen>
#define sakApp (static_cast<SAKApplication *>(QCoreApplication::instance()))
class SAKApplication:public QApplication
class SAKApplication : public QApplication
{
Q_OBJECT
public:

View File

@ -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

View File

@ -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 <QAction>
#include <QDir>
#include <QMenu>
#include <QAction>
#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);
}

Some files were not shown because too many files have changed in this diff Show More