-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget.cpp
More file actions
796 lines (699 loc) · 26.4 KB
/
widget.cpp
File metadata and controls
796 lines (699 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
#include "widget.h"
#include "ui_widget.h"
#include "appsettings.h"
#include "keywordhighlighter.h"
#include <QMessageBox>
#include <QSerialPortInfo>
#include <QRegularExpression>
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QComboBox>
#include <QCheckBox>
#include <QPushButton>
#include <QSpinBox>
#include <QAbstractItemView>
/**
* @brief Widget 构造函数
*
* 初始化所有组件并建立信号槽连接。
* Requirements: 1.3, 6.1, 6.2, 6.3, 6.4
*/
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
, m_worker(new SerialWorker())
, m_processor(new DataProcessor(this))
, m_buffer(new DataBuffer(65536, this))
, m_refreshTimer(new QTimer(this))
, m_highlighter(nullptr)
, m_speedMonitor(new SpeedMonitor(this))
, m_autoScroll(true)
{
ui->setupUi(this);
ui->open->setStyleSheet("color: red;");
ui->cbBaudRate->setCurrentText("115200");
QList<int> sizes;
sizes << 30000 << 50000;
ui->splitter->setSizes(sizes);
updatePortList();
setupConnections();
// Initialize AppSettings and connect signals to DataProcessor
// Requirements: 4.1
AppSettings *settings = AppSettings::instance();
// Apply initial settings to DataProcessor
m_processor->setEncoding(settings->encoding());
m_processor->setHexNewlineEnabled(settings->hexNewlineEnabled());
// Connect AppSettings signals to DataProcessor setters
connect(settings, &AppSettings::encodingChanged,
m_processor, &DataProcessor::setEncoding);
connect(settings, &AppSettings::hexNewlineEnabledChanged,
m_processor, &DataProcessor::setHexNewlineEnabled);
// Create and attach KeywordHighlighter to receiveEdit
// Requirements: 3.2, 3.3
m_highlighter = new KeywordHighlighter(ui->receiveEdit->document());
m_highlighter->setEnabled(settings->keywordHighlightEnabled());
// Connect AppSettings signal to highlighter
connect(settings, &AppSettings::keywordHighlightEnabledChanged,
m_highlighter, &KeywordHighlighter::setEnabled);
// Apply initial font settings from AppSettings
// Requirements: 5.2
QFont font = ui->receiveEdit->font();
font.setPointSize(settings->fontSize());
font.setFamily(settings->fontFamily());
ui->receiveEdit->setFont(font);
ui->sendEdit->setFont(font);
// Connect fontSizeChanged signal
connect(settings, &AppSettings::fontSizeChanged, this, [this](int size) {
QFont font = ui->receiveEdit->font();
font.setPointSize(size);
ui->receiveEdit->setFont(font);
ui->sendEdit->setFont(font);
});
// Connect fontFamilyChanged signal
connect(settings, &AppSettings::fontFamilyChanged, this, [this](const QString &family) {
QFont font = ui->receiveEdit->font();
font.setFamily(family);
ui->receiveEdit->setFont(font);
ui->sendEdit->setFont(font);
});
// Apply last used port name if available
// Requirements: 6.4
QString lastPort = settings->lastPortName();
if (!lastPort.isEmpty()) {
for (int i = 0; i < ui->cbPortName->count(); ++i) {
if (ui->cbPortName->itemData(i).toString() == lastPort) {
ui->cbPortName->setCurrentIndex(i);
break;
}
}
}
// Connect dark mode signal and apply initial dark mode setting
// Requirements: 3.3
connect(settings, &AppSettings::darkModeEnabledChanged,
this, &Widget::applyDarkMode);
applyDarkMode(settings->darkModeEnabled());
m_refreshTimer->setTimerType(Qt::PreciseTimer);
m_refreshTimer->setInterval(REFRESH_INTERVAL_MS);
// Restore window size and splitter state from settings
QSize savedSize = settings->windowSize();
if (savedSize.isValid()) {
resize(savedSize);
}
QByteArray splitterState = settings->splitterState();
if (!splitterState.isEmpty()) {
ui->splitter->restoreState(splitterState);
}
// Restore serial port settings
ui->cbBaudRate->setCurrentText(settings->baudRate());
ui->cbStopBits->setCurrentIndex(settings->stopBitsIndex());
ui->cbDataBits->setCurrentIndex(settings->dataBitsIndex());
ui->cbParity->setCurrentIndex(settings->parityIndex());
// Restore checkbox settings
ui->chk0x16Show->setChecked(settings->hexDisplayEnabled());
ui->chkTimeShow->setChecked(settings->timestampEnabled());
ui->chkClearAfterSend->setChecked(settings->clearAfterSendEnabled());
ui->chk0x16Send->setChecked(settings->hexSendEnabled());
ui->chkNewLine->setChecked(settings->newLineEnabled());
// Connect signals to save settings when changed
connect(ui->cbBaudRate, &QComboBox::currentTextChanged, settings, &AppSettings::setBaudRate);
connect(ui->cbStopBits, QOverload<int>::of(&QComboBox::currentIndexChanged), settings, &AppSettings::setStopBitsIndex);
connect(ui->cbDataBits, QOverload<int>::of(&QComboBox::currentIndexChanged), settings, &AppSettings::setDataBitsIndex);
connect(ui->cbParity, QOverload<int>::of(&QComboBox::currentIndexChanged), settings, &AppSettings::setParityIndex);
connect(ui->chk0x16Show, &QCheckBox::toggled, settings, &AppSettings::setHexDisplayEnabled);
connect(ui->chkTimeShow, &QCheckBox::toggled, settings, &AppSettings::setTimestampEnabled);
connect(ui->chkClearAfterSend, &QCheckBox::toggled, settings, &AppSettings::setClearAfterSendEnabled);
connect(ui->chk0x16Send, &QCheckBox::toggled, settings, &AppSettings::setHexSendEnabled);
connect(ui->chkNewLine, &QCheckBox::toggled, settings, &AppSettings::setNewLineEnabled);
}
Widget::~Widget()
{
// Save window size and splitter state before closing
AppSettings *settings = AppSettings::instance();
settings->setWindowSize(size());
settings->setSplitterState(ui->splitter->saveState());
m_refreshTimer->stop();
if (m_worker->isRunning()) {
m_worker->stop();
}
delete m_worker;
delete ui;
}
/**
* @brief 建立所有信号槽连接
*/
void Widget::setupConnections()
{
connect(m_worker, &SerialWorker::dataReceived, this, &Widget::onDataReceived);
connect(m_worker, &SerialWorker::errorOccurred, this, &Widget::onSerialError);
connect(m_worker, &SerialWorker::started, this, &Widget::onSerialStarted);
connect(m_worker, &SerialWorker::stopped, this, &Widget::onSerialStopped);
connect(m_processor, &DataProcessor::dataProcessed, this, &Widget::onDataProcessed);
connect(m_refreshTimer, &QTimer::timeout, this, &Widget::onRefreshTimeout);
QScrollBar *scrollBar = ui->receiveEdit->verticalScrollBar();
connect(scrollBar, &QScrollBar::valueChanged, this, &Widget::onScrollValueChanged);
connect(m_speedMonitor, &SpeedMonitor::speedUpdated, this, &Widget::onSpeedUpdated);
// 监听 splitter 移动,当左边面板消失时同时隐藏发送区
connect(ui->splitter, &QSplitter::splitterMoved, this, &Widget::onSplitterMoved);
}
/**
* @brief 更新可用串口列表
*/
void Widget::updatePortList()
{
QString lastPortName = ui->cbPortName->currentData().toString();
if (lastPortName.isEmpty()) {
lastPortName = ui->cbPortName->currentText().split(" ").first();
}
ui->cbPortName->clear();
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
QString displayText = info.portName();
QString tooltip = info.portName();
if (!info.description().isEmpty()) {
displayText += " - " + info.description();
tooltip += "\n" + info.description();
}
ui->cbPortName->addItem(displayText, info.portName());
ui->cbPortName->setItemData(ui->cbPortName->count() - 1, tooltip, Qt::ToolTipRole);
}
// 恢复之前选择的端口
for (int i = 0; i < ui->cbPortName->count(); ++i) {
if (ui->cbPortName->itemData(i).toString() == lastPortName) {
ui->cbPortName->setCurrentIndex(i);
break;
}
}
// 下拉列表展开时根据内容自动变宽
int maxWidth = 0;
QFontMetrics fm(ui->cbPortName->font());
for (int i = 0; i < ui->cbPortName->count(); ++i) {
int width = fm.horizontalAdvance(ui->cbPortName->itemText(i));
maxWidth = qMax(maxWidth, width);
}
if (ui->cbPortName->view()) {
ui->cbPortName->view()->setMinimumWidth(qMin(maxWidth + 40, 250)); // 上限250
}
}
/**
* @brief 设置串口配置控件的启用状态
* @param enabled true 启用,false 禁用
*/
void Widget::setPortControlsEnabled(bool enabled)
{
ui->cbBaudRate->setEnabled(enabled);
ui->cbDataBits->setEnabled(enabled);
ui->cbParity->setEnabled(enabled);
ui->cbPortName->setEnabled(enabled);
ui->cbStopBits->setEnabled(enabled);
}
/**
* @brief 从UI控件构建串口配置
* @return SerialConfig 配置结构
*/
SerialConfig Widget::buildConfig() const
{
SerialConfig config;
config.portName = ui->cbPortName->currentData().toString();
config.baudRate = ui->cbBaudRate->currentText().toInt();
switch (ui->cbStopBits->currentIndex()) {
case 0: config.stopBits = QSerialPort::OneStop; break;
case 1: config.stopBits = QSerialPort::OneAndHalfStop; break;
case 2: config.stopBits = QSerialPort::TwoStop; break;
default: config.stopBits = QSerialPort::OneStop; break;
}
switch (ui->cbParity->currentIndex()) {
case 0: config.parity = QSerialPort::NoParity; break;
case 1: config.parity = QSerialPort::OddParity; break;
case 2: config.parity = QSerialPort::EvenParity; break;
default: config.parity = QSerialPort::NoParity; break;
}
switch (ui->cbDataBits->currentIndex()) {
case 0: config.dataBits = QSerialPort::Data8; break;
case 1: config.dataBits = QSerialPort::Data7; break;
case 2: config.dataBits = QSerialPort::Data6; break;
case 3: config.dataBits = QSerialPort::Data5; break;
default: config.dataBits = QSerialPort::Data8; break;
}
config.flowControl = QSerialPort::NoFlowControl;
config.readBufferSize = 4096;
return config;
}
/**
* @brief 应用深色模式样式
*
* 根据启用状态应用或清除深色模式样式表。
* Requirements: 2.1, 2.2, 2.3, 2.4, 4.1, 4.2, 4.3, 4.4
*
* @param enabled true 启用深色模式,false 恢复默认样式
*/
void Widget::applyDarkMode(bool enabled)
{
if (enabled) {
// 深色模式样式表 - 仅修改颜色,不改变任何边距和布局
const QString darkStyleSheet = R"(
QWidget {
background-color: #2b2b2b;
color: #ffffff;
}
QGroupBox {
color: #ffffff;
}
QPushButton {
background-color: #3d3d3d;
color: #ffffff;
}
QPushButton:hover {
background-color: #4d4d4d;
}
QLineEdit, QComboBox, QSpinBox {
background-color: #383838;
color: #ffffff;
}
QPlainTextEdit, QTextEdit {
background-color: #1e1e1e;
color: #ffffff;
}
QCheckBox, QLabel {
color: #ffffff;
}
QComboBox QAbstractItemView {
background-color: #383838;
color: #ffffff;
selection-background-color: #4d4d4d;
}
QScrollBar:vertical {
background-color: #2b2b2b;
}
QScrollBar::handle:vertical {
background-color: #555555;
}
)";
setStyleSheet(darkStyleSheet);
} else {
// 清除样式表,恢复样式
setStyleSheet(QString());
}
}
/**
* @brief 追加文本到显示区域
*
* 根据自动滚动状态决定是否滚动到底部。
* Requirements: 6.4
*
* @param text 要追加的文本
*/
void Widget::appendToDisplay(const QString &text)
{
ui->receiveEdit->insertPlainText(text);
if (m_autoScroll) {
ui->receiveEdit->moveCursor(QTextCursor::End);
}
}
/**
* @brief 定时刷新回调
*
* 批量处理缓冲区中的数据并更新UI。
* Requirements: 6.1, 6.2, 6.3
*/
void Widget::onRefreshTimeout()
{
if (!m_pendingText.isEmpty()) {
appendToDisplay(m_pendingText);
m_pendingText.clear();
}
}
/**
* @brief 处理接收到的串口数据
*
* 将数据写入缓冲区并交给处理器处理。
*
* @param data 接收到的原始数据
*/
void Widget::onDataReceived(const QByteArray &data)
{
m_buffer->write(data);
m_speedMonitor->recordBytes(data.size());
m_processor->setFormat(ui->chk0x16Show->isChecked()
? DataProcessor::Hexadecimal
: DataProcessor::ASCII);
m_processor->setTimestampEnabled(ui->chkTimeShow->isChecked());
m_processor->process(data);
}
/**
* @brief 处理已处理的数据
*
* 将处理后的文本添加到待显示队列。
* Requirements: 6.1, 6.2
*
* @param text 处理后的文本
*/
void Widget::onDataProcessed(const QString &text)
{
m_pendingText.append(text);
}
/**
* @brief 处理串口错误
* @param error 错误描述
*/
void Widget::onSerialError(const QString &error)
{
QMessageBox::warning(this, "串口错误", error, QMessageBox::Ok);
}
/**
* @brief 显示系统消息
*
* 统一显示系统相关信息,添加"SystInfo >>"前缀
*
* @param message 系统消息内容
*/
void Widget::showSystemMessage(const QString &message)
{
ui->receiveEdit->insertPlainText("SYSINFO >> " + message + "\r\n");
ui->receiveEdit->moveCursor(QTextCursor::End);
}
/**
* @brief 串口启动成功回调
*/
void Widget::onSerialStarted()
{
setPortControlsEnabled(false);
ui->receiveEdit->setTextInteractionFlags(Qt::NoTextInteraction);
ui->open->setText("关闭串口");
ui->open->setStyleSheet("color: orange;");
ui->lbConnected->setText("当前已连接");
ui->lbConnected->setStyleSheet("color: green;");
showSystemMessage("串口已连接!");
// Save last used port name - Requirements: 6.4
AppSettings::instance()->setLastPortName(ui->cbPortName->currentData().toString());
// Start speed monitoring - Requirements: 1.3, 3.2
m_speedMonitor->reset();
m_speedMonitor->start();
m_refreshTimer->start();
}
/**
* @brief 串口停止回调
*/
void Widget::onSerialStopped()
{
m_refreshTimer->stop();
// Stop speed monitoring - Requirements: 1.3
m_speedMonitor->stop();
ui->groupBox_2->setTitle("接收区");
if (!m_pendingText.isEmpty()) {
appendToDisplay(m_pendingText);
m_pendingText.clear();
}
setPortControlsEnabled(true);
ui->receiveEdit->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
ui->open->setText("打开串口");
ui->open->setStyleSheet("color: red;");
ui->lbConnected->setText("当前未连接");
ui->lbConnected->setStyleSheet("color: rgb(0, 85, 255);");
showSystemMessage("串口已关闭!");
}
/**
* @brief 速度更新回调
*
* 更新接收区标题显示当前速度和累计字节数。
* Requirements: 1.1, 1.2, 3.4
*
* @param bytesPerSecond 当前速度(bytes/s)
* @param totalBytes 累计总字节数
*/
void Widget::onSpeedUpdated(double bytesPerSecond, qint64 totalBytes)
{
QString title = QString("接收区 [%1 | 总计: %2]")
.arg(SpeedMonitor::formatSpeed(bytesPerSecond),
SpeedMonitor::formatBytes(totalBytes));
ui->groupBox_2->setTitle(title);
}
/**
* @brief 滚动条值变化回调
*
* 实现自动滚动暂停/恢复逻辑。
* Requirements: 6.4
*
* @param value 当前滚动条值
*/
void Widget::onScrollValueChanged(int value)
{
QScrollBar *scrollBar = ui->receiveEdit->verticalScrollBar();
m_autoScroll = (value >= scrollBar->maximum() - 10);
}
/**
* @brief splitter 移动回调
*
* 当左边配置面板被拖动到消失时,同时隐藏发送区。
*
* @param pos 分割条位置
* @param index 分割条索引
*/
void Widget::onSplitterMoved(int pos, int index)
{
Q_UNUSED(index);
// 当左边面板宽度小于等于 5 像素时,认为已经消失,同时隐藏发送区
bool leftPanelVisible = (pos > 5);
ui->groupBox_3->setVisible(leftPanelVisible);
}
/**
* @brief 清空接收区
*/
void Widget::on_clear_clicked()
{
ui->receiveEdit->clear();
m_pendingText.clear();
m_buffer->clear();
// Reset speed monitor counters - Requirements: 3.3
m_speedMonitor->reset();
}
/**
* @brief 检测串口按钮点击
*/
void Widget::on_cbPortName_clicked()
{
updatePortList();
showSystemMessage("检测端口完毕");
}
/**
* @brief 打开/关闭串口按钮点击
*/
void Widget::on_open_clicked()
{
if (!m_worker->isRunning()) {
SerialConfig config = buildConfig();
if (!config.isValid()) {
QMessageBox::warning(this, "配置错误", config.validationError(), QMessageBox::Ok);
return;
}
m_worker->start(config);
} else {
m_worker->stop();
}
}
/**
* @brief 发送按钮点击
*
* 如果串口未打开,自动尝试打开串口后再发送。
*/
void Widget::on_send_clicked()
{
// 如果串口未打开,自动尝试打开
if (!m_worker->isRunning()) {
SerialConfig config = buildConfig();
if (!config.isValid()) {
QMessageBox::warning(this, "配置错误", config.validationError(), QMessageBox::Ok);
return;
}
m_worker->start(config);
// 等待串口打开后再发送(通过 QTimer 延迟执行)
// 如果打开失败,onSerialError 会处理错误提示
QTimer::singleShot(100, this, [this]() {
if (m_worker->isRunning()) {
performSend();
}
});
return;
}
performSend();
}
/**
* @brief 执行实际的发送操作
*/
void Widget::performSend()
{
QByteArray sendData = ui->sendEdit->toPlainText().toLocal8Bit();
if (sendData.isEmpty()) {
ui->sendEdit->setFocus();
return;
}
QString showTheSend = "SEND >> " + ui->sendEdit->toPlainText();
ui->receiveEdit->insertPlainText(showTheSend + "\r\n");
ui->receiveEdit->moveCursor(QTextCursor::End);
if (ui->chk0x16Send->isChecked()) {
static QRegularExpression hexRegex("[A-Fa-f0-9]{2}");
QString strData = ui->sendEdit->toPlainText();
if (!hexRegex.match(strData).hasMatch()) {
QMessageBox::information(this, "提示", "请输入16进制数", QMessageBox::Ok);
return;
}
sendData = QByteArray::fromHex(sendData);
}
if (ui->chkNewLine->isChecked()) {
sendData.append("\r\n");
}
m_worker->sendData(sendData);
if (ui->chkClearAfterSend->isChecked()) {
ui->sendEdit->clear();
}
ui->sendEdit->setFocus();
}
/**
* @brief 清空发送区按钮点击
*/
void Widget::on_clearSend_clicked()
{
ui->sendEdit->clear();
ui->sendEdit->setFocus();
}
/**
* @brief 打开设置对话框
*
* 创建并显示设置对话框,包含编码选择、十六进制换行控制和关键词高亮选项。
* Requirements: 1.1, 2.1, 3.1, 4.2, 4.3
*/
void Widget::on_openSetButton_clicked()
{
QDialog *settingsDialog = new QDialog(this);
settingsDialog->setWindowTitle("设置");
settingsDialog->setFixedSize(320, 330);
QVBoxLayout *mainLayout = new QVBoxLayout(settingsDialog);
mainLayout->setSpacing(15);
mainLayout->setContentsMargins(20, 20, 20, 20);
// Encoding selection - Requirements: 1.1
QHBoxLayout *encodingLayout = new QHBoxLayout();
QLabel *encodingLabel = new QLabel("文本编码:", settingsDialog);
QComboBox *encodingCombo = new QComboBox(settingsDialog);
encodingCombo->addItem("ANSI", AppSettings::ANSI);
encodingCombo->addItem("UTF-8", AppSettings::UTF8);
encodingCombo->addItem("GBK", AppSettings::GBK);
encodingCombo->setFixedHeight(28);
encodingLayout->addWidget(encodingLabel);
encodingLayout->addWidget(encodingCombo);
encodingLayout->addStretch();
mainLayout->addLayout(encodingLayout);
// Font size selection - Requirements: 5.1
QHBoxLayout *fontSizeLayout = new QHBoxLayout();
QLabel *fontSizeLabel = new QLabel("字体大小:", settingsDialog);
QSpinBox *fontSizeSpinBox = new QSpinBox(settingsDialog);
fontSizeSpinBox->setRange(6, 24);
fontSizeSpinBox->setFixedHeight(28);
fontSizeLayout->addWidget(fontSizeLabel);
fontSizeLayout->addWidget(fontSizeSpinBox);
fontSizeLayout->addStretch();
mainLayout->addLayout(fontSizeLayout);
// Font family selection - Requirements: 6.1
QHBoxLayout *fontFamilyLayout = new QHBoxLayout();
QLabel *fontFamilyLabel = new QLabel("字体选择:", settingsDialog);
QComboBox *fontFamilyCombo = new QComboBox(settingsDialog);
fontFamilyCombo->addItem("Default");
fontFamilyCombo->addItem("HarmonyOS Sans SC");
fontFamilyCombo->addItem("Alibaba PuHuiTi");
fontFamilyCombo->addItem("MiSans");
fontFamilyCombo->setFixedHeight(28);
fontFamilyLayout->addWidget(fontFamilyLabel);
fontFamilyLayout->addWidget(fontFamilyCombo);
fontFamilyLayout->addStretch();
mainLayout->addLayout(fontFamilyLayout);
// Hex newline checkbox - Requirements: 2.1
QCheckBox *hexNewlineCheck = new QCheckBox("16进制显示模式下 0A 0D 换行", settingsDialog);
mainLayout->addWidget(hexNewlineCheck);
// Keyword highlight checkbox with help button - Requirements: 3.1
QHBoxLayout *highlightLayout = new QHBoxLayout();
QCheckBox *keywordHighlightCheck = new QCheckBox("高亮接收区关键词", settingsDialog);
QPushButton *highlightHelpBtn = new QPushButton("?", settingsDialog);
highlightHelpBtn->setFixedSize(20, 20);
highlightHelpBtn->setToolTip("查看高亮规则");
highlightLayout->addWidget(keywordHighlightCheck);
highlightLayout->addWidget(highlightHelpBtn);
highlightLayout->addStretch();
mainLayout->addLayout(highlightLayout);
// 高亮规则帮助对话框
QObject::connect(highlightHelpBtn, &QPushButton::clicked, settingsDialog, [settingsDialog]() {
QMessageBox helpBox(settingsDialog);
helpBox.setWindowTitle("关键词高亮规则");
helpBox.setTextFormat(Qt::RichText);
helpBox.setText(
"<h3>支持的高亮规则</h3>"
"<p><b>【全文匹配 | 大小写不敏感】日志级别关键词:</b></p>"
"<ul>"
"<li><span style='color:#808080'>debug, trace, verbose</span> - 灰色</li>"
"<li><span style='color:#808080'>[DEBUG] [TRACE] [VERBOSE]</span> - 灰色</li>"
"<li><span style='color:#0066CC'>info, notice</span> - 蓝色</li>"
"<li><span style='color:#0066CC'>[INFO] [NOTICE]</span> - 蓝色</li>"
"<li><span style='color:#FF9900'>warning, warn</span> - 橙色</li>"
"<li><span style='color:#FF9900'>[WARN] [WARNING]</span> - 橙色</li>"
"<li><span style='color:#CC0000'>error, err, fail, failed, failure</span> - 红色</li>"
"<li><span style='color:#CC0000'>[ERROR] [ERR] [FAIL]</span> - 红色</li>"
"<li><span style='color:#990000'>fatal, critical, panic</span> - 深红</li>"
"<li><span style='color:#990000'>[FATAL] [CRITICAL]</span> - 深红</li>"
"<li><span style='color:#00AA00'>success, ok, pass, done, complete</span> - 绿色</li>"
"</ul>"
"<p><b>【行首匹配 | 大小写不敏感】简写前缀:</b></p>"
"<ul>"
"<li><span style='color:#808080'>D: V:</span> - 灰色 (Debug/Verbose)</li>"
"<li><span style='color:#0066CC'>I:</span> - 蓝色 (Info)</li>"
"<li><span style='color:#FF9900'>W:</span> - 橙色 (Warning)</li>"
"<li><span style='color:#CC0000'>E:</span> - 红色 (Error)</li>"
"<li><span style='color:#990000'>F:</span> - 深红 (Fatal)</li>"
"</ul>"
"<p><b>【全文匹配 | 大小写敏感】其他格式:</b></p>"
"<ul>"
"<li><span style='color:#9932CC'>0x1234 0xABCD</span> - 十六进制数(紫色)</li>"
"<li><span style='color:#808080'>HH:mm:ss.zzz >></span> - 时间戳(灰色)</li>"
"<li><span style='color:#666666; font-style:italic'>SEND >></span> - 发送前缀(灰色斜体)</li>"
"</ul>"
);
helpBox.exec();
});
// Dark mode checkbox - Requirements: 1.1, 1.2, 1.3, 1.4
QCheckBox *darkModeCheck = new QCheckBox("深色模式", settingsDialog);
mainLayout->addWidget(darkModeCheck);
mainLayout->addStretch();
// Confirm button
QHBoxLayout *buttonLayout = new QHBoxLayout();
buttonLayout->addStretch();
QPushButton *confirmButton = new QPushButton("确定", settingsDialog);
confirmButton->setFixedWidth(80);
buttonLayout->addWidget(confirmButton);
buttonLayout->addStretch();
mainLayout->addLayout(buttonLayout);
// Copyright label
QLabel *copyrightLabel = new QLabel("© 2025 tubohu-广工电子科技协会嵌入式组. All rights reserved.", settingsDialog);
copyrightLabel->setAlignment(Qt::AlignCenter);
QFont copyrightFont = copyrightLabel->font();
copyrightFont.setPointSize(7);
copyrightLabel->setFont(copyrightFont);
mainLayout->addWidget(copyrightLabel);
// Load current values from AppSettings - Requirements: 4.2, 6.1
AppSettings *settings = AppSettings::instance();
encodingCombo->setCurrentIndex(encodingCombo->findData(settings->encoding()));
fontSizeSpinBox->setValue(settings->fontSize());
fontFamilyCombo->setCurrentText(settings->fontFamily());
hexNewlineCheck->setChecked(settings->hexNewlineEnabled());
keywordHighlightCheck->setChecked(settings->keywordHighlightEnabled());
darkModeCheck->setChecked(settings->darkModeEnabled());
// Connect confirm button to save settings and close dialog - Requirements: 4.3, 1.3, 1.4, 6.2
QObject::connect(confirmButton, &QPushButton::clicked, settingsDialog, [=]() {
AppSettings *settings = AppSettings::instance();
settings->setEncoding(static_cast<AppSettings::Encoding>(encodingCombo->currentData().toInt()));
settings->setFontSize(fontSizeSpinBox->value());
settings->setFontFamily(fontFamilyCombo->currentText());
settings->setHexNewlineEnabled(hexNewlineCheck->isChecked());
settings->setKeywordHighlightEnabled(keywordHighlightCheck->isChecked());
settings->setDarkModeEnabled(darkModeCheck->isChecked());
settingsDialog->accept();
});
settingsDialog->exec();
delete settingsDialog;
}