-
Notifications
You must be signed in to change notification settings - Fork 289
/
mainwindow.cpp
1868 lines (1623 loc) · 62.7 KB
/
mainwindow.cpp
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 "can_structs.h"
#include <QDateTime>
#include <QFileDialog>
#include <QtSerialPort/QSerialPortInfo>
#include "connections/canconmanager.h"
#include "connections/connectionwindow.h"
#include "helpwindow.h"
#include "utility.h"
#include "filterutility.h"
/*
Some notes on things I'd like to put into the program but haven't put on github (yet)
Allow scripts to read/write signals from DBC files
allow scripts to load DBC files in support of the script - maybe the graphing system too.
*/
QString MainWindow::loadedFileName = "";
MainWindow *MainWindow::selfRef = nullptr;
MainWindow *MainWindow::getReference()
{
return selfRef;
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
#if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
qRegisterMetaTypeStreamOperators<QVector<QString>>();
qRegisterMetaTypeStreamOperators<QVector<int>>();
#endif
useHex = true;
selfRef = this;
this->setWindowTitle("Savvy CAN V" + QString::number(VERSION) + " [Built " + QString(__DATE__) +"]");
model = new CANFrameModel(this); // set parent to mainwindow to prevent canframemodel to change thread (might be done by setModel but just in case)
QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel;
proxyModel->setSourceModel(model);
ui->canFramesView->setModel(proxyModel);
settingsDialog = new MainSettingsDialog(); //instantiate the settings dialog so it can initialize settings if this is the first run or the config file was deleted.
settingsDialog->updateSettings(); //write out all the settings. If this is the first run it'll write defaults out.
readSettings();
QHeaderView *verticalHeader = ui->canFramesView->verticalHeader();
verticalHeader->setSectionResizeMode(QHeaderView::Fixed);
QSettings settings;
int fontSize = settings.value("Main/FontSize", 9).toUInt();
QFont sysFont;
if(settings.value("Main/FontFixedWidth", false).toBool())
sysFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); //get default fixed width font
else
sysFont = QFont(); //get default font
sysFont.setPointSize(fontSize);
verticalHeader->setDefaultSectionSize(sysFont.pixelSize());
verticalHeader->setFont(QFont());
ui->canFramesView->setFont(sysFont);
QHeaderView *HorzHdr = ui->canFramesView->horizontalHeader();
HorzHdr->setFont(QFont());
HorzHdr->setStretchLastSection(true); //causes the data column to automatically fill the tableview
connect(HorzHdr, SIGNAL(sectionClicked(int)), this, SLOT(headerClicked(int)));
lastGraphingWindow = nullptr;
frameInfoWindow = nullptr;
playbackWindow = nullptr;
flowViewWindow = nullptr;
frameSenderWindow = nullptr;
dbcMainEditor = nullptr;
comparatorWindow = nullptr;
settingsDialog = nullptr;
firmwareUploaderWindow = nullptr;
discreteStateWindow = nullptr;
connectionWindow = nullptr;
scriptingWindow = nullptr;
rangeWindow = nullptr;
dbcFileWindow = nullptr;
fuzzingWindow = nullptr;
udsScanWindow = nullptr;
motorctrlConfigWindow = nullptr;
isoWindow = nullptr;
snifferWindow = nullptr;
bisectWindow = nullptr;
signalViewerWindow = nullptr;
temporalGraphWindow = nullptr;
dbcComparatorWindow = nullptr;
canBridgeWindow = nullptr;
dbcHandler = DBCHandler::getReference();
bDirty = false;
inhibitFilterUpdate = false;
rxFrames = 0;
framesPerSec = 0;
continuousLogging = false;
continuousLogFlushCounter = 0;
//handlers for all menu entries
connect(ui->actionSetup, SIGNAL(triggered(bool)), SLOT(showConnectionSettingsWindow()));
connect(ui->actionOpen_Log_File, &QAction::triggered, this, &MainWindow::handleLoadFile);
connect(ui->actionGraph_Dta, &QAction::triggered, this, &MainWindow::showGraphingWindow);
connect(ui->actionFrame_Data_Analysis, &QAction::triggered, this, &MainWindow::showFrameDataAnalysis);
connect(ui->actionSave_Log_File, &QAction::triggered, this, &MainWindow::handleSaveFile);
connect(ui->actionSave_Filtered_Log_File, &QAction::triggered, this, &MainWindow::handleSaveFilteredFile);
connect(ui->actionLoad_Filter_Definition, &QAction::triggered, this, &MainWindow::handleLoadFilters);
connect(ui->actionSave_Filter_Definition, &QAction::triggered, this, &MainWindow::handleSaveFilters);
connect(ui->action_Playback, &QAction::triggered, this, &MainWindow::showPlaybackWindow);
connect(ui->actionFlow_View, &QAction::triggered, this, &MainWindow::showFlowViewWindow);
connect(ui->action_Custom, &QAction::triggered, this, &MainWindow::showFrameSenderWindow);
connect(ui->actionExit_Application, &QAction::triggered, this, &MainWindow::exitApp);
connect(ui->actionFuzzy_Scope, &QAction::triggered, this, &MainWindow::showFuzzyScopeWindow);
connect(ui->actionRange_State_2, &QAction::triggered, this, &MainWindow::showRangeWindow);
connect(ui->actionSave_Decoded_Frames, &QAction::triggered, this, &MainWindow::handleSaveDecoded);
connect(ui->actionSave_Decoded_Frames_CSV, &QAction::triggered, this, &MainWindow::handleSaveDecodedCsv);
connect(ui->actionSingle_Multi_State_2, &QAction::triggered, this, &MainWindow::showSingleMultiWindow);
connect(ui->actionFile_Comparison, &QAction::triggered, this, &MainWindow::showComparisonWindow);
connect(ui->actionDBC_Comparison, &QAction::triggered, this, &MainWindow::showDBCComparisonWindow);
connect(ui->actionScripting_INterface, &QAction::triggered, this, &MainWindow::showScriptingWindow);
connect(ui->actionPreferences, &QAction::triggered, this, &MainWindow::showSettingsDialog);
connect(ui->actionFirmware_Update, &QAction::triggered, this, &MainWindow::showFirmwareUploaderWindow);
connect(ui->actionDBC_File_Manager, &QAction::triggered, this, &MainWindow::showDBCFileWindow);
connect(ui->actionFuzzing, &QAction::triggered, this, &MainWindow::showFuzzingWindow);
connect(ui->actionUDS_Scanner, &QAction::triggered, this, &MainWindow::showUDSScanWindow);
connect(ui->actionISO_TP_Decoder, &QAction::triggered, this, &MainWindow::showISOInterpreterWindow);
connect(ui->actionSniffer, &QAction::triggered, this, &MainWindow::showSnifferWindow);
connect(ui->actionMotorControlConfig, &QAction::triggered, this, &MainWindow::showMCConfigWindow);
connect(ui->actionCapture_Bisector, &QAction::triggered, this, &MainWindow::showBisectWindow);
connect(ui->actionSignal_Viewer, &QAction::triggered, this, &MainWindow::showSignalViewer);
connect(ui->actionSave_Continuous_Logfile, &QAction::triggered, this, &MainWindow::handleContinousLogging);
connect(ui->actionTemporal_Graph, &QAction::triggered, this, &MainWindow::showTemporalGraphWindow);
connect(ui->actionCAN_Bridge, &QAction::triggered, this, &MainWindow::showCANBridgeWindow);
//handlers fror interactions with the main can frame view table
connect(ui->canFramesView, &QAbstractItemView::clicked, this, &MainWindow::gridClicked);
connect(ui->canFramesView, &QAbstractItemView::doubleClicked, this, &MainWindow::gridDoubleClicked);
ui->canFramesView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->canFramesView, &QAbstractItemView::customContextMenuRequested, this, &MainWindow::gridContextMenuRequest);
connect(model, &CANFrameModel::updatedFiltersList, this, &MainWindow::updateFilterList);
connect(CANConManager::getInstance(), &CANConManager::framesReceived, model, &CANFrameModel::addFrames);
//new implementation for continuous logging
connect(CANConManager::getInstance(), &CANConManager::framesReceived, this, &MainWindow::logReceivedFrame);
connect(ui->cbInterpret, &QAbstractButton::toggled, this, &MainWindow::interpretToggled);
connect(ui->cbOverwrite, &QAbstractButton::toggled, this, &MainWindow::overwriteToggled);
connect(ui->cbPersistentFilters, &QAbstractButton::toggled, this, &MainWindow::presistentFiltersToggled);
connect(ui->listFilters, &QListWidget::itemChanged, this, &MainWindow::filterListItemChanged);
connect(ui->listBusFilters, &QListWidget::itemChanged, this, &MainWindow::busFilterListItemChanged);
connect(ui->btnCaptureToggle, &QAbstractButton::clicked, this, &MainWindow::toggleCapture);
connect(ui->btnClearFrames, &QAbstractButton::clicked, this, &MainWindow::clearFrames);
connect(ui->btnNormalize, &QAbstractButton::clicked, this, &MainWindow::normalizeTiming);
connect(ui->btnFilterAll, &QAbstractButton::clicked, this, &MainWindow::filterSetAll);
connect(ui->btnFilterNone, &QAbstractButton::clicked, this, &MainWindow::filterClearAll);
connect(ui->btnExpandAll, &QAbstractButton::clicked, this, &MainWindow::expandAllRows);
connect(ui->btnCollapseAll, &QAbstractButton::clicked, this, &MainWindow::collapseAllRows);
connect(ui->tableSimpleSender, SIGNAL(cellChanged(int,int)), this, SLOT(onSenderCellChanged(int,int)));
lbStatusConnected.setText(tr("Connected to 0 buses"));
lbHelp.setText(tr("Press F1 on any screen for help"));
lbHelp.setAlignment(Qt::AlignCenter);
QFont boldFont;
boldFont.setBold(true);
lbHelp.setFont(boldFont);
updateFileStatus();
//lbStatusDatabase.setText(tr("No DBC database loaded"));
ui->statusBar->insertWidget(0, &lbStatusConnected, 1);
ui->statusBar->insertWidget(1, &lbStatusFilename, 1);
ui->statusBar->insertWidget(2, &lbHelp, 1);
//ui->statusBar->addWidget(&lbStatusDatabase);
ui->lblRemoteConn->setVisible(false);
ui->lineRemoteKey->setVisible(false);
ui->lbFPS->setText("0");
ui->lbNumFrames->setText("0");
// Prevent annoying accidental horizontal scrolling when filter list is populated with long interpreted message names
ui->listFilters->horizontalScrollBar()->setEnabled(false);
connect(&updateTimer, &QTimer::timeout, this, &MainWindow::tickGUIUpdate);
updateTimer.setInterval(250);
updateTimer.start();
elapsedTime = new QElapsedTimer;
elapsedTime->start();
isConnected = false;
allowCapture = true;
//create a temporary frame to be able to capture the correct
//default height of an item in the table. Need to do this in case
//of scaling or font differences between different computers.
CANFrame temp;
temp.bus = 0;
temp.setFrameId(0x100);
temp.isReceived = true;
temp.setTimeStamp(QCanBusFrame::TimeStamp(0, 100000000));
model->addFrame(temp, true);
ui->canFramesView->resizeRowToContents(0); // Resize the row to fit the contents so we get a proper height value
qApp->processEvents();
tickGUIUpdate(); //force a GUI refresh so that the row exists to measure
normalRowHeight = ui->canFramesView->rowHeight(0);
if (normalRowHeight == 0) normalRowHeight = 30; //should not be necessary but provides a sane number if something stupid happened.
qDebug() << "normal row height = " << normalRowHeight;
model->clearFrames();
ui->canFramesView->verticalHeader()->setDefaultSectionSize(normalRowHeight); // Set the default height for all rows to the height that was calculated
//connect(CANConManager::getInstance(), CANConManager::connectionStatusUpdated, this, MainWindow::connectionStatusUpdated);
connect(CANConManager::getInstance(), SIGNAL(connectionStatusUpdated(int)), this, SLOT(connectionStatusUpdated(int)));
//Automatically create the connection window so it can be updated even if we never opened it.
connectionWindow = new ConnectionWindow();
connect(this, SIGNAL(suspendCapturing(bool)), connectionWindow, SLOT(setSuspendAll(bool)));
//these either are unfinished/not working or are not for general use. But,they exist
//so if you want to enable them and play with them then go for it.
ui->actionFirmware_Update->setVisible(false);
ui->actionMotorControlConfig->setVisible(false);
ui->actionSingle_Multi_State_2->setVisible(false);
QStringList headers;
headers << "En" << "Bus" << "ID" << "Ext" << "Rem" << "Data"
<< "Interval" << "Count";
ui->tableSimpleSender->setColumnCount(8);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_EN, 70);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_BUS, 70);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_ID, 70);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_EXT, 70);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_REM, 70);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_DATA, 300);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_INTERVAL, 100);
ui->tableSimpleSender->setColumnWidth(SIMP_COL::SC_COL_COUNT, 100);
ui->tableSimpleSender->setHorizontalHeaderLabels(headers);
createSenderRow();
frameSender = new FrameSenderObject(model->getListReference());
frameSender->initialize(); //creates the thread and sets things up
frameSender->startSending(); //start the timer in the object so enabled things can send
installEventFilter(this);
}
MainWindow::~MainWindow()
{
updateTimer.stop();
frameSender->stopSending();
killEmAll(); //Ride the lightning
delete ui;
delete model;
delete elapsedTime;
delete dbcHandler;
}
//kill every sub window that could be open. At the moment a hard coded list
//but eventually each window should be registered and be able to be iterated.
void MainWindow::killEmAll()
{
foreach (GraphingWindow *win, graphWindows)
{
killWindow(win);
}
killWindow(frameInfoWindow);
killWindow(playbackWindow);
killWindow(flowViewWindow);
killWindow(frameSenderWindow);
killWindow(comparatorWindow);
killWindow(dbcMainEditor);
killWindow(settingsDialog);
killWindow(discreteStateWindow);
killWindow(scriptingWindow);
killWindow(rangeWindow);
killWindow(dbcFileWindow);
killWindow(fuzzingWindow);
killWindow(udsScanWindow);
killWindow(isoWindow);
killWindow(snifferWindow);
killWindow(bisectWindow);
killWindow(firmwareUploaderWindow);
killWindow(motorctrlConfigWindow);
killWindow(signalViewerWindow);
killWindow(temporalGraphWindow);
killWindow(canBridgeWindow);
//trying to kill this window can cause a fault to happen. It's closed last just in case.
killWindow(connectionWindow);
}
//forcefully close the window, kill it, and salt the earth
//note, for some stupid reason this function causes a seg fault
//it seems that when it runs just before the program closes it'll
//fault out when trying to close the connection window. I assume
//this could be because that window has long running threads open and doesn't
//close quickly or maybe cleanly. Investigate.
void MainWindow::killWindow(QDialog *win)
{
if (win)
{
win->close();
delete win;
win = nullptr;
}
}
void MainWindow::exitApp()
{
this->close();
QApplication::quit(); //forces the whole application to terminate when the main window is closed
}
//the close event can be trapped and ignored so put unsaved warnings in here so the user can abort the program closing if they forgot to save things.
void MainWindow::closeEvent(QCloseEvent *event)
{
QMessageBox::StandardButton confirmDialog;
for (int i = 0; i < dbcHandler->getFileCount(); i++)
{
DBCFile *file = dbcHandler->getFileByIdx(i);
if (file->getDirtyFlag())
{
confirmDialog = QMessageBox::question(this, "Unsaved DBC", "DBC File:\n" + file->getFilename() + "\nAppears to have unsaved changes\nReally close without saving?", QMessageBox::Yes|QMessageBox::No);
if (confirmDialog != QMessageBox::Yes)
{
event->ignore();
return;
}
}
}
removeEventFilter(this);
writeSettings();
exitApp();
event->accept();
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
switch (keyEvent->key())
{
case Qt::Key_F1:
HelpWindow::getRef()->showHelp("mainscreen.md");
return true;
break;
}
return false;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
return false;
}
void MainWindow::updateSettings()
{
readUpdateableSettings();
emit settingsUpdated();
}
void MainWindow::readSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
resize(settings.value("Main/WindowSize", QSize(800, 750)).toSize());
move(Utility::constrainedWindowPos(settings.value("Main/WindowPos", QPoint(100, 100)).toPoint()));
ui->canFramesView->setColumnWidth(0, settings.value("Main/TimeColumn", 150).toUInt()); //time stamp
ui->canFramesView->setColumnWidth(1, settings.value("Main/IDColumn", 70).toUInt()); //frame ID
ui->canFramesView->setColumnWidth(2, settings.value("Main/ExtColumn", 40).toUInt()); //extended
ui->canFramesView->setColumnWidth(3, settings.value("Main/RemColumn", 40).toUInt()); //remote
ui->canFramesView->setColumnWidth(4, settings.value("Main/DirColumn", 40).toUInt()); //direction
ui->canFramesView->setColumnWidth(5, settings.value("Main/BusColumn", 40).toUInt()); //bus
ui->canFramesView->setColumnWidth(6, settings.value("Main/LengthColumn", 40).toUInt()); //length
ui->canFramesView->setColumnWidth(7, settings.value("Main/AsciiColumn", 50).toUInt()); //ascii
//ui->canFramesView->setColumnWidth(8, settings.value("Main/DataColumn", 225).toUInt()); //data
}
if (settings.value("Main/AutoScroll", false).toBool())
{
ui->cbAutoScroll->setChecked(true);
}
int fontSize = settings.value("Main/FontSize", 9).toUInt();
QFont newFont = QFont(ui->canFramesView->font());
newFont.setPointSize(fontSize);
ui->canFramesView->setFont(newFont);
readUpdateableSettings();
}
/*
* TODO: The way the frame timing mode is specified is DEAD STUPID. There shouldn't be three boolean values
* for this. Instead switch it all to an ENUM or something sane.
*/
void MainWindow::readUpdateableSettings()
{
QSettings settings;
useHex = settings.value("Main/UseHex", true).toBool();
model->setHexMode(useHex);
Utility::decimalMode = !useHex;
bool tempBool;
TimeStyle ts = TS_MICROS;
tempBool = settings.value("Main/TimeSeconds", false).toBool();
if (tempBool) ts = TS_SECONDS;
tempBool = settings.value("Main/TimeClock", false).toBool();
if (tempBool) ts = TS_CLOCK;
tempBool = settings.value("Main/TimeMillis", false).toBool();
if (tempBool) ts = TS_MILLIS;
model->setTimeStyle(ts);
useFiltered = settings.value("Main/UseFiltered", false).toBool();
model->setTimeFormat(settings.value("Main/TimeFormat", "MMM-dd HH:mm:ss.zzz").toString());
ignoreDBCColors = settings.value("Main/IgnoreDBCColors", false).toBool();
model->setIgnoreDBCColors(ignoreDBCColors);
int bpl = settings.value("Main/BytesPerLine", 8).toInt();
model->setBytesPerLine(bpl);
CSVAbsTime = settings.value("Main/CSVAbsTime", false).toBool();
if (settings.value("Main/FilterLabeling", false).toBool())
ui->listFilters->setMaximumWidth(250);
else
ui->listFilters->setMaximumWidth(175);
updateFilterList();
}
void MainWindow::writeSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
settings.setValue("Main/WindowSize", size());
settings.setValue("Main/WindowPos", pos());
settings.setValue("Main/TimeColumn", ui->canFramesView->columnWidth(0));
settings.setValue("Main/IDColumn", ui->canFramesView->columnWidth(1));
settings.setValue("Main/ExtColumn", ui->canFramesView->columnWidth(2));
settings.setValue("Main/RemColumn", ui->canFramesView->columnWidth(3));
settings.setValue("Main/DirColumn", ui->canFramesView->columnWidth(4));
settings.setValue("Main/BusColumn", ui->canFramesView->columnWidth(5));
settings.setValue("Main/LengthColumn", ui->canFramesView->columnWidth(6));
settings.setValue("Main/AsciiColumn", ui->canFramesView->columnWidth(7));
//settings.setValue("Main/DataColumn", ui->canFramesView->columnWidth(8));
}
}
void MainWindow::onSenderCellChanged(int row, int col)
{
if (inhibitSenderChanged) return;
qDebug() << "onCellChanged";
if (row == ui->tableSimpleSender->rowCount() - 1)
{
createSenderRow();
}
processSenderCellChange(row, col);
}
void MainWindow::processSenderCellChange(int line, int col)
{
qDebug() << "processSenderCellChange";
FrameSendData *tempData;
QStringList tokens;
int tempVal;
int numBuses = CANConManager::getInstance()->getNumBuses();
QByteArray arr;
tempData = frameSender->getSendRecordRef(line);
if (!tempData)
{
qDebug() << "Need to set up a new entry in senders";
FrameSendData dat;
dat.enabled = false;
dat.count = 0;
dat.frameCount = 0;
dat.bus = 0;
frameSender->addSendRecord(dat);
tempData = frameSender->getSendRecordRef(line);
}
if (!tempData)
{
qDebug() << "No data to modify in processSenderCellChange. This is a bug!";
return;
}
switch (col)
{
case SIMP_COL::SC_COL_EN: //Enable check box
if (ui->tableSimpleSender->item(line, 0)->checkState() == Qt::Checked)
{
tempData->enabled = true;
}
else tempData->enabled = false;
qDebug() << "Setting enabled to " << tempData->enabled;
break;
case SIMP_COL::SC_COL_BUS: //Bus designation
tempVal = Utility::ParseStringToNum(ui->tableSimpleSender->item(line, SIMP_COL::SC_COL_BUS)->text());
if (tempVal < -1) tempVal = -1;
if (tempVal >= numBuses) tempVal = numBuses - 1;
tempData->bus = tempVal;
qDebug() << "Setting bus to " << tempVal;
break;
case SIMP_COL::SC_COL_ID: //ID field
tempVal = Utility::ParseStringToNum(ui->tableSimpleSender->item(line, SIMP_COL::SC_COL_ID)->text());
if (tempVal < 0) tempVal = 0;
if (tempVal > 0x7FFFFFFF) tempVal = 0x7FFFFFFF;
tempData->setFrameId(tempVal);
if (tempData->frameId() > 0x7FF) {
tempData->setExtendedFrameFormat(true);
ui->tableSimpleSender->blockSignals(true);
ui->tableSimpleSender->item(line, ST_COLS::SENDTAB_COL_EXT)->setCheckState(Qt::Checked);
ui->tableSimpleSender->blockSignals(false);
}
qDebug() << "setting ID to " << tempVal;
break;
case SIMP_COL::SC_COL_EXT:
if (ui->tableSimpleSender->item(line, SIMP_COL::SC_COL_EXT)->checkState() == Qt::Checked) {
tempData->setExtendedFrameFormat(true);
} else {
tempData->setExtendedFrameFormat(false);
}
break;
case SIMP_COL::SC_COL_REM:
if (ui->tableSimpleSender->item(line, SIMP_COL::SC_COL_REM)->checkState() == Qt::Checked) {
tempData->setFrameType(QCanBusFrame::RemoteRequestFrame);
} else {
tempData->setFrameType(QCanBusFrame::DataFrame);
}
break;
case SIMP_COL::SC_COL_DATA: //Data bytes
for (int i = 0; i < 8; i++) tempData->payload().data()[i] = 0;
#if QT_VERSION >= QT_VERSION_CHECK( 5, 14, 0 )
tokens = ui->tableSimpleSender->item(line, SIMP_COL::SC_COL_DATA)->text().split(" ", Qt::SkipEmptyParts);
#else
tokens = ui->tableSimpleSender->item(line, SIMP_COL::SC_COL_DATA)->text().split(" ", QString::SkipEmptyParts);
#endif
arr.clear();
arr.reserve(tokens.count());
for (int j = 0; j < tokens.count(); j++)
{
arr.append((uint8_t)Utility::ParseStringToNum(tokens[j]));
}
tempData->setPayload(arr);
break;
case SIMP_COL::SC_COL_INTERVAL: //interval in ms
QString trigger = ui->tableSimpleSender->item(line, SIMP_COL::SC_COL_INTERVAL)->text().toUpper();
Trigger thisTrigger;
thisTrigger.bus = -1; //-1 means we don't care which
thisTrigger.ID = -1; //the rest of these being -1 means nothing has changed it
thisTrigger.maxCount = -1;
thisTrigger.milliseconds = -1;
thisTrigger.currCount = 0;
thisTrigger.msCounter = 0;
thisTrigger.triggerMask = 0;
thisTrigger.readyCount = true;
tempData->triggers.clear();
tempData->triggers.reserve(1);
if (trigger != "")
{
thisTrigger.milliseconds = Utility::ParseStringToNum(trigger);
thisTrigger.triggerMask |= TriggerMask::TRG_MS;
}
if (thisTrigger.milliseconds < 1) thisTrigger.milliseconds = 1;
tempData->triggers.append(thisTrigger);
break;
}
}
void MainWindow::createSenderRow()
{
int row = ui->tableSimpleSender->rowCount();
ui->tableSimpleSender->insertRow(row);
QTableWidgetItem *item = new QTableWidgetItem();
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(Qt::Unchecked);
inhibitSenderChanged = true;
ui->tableSimpleSender->setItem(row, SIMP_COL::SC_COL_EN, item);
item = new QTableWidgetItem();
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(Qt::Unchecked);
ui->tableSimpleSender->setItem(row, SIMP_COL::SC_COL_EXT, item);
item = new QTableWidgetItem();
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(Qt::Unchecked);
ui->tableSimpleSender->setItem(row, SIMP_COL::SC_COL_REM, item);
for (int i = 1; i <= SIMP_COL::SC_COL_COUNT; i++)
{
if (i != SIMP_COL::SC_COL_EXT && i != SIMP_COL::SC_COL_REM) {
item = new QTableWidgetItem("");
ui->tableSimpleSender->setItem(row, i, item);
}
}
inhibitSenderChanged = false;
}
void MainWindow::updateConnectionSettings(QString connectionType, QString port, int speed0, int speed1)
{
Q_UNUSED(connectionType);
Q_UNUSED(port);
Q_UNUSED(speed0);
Q_UNUSED(speed1);
//connType = connectionType;
//portName = port;
//canSpeed0 = speed0;
//canSpeed1 = speed1;
if (isConnected)
{
//emit updateBaudRates(speed0, speed1);
}
}
void MainWindow::headerClicked(int logicalIndex)
{
//ui->canFramesView->sortByColumn(logicalIndex);
model->sortByColumn(logicalIndex);
manageRowExpansion();
}
void MainWindow::expandAllRows()
{
bool goAhead = false;
int numRows = ui->canFramesView->model()->rowCount();
if (numRows > 20000)
{
QMessageBox::StandardButton confirmDialog;
confirmDialog = QMessageBox::question(this, "Really?", "It's not recommended to use this\non more than 20000 frames.\nIt can take a long time.\n\nYou have been warned!\nStill do it?",
QMessageBox::Yes|QMessageBox::No);
if (confirmDialog == QMessageBox::Yes) goAhead = true;
}
else goAhead = true;
if (goAhead)
{
ui->canFramesView->resizeRowsToContents();
rowExpansionActive = true;
}
}
void MainWindow::manageRowExpansion()
{
int numRows = ui->canFramesView->model()->rowCount();
if(numRows < 20000)
{
if(rowExpansionActive && model->getInterpretMode())
ui->canFramesView->resizeRowsToContents();
}
else
{
disableAutoRowExpansion();
}
}
void MainWindow::disableAutoRowExpansion()
{
rowExpansionActive = false;
}
void MainWindow::collapseAllRows()
{
bool goAhead = false;
int numRows = ui->canFramesView->model()->rowCount();
if (numRows > 50000)
{
QMessageBox::StandardButton confirmDialog;
confirmDialog = QMessageBox::question(this, "Really?", "It's not recommended to use this\non more than 50000 frames.\nIt can take a long time.\n\nYou have been warned!\nStill do it?",
QMessageBox::Yes|QMessageBox::No);
if (confirmDialog == QMessageBox::Yes) goAhead = true;
}
else goAhead = true;
if (goAhead)
{
for (int i = 0; i < numRows; i++) ui->canFramesView->setRowHeight(i, normalRowHeight);
rowExpansionActive = false;
}
}
void MainWindow::gridClicked(QModelIndex idx)
{
//qDebug() << "Grid Clicked";
if (ui->canFramesView->rowHeight(idx.row()) > normalRowHeight)
{
ui->canFramesView->setRowHeight(idx.row(), normalRowHeight);
}
else {
ui->canFramesView->resizeRowToContents(idx.row());
}
}
void MainWindow::gridDoubleClicked(QModelIndex idx)
{
qDebug() << "Grid double clicked";
//grab ID and timestamp and send them away
CANFrame frame = model->getListReference()->at(idx.row());
emit sendCenterTimeID(frame.frameId(), frame.timeStamp().microSeconds() / 1000000.0);
}
void MainWindow::gridContextMenuRequest(QPoint pos)
{
QModelIndex idx = ui->canFramesView->indexAt(pos); //figure out where in the view we clicked (row, column)
qDebug() << "Pos: " << pos << " Row :" << idx.row() << " Col: " << idx.column();
qDebug() << "Data: " << idx.data();
if (idx.column() == 8) //we're over the DATA column
{
contextMenuPosition = pos;
QMenu *menu = new QMenu(this);
menu->setAttribute(Qt::WA_DeleteOnClose);
menu->addAction(tr("Add to a new graphing window"), this, SLOT(setupAddToNewGraph()));
menu->addSeparator();
menu->addAction(tr("Add to latest graphing window"), this, SLOT(setupSendToLatestGraphWindow()));
menu->popup(ui->canFramesView->mapToGlobal(pos));
}
}
QString MainWindow::getSignalNameFromPosition(QPoint pos)
{
//there's a bit of an issue to solve. The data column is one big string even if there are a number
//of signals in there. So, the basic idea is to find out how tall the font is and where the user
//clicked within the cell. Then find out which line that puts us over.
QModelIndex idx = ui->canFramesView->indexAt(pos); //figure out where in the view we clicked (row, column)
int fontHeight = ui->canFramesView->fontMetrics().height();
int cellBaseY = ui->canFramesView->rowViewportPosition(idx.row());
int lineOffset = (pos.y() - cellBaseY) / fontHeight;
qDebug() << "Offset: " << lineOffset;
QString lineText = idx.data().toString().split("\n")[lineOffset];
qDebug() << "Line Text: " << lineText;
return lineText.split(":")[0];
}
uint32_t MainWindow::getMessageIDFromPosition(QPoint pos)
{
QModelIndex idx = ui->canFramesView->indexAt(pos); //figure out where in the view we clicked (row, column)
QString idText = ui->canFramesView->model()->index(idx.row(), 1).data().toString();
return Utility::ParseStringToNum(idText);
}
void MainWindow::setupAddToNewGraph()
{
showGraphingWindow(); //creates a new window and sets it as latest
setupSendToLatestGraphWindow(); //then call the other function to finish
}
void MainWindow::setupSendToLatestGraphWindow()
{
if (!lastGraphingWindow) showGraphingWindow();
GraphParams param;
QString signalName = getSignalNameFromPosition(contextMenuPosition);
param.ID = getMessageIDFromPosition(contextMenuPosition);
DBC_MESSAGE *msg = dbcHandler->findMessage(param.ID);
if(msg)
{
DBC_SIGNAL *sig = msg->sigHandler->findSignalByName(signalName);
if(sig)
{
param.associatedSignal = sig;
param.bias = sig->bias;
param.intelFormat = sig->intelByteOrder;
param.isSigned = sig->valType == SIGNED_INT ? true : false;
param.numBits = sig->signalSize;
param.scale = sig->factor;
param.startBit = sig->startBit;
param.stride = 1;
param.graphName = sig->name;
param.lineColor = QColor(QRandomGenerator::global()->bounded(160), QRandomGenerator::global()->bounded(160), QRandomGenerator::global()->bounded(160));
param.lineWidth = 1;
param.fillColor = QColor(128, 128, 128, 0);
param.mask = 0xFFFFFFFFFFFFFFFFull;
param.drawOnlyPoints = false;
param.pointType = 0;
lastGraphingWindow->createGraph(param); //add the new graph to the window
}
else
{
QMessageBox msgbox;
QString boxmsg = "Cannot find ID 0x" + QStringLiteral("%1").arg(param.ID, 3, 16, QLatin1Char('0')) + " in DBC message " + msg->name + ". Not adding graph.";
msgbox.setText(boxmsg);
msgbox.exec();
}
}
else
{
QMessageBox msgbox;
QString boxmsg = "Cannot find ID 0x" + QStringLiteral("%1").arg(param.ID, 3, 16, QLatin1Char('0')) + " in DBC file(s). Not adding graph.";
msgbox.setText(boxmsg);
msgbox.exec();
}
}
void MainWindow::interpretToggled(bool state)
{
model->setInterpretMode(state);
//ui->canFramesView->resizeRowsToContents(); //a VERY costly operation!
}
void MainWindow::overwriteToggled(bool state)
{
if (state)
{
QMessageBox::StandardButton confirmDialog;
confirmDialog = QMessageBox::question(this, "Danger Will Robinson", "Enabling Overwrite mode will\ndelete your captured frames\nand replace them with one\nframe per ID.\n\nAre you ready to do that?",
QMessageBox::Yes|QMessageBox::No);
if (confirmDialog == QMessageBox::Yes)
{
model->setOverwriteMode(true);
}
else ui->cbOverwrite->setCheckState(Qt::Unchecked);
}
else
{
rowExpansionActive = false;
model->setOverwriteMode(false);
}
}
void MainWindow::presistentFiltersToggled(bool state)
{
if (state)
{
model->setClearMode(true);
}
else
{
model->setClearMode(false);
}
}
void MainWindow::updateFilterList()
{
if (model == nullptr) return;
const QMap<int, bool> *filters = model->getFiltersReference();
const QMap<int, bool> *busFilters = model->getBusFiltersReference();
if (filters == nullptr || busFilters == nullptr) return;
qDebug() << "updateFilterList called on MainWindow";
inhibitFilterUpdate = true;
ui->listFilters->clear();
ui->listBusFilters->clear();
if (filters->isEmpty()) return;
QMap<int, bool>::const_iterator filterIter;
for (filterIter = filters->begin(); filterIter != filters->end(); ++filterIter)
{
/*QListWidgetItem *thisItem = */FilterUtility::createCheckableFilterItem(filterIter.key(), filterIter.value(), ui->listFilters);
}
if (busFilters->isEmpty()) return;
for (filterIter = busFilters->begin(); filterIter != busFilters->end(); ++filterIter)
{
/*QListWidgetItem *thisItem = */ FilterUtility::createCheckableBusFilterItem(filterIter.key(), filterIter.value(), ui->listBusFilters);
}
inhibitFilterUpdate = false;
}
void MainWindow::filterListItemChanged(QListWidgetItem *item)
{
if (inhibitFilterUpdate) return;
//qDebug() << item->text();
// strip away possible filter label
int ID = FilterUtility::getIdAsInt(item);
bool isSet = false;
if (item->checkState() == Qt::Checked) isSet = true;
model->setFilterState(ID, isSet);
manageRowExpansion();
}
void MainWindow::busFilterListItemChanged(QListWidgetItem *item)
{
if (inhibitFilterUpdate) return;
//qDebug() << item->text();
// strip away possible filter label
int ID = FilterUtility::getIdAsInt(item);
bool isSet = false;
if (item->checkState() == Qt::Checked) isSet = true;
model->setBusFilterState(ID, isSet);
manageRowExpansion();
}
void MainWindow::filterSetAll()
{
inhibitFilterUpdate = true;
for (int i = 0; i < ui->listFilters->count(); i++)
{
ui->listFilters->item(i)->setCheckState(Qt::Checked);
}
inhibitFilterUpdate = false;
model->setAllFilters(true);
manageRowExpansion();
}
void MainWindow::filterClearAll()
{
inhibitFilterUpdate = true;
for (int i = 0; i < ui->listFilters->count(); i++)
{
ui->listFilters->item(i)->setCheckState(Qt::Unchecked);
}
inhibitFilterUpdate = false;
model->setAllFilters(false);
}
void MainWindow::logReceivedFrame(CANConnection* conn, QVector<CANFrame> frames)
{
Q_UNUSED(conn);
if (continuousLogging)
{
FrameFileIO::writeContinuousNative(&frames, 0);
}
}
void MainWindow::tickGUIUpdate()
{
rxFrames = model->sendBulkRefresh();
//if(rxFrames>0)
//{
int elapsed = elapsedTime->elapsed();
if(elapsed) {
framesPerSec = (framesPerSec + (rxFrames * 1000 / elapsed)) / 2;
elapsedTime->restart();
}
else
framesPerSec = 0;
ui->lbNumFrames->setText(QString::number(model->rowCount()));
if (rxFrames > 0 && /*allowCapture && */ ui->cbAutoScroll->isChecked())
ui->canFramesView->scrollToBottom();
ui->lbFPS->setText(QString::number(framesPerSec));
if (rxFrames > 0)
{
bDirty = true;
emit framesUpdated(rxFrames); //anyone care that frames were updated?
manageRowExpansion();
}
if (model->needsFilterRefresh()) updateFilterList();
if (continuousLogging)
{
// const QVector<CANFrame> *modelFrames = model->getListReference();
// FrameFileIO::writeContinuousNative(modelFrames, modelFrames->count() - rxFrames);
continuousLogFlushCounter++;
if ((continuousLogFlushCounter % 3) == 0)
{