-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
979 lines (832 loc) · 33.6 KB
/
MainWindow.cpp
File metadata and controls
979 lines (832 loc) · 33.6 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
#include "MainWindow.h"
#include "SettingsDialog.h"
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QAction>
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QSettings>
#include <QCloseEvent>
#include <QInputDialog>
#include <QMenuBar>
#include <QMenu>
#include <QByteArray>
#include <QTextEdit>
#include <QTextCursor>
#include <QLabel>
#include <QComboBox>
#include <QCheckBox>
#include <QLabel>
#include <QClipboard>
#include <QGuiApplication>
#include <QMimeData>
#include <QUrl>
#include <QDialogButtonBox>
//Includes for the codecs
#include "encoders/Base64Codec.h"
#include "encoders/Rot13.h"
#include "encoders/CaesarCipher.h"
#include "encoders/BinaryCodec.h"
#include "encoders/HexCodec.h"
#include "encoders/PigLatin.h"
#include "encoders/Atbash.h"
#include "encoders/MorseCodec.h"
#include "encoders/AESCodec.h"
#include "encoders/RSACodec.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) {
setupUI();
connectSignals();
loadRecentFiles();
restoreSession();
}
void MainWindow::setupUI() {
tabWidget = new QTabWidget(this);
tabWidget->setTabsClosable(true);
setCentralWidget(tabWidget);
connect(tabWidget, &QTabWidget::tabCloseRequested, this, [this](int index) {
QTextEdit *editor = qobject_cast<QTextEdit*>(tabWidget->widget(index));
closeTab(editor);
});
cursorLabel = new QLabel("Ln 1, Col 1");
statusBar()->addPermanentWidget(cursorLabel);
// Main toolbar
mainToolbar = addToolBar("Main Toolbar");
mainToolbar->setObjectName("mainToolbar");
QAction *newAction = new QAction(QIcon::fromTheme("document-new"), "New", this);
connect(newAction, &QAction::triggered, this, &MainWindow::newTab);
newAction->setShortcut(QKeySequence::New);
QAction *openAction = new QAction(QIcon::fromTheme("document-open"), "Open", this);
connect(openAction, &QAction::triggered, this, [this]() {
openFile();
});
openAction->setShortcut(QKeySequence::Open);
QAction *saveAction = new QAction(QIcon::fromTheme("document-save"), "Save", this);
connect(saveAction, &QAction::triggered, [this]() {
if (QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget())) {
saveFile(editor);
}
});
saveAction->setShortcut(QKeySequence::Save);
QIcon saveAllIcon = QIcon::hasThemeIcon("document-save-all")
? QIcon::fromTheme("document-save-all")
: QIcon::fromTheme("sync-synchronizing");
QAction *saveAllAction = new QAction(saveAllIcon, "Save All", this);
connect(saveAllAction, &QAction::triggered, this, &MainWindow::saveAll);
saveAllAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_S));
QAction *closeAction = new QAction(QIcon::fromTheme("window-close"), "Close Document", this);
closeAction->setShortcut(QKeySequence::Close);
connect(closeAction, &QAction::triggered, this, [this]() {
QWidget *current = tabWidget->currentWidget();
if (auto *editor = qobject_cast<QTextEdit *>(current)) {
maybeSaveAndClose(editor);
}
});
QAction *undoAction = new QAction(QIcon::fromTheme("edit-undo"), "Undo", this);
connect(undoAction, &QAction::triggered, this, &MainWindow::undoLastChange);
undoAction->setShortcut(QKeySequence::Undo);
QAction *redoAction = new QAction(QIcon::fromTheme("edit-redo"), "Redo", this);
connect(redoAction, &QAction::triggered, this, &MainWindow::redoLastChange);
redoAction->setShortcut(QKeySequence::Redo);
QAction *copyAction = new QAction(QIcon::fromTheme("edit-copy"), "Copy", this);
connect(copyAction, &QAction::triggered, [this]() {
QTextEdit *editor = qobject_cast<QTextEdit*>(tabWidget->currentWidget());
if (editor && tabDataMap.contains(editor)) {
QGuiApplication::clipboard()->setText(editor->textCursor().selectedText());
}
});
copyAction->setShortcut(QKeySequence::Copy);
QAction *cutAction = new QAction(QIcon::fromTheme("edit-cut"), "Cut", this);
connect(cutAction, &QAction::triggered, [this]() {
QTextEdit *editor = qobject_cast<QTextEdit*>(tabWidget->currentWidget());
if (editor && tabDataMap.contains(editor)) {
QTextCursor cursor = editor->textCursor();
QGuiApplication::clipboard()->setText(cursor.selectedText());
cursor.removeSelectedText();
editor->setTextCursor(cursor);
}
});
cutAction->setShortcut(QKeySequence::Cut);
QAction *pasteAction = new QAction(QIcon::fromTheme("edit-paste"), "Paste", this);
connect(pasteAction, &QAction::triggered, [this]() {
QTextEdit *editor = qobject_cast<QTextEdit*>(tabWidget->currentWidget());
if (editor && tabDataMap.contains(editor)) {
editor->insertPlainText(QGuiApplication::clipboard()->text());
}
});
pasteAction->setShortcut(QKeySequence::Paste);
QIcon settingsIcon = QIcon::hasThemeIcon("preferences-system")
? QIcon::fromTheme("preferences-system")
: QIcon::fromTheme("emblem-system");
QAction *settingsAction = new QAction(settingsIcon, "Settings", this);
connect(settingsAction, &QAction::triggered, this, &MainWindow::openSettingsDialog);
settingsAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Comma));
mainToolbar->addAction(newAction);
mainToolbar->addAction(openAction);
mainToolbar->addAction(saveAction);
mainToolbar->addAction(saveAllAction);
mainToolbar->addSeparator();
mainToolbar->addAction(closeAction);
mainToolbar->addSeparator();
mainToolbar->addAction(copyAction);
mainToolbar->addAction(cutAction);
mainToolbar->addAction(pasteAction);
mainToolbar->addSeparator();
mainToolbar->addAction(undoAction);
mainToolbar->addAction(redoAction);
mainToolbar->addSeparator();
mainToolbar->addAction(settingsAction);
// Codec toolbar
codecToolbar = addToolBar("Codec Toolbar");
codecToolbar->setObjectName("codecToolbar");
encoderSelector = new QComboBox;
encodeAction = new QAction(QIcon::fromTheme("list-add"), "Encode", this);
decodeAction = new QAction(QIcon::fromTheme("list-remove"), "Decode", this);
encoderSelector->addItems({"Base64", "Binary", "Hex", "Caesar", "ROT13", "Morse", "Atbash", "Pig Latin", "AES", "RSA"});
codecToolbar->addWidget(encoderSelector);
codecToolbar->addAction(encodeAction);
codecToolbar->addAction(decodeAction);
connect(encodeAction, &QAction::triggered, this, [this]() {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (editor)
encodeCurrentText(encoderSelector->currentText());
});
connect(decodeAction, &QAction::triggered, this, [this]() {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (editor)
decodeCurrentText(encoderSelector->currentText());
});
// Menus
QMenu *fileMenu = menuBar()->addMenu("File");
fileMenu->addAction(newAction);
fileMenu->addAction(openAction);
QMenu *recentMenu = new QMenu("Open Recent", this);
for (int i = 0; i < 10; ++i) {
recentFileActions[i] = new QAction(this);
recentFileActions[i]->setVisible(false);
connect(recentFileActions[i], &QAction::triggered, this, &MainWindow::openRecentFile);
recentMenu->addAction(recentFileActions[i]);
}
fileMenu->addMenu(recentMenu);
fileMenu->addAction(saveAction);
fileMenu->addAction(saveAllAction);
fileMenu->addSeparator();
fileMenu->addAction(closeAction);
fileMenu->addSeparator();
QAction *quitAction = new QAction("Quit", this);
connect(quitAction, &QAction::triggered, this, &QWidget::close);
fileMenu->addAction(quitAction);
quitAction->setShortcut(QKeySequence::Quit);
QMenu *editMenu = menuBar()->addMenu("Edit");
editMenu->addAction(undoAction);
editMenu->addAction(redoAction);
editMenu->addSeparator();
editMenu->addAction(copyAction);
editMenu->addAction(cutAction);
editMenu->addAction(pasteAction);
editMenu->addSeparator();
editMenu->addAction(settingsAction);
QMenu *viewMenu = menuBar()->addMenu("View");
toggleMainToolbar = new QAction("Show Main Toolbar", this);
toggleMainToolbar->setCheckable(true);
toggleMainToolbar->setChecked(true);
viewMenu->addAction(toggleMainToolbar);
connect(toggleMainToolbar, &QAction::toggled, mainToolbar, &QToolBar::setVisible);
toggleCodecToolbar = new QAction("Show Codec Toolbar", this);
toggleCodecToolbar->setCheckable(true);
toggleCodecToolbar->setChecked(true);
viewMenu->addAction(toggleCodecToolbar);
connect(toggleCodecToolbar, &QAction::toggled, codecToolbar, &QToolBar::setVisible);
toggleStatusBar = new QAction("Show Status Bar", this);
toggleStatusBar->setCheckable(true);
toggleStatusBar->setChecked(true);
viewMenu->addAction(toggleStatusBar);
connect(toggleStatusBar, &QAction::toggled, this, [this](bool visible){
statusBar()->setVisible(visible);
});
QMenu *codecMenu = menuBar()->addMenu("Codecs");
QMenu *encodeMenu = codecMenu->addMenu("Encode");
QMenu *decodeMenu = codecMenu->addMenu("Decode");
for (int i = 0; i < encoderSelector->count(); ++i) {
QString name = encoderSelector->itemText(i);
QAction *encodeAction = new QAction(name, this);
connect(encodeAction, &QAction::triggered, this, [this, name]() {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (editor && tabDataMap.contains(editor)) {
encodeCurrentText(name);
}
});
encodeMenu->addAction(encodeAction);
QAction *decodeAction = new QAction(name, this);
connect(decodeAction, &QAction::triggered, this, [this, name]() {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (editor && tabDataMap.contains(editor)) {
decodeCurrentText(name);
}
});
decodeMenu->addAction(decodeAction);
}
QMenu *helpMenu = menuBar()->addMenu("Help");
QAction *aboutAction = new QAction(QIcon::fromTheme("help-about"), "About", this);
helpMenu->addAction(aboutAction);
connect(aboutAction, &QAction::triggered, this, &MainWindow::showAboutDialog);
aboutAction->setShortcut(QKeySequence::HelpContents);
setAcceptDrops(true);
applyEditorSettings();
}
void MainWindow::connectSignals() {
connect(tabWidget, &QTabWidget::currentChanged, this, &MainWindow::updateCursorStatus);
}
void MainWindow::updateCursorStatus() {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (!editor || !tabDataMap.contains(editor)) return;
editor->blockSignals(true);
QTextCursor cursor = editor->textCursor();
int line = cursor.blockNumber() + 1;
int col = cursor.columnNumber() + 1;
cursorLabel->setText(QString("Ln %1, Col %2").arg(line).arg(col));
editor->blockSignals(false);
}
void MainWindow::newTab() {
QTextEdit *editor = new QTextEdit(this);
editor->setAcceptDrops(false);
tabWidget->addTab(editor, "Untitled");
tabWidget->setCurrentWidget(editor);
TabData data;
data.editor = editor;
data.isModified = false;
data.lastKnownText = "";
tabDataMap[editor] = data;
connect(editor, &QTextEdit::cursorPositionChanged, this, &MainWindow::updateCursorStatus);
connect(editor, &QTextEdit::textChanged, this, [this, editor]() {
if (tabDataMap.contains(editor)) {
QString currentText = editor->toPlainText();
if (currentText != tabDataMap[editor].lastKnownText) {
tabDataMap[editor].lastKnownText = currentText;
markModified(editor, true);
}
}
});
}
void MainWindow::markModified(QTextEdit *editor, bool modified) {
if (!editor || !tabDataMap.contains(editor)) return;
TabData &data = tabDataMap[editor];
// Only act if modified state is changing
if (data.isModified == modified)
return;
data.isModified = modified;
int index = tabWidget->indexOf(editor);
if (index == -1) return;
QString title;
if (!data.filePath.isEmpty()) {
title = QFileInfo(data.filePath).fileName();
} else {
title = "Untitled";
}
// Remove '*' if already present
if (title.endsWith('*'))
title.chop(1);
// Add '*' only if modified
if (modified)
title += '*';
// Only set the text if it's different
if (tabWidget->tabText(index) != title) {
tabWidget->setTabText(index, title);
}
}
void MainWindow::encodeCurrentText(const QString &method) {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (!editor) return;
QString text = editor->toPlainText();
QString result;
if (method == "Base64") {
result = Base64Codec::transform(text, false);
} else if (method == "ROT13") {
result = Rot13::transform(text);
} else if (method == "Caesar") {
bool ok;
int shift = QInputDialog::getInt(this, "Caesar Shift", "Shift: ", 3, -25, 25, 1, &ok);
if (ok) result = CaesarCipher::transform(text, shift, false);
else return;
} else if (method == "Binary") {
result = BinaryCodec::transform(text, false);
} else if (method == "Hex") {
result = HexCodec::transform(text, false);
} else if (method == "PigLatin") {
result = PigLatin::transform(text, false);
} else if (method == "Atbash") {
result = Atbash::transform(text);
} else if (method == "Morse") {
result = MorseCodec::transform(text, false);
} else if (method == "AES") {
bool ok;
QString key = QInputDialog::getText(this, "AES Key", "Enter encryption key:", QLineEdit::Password, "", &ok);
if (!ok || key.isEmpty()) return;
result = AESCodec::encode(text, key);
} else if (method == "RSA") {
QString key = promptForKeyFile("Select RSA Public Key", defaultRSAPublicKeyPath);
if (key.isEmpty()) return;
QByteArray input = text.toUtf8();
QByteArray output = RSACodec::encode(input, key);
if (!output.isEmpty()) {
result=output.toBase64();
} else {
QMessageBox::warning(this, "RSA Error", "RSA encoding failed. Check key and input size.");
}
} else {
QMessageBox::warning(this, "Unknown Codec", "The selected decoding method is not supported.");
return;
}
editor->setPlainText(result);
markModified(editor, true);
}
void MainWindow::decodeCurrentText(const QString &method) {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (!editor) return;
QString text = editor->toPlainText();
QString result;
if (method == "Base64") {
result = Base64Codec::transform(text, true);
} else if (method == "ROT13") {
result = Rot13::transform(text);
} else if (method == "Caesar") {
bool ok;
int shift = QInputDialog::getInt(this, "Caesar Shift", "Shift: ", 3, -25, 25, 1, &ok);
if (ok) result = CaesarCipher::transform(text, shift, true);
else return;
} else if (method == "Binary") {
result = BinaryCodec::transform(text, true);
} else if (method == "Hex") {
result = HexCodec::transform(text, true);
} else if (method == "PigLatin") {
result = PigLatin::transform(text, true);
} else if (method == "Atbash") {
result = Atbash::transform(text);
} else if (method == "Morse") {
result = MorseCodec::transform(text, true);
} else if (method == "AES") {
bool ok;
QString key = QInputDialog::getText(this, "AES Key", "Enter decryption key:", QLineEdit::Password, "", &ok);
if (!ok || key.isEmpty()) return;
result = AESCodec::decode(text, key);
} else if (method == "RSA") {
QString key = promptForKeyFile("Select RSA Private Key", defaultRSAPrivateKeyPath);
if (key.isEmpty()) return;
QByteArray input = QByteArray::fromBase64(text.toUtf8());
QByteArray output = RSACodec::decode(input, key);
if (!output.isEmpty()) {
result = QString::fromUtf8(output);
} else {
QMessageBox::warning(this, "RSA Error", "RSA encoding failed. Check key and input size.");
}
} else {
QMessageBox::warning(this, "Unknown Codec", "The selected decoding method is not supported.");
return;
}
editor->setPlainText(result);
markModified(editor, true);
}
void MainWindow::openFile() {
QObject *senderObj = sender();
if (qobject_cast<QAction *>(senderObj)) {
QString filePath = QFileDialog::getOpenFileName(this, "Open File");
if (!filePath.isEmpty()) {
loadFile(filePath);
}
}
}
void MainWindow::openFile(const QString &path) {
loadFile(path);
}
void MainWindow::loadFile(const QString &filePath) {
qDebug() << "Loading file:" << filePath;
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::warning(this, "Error", "Could not open file");
return;
}
QString content = QTextStream(&file).readAll();
file.close();
QTextEdit *editor = new QTextEdit(this);
editor->blockSignals(true);
editor->setPlainText(content);
editor->blockSignals(false);
int index = tabWidget->addTab(editor, QFileInfo(filePath).fileName());
tabWidget->setCurrentIndex(index);
TabData data;
data.editor = editor;
data.filePath = filePath;
data.isModified = false;
tabDataMap[editor] = data;
tabDataMap[editor].lastKnownText = content;
connect(editor, &QTextEdit::cursorPositionChanged, this, &MainWindow::updateCursorStatus);
connect(editor, &QTextEdit::textChanged, this, [this, editor]() {
markModified(editor, true);
});
// Apply font and tab settings
editor->blockSignals(true);
editor->setFont(currentFont);
QFontMetrics metrics(currentFont);
editor->setTabStopDistance(currentTabSize * metrics.horizontalAdvance(' '));
editor->blockSignals(false);
markModified(editor, false);
// Update recent files list
recentFiles.removeAll(filePath); // Remove any previous entry
recentFiles.prepend(filePath); // Add to the top
while (recentFiles.size() > 10) { // Limit list size
recentFiles.removeLast();
}
saveRecentFiles(); // Persist to QSettings
updateRecentFilesMenu(); // Refresh UI menu
qDebug() << "File loaded and tab added successfully.";
}
void MainWindow::saveFileAs(QTextEdit *editor) {
if (!editor || !tabDataMap.contains(editor)) return;
TabData &data = tabDataMap[editor];
QString filePath = QFileDialog::getSaveFileName(this, "Save File As");
if (filePath.isEmpty()) return;
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "Error", "Could not write to file.");
return;
}
QTextStream out(&file);
out << editor->toPlainText();
file.close();
data.filePath = filePath;
data.isModified = false;
data.lastKnownText = editor->toPlainText();
int index = indexForEditor(editor);
if (index >= 0) {
QFileInfo info(filePath);
tabWidget->setTabText(index, info.fileName());
}
markModified(editor, false);
}
void MainWindow::saveFile(QTextEdit *editor) {
if (!editor || !tabDataMap.contains(editor)) return;
TabData &data = tabDataMap[editor];
QString path = data.filePath;
if (path.isEmpty()) {
saveFileAs(editor);
return;
}
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "Error", "Could not write to file.");
return;
}
QTextStream out(&file);
out << editor->toPlainText();
file.close();
data.isModified = false;
data.lastKnownText = editor->toPlainText();
markModified(editor, false);
}
void MainWindow::saveAll() {
for (auto it = tabDataMap.begin(); it != tabDataMap.end(); ++it) {
QTextEdit *editor = it.key();
TabData &data = it.value();
if (!data.filePath.isEmpty()) {
saveFile(editor); // Saves to existing file path
} else {
tabWidget->setCurrentWidget(editor); // Brings the tab to front
saveFileAs(editor); // Prompt for location
}
}
}
void MainWindow::openRecentFile() {
QAction *action = qobject_cast<QAction *>(sender());
if (action) {
QString filePath = action->data().toString();
loadFile(filePath);
}
}
void MainWindow::updateRecentFilesMenu() {
for (int i = 0; i < 10; ++i) {
if (i < recentFiles.size()) {
QString text = QFileInfo(recentFiles[i]).fileName();
recentFileActions[i]->setText(text);
recentFileActions[i]->setData(recentFiles[i]);
recentFileActions[i]->setVisible(true);
} else {
recentFileActions[i]->setVisible(false);
}
}
}
void MainWindow::saveRecentFiles() {
QSettings settings(configName, "Decode");
settings.setValue("recentFiles", recentFiles);
}
void MainWindow::loadRecentFiles() {
QSettings settings(configName, "Decode");
recentFiles = settings.value("recentFiles").toStringList();
updateRecentFilesMenu();
}
// Session saving!
void MainWindow::saveSession() {
QSettings settings(configName, "Decode");
// Saving the current window state
settings.setValue("window/maximized", isMaximized());
settings.setValue("window/normalSize", normalGeometry().size());
settings.setValue("window/normalPos", normalGeometry().topLeft());
settings.setValue("window/geometry", saveGeometry());
settings.setValue("window/windowState", saveState());
if (settings.value("window/maximized", false).toBool()) {
showMaximized();
} else {
resize(settings.value("window/size", QSize(800, 600)).toSize());
move(settings.value("window/pos", QPoint(200, 200)).toPoint());
}
// UI element visibility
settings.setValue("ui/codecToolbarVisible", codecToolbar->isVisible());
settings.setValue("ui/mainToolbarVisible", mainToolbar->isVisible());
settings.setValue("ui/statusBarVisible", statusBar()->isVisible());
settings.setValue("restorePreviousSession", restorePreviousSession);
// Tab saving
settings.beginGroup("session");
QStringList paths;
QStringList contents;
QList<bool> modifiedFlags;
for (QTextEdit *editor : tabDataMap.keys()) {
const TabData &data = tabDataMap[editor];
paths.append(data.filePath);
contents.append(editor->toPlainText());
modifiedFlags.append(data.isModified);
}
settings.setValue("filePaths", paths);
settings.setValue("unsavedContents", contents);
settings.setValue("modifiedFlags", QVariant::fromValue(modifiedFlags));
settings.endGroup();
settings.sync();
}
// Session restoration!
void MainWindow::restoreSession() {
QSettings settings(configName, "Decode");
// Checks if session restoration is wanted, and loads the files if so
restorePreviousSession = settings.value("restorePreviousSession", true).toBool();
if (restorePreviousSession) {
// Loads the info from the config file
settings.beginGroup("session");
QStringList paths = settings.value("filePaths").toStringList();
QStringList contents = settings.value("unsavedContents").toStringList();
QList<QVariant> modifiedRaw = settings.value("modifiedFlags").toList();
settings.endGroup();
// Loops through to load each of the tabs
for (int i = 0; i < paths.size(); ++i) {
QString path = i < paths.size() ? paths[i] : "";
QString content = i < contents.size() ? contents[i] : "";
bool modified = (i < modifiedRaw.size()) ? modifiedRaw[i].toBool() : false;
newTab();
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (!editor) continue;
TabData &data = tabDataMap[editor];
if (!path.isEmpty()) {
data.filePath = path;
}
editor->blockSignals(true);
editor->setPlainText(content);
editor->blockSignals(false);
markModified(editor, modified);
if (!modified && !path.isEmpty()) {
// Load from disk if unchanged
loadFile(path);
}
}
}
// Saving Window position info, with logic to make sure that things don't get messed up if maximized.
if (settings.value("window/maximized", false).toBool()) {
resize(settings.value("window/normalSize", QSize(800, 600)).toSize());
move(settings.value("window/normalPos", QPoint(200, 200)).toPoint());
showMaximized();
} else {
resize(settings.value("window/normalSize", QSize(800, 600)).toSize());
move(settings.value("window/normalPos", QPoint(200, 200)).toPoint());
}
// Remember if the toolbars and statusbar is set to be visible or not.
codecToolbar->setVisible(settings.value("ui/codecToolbarVisible", true).toBool());
mainToolbar->setVisible(settings.value("ui/mainToolbarVisible", true).toBool());
statusBar()->setVisible(settings.value("ui/statusBarVisible", true).toBool());
// remembers the position of the toolbars
restoreGeometry(settings.value("window/geometry").toByteArray());
restoreState(settings.value("window/windowState").toByteArray());
// make sure that there is at least one tab
if (tabWidget->count() == 0) {
newTab();
}
}
void MainWindow::maybeSaveAndClose(QTextEdit *editor) {
if (!editor || !tabDataMap.contains(editor)) return;
if (tabDataMap[editor].isModified) {
auto response = QMessageBox::question(this, "Unsaved Changes",
"Do you want to save changes before closing?",
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
if (response == QMessageBox::Yes) {
saveFile(editor);
} else if (response == QMessageBox::Cancel) {
return;
}
}
int index = indexForEditor(editor);
tabDataMap.remove(editor);
tabWidget->removeTab(index);
editor->deleteLater();
if (tabWidget->count() == 0)
newTab();
}
void MainWindow::closeTab(QTextEdit *editor) {
// Kick back if no pointer is passed in
if (!editor) return;
// Trigger the function for closing and check with user if should save
maybeSaveAndClose(editor);
//open a new tab if no other tabs exist
if (tabWidget->count() == 0) {
newTab();
}
}
void MainWindow::undoLastChange() {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (!editor || !tabDataMap.contains(editor))
return;
auto &data = tabDataMap[editor];
if (!data.undoStack.isEmpty()) {
data.redoStack.push(editor->toPlainText());
QString last = data.undoStack.pop();
editor->blockSignals(true);
editor->setPlainText(last);
editor->blockSignals(false);
markModified(editor, true);
}
}
void MainWindow::redoLastChange() {
QTextEdit *editor = qobject_cast<QTextEdit *>(tabWidget->currentWidget());
if (!editor || !tabDataMap.contains(editor))
return;
auto &data = tabDataMap[editor];
if (!data.redoStack.isEmpty()) {
data.undoStack.push(editor->toPlainText());
QString next = data.redoStack.pop();
editor->blockSignals(true);
editor->setPlainText(next);
editor->blockSignals(false);
markModified(editor, true);
}
}
void MainWindow::closeEvent(QCloseEvent *event) {
saveSession();
QSettings settings(configName, "Decode");
QMainWindow::closeEvent(event);
}
void MainWindow::openSettingsDialog() {
SettingsDialog dialog(this);
dialog.setFont(currentFont);
dialog.setTabSize(currentTabSize);
dialog.setRestoreSession(restorePreviousSession);
dialog.setRSAPublicKeyPath(defaultRSAPublicKeyPath);
dialog.setRSAPrivateKeyPath(defaultRSAPrivateKeyPath);
connect(&dialog, &SettingsDialog::clearRecentFiles, this, &MainWindow::clearRecentFiles);
connect(&dialog, &SettingsDialog::resetUILayout, this, &MainWindow::resetUILayout);
if (dialog.exec() == QDialog::Accepted) {
QSettings settings(configName, "Decode");
settings.setValue("editor/font", dialog.getFont());
settings.setValue("editor/tabSize", dialog.getTabSize());
settings.setValue("editor/RSAPublicKeyPath", dialog.getRSAPublicKeyPath());
settings.setValue("editor/RSAPrivateKeyPath", dialog.getRSAPrivateKeyPath());
//settings.setValue("editor/restoreSession", dialog.shouldRestoreSession());
currentFont = dialog.getFont();
currentTabSize = dialog.getTabSize();
restorePreviousSession = dialog.shouldRestoreSession();
defaultRSAPublicKeyPath = dialog.getRSAPublicKeyPath();
defaultRSAPrivateKeyPath = dialog.getRSAPrivateKeyPath();
applyEditorSettings();
}
}
void MainWindow::applyEditorSettings() {
QSettings settings(configName, "Decode");
currentFont = settings.value("editor/font", QFont("Monospace", 10)).value<QFont>();
currentTabSize = settings.value("editor/tabSize", 4).toInt();
restorePreviousSession = settings.value("editor/restoreSession", true).toBool();
defaultRSAPublicKeyPath = settings.value("editor/RSAPublicKeyPath", "").toString();
defaultRSAPrivateKeyPath = settings.value("editor/RSAPrivateKeyPath", "").toString();
for (auto &tab : tabDataMap) {
if (tab.editor) {
tab.editor->setFont(currentFont);
QFontMetrics metrics(currentFont);
tab.editor->setTabStopDistance(currentTabSize * metrics.horizontalAdvance(' '));
}
}
}
void MainWindow::clearRecentFiles() {
QSettings settings(configName, "Decode");
recentFiles.clear();
updateRecentFilesMenu();
settings.remove("recentFiles");
}
void MainWindow::resetUILayout() {
QSettings settings(configName, "Decode");
settings.remove("geometry");
settings.remove("windowState");
settings.remove("mainToolbarVisible");
settings.remove("codecToolbarVisible");
settings.remove("statusBarVisible");
settings.remove("maximized");
settings.remove("editor/font");
settings.remove("editor/tabSize");
addToolBar(Qt::TopToolBarArea, mainToolbar);
addToolBar(Qt::TopToolBarArea, codecToolbar);
mainToolbar->show();
codecToolbar->show();
statusBar()->show();
restoreState(QByteArray());
resize(800, 600);
update();
currentFont = QFont("Monospace", 10);
currentTabSize = 4;
applyEditorSettings();
}
void MainWindow::setTabSize(int size) {
currentTabSize = size;
applyEditorSettings();
}
int MainWindow::getTabSize() const {
return currentTabSize;
}
void MainWindow::setRestoreSession(bool value) {
restorePreviousSession = value;
}
bool MainWindow::shouldRestoreSession() const {
return restorePreviousSession;
}
QFont MainWindow::getFont() const {
return currentFont;
}
void MainWindow::setFont(const QFont &font) {
currentFont = font;
applyEditorSettings();
}
void MainWindow::clearSession() {
QSettings settings(configName, "Decode");
settings.beginGroup("session");
settings.remove("");
settings.endGroup();
}
void MainWindow::showAboutDialog() {
QMessageBox::about(this, "About Decode",
"Decode v3.0\n"
"© 2025 Hellmark Programming Group\n\n"
"A simple cipher utility that helps make things more secure!");
}
int MainWindow::indexForEditor(QTextEdit *editor) const {
return tabWidget->indexOf(editor);
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
if (event->mimeData()->hasUrls() || event->mimeData()->hasText()) {
event->acceptProposedAction();
} else {
event->ignore();
}
}
void MainWindow::dropEvent(QDropEvent *event) {
if (event->mimeData()->hasUrls()) {
QList<QUrl> urls = event->mimeData()->urls();
for (const QUrl &url : urls) {
if (url.isLocalFile()) {
loadFile(url.toLocalFile());
}
}
event->acceptProposedAction();
} else if (event->mimeData()->hasText()) {
QTextEdit *editor = qobject_cast<QTextEdit *>(centralWidget()->focusWidget());
if (editor) {
editor->insertPlainText(event->mimeData()->text());
}
event->acceptProposedAction();
} else {
event->ignore();
}
}
QString MainWindow::promptForKeyFile(const QString &title, const QString &defaultPath)
{
QDialog dialog(this);
dialog.setWindowTitle(title);
QVBoxLayout *layout = new QVBoxLayout(&dialog);
QLineEdit *lineEdit = new QLineEdit(defaultPath);
QPushButton *browseButton = new QPushButton("Browse...");
QHBoxLayout *hbox = new QHBoxLayout;
hbox->addWidget(lineEdit);
hbox->addWidget(browseButton);
layout->addLayout(hbox);
connect(browseButton, &QPushButton::clicked, [&]() {
QString filePath = QFileDialog::getOpenFileName(&dialog, "Select Key File", lineEdit->text());
if (!filePath.isEmpty()) lineEdit->setText(filePath);
});
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
layout->addWidget(buttons);
connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
return dialog.exec() == QDialog::Accepted ? lineEdit->text() : QString();
}