-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplitWindow.cpp
More file actions
1805 lines (1596 loc) · 65.8 KB
/
SplitWindow.cpp
File metadata and controls
1805 lines (1596 loc) · 65.8 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 "AppSettings.h"
#include "DomPatch.h"
#include "MyWebEnginePage.h"
#include "SplitFrameWidget.h"
#include "SplitterDoubleClickFilter.h"
#include "SplitWindow.h"
#include "UpdateChecker.h"
#include "UpdateDialog.h"
#include "Utils.h"
#include "version.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <QAction>
#include <QActionGroup>
#include <QApplication>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDebug>
#include <QDesktopServices>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QFrame>
#include <QGridLayout>
#include <QGuiApplication>
#include <QInputDialog>
#include <QKeySequence>
#include <QLabel>
#include <QLineEdit>
#include <QMenuBar>
#include <QMessageBox>
#include <QPointer>
#include <QScreen>
#include <QScrollArea>
#include <QSplitter>
#include <QStandardPaths>
#include <QTextBrowser>
#include <QTimer>
#include <QUrl>
#include <QVariant>
#include <QUuid>
#include <QVBoxLayout>
#include <QWebEnginePage>
#include <QWebEngineProfile>
#include <QWebEngineView>
bool DEBUG_SHOW_WINDOW_ID = 0;
// Visual feedback constants for the frame addition flash effect
namespace {
constexpr int FLASH_HANDLE_WIDTH_INCREASE = 4; // pixels to increase splitter handle width
constexpr int FLASH_DURATION_MS = 150; // milliseconds to show the flash
// About dialog dimensions
constexpr int ABOUT_DIALOG_MIN_WIDTH = 400; // minimum width for About dialog
constexpr int ABOUT_DIALOG_MAX_HEIGHT = 300; // maximum height for text browser in About dialog
}
SplitWindow::SplitWindow(const QString &windowId, bool isIncognito, QWidget *parent)
: QMainWindow(parent), windowId_(windowId), isIncognito_(isIncognito) {
setWindowTitle(QCoreApplication::applicationName());
resize(800, 600);
AppSettings settings;
connect(qApp, &QApplication::focusChanged, this, [this](QWidget *, QWidget *now) {
QWidget *w = now;
while (w) {
if (auto *frame = qobject_cast<SplitFrameWidget *>(w)) {
if (frame->window() == this) lastFocusedFrame_ = frame;
return;
}
w = w->parentWidget();
}
});
// File menu: New Window (Cmd/Ctrl+N), New Incognito Window (Shift+Cmd/Ctrl+N), New Frame (Cmd/Ctrl+T)
auto *fileMenu = menuBar()->addMenu(tr("File"));
QAction *newWindowAction = fileMenu->addAction(tr("New Window"));
newWindowAction->setShortcut(QKeySequence::New);
connect(newWindowAction, &QAction::triggered, this, [](bool){ createAndShowWindow(); });
QAction *newIncognitoWindowAction = fileMenu->addAction(tr("New Incognito Window"));
newIncognitoWindowAction->setShortcut(QKeySequence(Qt::SHIFT | Qt::CTRL | Qt::Key_N));
connect(newIncognitoWindowAction, &QAction::triggered, this, [](bool){ createAndShowIncognitoWindow(); });
QAction *newFrameAction = fileMenu->addAction(tr("New Frame"));
newFrameAction->setShortcut(QKeySequence::AddTab); // Command-T on macOS, Ctrl+T elsewhere
connect(newFrameAction, &QAction::triggered, this, &SplitWindow::onNewFrameShortcut);
// No global toolbar; per-frame + / - buttons control sections.
// Load the profile for this window
if (isIncognito_) {
// Incognito windows use a new off-the-record profile
currentProfileName_ = QString(); // No profile name for Incognito
profile_ = createIncognitoProfile();
qDebug() << "SplitWindow: using Incognito profile" << profile_
<< "offTheRecord=" << profile_->isOffTheRecord();
} else if (!windowId_.isEmpty()) {
// Normal window with saved state: load profile from settings
AppSettings s;
GroupScope _gs(s, QStringLiteral("windows/%1").arg(windowId_));
currentProfileName_ = s->value("profileName", currentProfileName()).toString();
profile_ = getProfileByName(currentProfileName_);
qDebug() << "SplitWindow: using profile" << currentProfileName_ << profile_
<< "storage=" << profile_->persistentStoragePath();
} else {
// New normal window: use current global profile
currentProfileName_ = currentProfileName();
profile_ = getProfileByName(currentProfileName_);
qDebug() << "SplitWindow: using profile" << currentProfileName_ << profile_
<< "storage=" << profile_->persistentStoragePath();
}
// (window geometry/state restored later after UI is built)
// add a simple View menu with a helper to set the window height to the
// screen available height (preserves width and x position)
auto *viewMenu = menuBar()->addMenu(tr("View"));
QAction *setHeightAction = viewMenu->addAction(tr("Set height to screen"));
connect(setHeightAction, &QAction::triggered, this, &SplitWindow::setHeightToScreen);
QAction *toggleDevToolsAction = viewMenu->addAction(tr("Toggle DevTools"));
toggleDevToolsAction->setShortcut(QKeySequence(Qt::Key_F12));
connect(toggleDevToolsAction, &QAction::triggered, this, &SplitWindow::toggleDevToolsForFocusedFrame);
QAction *reloadFrameAction = viewMenu->addAction(tr("Reload Frame"));
reloadFrameAction->setShortcut(QKeySequence::Refresh);
reloadFrameAction->setShortcutContext(Qt::WindowShortcut);
connect(reloadFrameAction, &QAction::triggered, this, &SplitWindow::reloadFocusedFrame);
QAction *reloadBypassAction = viewMenu->addAction(tr("Reload Frame (Bypass Cache)"));
reloadBypassAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_R));
reloadBypassAction->setShortcutContext(Qt::WindowShortcut);
connect(reloadBypassAction, &QAction::triggered, this, &SplitWindow::reloadFocusedFrameBypassingCache);
viewMenu->addSeparator();
QAction *increaseScaleAction = viewMenu->addAction(tr("Increase Frame Scale"));
connect(increaseScaleAction, &QAction::triggered, this, &SplitWindow::increaseFocusedFrameScale);
QAction *decreaseScaleAction = viewMenu->addAction(tr("Decrease Frame Scale"));
connect(decreaseScaleAction, &QAction::triggered, this, &SplitWindow::decreaseFocusedFrameScale);
QAction *resetScaleAction = viewMenu->addAction(tr("Reset Frame Scale"));
connect(resetScaleAction, &QAction::triggered, this, &SplitWindow::resetFocusedFrameScale);
// Always-on-top toggle
QAction *alwaysOnTopAction = viewMenu->addAction(tr("Always on Top"));
alwaysOnTopAction->setCheckable(true);
// read persisted value (default: false)
{
const bool on = settings->value("alwaysOnTop", false).toBool();
alwaysOnTopAction->setChecked(on);
// apply the window flag; setWindowFlag requires a show() to take effect on some platforms
setWindowFlag(Qt::WindowStaysOnTopHint, on);
if (on) show();
}
connect(alwaysOnTopAction, &QAction::toggled, this, [this](bool checked){
setWindowFlag(Qt::WindowStaysOnTopHint, checked);
if (checked) show();
AppSettings s;
s->setValue("alwaysOnTop", checked);
});
// Layout menu: Grid, Stack Vertically, Stack Horizontally
auto *layoutMenu = menuBar()->addMenu(tr("Layout"));
QActionGroup *layoutGroup = new QActionGroup(this);
layoutGroup->setExclusive(true);
QAction *gridAction = layoutMenu->addAction(tr("Grid"));
gridAction->setCheckable(true);
layoutGroup->addAction(gridAction);
QAction *verticalAction = layoutMenu->addAction(tr("Stack Vertically"));
verticalAction->setCheckable(true);
layoutGroup->addAction(verticalAction);
QAction *horizontalAction = layoutMenu->addAction(tr("Stack Horizontally"));
horizontalAction->setCheckable(true);
layoutGroup->addAction(horizontalAction);
// restore persisted layout choice
int storedMode = settings->value("layoutMode", (int)Vertical).toInt();
layoutMode_ = (LayoutMode)storedMode;
switch (layoutMode_) {
case Grid: gridAction->setChecked(true); break;
case Horizontal: horizontalAction->setChecked(true); break;
case Vertical: default: verticalAction->setChecked(true); break;
}
connect(gridAction, &QAction::triggered, this, [this]() { setLayoutMode(Grid); });
connect(verticalAction, &QAction::triggered, this, [this]() { setLayoutMode(Vertical); });
connect(horizontalAction, &QAction::triggered, this, [this]() { setLayoutMode(Horizontal); });
// Tools menu: DOM patches manager
auto *toolsMenu = menuBar()->addMenu(tr("Tools"));
QAction *domPatchesAction = toolsMenu->addAction(tr("DOM Patches"));
connect(domPatchesAction, &QAction::triggered, this, &SplitWindow::showDomPatchesManager);
// Profiles menu: manage browser profiles (not available in Incognito mode)
if (!isIncognito_) {
profilesMenu_ = menuBar()->addMenu(tr("Profiles"));
QAction *newProfileAction = profilesMenu_->addAction(tr("New Profile..."));
connect(newProfileAction, &QAction::triggered, this, &SplitWindow::createNewProfile);
QAction *renameProfileAction = profilesMenu_->addAction(tr("Rename Profile..."));
connect(renameProfileAction, &QAction::triggered, this, &SplitWindow::renameCurrentProfile);
QAction *deleteProfileAction = profilesMenu_->addAction(tr("Delete Profile..."));
connect(deleteProfileAction, &QAction::triggered, this, &SplitWindow::deleteSelectedProfile);
profilesMenu_->addSeparator();
#ifndef NDEBUG
// Debug builds only: Add menu item to open profiles folder
QAction *openProfilesFolderAction = profilesMenu_->addAction(tr("Open Profiles Folder"));
connect(openProfilesFolderAction, &QAction::triggered, this, [this]() {
const QString dataRoot = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
const QString profilesDir = dataRoot + QStringLiteral("/profiles");
// Ensure the profiles directory exists before trying to open it
QDir().mkpath(profilesDir);
QDesktopServices::openUrl(QUrl::fromLocalFile(profilesDir));
});
profilesMenu_->addSeparator();
#endif
// Profile list will be populated by updateProfilesMenu()
}
// Window menu: per-macOS convention
windowMenu_ = menuBar()->addMenu(tr("Window"));
// Add standard close/minimize actions
QAction *minimizeAct = windowMenu_->addAction(tr("Minimize"));
minimizeAct->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_M));
connect(minimizeAct, &QAction::triggered, this, &QWidget::showMinimized);
QAction *closeAct = windowMenu_->addAction(tr("Close Window"));
closeAct->setShortcut(QKeySequence::Close);
connect(closeAct, &QAction::triggered, this, &SplitWindow::onCloseShortcut);
windowMenu_->addSeparator();
// Help menu: Check for Updates and About dialog
auto *helpMenu = menuBar()->addMenu(tr("Help"));
QAction *checkUpdatesAction = helpMenu->addAction(tr("Check for Updates..."));
connect(checkUpdatesAction, &QAction::triggered, this, &SplitWindow::checkForUpdates);
helpMenu->addSeparator();
QAction *aboutAction = helpMenu->addAction(tr("About Phraims"));
connect(aboutAction, &QAction::triggered, this, &SplitWindow::showAboutDialog);
// central scroll area to allow many sections
auto *scroll = new QScrollArea();
scroll->setWidgetResizable(true);
central_ = new QWidget();
scroll->setWidget(central_);
setCentralWidget(scroll);
layout_ = new QVBoxLayout(central_);
layout_->setContentsMargins(4, 4, 4, 4);
layout_->setSpacing(6);
auto loadFrameState = [this](const QStringList &addresses, const QVariantList &scales) {
frames_.clear();
if (addresses.isEmpty()) {
frames_.push_back(FrameState());
} else {
frames_.reserve(addresses.size());
for (const QString &addr : addresses) {
FrameState state;
state.address = addr;
frames_.push_back(state);
}
}
if (frames_.empty()) frames_.push_back(FrameState());
for (int i = 0; i < (int)frames_.size(); ++i) {
double value = (i < scales.size()) ? scales[i].toDouble() : 1.0;
frames_[i].scale = std::clamp(value, SplitFrameWidget::kMinScaleFactor, SplitFrameWidget::kMaxScaleFactor);
}
};
// load persisted addresses (per-window if windowId_ present and not Incognito, otherwise global)
if (isIncognito_) {
// Incognito windows always start with a single empty frame
loadFrameState(QStringList(), QVariantList());
} else if (!windowId_.isEmpty()) {
AppSettings s;
{
GroupScope _gs(s, QStringLiteral("windows/%1").arg(windowId_));
const QStringList savedAddresses = s->value("addresses").toStringList();
const QVariantList savedScales = s->value("frameScales").toList();
loadFrameState(savedAddresses, savedScales);
layoutMode_ = (LayoutMode)s->value("layoutMode", (int)layoutMode_).toInt();
}
} else {
const QStringList savedAddresses = settings->value("addresses").toStringList();
const QVariantList savedScales = settings->value("frameScales").toList();
loadFrameState(savedAddresses, savedScales);
}
// build initial UI
rebuildSections((int)frames_.size());
// restore splitter sizes only once at startup (subsequent layout
// selections/rebuilds should reset splitters to defaults)
// Incognito windows skip splitter size restoration
if (!isIncognito_) {
if (!windowId_.isEmpty()) {
restoreSplitterSizes(QStringLiteral("windows/%1/splitterSizes").arg(windowId_));
} else {
restoreSplitterSizes();
}
}
restoredOnStartup_ = true;
// restore saved window geometry and window state (position/size/state)
// Incognito windows skip geometry restoration
if (!isIncognito_) {
if (!windowId_.isEmpty()) {
AppSettings s;
{
GroupScope _gs(s, QStringLiteral("windows/%1").arg(windowId_));
const QByteArray savedGeom = s->value("windowGeometry").toByteArray();
if (!savedGeom.isEmpty()) restoreGeometry(savedGeom);
const QByteArray savedState = s->value("windowState").toByteArray();
if (!savedState.isEmpty()) restoreState(savedState);
}
} else {
const QByteArray savedGeom = settings->value("windowGeometry").toByteArray();
if (!savedGeom.isEmpty()) restoreGeometry(savedGeom);
const QByteArray savedState = settings->value("windowState").toByteArray();
if (!savedState.isEmpty()) restoreState(savedState);
}
}
// Initialize the Profiles menu with the current profile list
updateProfilesMenu();
}
void SplitWindow::savePersistentStateToSettings() {
// Incognito windows should never persist state
if (isIncognito_) {
qDebug() << "savePersistentStateToSettings: skipping save for Incognito window";
return;
}
AppSettings s;
QString id = windowId_;
if (id.isEmpty()) id = QUuid::createUuid().toString();
qDebug() << "savePersistentStateToSettings: saving window id=" << id << " addresses.count=" << frames_.size() << " layoutMode=" << (int)layoutMode_ << " profile=" << currentProfileName_;
{
GroupScope _gs(s, QStringLiteral("windows/%1").arg(id));
QStringList addressList;
QVariantList scaleList;
for (const auto &state : frames_) {
addressList << state.address;
scaleList << state.scale;
}
s->setValue("addresses", addressList);
s->setValue("frameScales", scaleList);
s->setValue("profileName", currentProfileName_);
s->setValue("layoutMode", (int)layoutMode_);
s->setValue("windowGeometry", saveGeometry());
s->setValue("windowState", saveState());
}
s->sync();
// persist splitter sizes under windows/<id>/splitterSizes/<index>
saveCurrentSplitterSizes(QStringLiteral("windows/%1/splitterSizes").arg(id));
}
void SplitWindow::resetToSingleEmptySection() {
frames_.clear();
frames_.push_back(FrameState());
rebuildSections(1);
// Do not persist immediately; keep in-memory until user changes or window closes.
// After rebuilding, focus the address field so the user can start typing
// immediately. Use a queued invoke so focus is set after layout/stacking
// completes.
QMetaObject::invokeMethod(this, "focusFirstAddress", Qt::QueuedConnection);
}
void SplitWindow::refreshWindowMenu() { updateWindowMenu(); }
void SplitWindow::focusFirstAddress() {
if (!central_) return;
// Find the first SplitFrameWidget and its QLineEdit child
SplitFrameWidget *frame = central_->findChild<SplitFrameWidget *>();
if (!frame) return;
QLineEdit *le = frame->findChild<QLineEdit *>();
if (!le) return;
le->setFocus(Qt::OtherFocusReason);
// select all so typing replaces existing content
le->selectAll();
}
void SplitWindow::updateWindowTitle() {
// Determine 1-based index in g_windows
int idx = 0;
for (size_t i = 0; i < g_windows.size(); ++i) {
if (g_windows[i] == this) { idx = (int)i + 1; break; }
}
const int count = (int)frames_.size();
QString profileDisplay = isIncognito_ ? QStringLiteral("Incognito") : currentProfileName_;
QString title = QStringLiteral("Group %1 (%2) - %3").arg(idx).arg(count).arg(profileDisplay);
if (DEBUG_SHOW_WINDOW_ID && !windowId_.isEmpty()) {
title += QStringLiteral(" [%1]").arg(windowId_);
}
setWindowTitle(title);
}
void SplitWindow::setFirstFrameAddress(const QString &address) {
SplitFrameWidget *frame = central_ ? central_->findChild<SplitFrameWidget *>() : nullptr;
if (frame) frame->setAddress(address);
}
void SplitWindow::rebuildSections(int n) {
// Ensure frames_ vector matches requested size, preserving existing values.
if ((int)frames_.size() != n) {
frames_.resize(n);
}
// clamp n
if (n < 1) n = 1;
// clear existing items
QLayoutItem *child;
while ((child = layout_->takeAt(0)) != nullptr) {
if (auto *w = child->widget()) {
w->hide();
w->deleteLater();
}
delete child;
}
// old splitters are going away; clear tracking vector so we start fresh
currentSplitters_.clear();
// create n sections according to the selected layout mode.
QWidget *container = nullptr;
if (layoutMode_ == Vertical || layoutMode_ == Horizontal) {
QSplitter *split = new QSplitter(layoutMode_ == Vertical ? Qt::Vertical : Qt::Horizontal);
// track this splitter for state persistence
currentSplitters_.push_back(split);
for (int i = 0; i < n; ++i) {
auto *frame = new SplitFrameWidget(i);
// logicalIndex property used for mapping frame -> frames_ index
frame->setProperty("logicalIndex", i);
frame->setProfile(profile_);
frame->setScaleFactor(frames_[i].scale);
frame->setAddress(frames_[i].address);
connect(frame, &SplitFrameWidget::plusClicked, this, &SplitWindow::onPlusFromFrame);
connect(frame, &SplitFrameWidget::minusClicked, this, &SplitWindow::onMinusFromFrame);
connect(frame, &SplitFrameWidget::addressEdited, this, &SplitWindow::onAddressEdited);
connect(frame, &SplitFrameWidget::upClicked, this, &SplitWindow::onUpFromFrame);
connect(frame, &SplitFrameWidget::downClicked, this, &SplitWindow::onDownFromFrame);
connect(frame, &SplitFrameWidget::devToolsRequested, this, &SplitWindow::onFrameDevToolsRequested);
connect(frame, &SplitFrameWidget::translateRequested, this, &SplitWindow::onFrameTranslateRequested);
connect(frame, &SplitFrameWidget::openLinkInNewFrameRequested, this, &SplitWindow::onFrameOpenLinkInNewFrameRequested);
connect(frame, &SplitFrameWidget::scaleChanged, this, &SplitWindow::onFrameScaleChanged);
connect(frame, &SplitFrameWidget::interactionOccurred, this, &SplitWindow::onFrameInteraction);
connect(frame, &QObject::destroyed, this, [this, frame]() {
if (lastFocusedFrame_ == frame) lastFocusedFrame_ = nullptr;
});
updateFrameButtonStates(frame, n);
qDebug() << "";
split->addWidget(frame);
}
// distribute sizes evenly across the children so switching layouts
// starts with a balanced view
if (n > 0) {
QList<int> sizes;
for (int i = 0; i < n; ++i) sizes << 1;
split->setSizes(sizes);
}
// Install double-click handler for equal sizing after widgets/handles exist
{
SplitterDoubleClickFilter *filter = new SplitterDoubleClickFilter(split, this);
connect(filter, &SplitterDoubleClickFilter::splitterResized, this, &SplitWindow::onSplitterDoubleClickResized);
}
container = split;
} else { // Grid mode: nested splitters for resizable grid
// Create a vertical splitter containing one horizontal splitter per row.
QSplitter *outer = new QSplitter(Qt::Vertical);
currentSplitters_.push_back(outer);
int rows = (int)std::ceil(std::sqrt((double)n));
int cols = (n + rows - 1) / rows;
int idx = 0;
for (int r = 0; r < rows; ++r) {
// how many items in this row
int itemsInRow = std::min(cols, n - idx);
if (itemsInRow <= 0) break;
QSplitter *rowSplit = new QSplitter(Qt::Horizontal);
currentSplitters_.push_back(rowSplit);
for (int c = 0; c < itemsInRow; ++c) {
auto *frame = new SplitFrameWidget(idx);
// logicalIndex property used for mapping frame -> frames_ index
frame->setProperty("logicalIndex", idx);
frame->setProfile(profile_);
frame->setScaleFactor(frames_[idx].scale);
frame->setAddress(frames_[idx].address);
connect(frame, &SplitFrameWidget::plusClicked, this, &SplitWindow::onPlusFromFrame);
connect(frame, &SplitFrameWidget::minusClicked, this, &SplitWindow::onMinusFromFrame);
connect(frame, &SplitFrameWidget::addressEdited, this, &SplitWindow::onAddressEdited);
connect(frame, &SplitFrameWidget::upClicked, this, &SplitWindow::onUpFromFrame);
connect(frame, &SplitFrameWidget::downClicked, this, &SplitWindow::onDownFromFrame);
connect(frame, &SplitFrameWidget::devToolsRequested, this, &SplitWindow::onFrameDevToolsRequested);
connect(frame, &SplitFrameWidget::translateRequested, this, &SplitWindow::onFrameTranslateRequested);
connect(frame, &SplitFrameWidget::openLinkInNewFrameRequested, this, &SplitWindow::onFrameOpenLinkInNewFrameRequested);
connect(frame, &SplitFrameWidget::scaleChanged, this, &SplitWindow::onFrameScaleChanged);
connect(frame, &SplitFrameWidget::interactionOccurred, this, &SplitWindow::onFrameInteraction);
connect(frame, &QObject::destroyed, this, [this, frame]() {
if (lastFocusedFrame_ == frame) lastFocusedFrame_ = nullptr;
});
updateFrameButtonStates(frame, n);
qDebug() << "";
rowSplit->addWidget(frame);
++idx;
}
// evenly distribute columns in this row
if (itemsInRow > 0) {
QList<int> colSizes;
for (int i = 0; i < itemsInRow; ++i) colSizes << 1;
rowSplit->setSizes(colSizes);
// Install rowFilter now that the rowSplit and its handles exist
{
SplitterDoubleClickFilter *rowFilter = new SplitterDoubleClickFilter(rowSplit, this);
connect(rowFilter, &SplitterDoubleClickFilter::splitterResized, this, &SplitWindow::onSplitterDoubleClickResized);
}
}
outer->addWidget(rowSplit);
}
// evenly distribute rows in the outer splitter
int actualRows = outer->count();
if (actualRows > 0) {
QList<int> rowSizes;
for (int i = 0; i < actualRows; ++i) rowSizes << 1;
outer->setSizes(rowSizes);
}
// Install outerFilter now that outer and its handles exist
{
SplitterDoubleClickFilter *outerFilter = new SplitterDoubleClickFilter(outer, this);
connect(outerFilter, &SplitterDoubleClickFilter::splitterResized, this, &SplitWindow::onSplitterDoubleClickResized);
}
container = outer;
}
if (container) {
layout_->addWidget(container, 1);
}
// add a final stretch with zero so that widgets entirely control spacing
layout_->addStretch(0);
central_->update();
if (!lastFocusedFrame_) lastFocusedFrame_ = firstFrameWidget();
// Update this window's title now that the number of frames may have changed
// and ensure the Window menus across the app reflect the new title.
updateWindowTitle();
rebuildAllWindowMenus();
}
void SplitWindow::toggleDevToolsForFocusedFrame() {
// If the shared DevTools view is open, hide it. Otherwise attach it to
// the focused frame's page (or the first frame) and show it.
if (sharedDevToolsView_ && sharedDevToolsView_->isVisible()) {
sharedDevToolsView_->hide();
return;
}
SplitFrameWidget *target = focusedFrameOrFirst();
if (target) {
QWebEnginePage *p = target->page();
if (p) {
createAndAttachSharedDevToolsForPage(p);
if (sharedDevToolsView_) {
sharedDevToolsView_->show();
sharedDevToolsView_->raise();
sharedDevToolsView_->activateWindow();
}
}
}
}
void SplitWindow::onNewFrameShortcut() {
// Find the currently focused frame (similar to toggleDevToolsForFocusedFrame)
SplitFrameWidget *target = focusedFrameOrFirst();
if (!target) {
qDebug() << "onNewFrameShortcut: no target frame found";
return;
}
const int pos = frameIndexFor(target);
if (pos < 0) {
qDebug() << "onNewFrameShortcut: target has no logicalIndex property";
return;
}
// Try surgical addition first (works for Vertical/Horizontal modes)
if (addSingleFrame(pos)) {
// Provide a visual cue by briefly flashing the divider handle
if (!currentSplitters_.empty()) {
for (QSplitter *splitter : currentSplitters_) {
if (!splitter) continue;
QPointer<QSplitter> splitterGuard(splitter);
QTimer::singleShot(0, this, [splitterGuard]() {
if (!splitterGuard) return;
const int origWidth = splitterGuard->handleWidth();
splitterGuard->setHandleWidth(origWidth + FLASH_HANDLE_WIDTH_INCREASE);
QTimer::singleShot(FLASH_DURATION_MS, [splitterGuard, origWidth]() {
if (splitterGuard) {
splitterGuard->setHandleWidth(origWidth);
}
});
});
}
}
qDebug() << "onNewFrameShortcut: added new frame after position" << pos << "(surgical)";
return;
}
// Fall back to rebuildSections for Grid mode
frames_.insert(frames_.begin() + pos + 1, FrameState());
persistGlobalFrameState();
rebuildSections((int)frames_.size());
// Provide a visual cue by briefly flashing the divider handle
if (!currentSplitters_.empty()) {
for (QSplitter *splitter : currentSplitters_) {
if (!splitter) continue;
QPointer<QSplitter> splitterGuard(splitter);
QTimer::singleShot(0, this, [splitterGuard]() {
if (!splitterGuard) return;
const int origWidth = splitterGuard->handleWidth();
splitterGuard->setHandleWidth(origWidth + FLASH_HANDLE_WIDTH_INCREASE);
QTimer::singleShot(FLASH_DURATION_MS, [splitterGuard, origWidth]() {
if (splitterGuard) {
splitterGuard->setHandleWidth(origWidth);
}
});
});
}
}
qDebug() << "onNewFrameShortcut: added new frame after position" << pos << "(rebuild)";
}
void SplitWindow::reloadFocusedFrame() {
SplitFrameWidget *target = focusedFrameOrFirst();
if (!target) return;
target->reload(false);
}
void SplitWindow::reloadFocusedFrameBypassingCache() {
SplitFrameWidget *target = focusedFrameOrFirst();
if (!target) return;
target->reload(true);
}
void SplitWindow::onPlusFromFrame(SplitFrameWidget *who) {
// use logicalIndex property assigned during rebuildSections
const QVariant v = who->property("logicalIndex");
if (!v.isValid()) return;
int pos = v.toInt();
// Try surgical addition first (works for Vertical/Horizontal modes)
if (addSingleFrame(pos)) {
return;
}
// Fall back to rebuildSections for Grid mode
frames_.insert(frames_.begin() + pos + 1, FrameState());
persistGlobalFrameState();
rebuildSections((int)frames_.size());
// Focus the newly added frame's address bar
const int newFrameIndex = pos + 1;
QMetaObject::invokeMethod(this, [this, newFrameIndex]() {
if (!central_) return;
const QList<SplitFrameWidget *> frames = central_->findChildren<SplitFrameWidget *>();
for (SplitFrameWidget *frame : frames) {
if (frame->property("logicalIndex").toInt() == newFrameIndex) {
frame->focusAddress();
break;
}
}
}, Qt::QueuedConnection);
}
void SplitWindow::onUpFromFrame(SplitFrameWidget *who) {
// move this frame up (towards index 0)
const QVariant v = who->property("logicalIndex");
if (!v.isValid()) return;
int pos = v.toInt();
if (pos <= 0) return; // already at top or not found
std::swap(frames_[pos], frames_[pos - 1]);
persistGlobalFrameState();
rebuildSections((int)frames_.size());
}
void SplitWindow::onDownFromFrame(SplitFrameWidget *who) {
// move this frame down (towards larger indices)
const QVariant v = who->property("logicalIndex");
if (!v.isValid()) return;
int pos = v.toInt();
if (pos < 0 || pos >= (int)frames_.size() - 1) return; // at bottom or not found
std::swap(frames_[pos], frames_[pos + 1]);
persistGlobalFrameState();
rebuildSections((int)frames_.size());
}
void SplitWindow::setLayoutMode(SplitWindow::LayoutMode m) {
AppSettings settings;
// If the user re-selects the already-selected layout, treat that as a
// request to reset splitters to their default sizes. Clear any saved
// sizes for this layout and rebuild without saving the current sizes.
if (m == layoutMode_) {
const QString base = QStringLiteral("splitterSizes/%1").arg(layoutModeKey(layoutMode_));
settings->remove(base);
// rebuild so splitters are reset to defaults
rebuildSections((int)frames_.size());
return;
}
// Note: we do not save splitter sizes during runtime; sizes are only
// persisted on application exit. When switching layouts we clear any
// saved sizes for the target layout so the new layout starts with
// default splitter positions.
// Remove any previously-saved sizes for the new target layout so that
// switching layouts starts with default splitter positions rather than
// restoring an older saved configuration for that layout.
{
const QString targetBase = QStringLiteral("splitterSizes/%1").arg(layoutModeKey(m));
settings->remove(targetBase);
}
// Apply the new layout mode and persist it.
layoutMode_ = m;
settings->setValue("layoutMode", (int)layoutMode_);
// Rebuild UI for the new layout (splitter sizes are only restored at startup)
rebuildSections((int)frames_.size());
}
void SplitWindow::setHeightToScreen() {
QScreen *screen = QGuiApplication::primaryScreen();
if (!screen) return;
const QRect avail = screen->availableGeometry();
// preserve current x and width, set y to top of available area and
// height to available height
const QRect geom = geometry();
const int x = geom.x();
const int w = geom.width();
setGeometry(x, avail.y(), w, avail.height());
}
void SplitWindow::onMinusFromFrame(SplitFrameWidget *who) {
if (frames_.size() <= 1) return; // shouldn't remove last
const QVariant v = who->property("logicalIndex");
if (!v.isValid()) return;
int pos = v.toInt();
if (pos < 0) return;
// confirm with the user before removing
const QMessageBox::StandardButton reply = QMessageBox::question(
this, tr("Remove section"), tr("Remove this section?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (reply != QMessageBox::Yes) return;
// Remove the frame surgically without rebuilding all frames
removeSingleFrame(who);
}
void SplitWindow::removeSingleFrame(SplitFrameWidget *frameToRemove) {
if (!frameToRemove) return;
const QVariant v = frameToRemove->property("logicalIndex");
if (!v.isValid()) {
qWarning() << "removeSingleFrame: frame has no logicalIndex property";
return;
}
const int removedIndex = v.toInt();
if (removedIndex < 0 || removedIndex >= (int)frames_.size()) {
qWarning() << "removeSingleFrame: invalid frame index" << removedIndex
<< "for frames_.size()=" << frames_.size();
return;
}
// Remove the frame from the data model
frames_.erase(frames_.begin() + removedIndex);
// Persist the updated frame state
persistGlobalFrameState();
// Find all remaining frames and validate their logical indices
const QList<SplitFrameWidget *> allFrames = central_->findChildren<SplitFrameWidget *>();
QList<SplitFrameWidget *> remainingFrames;
for (SplitFrameWidget *frame : allFrames) {
if (frame != frameToRemove) {
const QVariant v = frame->property("logicalIndex");
if (v.isValid()) {
remainingFrames.append(frame);
} else {
qWarning() << "removeSingleFrame: found frame without valid logicalIndex, skipping";
}
}
}
// Sort remaining frames by their current logical index
std::sort(remainingFrames.begin(), remainingFrames.end(), [](SplitFrameWidget *a, SplitFrameWidget *b) {
// At this point all frames are validated to have valid logicalIndex properties
const int idxA = a->property("logicalIndex").toInt();
const int idxB = b->property("logicalIndex").toInt();
return idxA < idxB;
});
// Update logical indices for frames after the removed one
for (SplitFrameWidget *frame : remainingFrames) {
const int oldIndex = frame->property("logicalIndex").toInt();
// If this frame was after the removed one, decrement its index
if (oldIndex > removedIndex) {
frame->setProperty("logicalIndex", oldIndex - 1);
}
}
// Update button states for all remaining frames
const int totalFrames = (int)frames_.size();
for (SplitFrameWidget *frame : remainingFrames) {
updateFrameButtonStates(frame, totalFrames);
}
// Remove the frame widget from the UI
frameToRemove->hide();
frameToRemove->deleteLater();
// Clear the last focused frame if it's being removed
if (lastFocusedFrame_ == frameToRemove) {
lastFocusedFrame_ = nullptr;
}
// Update window title and menus
updateWindowTitle();
rebuildAllWindowMenus();
}
void SplitWindow::updateFrameButtonStates(SplitFrameWidget *frame, int totalFrames) {
if (!frame) return;
const QVariant v = frame->property("logicalIndex");
if (!v.isValid()) return;
const int idx = v.toInt();
frame->setMinusEnabled(totalFrames > 1);
frame->setUpEnabled(idx > 0);
frame->setDownEnabled(idx < totalFrames - 1);
}
bool SplitWindow::addSingleFrame(int afterIndex) {
// Only support surgical addition for Vertical/Horizontal modes
// Grid mode requires rebuildSections due to nested splitter complexity
if (layoutMode_ == Grid) {
return false;
}
// Verify we have a single splitter (Vertical/Horizontal mode)
if (currentSplitters_.empty() || !currentSplitters_[0]) {
qWarning() << "addSingleFrame: no splitter available";
return false;
}
QSplitter *splitter = currentSplitters_[0];
const int insertPosition = afterIndex + 1;
// Insert frame data into the model
frames_.insert(frames_.begin() + insertPosition, FrameState());
persistGlobalFrameState();
// Create the new frame widget
auto *newFrame = new SplitFrameWidget(insertPosition);
newFrame->setProperty("logicalIndex", insertPosition);
newFrame->setProfile(profile_);
newFrame->setScaleFactor(frames_[insertPosition].scale);
newFrame->setAddress(frames_[insertPosition].address);
// Connect all signals
connect(newFrame, &SplitFrameWidget::plusClicked, this, &SplitWindow::onPlusFromFrame);
connect(newFrame, &SplitFrameWidget::minusClicked, this, &SplitWindow::onMinusFromFrame);
connect(newFrame, &SplitFrameWidget::addressEdited, this, &SplitWindow::onAddressEdited);
connect(newFrame, &SplitFrameWidget::upClicked, this, &SplitWindow::onUpFromFrame);
connect(newFrame, &SplitFrameWidget::downClicked, this, &SplitWindow::onDownFromFrame);
connect(newFrame, &SplitFrameWidget::devToolsRequested, this, &SplitWindow::onFrameDevToolsRequested);
connect(newFrame, &SplitFrameWidget::translateRequested, this, &SplitWindow::onFrameTranslateRequested);
connect(newFrame, &SplitFrameWidget::openLinkInNewFrameRequested, this, &SplitWindow::onFrameOpenLinkInNewFrameRequested);
connect(newFrame, &SplitFrameWidget::scaleChanged, this, &SplitWindow::onFrameScaleChanged);
connect(newFrame, &SplitFrameWidget::interactionOccurred, this, &SplitWindow::onFrameInteraction);
connect(newFrame, &QObject::destroyed, this, [this, newFrame]() {
if (lastFocusedFrame_ == newFrame) lastFocusedFrame_ = nullptr;
});
// Insert the widget into the splitter at the correct position
splitter->insertWidget(insertPosition, newFrame);
// Update logical indices for all frames after the insertion point
const QList<SplitFrameWidget *> allFrames = central_->findChildren<SplitFrameWidget *>();
for (SplitFrameWidget *frame : allFrames) {
const QVariant v = frame->property("logicalIndex");
if (v.isValid()) {
const int idx = v.toInt();
if (idx > afterIndex && frame != newFrame) {
frame->setProperty("logicalIndex", idx + 1);
}
}
}
// Update button states for all frames
const int totalFrames = (int)frames_.size();
for (SplitFrameWidget *frame : allFrames) {
updateFrameButtonStates(frame, totalFrames);
}
// Update window title and menus
updateWindowTitle();
rebuildAllWindowMenus();
// Focus the newly added frame's address bar
QMetaObject::invokeMethod(this, [this, newFrame]() {
if (newFrame) {
newFrame->focusAddress();
}
}, Qt::QueuedConnection);
return true;
}
void SplitWindow::onAddressEdited(SplitFrameWidget *who, const QString &text) {
const QVariant v = who->property("logicalIndex");
if (!v.isValid()) return;
int pos = v.toInt();
if (pos < 0) return;
if (pos < (int)frames_.size()) {
frames_[pos].address = text;
// persist addresses list
persistGlobalFrameState();
}
}
void SplitWindow::onFrameScaleChanged(SplitFrameWidget *who, double scale) {
const int pos = frameIndexFor(who);
if (pos < 0 || pos >= (int)frames_.size()) return;
frames_[pos].scale = std::clamp(scale, SplitFrameWidget::kMinScaleFactor, SplitFrameWidget::kMaxScaleFactor);
persistGlobalFrameState();
}
void SplitWindow::closeEvent(QCloseEvent *event) {
// Stop all media playback immediately to prevent audio/video from continuing
// after the window closes. This must be done first, before any state saving
// or cleanup, to ensure media stops as soon as possible.
stopAllFramesMediaPlayback();
// Incognito windows should never persist state
if (isIncognito_) {
qDebug() << "SplitWindow::closeEvent: Incognito window - skipping all persistence";
rebuildAllWindowMenus();
QMainWindow::closeEvent(event);
return;
}
// Persist splitter sizes and either save or remove per-window restore data.
// If this window has a persistent windowId_ it means it was part of the
// saved session; when the user explicitly closes the window we remove
// that saved group so the window will NOT be restored on next launch.
if (!windowId_.isEmpty()) {
// If the application is shutting down, persist this window's state so
// it will be restored on next launch. If the user explicitly closed
// the window during a running session, remove its saved group so it
// does not get restored.
if (qApp && qApp->closingDown()) {
// During shutdown: save (do not remove) so session is preserved.
AppSettings s;
{
GroupScope _gs(s, QStringLiteral("windows/%1").arg(windowId_));
QStringList addressList;
QVariantList scaleList;
for (const auto &state : frames_) {
addressList << state.address;
scaleList << state.scale;
}
s->setValue("addresses", addressList);
s->setValue("frameScales", scaleList);
s->setValue("layoutMode", (int)layoutMode_);
s->setValue("windowGeometry", saveGeometry());
s->setValue("windowState", saveState());
}
// Ensure these shutdown-time writes are flushed to the backend.
s->sync();
saveCurrentSplitterSizes(QStringLiteral("windows/%1/splitterSizes").arg(windowId_));
} else {
// If other windows exist, remove this window's saved group now.
// If this is the last window, preserve the saved group so it
// reopens on next launch.
saveCurrentSplitterSizes(QStringLiteral("windows/%1/splitterSizes").arg(windowId_));
const size_t windowsCount = g_windows.size();
qDebug() << "SplitWindow::closeEvent: g_windows.count (including this)=" << windowsCount;
if (windowsCount > 1) {
AppSettings s;