-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
2366 lines (1969 loc) · 88.5 KB
/
mainwindow.cpp
File metadata and controls
2366 lines (1969 loc) · 88.5 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 "qforeach.h"
#include "ui_mainwindow.h"
#include <QStorageInfo>
#include <QMessageBox>
#include <QProcess>
#include <QSettings>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QStandardItemModel>
#include <QtMultimediaWidgets/QtMultimediaWidgets>
#include <QtWidgets>
#include <QtMultimedia>
struct LightShow {
QString title;
QString audioDownloadLink;
QString lightshowDownloadLink;
};
QList<LightShow> collectedLightshows;
struct Settings {
int vehName; // Integer for vehicle name
};
QTimer *updateTimer;
bool VideoActive;
QList<QMediaPlayer*> mediaPlayers;
QList<QVideoWidget*> videoWidgets;
QWidget *cameraFront = nullptr;
QWidget *cameraBack = nullptr;
QWidget *cameraLeft = nullptr;
QWidget *cameraRight = nullptr;
qint64 lastpos_slider = 0;
bool wasPlaying;
QString configFilePath = QDir::currentPath() + "/tconfig.ini";
QString savFilePath = QDir::currentPath() + "/tdata.dat";
bool findTman(const QString& driveLetter) {
// Ensure the drive letter has a trailing backslash
QString rootDir = driveLetter;
if (!rootDir.endsWith("/") && !rootDir.endsWith("\\")) {
rootDir.append("/"); // Append a forward slash if it doesn't end with one
}
// Construct the path for tman.find
QString tmanFilePath = rootDir + "tman.find";
// Check if the file exists
QFile tmanFile(tmanFilePath);
if (tmanFile.exists()) {
// Check if the file has hidden attribute (Windows specific check)
QFileInfo fileInfo(tmanFilePath);
if (fileInfo.isHidden()) {
return true; // tman.find exists and is hidden
}
}
return false; // File not found or not hidden
}
bool findFolder(const QString &drivePath, const QString &folderName) {
QDir dir(drivePath);
// Check if the directory exists
if (!dir.exists()) {
qDebug() << "The specified drive does not exist:" << drivePath;
return false;
}
// Set filter to include only directories and exclude '.' and '..'
dir.setFilter(QDir::NoDotAndDotDot | QDir::AllDirs);
QFileInfoList entries = dir.entryInfoList();
// Loop through the entries to find the target folder
for (const QFileInfo &entry : entries) {
if (entry.fileName() == folderName) {
qDebug() << "Found folder:" << entry.absoluteFilePath();
return true; // Folder found
}
}
return false; // Folder not found
}
QStorageInfo getUSB() {
QList<QStorageInfo> volumes = QStorageInfo::mountedVolumes();
QStorageInfo usbStorageDevice;
// Loop through each volume to find a suitable USB device
for (const QStorageInfo &volume : volumes) {
QString drive = volume.rootPath();
if (drive.endsWith('/')) {
drive.chop(1); // Remove the trailing slash
}
if ((findFolder(volume.rootPath(), "LightShow") && volume.fileSystemType() != "NTFS") ||
(findFolder(volume.rootPath(), "TeslaCam") && volume.fileSystemType() != "NTFS") ||
(findTman(drive) && volume.fileSystemType() != "NTFS")) {
usbStorageDevice = volume; // Assign the valid USB device
break; // Exit the loop after finding the first valid device
}
}
return usbStorageDevice;
}
QString getRootUSB() {
QStorageInfo usbStorageDevice = getUSB(); // Use the helper function
QString letter = usbStorageDevice.rootPath();
if (letter.endsWith('/')) {
letter.chop(1); // Remove the trailing slash
}
return letter;
}
void MainWindow::updateCheckboxes(QString& usbDriveLetter) {
if (usbDriveLetter.endsWith('/')) {
usbDriveLetter.chop(1); // Remove the trailing slash
}
// Check for TeslaCam folder
if (findFolder(usbDriveLetter, "TeslaCam")) {
ui->dashcam_enabled->setChecked(true); // Check dashcam_enabled if folder is found
} else {
ui->dashcam_enabled->setChecked(false); // Uncheck if folder is not found
}
// Check for LightShow folder
if (findFolder(usbDriveLetter, "LightShow")) {
ui->customLightshows_enabled->setChecked(true); // Check customLightshows_enabled if folder is found
} else {
ui->customLightshows_enabled->setChecked(false); // Uncheck if folder is not found
}
}
// Create configuration file with default settings
void MainWindow::CreateConfig() {
QSettings settings(configFilePath, QSettings::IniFormat);
// Set default settings
settings.beginGroup("General");
settings.setValue("vehName", -1); // Default vehicle name
settings.endGroup();
qDebug() << "tconfig.ini created with default settings.";
}
// Load configuration settings
Settings loadConfig(MainWindow *mainWindow) {
Settings settingsData;
QFile configFile(configFilePath);
// Check if the config file exists
if (!configFile.exists()) {
if (mainWindow) {
mainWindow->CreateConfig(); // Call CreateConfig through the MainWindow instance
} else {
qDebug() << "Error: MainWindow instance is null. Cannot create config.";
return settingsData; // Return default settings
}
}
QSettings settings(configFilePath, QSettings::IniFormat);
// Load settings
settings.beginGroup("General");
settingsData.vehName = settings.value("vehName", 1).toInt(); // Default to 1 if not found
settings.endGroup();
qDebug() << "tconfig.ini loaded. vehName:" << settingsData.vehName;
return settingsData;
}
void MainWindow::SaveConfig() {
QFile configFile(configFilePath);
// Check if the config file exists
if (!configFile.exists()) {
CreateConfig();
}
QSettings settings(configFilePath, QSettings::IniFormat);
// Begin saving settings
settings.beginGroup("General");
settings.setValue("vehName", ui->vehicles_comboBox->currentIndex()); // Default vehicle name
settings.endGroup();
}
QString convertTo12HourFormat(const QString &time24hr) {
QStringList timeParts = time24hr.split(':');
if (timeParts.size() != 3) {
qDebug() << "Invalid time format:" << time24hr;
return QString();
}
int hour = timeParts.at(0).toInt();
int minute = timeParts.at(1).toInt();
int second = timeParts.at(2).toInt();
QString period = (hour >= 12) ? "PM" : "AM";
// Convert hour to 12-hour format
if (hour == 0) {
hour = 12; // Midnight
} else if (hour > 12) {
hour -= 12; // Afternoon/evening
}
return QString("%1:%2:%3 %4")
.arg(hour, 2, 10, QChar('0')) // Ensure 2-digit hour
.arg(minute, 2, 10, QChar('0')) // Ensure 2-digit minute
.arg(second, 2, 10, QChar('0')) // Ensure 2-digit second
.arg(period);
}
QString getMonthName(int month) {
static const QStringList monthNames = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
if (month >= 1 && month <= 12) {
return monthNames.at(month - 1);
}
return "Invalid Month"; // Fallback for invalid month values
}
void MainWindow::loadDetectedClips(const QString &rootDir) {
qDebug() << "Load: Begin detected clips";
QString teslaCamDir = rootDir + "/TeslaCam";
QString sentryClipsDir = teslaCamDir + "/SentryClips";
QString savedClipsDir = teslaCamDir + "/SavedClips";
QDir sentryDir(sentryClipsDir);
QDir savedDir(savedClipsDir);
// Create models for each tree view
QStandardItemModel *sentryModel = new QStandardItemModel(this);
QStandardItemModel *savedModel = new QStandardItemModel(this);
ui->sentry_treeView->setModel(sentryModel);
ui->savedclips_treeView->setModel(savedModel);
auto processClipDirectory = [](const QString &clipDirPath, QStandardItemModel *model) {
QDir dir(clipDirPath);
QStringList videoFolders = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
QMap<QString, QStandardItem*> yearItems; // Map for year-level items
QMap<QString, QStandardItem*> monthItems; // Map for month-level items
for (const QString &folder : videoFolders) {
QString fullFolderPath = clipDirPath + "/" + folder;
QDir videoFolder(fullFolderPath);
// Read event.json for metadata
QFile eventFile(videoFolder.filePath("event.json"));
if (eventFile.exists() && eventFile.open(QIODevice::ReadOnly)) {
QJsonDocument doc = QJsonDocument::fromJson(eventFile.readAll());
QJsonObject jsonObject = doc.object();
QString timestamp = jsonObject.value("timestamp").toString();
QString city = jsonObject.value("city").toString();
QString reason = jsonObject.value("reason").toString();
QStringList timestampParts = timestamp.split('T');
if (timestampParts.size() != 2) {
qDebug() << "Invalid timestamp format:" << timestamp;
continue;
}
QString date = timestampParts.at(0); // Extract date part (YYYY-MM-DD)
QString time = timestampParts.at(1); // Extract time part (hh:mm:ss)
QStringList dateParts = date.split('-');
if (dateParts.size() != 3) {
qDebug() << "Invalid date format:" << date;
continue;
}
QString year = dateParts.at(0);
QString month = dateParts.at(1); // Month in MM format
QString day = dateParts.at(2);
// Convert time to 12-hour format
QString time12Hour = convertTo12HourFormat(time);
// Prepare display text for the clip
QString displayText = QString("%1 [%2]").arg(date).arg(city.isEmpty() ? reason : city);
// Check or create year node
QStandardItem *yearItem = yearItems.value(year, nullptr);
if (!yearItem) {
yearItem = new QStandardItem(year);
model->appendRow(yearItem);
yearItems[year] = yearItem;
}
// Check or create month node
QString monthLabel = getMonthName(month.toInt()) + " (" + month + ")";
QStandardItem *monthItem = monthItems.value(year + month, nullptr);
if (!monthItem) {
monthItem = new QStandardItem(monthLabel);
yearItem->appendRow(monthItem);
monthItems[year + month] = monthItem;
}
// Add clip to month node
QStandardItem *clipItem = new QStandardItem(displayText);
clipItem->setIcon(QIcon(":/gui/build/Desktop_Qt_6_8_1_MinGW_64_bit-Debug/debug/video_icon.png"));
monthItem->appendRow(clipItem);
} else {
qDebug() << "Missing or unreadable event.json in folder:" << folder;
}
}
};
// Process SentryClips and SavedClips
processClipDirectory(sentryClipsDir, sentryModel);
processClipDirectory(savedClipsDir, savedModel);
qDebug() << "Load: Detected Sentry and Saved clips loaded.";
}
QString formatSize(qint64 bytes) {
const double KB = 1024.0;
const double MB = KB * 1024.0;
const double GB = MB * 1024.0;
const double TB = GB * 1024.0;
double result = bytes;
QString unit = "Bytes";
if (bytes >= TB) {
result = bytes / TB;
unit = "TB";
} else if (bytes >= GB) {
result = bytes / GB;
unit = "GB";
} else if (bytes >= MB) {
result = bytes / MB;
unit = "MB";
} else if (bytes >= KB) {
result = bytes / KB;
unit = "KB";
}
return QString::number(result, 'f', 2) + unit;
}
QString getVeh(int id) {
switch (id) {
case 0:
return "Model S";
case 1:
return "Model X";
case 2:
return "Model 3";
case 3:
return "Model Y";
case 4:
return "Cybertruck";
case 5:
return "2017-2023 Model 3";
case 6:
return "2012-2020 Model S";
case 7:
return "2015-2020 Model X";
default:
return "Unknown Vehicle";
}
}
void MainWindow::ShowWarningMsg(QString msg) {
ui->warning_label->setText(msg);
ui->warning_frame->show();
}
void MainWindow::ScanFolders() {
ui->driveproperties_label->setText("Scanning..."); // Use old way to bypass error checks
QList<QStorageInfo> volumes = QStorageInfo::mountedVolumes();
bool tmanFound = false; // Flag to check if tman.find is found
bool foldersFound = false; // Flag to check if folders are found
// Loop through each volume and display details
for (const QStorageInfo &volume : volumes) {
QString rootPath = volume.rootPath();
QString rootFreeSpace = formatSize(volume.bytesFree());
QString formatted = "Detected Tesla Drive [" + rootPath + "] " + rootFreeSpace + " Free";
qDebug() << "scan " + rootPath;
if (findFolder(rootPath, "TeslaCam") || findFolder(rootPath, "LightShow")) {
foldersFound = true; // At least one folder found
}
// Check if tman.find is found
if (findTman(rootPath)) {
tmanFound = true; // tman.find file found
}
if (foldersFound || tmanFound) {
if (volume.fileSystemType() != "NTFS") {
ui->radioButton->hide();
ui->driveproperties_label->setText(formatted);
ui->driveproperties_label->show();
ui->reformat_drive->show();
ui->warning_frame->hide();
ui->loadCacheButton->setEnabled(true);
ui->tabWidget->setTabEnabled(0, true);
ui->tabWidget->setTabEnabled(1, true);
ui->tabWidget->setCurrentIndex(0);
QString usbDriveLetter = rootPath;
if (!usbDriveLetter.endsWith("/") && !usbDriveLetter.endsWith("\\")) {
usbDriveLetter.append("/"); // Append a forward slash if it doesn't end with one
}
QString hiddenFilePath = usbDriveLetter + "/tman.find";
QFile hiddenFile(hiddenFilePath);
if (hiddenFile.open(QIODevice::WriteOnly)) {
hiddenFile.close(); // Close the file after creating it
} else {
QMessageBox::critical(this, "Error", "Failed to create tman.find file.");
return;
}
// Set the hidden attribute using system command
QString setHiddenCommand = QString("attrib +h \"%1\"").arg(hiddenFilePath);
system(setHiddenCommand.toStdString().c_str());
updateCheckboxes(rootPath);
loadDetectedClips(rootPath);
if ((volume.bytesTotal() * 1024 * 1024 * 1024) < 64) {
ShowWarningMsg("Warning: Your Tesla drive is under the recommended capacity of 64GB");
}
if (!foldersFound && tmanFound) {
// If no folders were found but tman.find was found
ShowWarningMsg("No files found on drive, please reformat or load cache.");
ui->driveproperties_label->setText("No files found on drive ["+usbDriveLetter+"]");
ui->pushButton_2->show();
ui->tabWidget->setTabEnabled(0, false);
ui->tabWidget->setTabEnabled(1, false);
ui->tabWidget->setCurrentIndex(2);
}
break;
} else if (findFolder(rootPath, "TeslaCam") && volume.fileSystemType() != "NTFS" && findFolder(rootPath, "LightShow")) {
ShowWarningMsg("Your Tesla drive cannot have custom lightshows and dashcam at the same time");
ui->driveproperties_label->setText("Tesla Drive Detected, Multi Feature Violation");
ui->pushButton_2->show();
break;
} else if (findFolder(rootPath, "TeslaCam") || findFolder(rootPath, "LightShow")) {
ShowWarningMsg("Your Tesla drive is not exFAT, MS-DOS FAT (for Mac), ext3, or ext4");
ui->driveproperties_label->setText("Tesla Drive Detected, Invalid formatting");
ui->pushButton_2->show();
break;
}
} else {
ShowWarningMsg("No Tesla Drive Detected!");
ui->radioButton->show();
ui->reformat_drive->hide();
ui->pushButton_2->hide();
ui->driveproperties_label->setText("No Tesla Drive Detected");
ui->loadCacheButton->setEnabled(false);
ui->tabWidget->setTabEnabled(0, false);
ui->tabWidget->setTabEnabled(1, false);
ui->tabWidget->setCurrentIndex(2);
}
}
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
updateTimer = new QTimer(this);
connect(updateTimer, &QTimer::timeout, this, &MainWindow::updateVideoUI);
Settings configSettings = loadConfig(this);
ui->warning_frame->hide();
ui->pushButton_2->hide();
//ui->videoButton_frame->hide();
ui->comboBox->addItem("4xS");
ui->comboBox->addItem("1xL");
ui->comboBox->addItem("2xM");
ui->comboBox->itemText(0);
ui->videoButton_framebackwards->setIcon(style()->standardIcon(QStyle::SP_MediaSeekBackward));
ui->videoButton_frameforward->setIcon(style()->standardIcon(QStyle::SP_MediaSeekForward));
ui->videoButton_playpause->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
ui->videoButton_startframe->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));
ui->videoButton_skiptoend->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));
ui->vehicles_comboBox->addItem("Model S");
ui->vehicles_comboBox->addItem("Model X");
ui->vehicles_comboBox->addItem("Model 3");
ui->vehicles_comboBox->addItem("Model Y");
ui->vehicles_comboBox->addItem("Cybertruck");
ui->vehicles_comboBox->addItem("2017-2023 Model 3");
ui->vehicles_comboBox->addItem("2012-2020 Model S");
ui->vehicles_comboBox->addItem("2015-2020 Model X");
ui->vehicles_comboBox->setPlaceholderText(getVeh(configSettings.vehName));
ui->vehicles_comboBox->setCurrentIndex(configSettings.vehName);
ScanFolders();
ui->recentClipsTab->setEnabled(false); // disable until implemented
}
MainWindow::~MainWindow()
{
delete ui;
delete updateTimer;
}
void MainWindow::on_radioButton_clicked() // scan drive button
{
if (ui->radioButton->isChecked()) {
ui->radioButton->setChecked(false);
}
ScanFolders();
}
void MainWindow::on_pushButton_clicked() // ack button
{
ui->warning_frame->hide();
}
void MainWindow::formatDrive(const QString& driveLetter) {
QMessageBox::StandardButton reply = QMessageBox::warning(
this,
"Warning",
QString("Formatting will erase all data on the drive [%1]. Do you want to continue?").arg(driveLetter),
QMessageBox::Yes | QMessageBox::No
);
if (reply == QMessageBox::Yes) {
QString usbDriveLetter = driveLetter;
qDebug() << "Beginning Format";
// Ensure the drive letter has a trailing backslash removed
if (usbDriveLetter.endsWith("/") || usbDriveLetter.endsWith("\\")) {
usbDriveLetter.chop(1); // Remove the last character
}
// Create the format command
QString command = QString("format %1 /FS:exFAT /Q /Y").arg(usbDriveLetter);
qDebug() << command;
// Call the system command
int result = system(command.toStdString().c_str());
// Check the result of the system call
if (result != 0) {
QMessageBox::critical(this, "Error", "Formatting failed. Please check the drive and try again.");
return;
}
// Create the TeslaCam folder
QDir usbDir(usbDriveLetter);
if (!usbDir.exists()) {
QMessageBox::critical(this, "Error", "Drive is not accessible.");
return;
}
if (!usbDir.mkdir("TeslaCam")) {
QMessageBox::critical(this, "Error", "Failed to create TeslaCam folder.");
return;
}
// Create the tman.find file with hidden attribute
QString hiddenFilePath = usbDriveLetter + "/tman.find";
QFile hiddenFile(hiddenFilePath);
if (hiddenFile.open(QIODevice::WriteOnly)) {
hiddenFile.close(); // Close the file after creating it
} else {
QMessageBox::critical(this, "Error", "Failed to create tman.find file.");
return;
}
// Set the hidden attribute using system command
QString setHiddenCommand = QString("attrib +h \"%1\"").arg(hiddenFilePath);
system(setHiddenCommand.toStdString().c_str());
ScanFolders();
QMessageBox::information(this, "Success", "Drive formatted to exFAT, TeslaCam folder created, and tman.find file created successfully.");
ui->pushButton_2->hide();
}
}
void MainWindow::on_pushButton_2_clicked() // format button
{
formatDrive(getRootUSB());
}
void MainWindow::on_vehicles_comboBox_currentIndexChanged(int index)
{
// Construct resource path
QString resourcePath = ":/gui/build/Desktop_Qt_6_8_1_MinGW_64_bit-Debug/debug/" + QString::number(index) + ".png";
QPixmap pixmap(resourcePath);
if (!pixmap.isNull()) {
// Set the pixmap directly; QLabel with scaled contents will handle resizing
ui->label_3->setPixmap(pixmap);
} else {
qDebug() << "Failed to load resource image:" << resourcePath;
}
SaveConfig();
}
void MainWindow::resetLayout(int index) {
// Clear any existing media players
for (QMediaPlayer *mediaPlayer : mediaPlayers) {
if (mediaPlayer) {
lastpos_slider = mediaPlayer->position();
// Disconnect signals if necessary
disconnect(mediaPlayer); // Disconnect all signals
// Stop the media player
mediaPlayer->stop();
// Delete the media player
delete mediaPlayer;
}
}
mediaPlayers.clear(); // Clear the list of media players
// Reset global widget pointers
cameraFront->disconnect();
cameraFront = nullptr;
cameraBack->disconnect();
cameraBack = nullptr;
cameraLeft->disconnect();
cameraLeft = nullptr;
cameraRight->disconnect();
cameraRight = nullptr;
// Clear the existing layout in videos_area
QLayout *existingLayout = ui->videos_area->layout();
if (existingLayout) {
QLayoutItem *child;
while ((child = existingLayout->takeAt(0)) != nullptr) {
delete child->widget(); // Delete the widget
delete child; // Delete the layout item
}
delete existingLayout;
}
// Create a new layout
QGridLayout *layout = new QGridLayout();
layout->setContentsMargins(0, 0, 0, 0); // Set layout margins to 0
switch (index) {
case 0: // 4xS
{
// Create four small widgets in a 2x2 pattern
QWidget *widgets[4] = {nullptr, nullptr, nullptr, nullptr};
int count = 0;
for (int row = 0; row < 2; ++row) {
for (int col = 0; col < 2; ++col) {
widgets[count] = new QWidget();
widgets[count]->setStyleSheet("background-color: gray;");
QGridLayout *smallLayout = new QGridLayout(widgets[count]);
smallLayout->setContentsMargins(0, 0, 0, 0); // Set margins to 0
layout->addWidget(widgets[count], row, col, 1, 1);
count++;
}
}
cameraFront = widgets[0];
cameraBack = widgets[1];
cameraLeft = widgets[2];
cameraRight = widgets[3];
}
break;
case 1: // 1xL
{
// Create one large widget filling the entire area
QWidget *largeWidget = new QWidget();
largeWidget->setStyleSheet("background-color: gray;");
QGridLayout *largeLayout = new QGridLayout(largeWidget);
largeLayout->setContentsMargins(0, 0, 0, 0); // Set margins to 0
layout->addWidget(largeWidget, 0, 0, 3, 3); // Spanning all rows/columns
cameraFront = largeWidget; // Assign to cameraFront
}
break;
case 2: // 2xM
{
// Create two medium-sized widgets side-by-side
QWidget *widgets[2] = {nullptr, nullptr};
for (int col = 0; col < 2; ++col) {
widgets[col] = new QWidget();
widgets[col]->setStyleSheet("background-color: gray;");
QGridLayout *smallLayout = new QGridLayout(widgets[col]);
smallLayout->setContentsMargins(0, 0, 0, 0); // Set margins to 0
layout->addWidget(widgets[col], 0, col, 1, 1);
}
cameraFront = widgets[0];
cameraBack = widgets[1];
// Remaining global pointers are already nullptr
}
break;
default:
qDebug() << "Invalid index selected.";
break;
}
// Set the layout to videos_area
ui->videos_area->setLayout(layout);
setupContextMenus();
if (VideoActive) {
setupPreviewVideoPlayers();
}
}
// Get the video file path for the selected camera
QString getCameraVideoPath(const QString &cameraSuffix) {
return QCoreApplication::applicationDirPath() + "/previews/combined_" + cameraSuffix + ".mp4";
}
void MainWindow::on_comboBox_currentIndexChanged(int index)
{
resetLayout(index);
}
void MainWindow::setupContextMenus() {
QWidget *cameraWidgets[] = {cameraFront, cameraBack, cameraLeft, cameraRight};
for (QWidget *widget : cameraWidgets) {
if (widget) {
widget->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(widget, &QWidget::customContextMenuRequested, [widget, this](const QPoint &pos) {
showContextMenu(widget, pos);
});
}
}
}
// Show context menu for a widget
void MainWindow::showContextMenu(QWidget *widget, const QPoint &pos) {
QMenu contextMenu;
QAction *frontCameraAction = contextMenu.addAction("Set to Front Camera");
QAction *backCameraAction = contextMenu.addAction("Set to Back Camera");
QAction *leftCameraAction = contextMenu.addAction("Set to Left Camera");
QAction *rightCameraAction = contextMenu.addAction("Set to Right Camera");
QAction *selectedAction = contextMenu.exec(widget->mapToGlobal(pos));
if (selectedAction) {
lastpos_slider = mediaPlayers[0]->position();
wasPlaying = mediaPlayers[0]->isPlaying();
if (selectedAction == frontCameraAction) {
setMediaSource(widget, "front");
} else if (selectedAction == backCameraAction) {
setMediaSource(widget, "back");
} else if (selectedAction == leftCameraAction) {
setMediaSource(widget, "left_repeater");
} else if (selectedAction == rightCameraAction) {
setMediaSource(widget, "right_repeater");
}
}
}
// Set media source for the widget's associated media player
void MainWindow::setMediaSource(QWidget *widget, const QString &camera) {
QString videoPath = getCameraVideoPath(camera);
if (widget == cameraFront && mediaPlayers[0]) {
mediaPlayers[0]->setSource(QUrl::fromLocalFile(videoPath));
mediaPlayers[0]->setPosition(lastpos_slider);
mediaPlayers[0]->play();
mediaPlayers[0]->pause();
if (wasPlaying) {
mediaPlayers[0]->play();
}
} else if (widget == cameraBack && mediaPlayers[1]) {
mediaPlayers[1]->setSource(QUrl::fromLocalFile(videoPath));
mediaPlayers[1]->setPosition(lastpos_slider);
mediaPlayers[1]->play();
mediaPlayers[1]->pause();
if (wasPlaying) {
mediaPlayers[1]->play();
}
} else if (widget == cameraLeft && mediaPlayers[2]) {
mediaPlayers[2]->setSource(QUrl::fromLocalFile(videoPath));
mediaPlayers[2]->setPosition(lastpos_slider);
mediaPlayers[2]->play();
mediaPlayers[2]->pause();
if (wasPlaying) {
mediaPlayers[2]->play();
}
} else if (widget == cameraRight && mediaPlayers[3]) {
mediaPlayers[3]->setSource(QUrl::fromLocalFile(videoPath));
mediaPlayers[3]->setPosition(lastpos_slider);
mediaPlayers[3]->play();
mediaPlayers[3]->pause();
if (wasPlaying) {
mediaPlayers[3]->play();
}
}
}
void MainWindow::on_savedclips_treeView_clicked(const QModelIndex &index)
{
QString usbDriveLetter = getRootUSB();
if (findFolder(usbDriveLetter, "TeslaCam")) {
if (!usbDriveLetter.isEmpty()) {
VideoActive = false;
updateTimer->stop();
handleTreeViewClick(index, usbDriveLetter + "/TeslaCam/SavedClips");
}
}
}
void MainWindow::on_sentry_treeView_clicked(const QModelIndex &index)
{
QString usbDriveLetter = getRootUSB();
if (findFolder(usbDriveLetter, "TeslaCam")) {
if (!usbDriveLetter.isEmpty()) {
VideoActive = false;
updateTimer->stop();
handleTreeViewClick(index, usbDriveLetter + "/TeslaCam/SentryClips");
}
}
}
QString joinVideos(const QList<QString>& videoFiles, const QString& cameraSuffix) {
// Create the "previews" directory in the executable's directory
QDir previewsDir(QCoreApplication::applicationDirPath() + "/previews");
if (!previewsDir.exists()) {
previewsDir.mkpath("."); // Create the directory
}
// Define the output path for the combined video
QString outputPath = previewsDir.absoluteFilePath("combined_" + cameraSuffix + ".mp4");
// Create a temporary file to hold the list of video files
QString fileListPath = previewsDir.absoluteFilePath("file_list.txt");
QFile file(fileListPath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Failed to open file list for writing";
return QString();
}
// Write the file list for ffmpeg
for (const QString& videoFile : videoFiles) {
file.write(QString("file '%1'\n").arg(videoFile).toUtf8());
}
file.close();
// Prepare the ffmpeg command
QString ffmpegPath = QCoreApplication::applicationDirPath() + "/tools/ffmpeg.exe"; // Replace with the actual path to ffmpeg.exe
QStringList arguments;
arguments << "-f" << "concat" << "-safe" << "0" << "-i" << fileListPath << "-c" << "copy" << outputPath;
// Run ffmpeg process
QProcess ffmpegProcess;
ffmpegProcess.start(ffmpegPath, arguments);
if (!ffmpegProcess.waitForFinished()) {
qDebug() << "ffmpeg process did not finish successfully";
return QString();
}
// Check if ffmpeg executed successfully
QString output = ffmpegProcess.readAllStandardOutput();
QString error = ffmpegProcess.readAllStandardError();
if (!error.isEmpty()) {
qDebug() << "ffmpeg error:" << error;
}
// Return the path to the combined video
return outputPath;
}
void MainWindow::handleTreeViewClick(const QModelIndex &index, const QString &baseDir)
{
// Get the text of the clicked item
QString clickedText = index.data(Qt::DisplayRole).toString();
qDebug() << "Clicked item text:" << clickedText;
// Extract the date (YYYY-MM-DD) from the clicked text
QRegularExpression dateRegex("^(\\d{4}-\\d{2}-\\d{2})"); // Match YYYY-MM-DD at the beginning
QRegularExpressionMatch match = dateRegex.match(clickedText);
if (!match.hasMatch()) {
qDebug() << "Invalid date format or unrecognized text clicked:" << clickedText;
return;
}
QString extractedDate = match.captured(1); // Extracted YYYY-MM-DD
qDebug() << "Extracted date:" << extractedDate;
// Search for a folder starting with the extracted date
QDir baseDirObj(baseDir);
QStringList matchingFolders = baseDirObj.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
qDebug() << "Matching folders:" << matchingFolders;
QString folderPath;
for (const QString &folderName : matchingFolders) {
if (folderName.startsWith(extractedDate)) {
folderPath = baseDir + "/" + folderName;
qDebug() << "Found matching folder:" << folderPath;
break;
}
}
if (folderPath.isEmpty()) {
qDebug() << "No folder found starting with date:" << extractedDate;
return;
}
QDir folderDir(folderPath);
if (!folderDir.exists()) {
qDebug() << "Folder does not exist for the clicked date:" << folderPath;
return;
}
// Get all .mp4 files in the folder
QStringList videoFiles = folderDir.entryList({"*.mp4"}, QDir::Files);
qDebug() << "Video files found in folder:" << videoFiles;
// Group videos by angle
QMap<QString, QList<QString>> groupedVideos;
for (const QString &fileName : videoFiles) {
QStringList parts = fileName.split('-');
if (parts.size() < 5) {
qDebug() << "Skipping file due to insufficient parts:" << fileName;
continue;
}
// Check and split parts if necessary
QStringList newParts;
for (const QString &part : parts) {
if (part.contains("_") && !part.contains("repeater")) {
// Split this part and add to newParts
QStringList subParts = part.split("_");
newParts.append(subParts);
} else {
newParts.append(part);
}
}
// Use the last part to determine the camera angle
QString cameraAngle = newParts.last();
if (cameraAngle.endsWith(".mp4")) {
cameraAngle.chop(4); // Remove ".mp4"
}
if (cameraAngle == "back" || cameraAngle == "front" ||
cameraAngle == "left_repeater" || cameraAngle == "right_repeater") {
groupedVideos[cameraAngle].append(folderPath + "/" + fileName);
qDebug() << "Added video to group:" << cameraAngle << fileName;
} else {
qDebug() << "Unrecognized camera angle in file name:" << cameraAngle;
}
}
// Sort each group by filename (timestamps)
for (auto &group : groupedVideos) {
std::sort(group.begin(), group.end());
qDebug() << "Sorted group:" << group;
}
QProgressDialog progressDialog("Processing clips...", "Cancel", 0, groupedVideos.size(), this);
progressDialog.setWindowModality(Qt::WindowModal); // Make it modal
progressDialog.setMinimumDuration(0); // Show immediately
progressDialog.show(); // Show the dialog now