-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1786 lines (1659 loc) · 68.3 KB
/
mainwindow.cpp
File metadata and controls
1786 lines (1659 loc) · 68.3 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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QCheckBox>
#include <QComboBox>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QFontMetrics>
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QMutexLocker>
#include <QPalette>
#include <QRegularExpression>
#include <QMouseEvent>
#include <QScrollBar>
#include <QSerialPortInfo>
#include <QSignalBlocker>
#include <QSpinBox>
#include <QStatusBar>
#include <QTextEdit>
#include <QTextStream>
#include <QStringDecoder>
#include <QTimer>
#include <QVBoxLayout>
#include <QToolTip>
#include <limits>
#include <QStackedLayout>
#include <Qt3DCore/QEntity>
#include <Qt3DExtras/Qt3DWindow>
#include <Qt3DExtras/QPhongMaterial>
#include <Qt3DExtras/QCuboidMesh>
#include <Qt3DExtras/QConeMesh>
#include <Qt3DExtras/QCylinderMesh>
#include <Qt3DExtras/QPlaneMesh>
#include <Qt3DExtras/QOrbitCameraController>
#include <Qt3DCore/QTransform>
#include <Qt3DRender/QCamera>
#include <Qt3DRender/QDirectionalLight>
#include <Qt3DExtras/QForwardRenderer>
#include <algorithm>
#ifndef ENABLE_DEBUG_LOG
#define ENABLE_DEBUG_LOG 1
#endif
namespace {
QString formatAsHex(const QByteArray &data) {
return data.toHex(' ').toUpper();
}
QByteArray parseHexString(const QString &text, bool *ok) {
QByteArray result;
QString cleaned = text;
cleaned.remove(QRegularExpression(QStringLiteral("[^0-9A-Fa-f]")));
if (cleaned.size() % 2 != 0) {
cleaned.prepend('0');
}
result.reserve(cleaned.size() / 2);
for (int i = 0; i < cleaned.size(); i += 2) {
bool byteOk = false;
const quint8 value = static_cast<quint8>(cleaned.mid(i, 2).toUInt(&byteOk, 16));
if (!byteOk) {
if (ok) *ok = false;
return {};
}
result.append(static_cast<char>(value));
}
if (ok) *ok = true;
return result;
}
} // namespace
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_serialThread(new QThread(this))
, m_serialWorker(new SerialPortWorker)
, m_isWriting(false)
{
ui->setupUi(this);
m_sendTimer = new QTimer(this);
m_sendTimer->setSingleShot(false);
m_portPollTimer = new QTimer(this);
m_portPollTimer->setSingleShot(false);
m_portPollTimer->setInterval(1500);
m_statusConn = new QLabel(this);
m_statusRx = new QLabel(this);
m_statusTx = new QLabel(this);
m_statusMatch = new QLabel(this);
m_statusMatch->setTextFormat(Qt::PlainText);
m_statusMatch->setMinimumWidth(200);
m_statusMatch->setAlignment(Qt::AlignCenter);
m_recvSearchPanel = new QWidget(this);
{
auto h = new QHBoxLayout(m_recvSearchPanel);
h->setContentsMargins(4, 0, 4, 0);
h->setSpacing(4);
QLabel* lbl = new QLabel(QString::fromUtf8(u8"搜索"), m_recvSearchPanel);
m_recvSearchEdit = new QLineEdit(m_recvSearchPanel);
m_recvSearchEdit->setPlaceholderText(QString::fromUtf8(u8"在接收区查找,按 Enter 查找下一个"));
m_recvSearchPrev = new QToolButton(m_recvSearchPanel);
m_recvSearchPrev->setText(QStringLiteral("▲"));
m_recvSearchNext = new QToolButton(m_recvSearchPanel);
m_recvSearchNext->setText(QStringLiteral("▼"));
m_recvSearchClose = new QToolButton(m_recvSearchPanel);
m_recvSearchClose->setText(QStringLiteral("✕"));
h->addWidget(lbl);
h->addWidget(m_recvSearchEdit, 1);
h->addWidget(m_recvSearchPrev);
h->addWidget(m_recvSearchNext);
h->addWidget(m_recvSearchClose);
m_recvSearchPanel->setVisible(false);
}
m_enableDebug = (ENABLE_DEBUG_LOG != 0);
resetDecoderFromUi();
updateStatusLabels();
ui->statusbar->addWidget(m_statusConn);
ui->statusbar->addWidget(m_statusMatch, 1);
ui->statusbar->addPermanentWidget(m_statusRx);
ui->statusbar->addPermanentWidget(m_statusTx);
m_recvFontPt = ui->recvEdit->font().pointSize();
m_sendFontPt = ui->sendEdit->font().pointSize();
if (m_recvFontPt <= 0) m_recvFontPt = 10;
if (m_sendFontPt <= 0) m_sendFontPt = 10;
ui->recvEdit->installEventFilter(this);
ui->sendEdit->installEventFilter(this);
ui->recvEdit->viewport()->installEventFilter(this);
ui->sendEdit->viewport()->installEventFilter(this);
if (ui->recvEdit->verticalScrollBar()) ui->recvEdit->verticalScrollBar()->installEventFilter(this);
if (ui->recvEdit->horizontalScrollBar()) ui->recvEdit->horizontalScrollBar()->installEventFilter(this);
if (ui->sendEdit->verticalScrollBar()) ui->sendEdit->verticalScrollBar()->installEventFilter(this);
if (ui->sendEdit->horizontalScrollBar()) ui->sendEdit->horizontalScrollBar()->installEventFilter(this);
connect(ui->openBt, &QPushButton::clicked, this, &MainWindow::on_openButton_clicked);
connect(ui->sendBt, &QPushButton::clicked, this, &MainWindow::on_sendButton_clicked);
connect(ui->btnClearSend, &QPushButton::clicked, this, [this]() {
ui->sendEdit->clear();
m_txBytes = 0;
updateStatusLabels();
});
connect(ui->clearBt, &QPushButton::clicked, this, [this]() {
ui->recvEdit->clear();
m_recvAutoFollow = true;
m_rxBytes = 0;
updateStatusLabels();
resetDecoderFromUi();
m_hasAttData = false;
m_recvLineBuffer.clear();
m_lastRecvFlushMs = 0;
});
// 搜索栏与快捷键
QShortcut* findShortcut = new QShortcut(QKeySequence::Find, ui->recvEdit);
connect(findShortcut, &QShortcut::activated, this, [this]() { showRecvSearch(); });
connect(m_recvSearchClose, &QToolButton::clicked, this, [this]() { hideRecvSearch(); });
connect(m_recvSearchNext, &QToolButton::clicked, this, [this]() { findInRecv(false); });
connect(m_recvSearchPrev, &QToolButton::clicked, this, [this]() { findInRecv(true); });
connect(m_recvSearchEdit, &QLineEdit::returnPressed, this, [this]() { findInRecv(false); });
connect(m_recvSearchEdit, &QLineEdit::textChanged, this, [this]() { updateRecvSearchHighlights(); });
connect(ui->chkTimSend, &QCheckBox::toggled, this, [this](bool on) {
m_autoSend = on;
if (on) {
const int interval = ui->txtSendMs->value();
m_sendTimer->setInterval(interval);
m_sendTimer->start();
} else {
m_sendTimer->stop();
}
});
// 发送区 HEX 开关:切换时自动转换内容,校验 HEX 有效性
connect(ui->chk_send_hex, &QCheckBox::toggled, this, [this](bool on) {
const QString txt = ui->sendEdit->toPlainText();
const QString trimmed = txt.trimmed();
const QRegularExpression hexRe(QStringLiteral("^[0-9A-Fa-f\\s]+$"));
if (on) {
const bool looksLikeHex = !trimmed.isEmpty() && hexRe.match(trimmed).hasMatch();
if (looksLikeHex) {
QString cleaned = trimmed;
cleaned.remove(QRegularExpression(QStringLiteral("\\s")));
if (cleaned.size() % 2 != 0) {
QSignalBlocker b(ui->chk_send_hex);
ui->chk_send_hex->setChecked(false);
QMessageBox::warning(this,
QString::fromUtf8(u8"HEX格式无效"),
QString::fromUtf8(u8"HEX字节数为奇数,请补全或调整后再开启。"));
return;
}
bool ok = false;
QByteArray data = parseHexString(trimmed, &ok);
if (!ok || data.isEmpty()) {
QSignalBlocker b(ui->chk_send_hex);
ui->chk_send_hex->setChecked(false);
QMessageBox::warning(this,
QString::fromUtf8(u8"HEX格式无效"),
QString::fromUtf8(u8"当前内容不是有效的HEX字符串,无法进入HEX模式。"));
return;
}
QString normalized = QString::fromLatin1(data.toHex(' ').toUpper());
QSignalBlocker b(ui->sendEdit);
ui->sendEdit->setPlainText(normalized);
return;
}
// 非 HEX 文本:按 UTF-8 转为 HEX
QString hex = QString::fromLatin1(txt.toUtf8().toHex(' ').toUpper());
QSignalBlocker b(ui->sendEdit);
ui->sendEdit->setPlainText(hex);
} else {
bool ok = false;
QByteArray data = parseHexString(trimmed, &ok);
if (!ok) {
QSignalBlocker b(ui->chk_send_hex);
ui->chk_send_hex->setChecked(true);
QMessageBox::warning(this,
QString::fromUtf8(u8"HEX格式无效"),
QString::fromUtf8(u8"当前内容不是有效的HEX字符串,无法退出HEX模式。"));
return;
}
QString plain = QString::fromUtf8(data);
QSignalBlocker b(ui->sendEdit);
ui->sendEdit->setPlainText(plain);
}
});
connect(ui->chkDtrSend, &QCheckBox::toggled, this, [this](bool on) {
if (m_isPortOpen) {
QMetaObject::invokeMethod(m_serialWorker, "setDtr",
Qt::QueuedConnection,
Q_ARG(bool, on));
}
m_currentSettings.dtrEnabled = on;
});
// ANSI 颜色开关
m_enableAnsiColors = ui->chk_rev_ansi->isChecked();
connect(ui->chk_rev_ansi, &QCheckBox::toggled, this, [this](bool on) {
m_enableAnsiColors = on;
});
connect(ui->comboEncoding, qOverload<int>(&QComboBox::currentIndexChanged), this, [this](int){
resetDecoderFromUi();
});
connect(ui->txtSendMs, qOverload<int>(&QSpinBox::valueChanged), this, [this](int v) {
if (m_autoSend) {
m_sendTimer->setInterval(v);
}
});
connect(m_sendTimer, &QTimer::timeout, this, [this]() { on_sendButton_clicked(); });
connect(m_portPollTimer, &QTimer::timeout, this, [this]() { checkPortHotplug(); });
m_serialWorker->moveToThread(m_serialThread);
connect(m_serialThread, &QThread::finished, m_serialWorker, &QObject::deleteLater);
m_serialThread->start();
connect(m_serialWorker, &SerialPortWorker::packetReady,
this, &MainWindow::onPacketReceived, Qt::QueuedConnection);
connect(m_serialWorker, &SerialPortWorker::errorOccurred,
this, &MainWindow::onErrorOccurred, Qt::QueuedConnection);
connect(m_serialWorker, &SerialPortWorker::fatalError,
this, &MainWindow::onFatalError, Qt::QueuedConnection);
connect(m_serialWorker, &SerialPortWorker::portOpened,
this, &MainWindow::onPortOpened, Qt::QueuedConnection);
connect(m_serialWorker, &SerialPortWorker::portClosed,
this, &MainWindow::onPortClosed, Qt::QueuedConnection);
connect(m_serialWorker, &SerialPortWorker::infoMessage,
this, [this](const QString& msg) { appendDebug(msg); }, Qt::QueuedConnection);
// Attitude worker thread for 3D display
m_attThread = new QThread(this);
m_attWorker = new AttitudeWorker;
m_attWorker->moveToThread(m_attThread);
connect(m_attWorker, &AttitudeWorker::attitudeReady,
this, &MainWindow::updateAttitude, Qt::QueuedConnection);
m_attThread->start();
// waveform worker/thread
m_waveThread = new QThread(this);
m_waveWorker = new WaveformWorker;
m_waveWorker->moveToThread(m_waveThread);
connect(m_waveWorker, &WaveformWorker::dataReady, this, &MainWindow::updateWaveform, Qt::QueuedConnection);
m_waveThread->start();
// setup UI extras
setupWaveformTab();
QTimer::singleShot(0, this, [this]() {
QMetaObject::invokeMethod(m_serialWorker, "initializeSerialPort", Qt::QueuedConnection);
});
refreshSerialPorts();
m_portPollTimer->start();
connect(ui->serialCb, qOverload<int>(&QComboBox::currentIndexChanged), this, [this](int) {
updateSerialTooltip();
});
if (QScrollBar* vs = ui->recvEdit->verticalScrollBar()) {
auto syncFollow = [this, vs](int value) {
if (m_inRecvAppend) return;
const bool atBottom = (value >= vs->maximum());
m_recvAutoFollow = atBottom;
if (atBottom) {
vs->setStyleSheet(QString());
}
};
connect(vs, &QScrollBar::valueChanged, this, syncFollow);
connect(vs, &QScrollBar::sliderReleased, this, [this, vs, syncFollow]() { syncFollow(vs->value()); });
connect(vs, &QScrollBar::sliderPressed, this, [this]() { m_recvAutoFollow = false; });
connect(vs, &QAbstractSlider::actionTriggered, this, [this, vs](int action) {
if (m_inRecvAppend) return;
if (action != QAbstractSlider::SliderNoAction && action != QAbstractSlider::SliderToMaximum) {
m_recvAutoFollow = false;
}
if (vs->value() >= vs->maximum()) {
m_recvAutoFollow = true;
}
});
}
ui->btnSerialCheck->setText(QString::fromUtf8(u8"保存记录"));
connect(ui->btnSerialCheck, &QPushButton::clicked, this, [this]() { saveLogs(); });
// 默认正则
m_waveRegexList = {QString::fromUtf8(u8"(-?\\d+(?:\\.\\d+)?)")};
m_attRegex = QString::fromUtf8(u8"Roll:\\s*([-+]?\\d+(?:\\.\\d+)?)\\s+Pitch:\\s*([-+]?\\d+(?:\\.\\d+)?)\\s+Yaw:\\s*([-+]?\\d+(?:\\.\\d+)?)");
m_customRegexEnableSpec = QStringLiteral("0");
// 右上角格式按钮,打开设置弹窗
m_formatBtn = new QToolButton(this);
m_formatBtn->setText(QString::fromUtf8(u8"⚙"));
m_formatBtn->setToolTip(QString::fromUtf8(u8"格式设置"));
m_formatBtn->setAutoRaise(true);
m_formatBtn->setFixedSize(24, 24);
connect(m_formatBtn, &QToolButton::clicked, this, &MainWindow::openFormatDialog);
// 主题切换按钮(月亮/太阳)
m_themeBtn = new QToolButton(this);
m_themeBtn->setText(QString::fromUtf8(u8"🌙"));
m_themeBtn->setToolTip(QString::fromUtf8(u8"切换明暗主题"));
m_themeBtn->setAutoRaise(true);
m_themeBtn->setFixedSize(24, 24);
connect(m_themeBtn, &QToolButton::clicked, this, [this]() {
m_darkTheme = !m_darkTheme;
applyTheme(m_darkTheme);
m_themeBtn->setText(QString::fromUtf8(m_darkTheme ? u8"🌙" : u8"☀"));
});
// 右上角工具栏:搜索 + 格式按钮
if (ui->tabWidget) {
QWidget* corner = new QWidget(this);
auto cornerLayout = new QHBoxLayout(corner);
cornerLayout->setContentsMargins(0, 0, 0, 0);
cornerLayout->setSpacing(4);
cornerLayout->addWidget(m_recvSearchPanel);
cornerLayout->addWidget(m_themeBtn);
cornerLayout->addWidget(m_formatBtn);
ui->tabWidget->setCornerWidget(corner, Qt::TopRightCorner);
} else {
ui->statusbar->addPermanentWidget(m_recvSearchPanel);
ui->statusbar->addPermanentWidget(m_themeBtn);
ui->statusbar->addPermanentWidget(m_formatBtn);
}
applyTheme(m_darkTheme);
setup3DTab();
}
MainWindow::~MainWindow()
{
if (m_serialWorker) {
QMetaObject::invokeMethod(m_serialWorker, "stopPort", Qt::QueuedConnection);
}
if (m_serialThread) {
m_serialThread->quit();
m_serialThread->wait();
}
if (m_attThread) {
m_attThread->quit();
m_attThread->wait();
delete m_attWorker;
}
if (m_waveThread) {
m_waveThread->quit();
m_waveThread->wait();
}
delete ui;
}
void MainWindow::on_openButton_clicked()
{
if (!m_isPortOpen) {
SerialSettings settings = getCurrentSerialSettings();
m_currentSettings = settings;
m_hasCurrentSettings = true;
QMetaObject::invokeMethod(m_serialWorker, "startPort",
Qt::QueuedConnection,
Q_ARG(SerialSettings, settings));
} else {
QMetaObject::invokeMethod(m_serialWorker, "stopPort", Qt::QueuedConnection);
}
}
void MainWindow::on_sendButton_clicked()
{
const QString text = ui->sendEdit->toPlainText();
QByteArray payload = buildSendPayload(text);
if (payload.isEmpty() && !text.isEmpty()) {
QMessageBox::warning(this,
QString::fromUtf8(u8"发送失败"),
QString::fromUtf8(u8"HEX格式无效,未发送。"));
return;
}
writeData(payload);
}
SerialSettings MainWindow::getCurrentSerialSettings() const
{
SerialSettings settings;
const QVariant portData = ui->serialCb->currentData();
settings.portName = portData.isValid() ? portData.toString() : ui->serialCb->currentText();
settings.baudRate = static_cast<QSerialPort::BaudRate>(ui->baundrateCb->currentText().toInt());
settings.dataBits = static_cast<QSerialPort::DataBits>(ui->databitCb->currentText().toInt());
switch (ui->checkbitCb->currentIndex()) {
case 1: settings.parity = QSerialPort::OddParity; break;
case 2: settings.parity = QSerialPort::EvenParity; break;
default: settings.parity = QSerialPort::NoParity; break;
}
switch (ui->stopbitCb->currentIndex()) {
case 1: settings.stopBits = QSerialPort::OneAndHalfStop; break;
case 2: settings.stopBits = QSerialPort::TwoStop; break;
default: settings.stopBits = QSerialPort::OneStop; break;
}
// 流控
switch (ui->flowCtrlCb->currentIndex()) {
case 1: settings.flowControl = QSerialPort::HardwareControl; break;
case 2: settings.flowControl = QSerialPort::SoftwareControl; break;
default: settings.flowControl = QSerialPort::NoFlowControl; break;
}
settings.dtrEnabled = (ui->chkDtrSend && ui->chkDtrSend->isChecked());
return settings;
}
void MainWindow::writeData(const QByteArray &data)
{
if (!m_isPortOpen) {
appendDebug(QStringLiteral("Send skipped: port not open"));
return;
}
QMutexLocker locker(&m_queueMutex);
m_writeQueue.append(data);
m_txBytes += data.size();
updateStatusLabels();
if (m_isWriting) {
return;
}
m_isWriting = true;
locker.unlock();
QMetaObject::invokeMethod(this, [this]() { processWriteQueue(); }, Qt::QueuedConnection);
}
void MainWindow::processWriteQueue()
{
QByteArray data;
{
QMutexLocker locker(&m_queueMutex);
if (m_writeQueue.isEmpty()) {
m_isWriting = false;
return;
}
data = m_writeQueue.takeFirst();
}
QMetaObject::invokeMethod(m_serialWorker, "writeToPort",
Qt::QueuedConnection,
Q_ARG(QByteArray, data));
QMetaObject::invokeMethod(this, [this]() { processWriteQueue(); }, Qt::QueuedConnection);
}
void MainWindow::resetDecoderFromUi()
{
QString name = QStringLiteral("UTF-8");
if (ui->comboEncoding) {
name = ui->comboEncoding->currentText();
}
m_decoderName = name;
if (name.compare(QStringLiteral("UTF-8"), Qt::CaseInsensitive) == 0) {
m_textDecoder = QStringDecoder(QStringConverter::Utf8);
} else if (name.compare(QStringLiteral("GBK"), Qt::CaseInsensitive) == 0
|| name.compare(QStringLiteral("GB18030"), Qt::CaseInsensitive) == 0) {
m_textDecoder = QStringDecoder("GB18030");
} else if (name.compare(QStringLiteral("本地编码")) == 0
|| name.compare(QStringLiteral("Local")) == 0) {
m_textDecoder = QStringDecoder(QStringConverter::System);
} else {
m_textDecoder = QStringDecoder(QStringConverter::Utf8);
}
}
void MainWindow::applyTheme(bool dark)
{
QPalette pal;
if (dark) {
pal.setColor(QPalette::Window, QColor(32, 32, 32));
pal.setColor(QPalette::WindowText, QColor(230, 230, 230));
pal.setColor(QPalette::Base, QColor(24, 24, 24));
pal.setColor(QPalette::AlternateBase, QColor(38, 38, 38));
pal.setColor(QPalette::Text, QColor(230, 230, 230));
pal.setColor(QPalette::Button, QColor(45, 45, 45));
pal.setColor(QPalette::ButtonText, QColor(230, 230, 230));
pal.setColor(QPalette::Highlight, QColor(0, 122, 204));
pal.setColor(QPalette::HighlightedText, Qt::white);
} else {
pal = QApplication::style()->standardPalette();
// 提升亮色模式的对比度和边框可见度
pal.setColor(QPalette::Base, QColor(247, 247, 247));
pal.setColor(QPalette::AlternateBase, QColor(236, 236, 236));
pal.setColor(QPalette::Text, QColor(20, 20, 20));
pal.setColor(QPalette::Window, QColor(244, 244, 244));
pal.setColor(QPalette::Button, QColor(235, 235, 235));
pal.setColor(QPalette::ButtonText, QColor(20, 20, 20));
pal.setColor(QPalette::Highlight, QColor(0, 120, 215));
pal.setColor(QPalette::HighlightedText, QColor(255, 255, 255));
pal.setColor(QPalette::Mid, QColor(200, 200, 200)); // 边框阴影
}
qApp->setPalette(pal);
// 样式:文本框和按钮边框
QString style;
if (dark) {
style = QStringLiteral(
"QTextEdit, QPlainTextEdit {"
" border: 1px solid #3c3c3c;"
" border-radius: 4px;"
"}"
"QPushButton {"
" border: 1px solid #5a5a5a;"
" border-radius: 4px;"
" padding: 4px 8px;"
"}"
"QPushButton:pressed {"
" background: #3a3a3a;"
"}"
);
} else {
style = QStringLiteral(
"QTextEdit, QPlainTextEdit {"
" border: 1px solid #9a9a9a;"
" border-radius: 4px;"
" background: #fbfbfb;"
"}"
"QPushButton {"
" border: 1px solid #8a8a8a;"
" border-radius: 4px;"
" padding: 4px 8px;"
"}"
"QPushButton:pressed {"
" background: #dcdcdc;"
"}"
);
}
qApp->setStyleSheet(style);
// 波形区主题同步
if (m_wavePlot) {
const QColor bg = dark ? QColor(24, 24, 24) : QColor(255, 255, 255);
const QColor axis = dark ? QColor(230, 230, 230) : QColor(30, 30, 30);
const QColor grid = dark ? QColor(80, 80, 80) : QColor(180, 180, 180);
m_wavePlot->setBackground(bg);
if (auto rect = m_wavePlot->axisRect()) rect->setBackground(bg);
auto applyAxis = [&](QCPAxis* ax) {
if (!ax) return;
ax->setBasePen(QPen(axis));
ax->setTickPen(QPen(axis));
ax->setSubTickPen(QPen(axis));
ax->setLabelColor(axis);
ax->setTickLabelColor(axis);
if (ax->grid()) {
ax->grid()->setPen(QPen(grid));
ax->grid()->setSubGridPen(QPen(grid.lighter()));
}
};
applyAxis(m_wavePlot->xAxis);
applyAxis(m_wavePlot->yAxis);
m_wavePlot->replot(QCustomPlot::rpQueuedReplot);
}
// 3D 区域背景与姿态标签
if (m_3dWindow) {
const QColor clear = dark ? QColor(24, 28, 32) : QColor(235, 235, 235);
m_3dWindow->defaultFrameGraph()->setClearColor(clear);
}
if (m_baseMat) {
if (dark) {
m_baseMat->setDiffuse(QColor(90, 105, 130));
m_baseMat->setAmbient(QColor(70, 80, 100));
m_baseMat->setSpecular(QColor(180, 180, 190));
} else {
// 亮色模式:进一步加深主体色,提高对比度
m_baseMat->setDiffuse(QColor(80, 90, 100));
m_baseMat->setAmbient(QColor(70, 80, 100));
m_baseMat->setSpecular(QColor(50, 50, 60));
}
}
if (m_attLabel) {
if (dark) {
m_attLabel->setStyleSheet("color: #f0f0f0; background-color: rgba(0,0,0,120); padding:4px; font-weight:600;");
} else {
m_attLabel->setStyleSheet("color: #222; background-color: rgba(255,255,255,180); padding:4px; font-weight:600; border: 1px solid #cccccc;");
}
}
}
void MainWindow::onPacketReceived(const QByteArray &packet)
{
QVector<double> waveValues;
const QString decoded = decodeTextSmart(packet);
const QString raw = decoded.trimmed();
if (m_useWaveRegex) {
if (tryParseWaveValues(raw, waveValues) && !waveValues.isEmpty()) {
updateWaveformValues(waveValues);
}
}
// 当未启用波形正则或未能成功解析时,不再按字节值灌入波形,避免显示三角波
// 姿态显示只由解析结果更新,避免原始文本闪烁
if (m_attWorker && m_useAttRegex) {
double r, p, y;
if (tryParseAttitude(decoded, r, p, y)) {
QMetaObject::invokeMethod(m_attWorker, "appendAttitude", Qt::QueuedConnection,
Q_ARG(double, r), Q_ARG(double, p), Q_ARG(double, y));
}
}
m_rxBytes += packet.size();
updateStatusLabels();
updateCustomMatchDisplay(raw);
const qint64 nowMs = QDateTime::currentDateTime().toMSecsSinceEpoch();
QStringList linesToAppend;
auto appendLine = [this, &linesToAppend](const QString& seg, bool addBreak) {
QString line;
if (ui->chk_rev_time->isChecked()) {
const QString ts = QDateTime::currentDateTime().toString(QStringLiteral("[HH:mm:ss.zzz] "));
m_toggleTimestampColor = !m_toggleTimestampColor;
const QString color = m_toggleTimestampColor ? QStringLiteral("#007aff") : QStringLiteral("#ff6a00");
line += QStringLiteral("<span style=\"color:%1;\">%2</span> ").arg(color, ts.toHtmlEscaped());
}
QString htmlBody = m_enableAnsiColors ? ansiToHtml(seg) : seg.toHtmlEscaped();
line += htmlBody;
if (addBreak && ui->chk_rev_line->isChecked()) line += QStringLiteral("<br/>");
linesToAppend << line;
};
if (ui->chk_rev_hex->isChecked()) {
appendLine(formatAsHex(packet), ui->chk_rev_line->isChecked());
} else {
if (!ui->chk_rev_line->isChecked()) {
// 未勾选自动换行:每包直接输出,不额外换行
appendLine(decoded, false);
} else {
// 勾选自动换行:仅按换行符换行,超时才按当前缓冲输出
QString combined = m_recvLineBuffer + decoded;
int startIdx = 0;
bool hasEol = false;
for (int i = 0; i < combined.size(); ++i) {
const QChar c = combined.at(i);
if (c == QChar('\r') || c == QChar('\n')) {
hasEol = true;
const bool crlf = (c == QChar('\r') && i + 1 < combined.size() && combined.at(i + 1) == QChar('\n'));
QString seg = combined.mid(startIdx, i - startIdx);
appendLine(seg, true);
if (crlf) ++i;
startIdx = i + 1;
}
}
m_recvLineBuffer = combined.mid(startIdx);
// 无换行时不立即输出,等待后续;但若超时则按当前缓冲输出一行
const qint64 gap = (m_lastRecvFlushMs > 0) ? (nowMs - m_lastRecvFlushMs) : std::numeric_limits<qint64>::max();
if (!hasEol && !m_recvLineBuffer.isEmpty() && gap > 300) {
appendLine(m_recvLineBuffer, true);
m_recvLineBuffer.clear();
}
}
}
QScrollBar* vs = ui->recvEdit->verticalScrollBar();
int restorePos = -1;
if (vs && !m_recvAutoFollow) restorePos = vs->value();
m_inRecvAppend = true;
for (const QString& l : linesToAppend) {
ui->recvEdit->append(l);
}
m_inRecvAppend = false;
if (!linesToAppend.isEmpty()) {
m_lastRecvFlushMs = nowMs;
}
if (m_recvAutoFollow) {
QTextCursor c = ui->recvEdit->textCursor();
c.movePosition(QTextCursor::End);
ui->recvEdit->setTextCursor(c);
ui->recvEdit->ensureCursorVisible();
if (vs) vs->setStyleSheet(QStringLiteral(
"QScrollBar:vertical {background: #e6f5e6;}"
"QScrollBar::handle:vertical {background: #1f5c1f; min-height: 24px; border-radius: 4px;}"));
} else if (vs && restorePos >= 0) {
QSignalBlocker block(vs);
vs->setValue(restorePos);
vs->setStyleSheet(QStringLiteral(
"QScrollBar:vertical {background: #e8ffe8;}"
"QScrollBar::handle:vertical {background: #3fa34a; min-height: 24px; border-radius: 4px;}"));
}
if (vs) {
const int token = ++m_recvColorToken;
QScrollBar* vsPtr = vs;
QTimer::singleShot(800, this, [this, vsPtr, token]() {
if (token == m_recvColorToken && ui && ui->recvEdit && ui->recvEdit->verticalScrollBar() == vsPtr) {
vsPtr->setStyleSheet(QString());
}
});
}
}
void MainWindow::onErrorOccurred(const QString &error)
{
QMessageBox::warning(this, "Serial Port Error", error);
ui->recvEdit->append(QStringLiteral("<span style=\"color:red;\">[ERROR] %1</span>")
.arg(error.toHtmlEscaped()));
}
void MainWindow::onFatalError(const QString &error)
{
QMessageBox::critical(this, "Serial Port Fatal Error", error);
ui->recvEdit->append(QStringLiteral("<span style=\"color:red;\">[FATAL] %1</span>")
.arg(error.toHtmlEscaped()));
ui->openBt->setText(QString::fromUtf8(u8"打开串口"));
}
void MainWindow::onPortOpened()
{
m_isPortOpen = true;
m_recvAutoFollow = true;
m_inRecvAppend = false;
resetDecoderFromUi();
m_hasAttData = false;
m_recvLineBuffer.clear();
m_lastRecvFlushMs = 0;
m_lastAttText.clear();
updateRecvSearchHighlights();
if (QScrollBar* vs = ui->recvEdit->verticalScrollBar()) {
vs->setValue(vs->maximum());
}
QTextCursor c = ui->recvEdit->textCursor();
c.movePosition(QTextCursor::End);
ui->recvEdit->setTextCursor(c);
ui->recvEdit->ensureCursorVisible();
ui->openBt->setText(QString::fromUtf8(u8"关闭串口"));
ui->serialCb->setEnabled(false);
ui->baundrateCb->setEnabled(false);
ui->databitCb->setEnabled(false);
ui->checkbitCb->setEnabled(false);
ui->stopbitCb->setEnabled(false);
if (ui->flowCtrlCb) ui->flowCtrlCb->setEnabled(false);
m_rxBytes = 0;
m_txBytes = 0;
updateStatusLabels();
appendDebug(QStringLiteral("Serial port opened successfully."));
}
void MainWindow::onPortClosed()
{
m_isPortOpen = false;
m_recvAutoFollow = true;
m_inRecvAppend = false;
resetDecoderFromUi();
m_hasAttData = false;
m_recvLineBuffer.clear();
m_lastRecvFlushMs = 0;
m_lastAttText.clear();
updateRecvSearchHighlights();
ui->openBt->setText(QString::fromUtf8(u8"打开串口"));
ui->serialCb->setEnabled(true);
ui->baundrateCb->setEnabled(true);
ui->databitCb->setEnabled(true);
ui->checkbitCb->setEnabled(true);
ui->stopbitCb->setEnabled(true);
if (ui->flowCtrlCb) ui->flowCtrlCb->setEnabled(true);
m_hasCurrentSettings = false;
{
QMutexLocker locker(&m_queueMutex);
m_writeQueue.clear();
m_isWriting = false;
}
updateStatusLabels();
appendDebug(QStringLiteral("Serial port closed."));
}
QByteArray MainWindow::buildSendPayload(const QString &text) const
{
QString content = text;
if (ui->chk_send_line->isChecked()) {
content.append(QLatin1Char('\n'));
}
if (ui->chk_send_hex->isChecked()) {
bool ok = false;
QByteArray data = parseHexString(content, &ok);
if (!ok) return {};
return data;
}
// 文本模式?UTF-8 编码发送,emoji/中文等多字节字符才能完整传输
return content.toUtf8();
}
void MainWindow::appendDebug(const QString &text)
{
if (!m_enableDebug) {
return;
}
ui->recvEdit->append(QStringLiteral("<span style=\"color:red;\">%1</span>")
.arg(text.toHtmlEscaped()));
}
void MainWindow::refreshSerialPorts()
{
const QVariant currentData = ui->serialCb->currentData();
const QString currentText = ui->serialCb->currentText();
ui->serialCb->clear();
const int maxWidth = 165;
const QFontMetrics fm(ui->serialCb->font());
QStringList names;
for (const QSerialPortInfo &info : QSerialPortInfo::availablePorts()) {
const QString full = QStringLiteral("%1-%2(VID:0x%3 PID:0x%4 MFR:%5 SN:%6)")
.arg(info.portName(),
info.description().isEmpty() ? QStringLiteral("Unknown") : info.description(),
QString::number(info.vendorIdentifier(), 16).toUpper().rightJustified(4, '0'),
QString::number(info.productIdentifier(), 16).toUpper().rightJustified(4, '0'),
info.manufacturer().isEmpty() ? QStringLiteral("N/A") : info.manufacturer(),
info.serialNumber().isEmpty() ? QStringLiteral("N/A") : info.serialNumber());
const QString elided = fm.elidedText(full, Qt::ElideRight, maxWidth);
ui->serialCb->addItem(elided, info.portName());
const int idx = ui->serialCb->count() - 1;
ui->serialCb->setItemData(idx, full, Qt::ToolTipRole);
names << info.portName();
}
int restoreIndex = -1;
if (currentData.isValid()) {
restoreIndex = ui->serialCb->findData(currentData);
} else if (!currentText.isEmpty()) {
restoreIndex = ui->serialCb->findText(currentText);
}
if (restoreIndex >= 0) {
ui->serialCb->setCurrentIndex(restoreIndex);
} else if (ui->serialCb->count() > 0) {
ui->serialCb->setCurrentIndex(0);
}
names.sort();
m_knownPorts = names;
updateSerialTooltip();
}
void MainWindow::updateSerialTooltip()
{
const int idx = ui->serialCb->currentIndex();
if (idx >= 0) {
const QVariant tip = ui->serialCb->itemData(idx, Qt::ToolTipRole);
if (tip.isValid()) {
ui->serialCb->setToolTip(tip.toString());
return;
}
}
ui->serialCb->setToolTip(QString());
}
void MainWindow::updateStatusLabels()
{
if (m_statusConn) {
if (m_isPortOpen && m_hasCurrentSettings) {
QString parityText;
switch (m_currentSettings.parity) {
case QSerialPort::EvenParity: parityText = QStringLiteral("E"); break;
case QSerialPort::OddParity: parityText = QStringLiteral("O"); break;
default: parityText = QStringLiteral("N"); break;
}
QString stopText;
switch (m_currentSettings.stopBits) {
case QSerialPort::OneAndHalfStop: stopText = QStringLiteral("1.5"); break;
case QSerialPort::TwoStop: stopText = QStringLiteral("2"); break;
default: stopText = QStringLiteral("1"); break;
}
const QString text = QStringLiteral("%1 | %2 %3%4%5")
.arg(m_currentSettings.portName)
.arg(m_currentSettings.baudRate)
.arg(static_cast<int>(m_currentSettings.dataBits))
.arg(parityText)
.arg(stopText);
m_statusConn->setText(text);
m_statusConn->setStyleSheet(QStringLiteral("color: green;"));
} else {
m_statusConn->setText(QString::fromUtf8(u8"未连接"));
m_statusConn->setStyleSheet(QStringLiteral("color: red;"));
}
}
if (m_statusRx) {
m_statusRx->setText(QStringLiteral("RX: %1").arg(m_rxBytes));
}
if (m_statusMatch && !m_isPortOpen) {
m_statusMatch->clear();
}
if (m_statusTx) {
m_statusTx->setText(QStringLiteral("TX: %1").arg(m_txBytes));
}
}
void MainWindow::checkPortHotplug()
{
QStringList names;
for (const QSerialPortInfo &info : QSerialPortInfo::availablePorts()) {
names << info.portName();
}
names.sort();
if (names != m_knownPorts) {
refreshSerialPorts();
}
}
void MainWindow::saveLogs()
{
const QString path = QFileDialog::getSaveFileName(
this, QString::fromUtf8(u8"保存记录"),
QDir::homePath() + QLatin1String("/hicom_log_") + QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") + ".txt",
QString::fromUtf8(u8"文本文件 (*.txt);;所有文件 (*.*)"));
if (path.isEmpty()) return;
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, QString::fromUtf8(u8"保存失败"), QString::fromUtf8(u8"无法打开文件写入。"));
return;
}
QTextStream out(&file);
out << "===== Receive =====\n";
out << ui->recvEdit->toPlainText() << "\n";
out << "===== Send =====\n";
out << ui->sendEdit->toPlainText() << "\n";
file.close();
QMessageBox::information(this, QString::fromUtf8(u8"保存完成"), QString::fromUtf8(u8"已保存到:\n") + path);
}
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
const bool isRecv = (watched == ui->recvEdit || watched == ui->recvEdit->viewport() ||
watched == ui->recvEdit->verticalScrollBar() || watched == ui->recvEdit->horizontalScrollBar());
const bool isSend = (watched == ui->sendEdit || watched == ui->sendEdit->viewport() ||
watched == ui->sendEdit->verticalScrollBar() || watched == ui->sendEdit->horizontalScrollBar());
const bool isWave = (watched == m_wavePlot);
if ((isRecv || isSend) && event->type() == QEvent::Wheel) {
QWheelEvent *wheel = static_cast<QWheelEvent*>(event);
if (wheel->modifiers() & Qt::ControlModifier) {
const int delta = wheel->angleDelta().y();
const int step = (delta > 0) ? 1 : -1;
const int minSize = 8;
const int maxSize = 40;
if (isRecv) {
m_recvFontPt = std::clamp(m_recvFontPt + step, minSize, maxSize);
QFont f = ui->recvEdit->font();
f.setPointSize(m_recvFontPt);
ui->recvEdit->setFont(f);
} else {
m_sendFontPt = std::clamp(m_sendFontPt + step, minSize, maxSize);
QFont f = ui->sendEdit->font();
f.setPointSize(m_sendFontPt);
ui->sendEdit->setFont(f);
}
return true; // consume to avoid scroll
} else if (isRecv) {
// 用户滚动接收区:立即暂停自动跟随
m_recvAutoFollow = false;
return false;
}
}
if (isRecv && (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseMove)) {
if (QMouseEvent* me = static_cast<QMouseEvent*>(event)) {
if (me->buttons() & Qt::LeftButton) {
m_recvAutoFollow = false;
}
}
}
if (watched == m_3dContainer || watched == m_3dWindow) {
if (event->type() == QEvent::MouseButtonPress) {