-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
1883 lines (1739 loc) · 66.9 KB
/
main.js
File metadata and controls
1883 lines (1739 loc) · 66.9 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
const { app, BrowserWindow, BrowserView, ipcMain, globalShortcut, session } = require("electron");
const fs = require("fs");
const path = require("path");
const STATE_FILE = path.join(app.getPath("userData"), "app-state.json");
let windows = [];
let pages = [{ id: 1, name: "Session 1", sessionId: "persist:page_1" }];
let nextPageId = 2;
let deletedPageNumbers = [];
let globalZoomLevel = 100; // Global zoom for all windows
let lastCycleTabsAt = 0; // throttle for rapid Ctrl+Tab
let settings = {
defaultTabs: 4,
layoutPreset: "auto",
hotkeys: {
fullscreen: "F11",
new_window: "CommandOrControl+N",
add_tab: "CommandOrControl+T",
delete_tab: "CommandOrControl+W",
cycle_tabs: "CommandOrControl+Tab",
cycle_sessions: "CommandOrControl+Shift+Tab",
back: "Alt+Left",
forward: "Alt+Right",
search: "CommandOrControl+F",
add_session: "CommandOrControl+Shift+N"
}
};
function createOverlay(parent, file) {
const w = new BrowserWindow({
width: 1200, height: 900,
frame: false, transparent: true,
parent, show: false, skipTaskbar: true,
webPreferences: { nodeIntegration: true, contextIsolation: false }
});
w.setAlwaysOnTop(true, "floating");
w.setIgnoreMouseEvents(true);
w.loadFile(file);
try { w.webContents.setMaxListeners(0); } catch (e) {}
return w;
}
function pagesWithTabsFor(win) {
return pages.map(p => ({ ...p, tabs: win.pageTabs[p.id] || 4 }));
}
function getActiveView(win) {
const pid = win.currentPage;
const idx = win.activeTabPerPage[pid];
if (typeof idx !== "number") return undefined;
return win.pageViews[pid]?.[idx];
}
function applyZoomToViews(views, zoom) {
if (!views) return;
views.forEach(v => {
try {
if (v.webContents && !v.webContents.isDestroyed()) {
v.webContents.setZoomFactor(zoom / 100);
}
} catch (e) {}
});
}
function applyZoomAllWindows() {
windows.forEach(w => {
Object.keys(w.pageViews).forEach(pid => {
applyZoomToViews(w.pageViews[pid], globalZoomLevel);
});
sendToHeader(w, "update-zoom", globalZoomLevel);
});
}
function enforceGlobalZoom(view) {
if (!view || !view.webContents) return;
const apply = () => {
try { view.webContents.setZoomFactor(globalZoomLevel / 100); } catch (e) {}
};
apply();
try {
view.webContents.on("zoom-changed", apply);
view.webContents.on("did-start-loading", apply);
view.webContents.on("did-navigate", apply);
view.webContents.on("did-navigate-in-page", apply);
view.webContents.on("did-finish-load", apply);
} catch (e) {}
}
function createTabView(sessionId, pageId, index) {
const view = new BrowserView({
webPreferences: { partition: sessionId, preload: path.join(__dirname, "preload.js") }
});
setupTabNavigationListeners(view, pageId, index);
enforceGlobalZoom(view);
return view;
}
function ensureViewsFor(win, pageId, count) {
const page = pages.find(p => p.id === pageId);
const sessionId = page?.sessionId;
if (!win.pageViews[pageId]) win.pageViews[pageId] = [];
const arr = win.pageViews[pageId];
for (let i = arr.length; i < count; i++) {
arr.push(createTabView(sessionId, pageId, i));
}
return arr;
}
function triggerLayout(win) {
setTimeout(() => {
if (!win.isDestroyed()) win.emit("resize");
}, 50);
}
function getActiveMainWindow() {
let fw;
try { fw = BrowserWindow.getFocusedWindow(); } catch (e) {}
if (fw && fw.headerView) return fw;
try {
if (fw && typeof fw.getParentWindow === "function") {
const pw = fw.getParentWindow();
if (pw && pw.headerView) return pw;
}
} catch (e) {}
const candidate = windows.find(w => !w.isDestroyed());
if (candidate) return candidate;
const any = BrowserWindow.getAllWindows().find(w => w.headerView);
return any || null;
}
function updateOverlaysBounds(win) {
try {
if (!win.isDestroyed()) {
const [x, y] = win.getPosition();
const [w, h] = win.getContentSize();
[win.popupWindow, win.deleteModeWindow, win.settingsWindow].forEach(ow => {
if (ow && !ow.isDestroyed()) ow.setBounds({ x, y, width: w, height: h });
});
if (win.searchBoxWindow && !win.searchBoxWindow.isDestroyed()) {
const contentBounds = win.getContentBounds();
if (win.searchBoxWindow.isVisible()) {
const v = getActiveView(win);
const b = v ? v.getBounds() : { x: 0, y: 0, width: w, height: h };
win.searchBoxWindow.setBounds({
x: contentBounds.x + b.x,
y: contentBounds.y + b.y,
width: b.width,
height: b.height
});
} else {
win.searchBoxWindow.setBounds({ x: contentBounds.x, y: contentBounds.y, width: contentBounds.width, height: contentBounds.height });
}
}
}
} catch (e) {}
}
function computeTabBounds(win) {
const pid = win.currentPage;
const count = win.pageTabs[pid] || 4;
const [w, h] = win.getContentSize();
const headerHeight = win.isFullScreen() ? 0 : 80;
const contentY = headerHeight;
const contentH = h - headerHeight;
return boundsForPreset(w, contentY, contentH, count, settings.layoutPreset);
}
function cleanupSearch(win) {
try {
const targetPid = win.searchTargetPageId || win.currentPage;
const targetIdx = typeof win.searchTargetTabIndex === "number" ? win.searchTargetTabIndex : win.activeTabPerPage[targetPid];
const v = (typeof targetIdx === "number") ? (win.pageViews[targetPid]?.[targetIdx]) : undefined;
if (v && v.webContents && !v.webContents.isDestroyed() && win.searchHighlightCSSKey) {
v.webContents.removeInsertedCSS(win.searchHighlightCSSKey).catch(() => {});
win.searchHighlightCSSKey = null;
}
win.searchTargetPageId = undefined;
win.searchTargetTabIndex = undefined;
if (!win.searchBoxWindow.isDestroyed() && win.searchBoxWindow.isVisible()) {
win.searchBoxWindow.hide();
win.searchBoxWindow.setIgnoreMouseEvents(true);
}
} catch (e) {}
}
function insertSnakeAnimation(view, win) {
if (!view || !view.webContents || view.webContents.isDestroyed()) return;
if (win.tabAnimationCSSKey) {
view.webContents.removeInsertedCSS(win.tabAnimationCSSKey).catch(() => {});
win.tabAnimationCSSKey = null;
}
view.webContents.executeJavaScript(`
(function() {
try {
var old = document.getElementById('__snakeAnimOverlay');
if (old) old.remove();
var style = document.getElementById('__snakeAnimStyle');
if (!style) {
style = document.createElement('style');
style.id = '__snakeAnimStyle';
style.textContent = "@keyframes snakeBorderAnim{0%{left:var(--inset);bottom:var(--inset);width:100px;height:3px;}23%{left:calc(100% - 100px - var(--inset));bottom:var(--inset);width:100px;height:3px;}25%{left:calc(100% - 3px - var(--inset));bottom:var(--inset);width:3px;height:100px;}48%{left:calc(100% - 3px - var(--inset));bottom:calc(100% - 100px - var(--inset));width:3px;height:100px;}50%{left:calc(100% - 100px - var(--inset));bottom:calc(100% - 3px - var(--inset));width:100px;height:3px;}73%{left:var(--inset);bottom:calc(100% - 3px - var(--inset));width:100px;height:3px;}75%{left:var(--inset);bottom:calc(100% - 100px - var(--inset));width:3px;height:100px;}98%{left:var(--inset);bottom:var(--inset);width:3px;height:100px;}100%{left:var(--inset);bottom:var(--inset);width:100px;height:3px;opacity:0;}}";
document.documentElement.appendChild(style);
}
var el = document.createElement('div');
el.id = '__snakeAnimOverlay';
el.style.position = 'fixed';
el.style.left = 'var(--inset)';
el.style.bottom = 'var(--inset)';
el.style.width = '100px';
el.style.height = '3px';
el.style.pointerEvents = 'none';
el.style.zIndex = '2147483647';
el.style.animation = 'snakeBorderAnim 0.6s ease-in-out forwards';
el.style.mixBlendMode = 'difference';
el.style.background = 'linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.4) 25%, rgba(255,255,255,0.95) 50%, rgba(255,255,255,0.4) 75%, transparent 100%)';
el.style.boxShadow = '0 0 12px rgba(255,255,255,0.9)';
el.style.setProperty('--inset', '6px');
document.documentElement.appendChild(el);
setTimeout(function() {
var e = document.getElementById('__snakeAnimOverlay');
if (e) e.remove();
}, 650);
} catch (e) {
try {
var css = "@keyframes snakeBorderAnim{0%{left:var(--inset);bottom:var(--inset);width:100px;height:3px;}23%{left:calc(100% - 100px - var(--inset));bottom:var(--inset);width:100px;height:3px;}25%{left:calc(100% - 3px - var(--inset));bottom:var(--inset);width:3px;height:100px;}48%{left:calc(100% - 3px - var(--inset));bottom:calc(100% - 100px - var(--inset));width:3px;height:100px;}50%{left:calc(100% - 100px - var(--inset));bottom:calc(100% - 3px - var(--inset));width:100px;height:3px;}73%{left:var(--inset);bottom:calc(100% - 3px - var(--inset));width:100px;height:3px;}75%{left:var(--inset);bottom:calc(100% - 100px - var(--inset));width:3px;height:100px;}98%{left:var(--inset);bottom:var(--inset);width:3px;height:100px;}100%{left:var(--inset);bottom:var(--inset);width:100px;height:3px;opacity:0;}} html::after{--inset:6px;content:'';position:fixed;left:var(--inset);bottom:var(--inset);width:100px;height:3px;background:linear-gradient(90deg,transparent 0%,rgba(255,255,255,0.4) 25%,rgba(255,255,255,0.95) 50%,rgba(255,255,255,0.4) 75%,transparent 100%);box-shadow:0 0 12px rgba(255,255,255,0.9);pointer-events:none;z-index:2147483647;animation:snakeBorderAnim 0.6s ease-in-out forwards;mix-blend-mode:difference;}";
if (view && view.webContents && !view.webContents.isDestroyed()) {
view.webContents.insertCSS(css).then((key) => {
win.tabAnimationCSSKey = key;
setTimeout(() => {
if (view && view.webContents && !view.webContents.isDestroyed()) {
view.webContents.removeInsertedCSS(key).catch(() => {});
if (win.tabAnimationCSSKey === key) win.tabAnimationCSSKey = null;
}
}, 650);
}).catch(() => {});
}
} catch (_) {}
}
})();
`).catch(() => {});
}
function activateTab(win, pageId, tabIndex) {
if (!win || win.isDestroyed()) return;
if (win.activeTabPerPage[pageId] === tabIndex) return;
win.activeTabPerPage[pageId] = tabIndex;
updateHeaderTabState(win);
const v = win.pageViews[pageId]?.[tabIndex];
if (v && v.webContents && !v.webContents.isDestroyed()) {
try { win.focus(); } catch (e) {}
try { v.webContents.focus(); } catch (e) {}
insertSnakeAnimation(v, win);
}
}
function addTabToCurrentPage(win, makeActive) {
const pid = win.currentPage;
const count = win.pageTabs[pid] || 4;
if (count >= 12) {
showPopup(win, "show-error", "Maximum 12 tabs allowed!");
return;
}
win.pageTabs[pid] = count + 1;
const idx = win.pageTabs[pid] - 1;
if (makeActive) win.activeTabPerPage[pid] = idx;
const startPage = `file://${__dirname}/start.html`;
try {
const newView = win.pageViews[pid][idx];
try { newView.webContents.setZoomFactor(globalZoomLevel / 100); } catch (e) {}
newView.webContents.loadURL(startPage);
newView.webContents.once("did-finish-load", () => {
try {
if (!newView.webContents.isDestroyed()) {
newView.webContents.setZoomFactor(globalZoomLevel / 100);
injectClickDetection(newView, pid, idx);
}
} catch (e) {}
});
} catch (e) {}
sendToHeader(win, "update-pages", pagesWithTabsFor(win));
updateHeaderTabState(win);
triggerLayout(win);
debouncedSaveState();
}
function activateDeleteMode(win) {
if (!win || win.isDestroyed()) return;
if (!win.deleteModeWindow || win.deleteModeWindow.isDestroyed()) return;
if (!win.pageTabs || !win.currentPage) return;
const pid = win.currentPage;
const count = win.pageTabs[pid] || 4;
const tabBounds = computeTabBounds(win);
try {
if (win.deleteModeWindow && !win.deleteModeWindow.isDestroyed()) {
const contentBounds = win.getContentBounds();
win.deleteModeWindow.setBounds({
x: contentBounds.x,
y: contentBounds.y,
width: contentBounds.width,
height: contentBounds.height
});
win.deleteModeWindow.webContents.send("activate-delete-mode", tabBounds);
win.deleteModeWindow.setIgnoreMouseEvents(false);
win.deleteModeWindow.show();
try { win.deleteModeWindow.focus(); } catch (e) {}
win.isDeleteModeActive = true;
try { win.moveTop(); } catch (e) {}
}
} catch (e) {
console.error("Failed to activate delete mode:", e);
}
}
function openSearchOverlay(win) {
const pid = win.currentPage;
const idx = win.activeTabPerPage[pid];
if (typeof idx !== "number") return;
const activeView = win.pageViews[pid]?.[idx];
if (!activeView) return;
win.searchTargetPageId = pid;
win.searchTargetTabIndex = idx;
const tabBounds = activeView.getBounds();
const contentBounds = win.getContentBounds();
try {
if (!win.searchBoxWindow.isDestroyed()) {
win.searchBoxWindow.setBounds({
x: contentBounds.x + tabBounds.x,
y: contentBounds.y + tabBounds.y,
width: tabBounds.width,
height: tabBounds.height
});
const level = win.isFullScreen() ? "screen-saver" : "floating";
win.searchBoxWindow.setAlwaysOnTop(true, level);
let currentUrl = "";
try {
if (activeView && activeView.webContents && !activeView.webContents.isDestroyed()) {
currentUrl = activeView.webContents.getURL() || "";
}
} catch (e) {}
win.searchBoxWindow.webContents.send("activate-search", tabBounds, currentUrl);
win.searchBoxWindow.setIgnoreMouseEvents(false);
win.searchBoxWindow.showInactive();
try { win.searchBoxWindow.focus(); } catch (e) {}
try { win.searchBoxWindow.webContents.focus(); } catch (e) {}
}
} catch (e) {
console.error("Failed to open search:", e);
}
}
function switchToPage(win, pageId) {
if (!win || win.isDestroyed()) return;
try {
cleanupSearch(win);
if (win.searchBoxWindow && !win.searchBoxWindow.isDestroyed()) {
win.searchBoxWindow.setAlwaysOnTop(false);
win.searchBoxWindow.hide();
win.searchBoxWindow.setIgnoreMouseEvents(true);
}
} catch (e) {}
const newPage = pages.find(p => p.id === pageId);
if (!newPage || win.currentPage === pageId) return;
const oldPageViews = win.pageViews[win.currentPage];
if (oldPageViews) {
oldPageViews.forEach(view => {
try {
win.removeBrowserView(view);
} catch (e) {}
});
}
const newPageViews = win.pageViews[pageId];
if (newPageViews) {
newPageViews.forEach(view => {
try {
win.addBrowserView(view);
} catch (e) {}
});
}
win.currentPage = pageId;
try {
win.removeBrowserView(win.headerView);
win.addBrowserView(win.headerView);
} catch (e) {}
updateHeaderTabState(win);
applyZoomToViews(newPageViews, globalZoomLevel);
triggerLayout(win);
sendToHeader(win, "update-current-page", pageId);
debouncedSaveState();
try {
const tabCount = win.pageTabs[pageId] || 4;
let activeIdx = win.activeTabPerPage[pageId];
const valid = typeof activeIdx === "number" && activeIdx >= 0 && activeIdx < tabCount;
if (!valid) {
activeIdx = 0;
win.activeTabPerPage[pageId] = activeIdx;
updateHeaderTabState(win);
}
const activeView = win.pageViews[pageId]?.[activeIdx];
if (activeView && activeView.webContents && !activeView.webContents.isDestroyed()) {
try { win.focus(); } catch (e) {}
try { activeView.webContents.focus(); } catch (e) {}
}
} catch (e) {}
}
function addPageGlobal() {
let pageNumber;
if (deletedPageNumbers.length > 0) {
deletedPageNumbers.sort((a, b) => a - b);
pageNumber = deletedPageNumbers.shift();
} else {
pageNumber = nextPageId++;
}
const newSessionId = `persist:page_${pageNumber}`;
const newPage = { id: pageNumber, name: `Session ${pageNumber}`, sessionId: newSessionId };
pages.push(newPage);
windows.forEach(w => {
const views = [];
for (let i = 0; i < 12; i++) {
const view = new BrowserView({
webPreferences: { partition: newSessionId, preload: path.join(__dirname, "preload.js") }
});
views.push(view);
setupTabNavigationListeners(view, pageNumber, i);
// Attach global zoom enforcement to each new view
const enforce = () => {
try { view.webContents.setZoomFactor(globalZoomLevel / 100); } catch (e) {}
};
try {
enforce();
view.webContents.on('zoom-changed', enforce);
view.webContents.on('did-start-loading', enforce);
view.webContents.on('did-navigate', enforce);
view.webContents.on('did-navigate-in-page', enforce);
view.webContents.on('did-finish-load', enforce);
} catch (e) {}
}
const startPage = `file://${__dirname}/start.html`;
const defTabs = Math.max(1, Math.min(12, settings.defaultTabs || 4));
w.pageTabs[pageNumber] = defTabs;
for (let i = 0; i < defTabs; i++) {
try { views[i].webContents.setZoomFactor(globalZoomLevel / 100); } catch (e) {}
views[i].webContents.loadURL(startPage);
views[i].webContents.once("did-finish-load", () => {
try {
if (!views[i].webContents.isDestroyed()) {
views[i].webContents.setZoomFactor(globalZoomLevel / 100);
}
} catch (e) {}
});
}
w.pageViews[pageNumber] = views;
if (w.activeTabPerPage) {
delete w.activeTabPerPage[pageNumber];
}
sendToHeader(w, "update-pages", pagesWithTabsFor(w));
});
debouncedSaveState();
}
// State persistence
function saveState() {
if (windows.length === 0) return; // Don't save if no windows
try {
const state = {
pages: pages,
nextPageId: nextPageId,
deletedPageNumbers: deletedPageNumbers,
globalZoomLevel: globalZoomLevel,
settings: settings,
windows: windows.map(win => {
if (win.isDestroyed()) return null;
const tabUrls = {};
Object.keys(win.pageViews).forEach(pageId => {
const views = win.pageViews[pageId];
const urls = [];
const tabCount = win.pageTabs[pageId] || 4;
for (let i = 0; i < tabCount; i++) {
if (views[i] && views[i].webContents && !views[i].webContents.isDestroyed()) {
urls.push(views[i].webContents.getURL());
} else {
urls.push(`file://${__dirname}/start.html`);
}
}
tabUrls[pageId] = urls;
});
return {
bounds: win.getBounds(),
isMaximized: win.isMaximized(),
isFullScreen: win.isFullScreen(),
currentPage: win.currentPage,
pageTabs: win.pageTabs,
tabUrls: tabUrls
};
}).filter(w => w !== null)
};
fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
} catch (err) {
console.error("Failed to save state:", err);
}
}
function loadState() {
try {
if (fs.existsSync(STATE_FILE)) {
const data = fs.readFileSync(STATE_FILE, "utf8");
return JSON.parse(data);
}
} catch (err) {
console.error("Failed to load state:", err);
}
return null;
}
// Debounced save
let saveTimeout = null;
function debouncedSaveState() {
if (saveTimeout) clearTimeout(saveTimeout);
saveTimeout = setTimeout(() => {
if (windows.length > 0) saveState();
}, 1000);
}
// Calculate optimal grid layout
function calculateLayout(tabCount) {
if (tabCount === 1) return { cols: 1, rows: 1 };
if (tabCount === 2) return { cols: 2, rows: 1 };
if (tabCount === 3) return { cols: 2, rows: 2 }; // 2x2 with one empty
if (tabCount === 4) return { cols: 2, rows: 2 };
if (tabCount <= 6) return { cols: 3, rows: 2 };
if (tabCount <= 9) return { cols: 3, rows: 3 };
return { cols: 4, rows: 3 }; // 10-12 tabs
}
function boundsForPreset(w, contentY, contentH, tabCount, preset) {
const out = [];
const gridWithCols = (fixedCols) => {
const cols = Math.max(1, Math.min(fixedCols, tabCount));
const rows = Math.max(1, Math.ceil(tabCount / cols));
const cellW = w / cols;
const cellH = contentH / rows;
for (let i = 0; i < tabCount; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
const isLastRow = row === rows - 1;
const isLastTab = i === tabCount - 1;
const tabsInLastRow = tabCount - (cols * (rows - 1));
if (isLastTab && isLastRow && tabsInLastRow < cols) {
const usedCols = tabsInLastRow;
const remainingCols = cols - usedCols + 1;
out.push({ x: col * cellW, y: contentY + row * cellH, width: cellW * remainingCols, height: cellH });
} else {
out.push({ x: col * cellW, y: contentY + row * cellH, width: cellW, height: cellH });
}
}
};
if (!preset || preset === "auto") {
const { cols, rows } = calculateLayout(tabCount);
const cellW = w / cols;
const cellH = contentH / rows;
for (let i = 0; i < tabCount; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
const isLastRow = row === rows - 1;
const isLastTab = i === tabCount - 1;
const tabsInLastRow = tabCount - (cols * (rows - 1));
if (isLastTab && isLastRow && tabsInLastRow < cols) {
const usedCols = tabsInLastRow;
const remainingCols = cols - usedCols + 1;
out.push({ x: col * cellW, y: contentY + row * cellH, width: cellW * remainingCols, height: cellH });
} else {
out.push({ x: col * cellW, y: contentY + row * cellH, width: cellW, height: cellH });
}
}
return out;
}
if (preset === "columns_2") return gridWithCols(2), out;
if (preset === "columns_3") return gridWithCols(3), out;
if (preset === "columns_4") return gridWithCols(4), out;
if (preset === "one_big_left") {
const halfW = w / 2;
out.push({ x: 0, y: contentY, width: halfW, height: contentH });
const remaining = Math.max(0, tabCount - 1);
if (remaining === 0) return out;
const cols = Math.min(2, remaining);
const rows = Math.ceil(remaining / cols);
const cellW = halfW / cols;
const cellH = contentH / rows;
for (let i = 0; i < remaining; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
out.push({ x: halfW + col * cellW, y: contentY + row * cellH, width: cellW, height: cellH });
}
return out;
}
if (preset === "one_big_right") {
const halfW = w / 2;
const remaining = Math.max(0, tabCount - 1);
if (remaining > 0) {
const cols = Math.min(2, remaining);
const rows = Math.ceil(remaining / cols);
const cellW = halfW / cols;
const cellH = contentH / rows;
for (let i = 0; i < remaining; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
out.push({ x: col * cellW, y: contentY + row * cellH, width: cellW, height: cellH });
}
}
out.push({ x: halfW, y: contentY, width: halfW, height: contentH });
return out;
}
if (preset === "odd_second_tall") {
if (tabCount >= 3 && tabCount % 2 === 1) {
const arr = new Array(tabCount);
const halfW = w / 2;
arr[1] = { x: halfW, y: contentY, width: halfW, height: contentH };
const remainingIdxs = [];
for (let i = 0; i < tabCount; i++) {
if (i !== 1) remainingIdxs.push(i);
}
const rows = remainingIdxs.length;
const cellH = contentH / rows;
remainingIdxs.forEach((ti, p) => {
arr[ti] = { x: 0, y: contentY + p * cellH, width: halfW, height: cellH };
});
return arr;
}
}
if (preset === "odd_last_wide") {
if (tabCount >= 3 && tabCount % 2 === 1) {
const arr = new Array(tabCount);
const bottomH = contentH / 3;
const topH = contentH - bottomH;
arr[tabCount - 1] = { x: 0, y: contentY + topH, width: w, height: bottomH };
const remaining = tabCount - 1;
const cols = Math.min(2, remaining);
const rows = Math.ceil(remaining / cols);
const cellW = w / cols;
const cellH = topH / rows;
for (let i = 0; i < remaining; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
arr[i] = { x: col * cellW, y: contentY + row * cellH, width: cellW, height: cellH };
}
return arr;
}
}
if (preset === "first_wide_top") {
if (tabCount >= 1) {
const arr = new Array(tabCount);
if (tabCount === 1) {
arr[0] = { x: 0, y: contentY, width: w, height: contentH };
return arr;
}
const topH = contentH / 3;
arr[0] = { x: 0, y: contentY, width: w, height: topH };
const remaining = tabCount - 1;
const cols = Math.min(2, remaining);
const rows = Math.ceil(remaining / cols);
const cellW = w / cols;
const cellH = (contentH - topH) / rows;
for (let i = 0; i < remaining; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
const ti = i + 1;
arr[ti] = { x: col * cellW, y: contentY + topH + row * cellH, width: cellW, height: cellH };
}
return arr;
}
}
const { cols, rows } = calculateLayout(tabCount);
const cellW = w / cols;
const cellH = contentH / rows;
for (let i = 0; i < tabCount; i++) {
const col = i % cols;
const row = Math.floor(i / cols);
out.push({ x: col * cellW, y: contentY + row * cellH, width: cellW, height: cellH });
}
return out;
}
function createWindow(restoreState = null) {
const win = new BrowserWindow({
width: restoreState?.bounds?.width || 1200,
height: restoreState?.bounds?.height || 900,
x: restoreState?.bounds?.x,
y: restoreState?.bounds?.y,
frame: false,
backgroundColor: "#000000",
webPreferences: { nodeIntegration: true, contextIsolation: false }
});
win.setMaxListeners(0);
const popupWindow = createOverlay(win, "popup.html");
const deleteModeWindow = createOverlay(win, "delete-mode.html");
const searchBoxWindow = createOverlay(win, "search-box.html");
const settingsWindow = createOverlay(win, "settings.html");
// Header
const header = new BrowserView({
webPreferences: { nodeIntegration: true, contextIsolation: false }
});
win.addBrowserView(header);
header.webContents.loadFile("header.html");
try { header.webContents.setMaxListeners(0); } catch (e) {}
// Create views for each page
win.pageViews = {};
win.pageTabs = {};
pages.forEach(page => {
const views = [];
for (let i = 0; i < 12; i++) {
const view = new BrowserView({
webPreferences: { partition: page.sessionId, preload: path.join(__dirname, "preload.js") }
});
views.push(view);
setupTabNavigationListeners(view, page.id, i);
}
win.pageTabs[page.id] = restoreState?.pageTabs?.[page.id] || 4;
win.pageViews[page.id] = views;
// Enforce global zoom on all views
views.forEach(view => {
const enforce = () => {
try { view.webContents.setZoomFactor(globalZoomLevel / 100); } catch (e) {}
};
enforce();
view.webContents.on('zoom-changed', enforce);
view.webContents.on('did-start-loading', enforce);
view.webContents.on('did-navigate', enforce);
view.webContents.on('did-navigate-in-page', enforce);
view.webContents.on('did-finish-load', enforce);
});
win.activeTabPerPage = win.activeTabPerPage || {};
});
win.activeTabPerPage = win.activeTabPerPage || {};
// Set current page
const restoredPage = restoreState?.currentPage || (pages.length > 0 ? pages[0].id : 1);
win.currentPage = restoredPage;
if (win.pageViews[win.currentPage]) {
win.pageViews[win.currentPage].forEach(v => win.addBrowserView(v));
} else if (pages.length > 0 && win.pageViews[pages[0].id]) {
win.currentPage = pages[0].id;
win.pageViews[pages[0].id].forEach(v => win.addBrowserView(v));
}
win.headerView = header;
win.popupWindow = popupWindow;
win.deleteModeWindow = deleteModeWindow;
win.searchBoxWindow = searchBoxWindow;
win.settingsWindow = settingsWindow;
win.isDeleteModeActive = false;
// Layout function with improved grid system
const layoutViews = () => {
try {
if (win.isDestroyed()) return;
const [w, h] = win.getContentSize();
const headerHeight = win.isFullScreen() ? 0 : 80;
// Update header
header.setBounds({
x: 0,
y: win.isFullScreen() ? -80 : 0,
width: w,
height: 80
});
const currentPage = pages.find(p => p.id === win.currentPage);
if (!currentPage || !win.pageViews[win.currentPage]) return;
const tabCount = win.pageTabs[win.currentPage] || 4;
const contentY = headerHeight;
const contentH = h - headerHeight;
const views = ensureViewsFor(win, win.currentPage, tabCount);
// Hide all first
views.forEach(v => v.setBounds({ x: 0, y: 0, width: 0, height: 0 }));
const bounds = boundsForPreset(w, contentY, contentH, tabCount, settings.layoutPreset);
for (let i = 0; i < tabCount; i++) {
const b = bounds[i];
try { win.addBrowserView(views[i]); } catch (e) {}
views[i].setBounds(b);
}
} catch (err) {
console.error('Layout error:', err);
}
};
const updatePopup = () => updateOverlaysBounds(win);
// Event handlers
let resizeTimer = null;
win.on("resize", () => {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
layoutViews();
updatePopup();
}, 16);
});
let moveTimer = null;
win.on("move", () => {
if (moveTimer) clearTimeout(moveTimer);
moveTimer = setTimeout(updatePopup, 16);
});
win.on("leave-full-screen", () => {
cleanupSearch(win);
try {
if (header.webContents && !header.webContents.isDestroyed()) {
header.webContents.send("toggle-header", true);
}
layoutViews();
} catch (err) {}
});
win.on("maximize", () => {
try {
if (header.webContents && !header.webContents.isDestroyed()) {
header.webContents.send("update-maximize", true);
}
setTimeout(() => {
if (!win.isDestroyed()) {
layoutViews();
updatePopup();
}
}, 150);
} catch (err) {}
});
win.on("unmaximize", () => {
try {
if (header.webContents && !header.webContents.isDestroyed()) {
header.webContents.send("update-maximize", false);
}
setTimeout(() => {
if (!win.isDestroyed()) {
layoutViews();
updatePopup();
}
}, 150);
} catch (err) {}
});
win.on("enter-full-screen", () => {
try {
if (header.webContents && !header.webContents.isDestroyed()) {
header.webContents.send("toggle-header", false);
}
layoutViews();
} catch (err) {}
});
win.on("blur", () => {
try {
const focusedWin = BrowserWindow.getFocusedWindow();
if (focusedWin === win.searchBoxWindow) return;
cleanupSearch(win);
try {
if (!win.searchBoxWindow.isDestroyed()) win.searchBoxWindow.setAlwaysOnTop(false);
} catch (e) {}
} catch (err) {}
});
layoutViews();
updatePopup();
header.webContents.on("did-finish-load", () => {
try {
header.webContents.send("update-state", {
pages: pagesWithTabsFor(win),
currentPage: win.currentPage,
zoomLevel: globalZoomLevel,
isMaximized: win.isMaximized()
});
updateHeaderTabState(win);
} catch (err) {}
});
windows.push(win);
win.on("closed", () => {
windows = windows.filter(w => w !== win);
// Destroy views
Object.keys(win.pageViews).forEach(pageId => {
win.pageViews[pageId].forEach(view => {
try {
if (view.webContents && !view.webContents.isDestroyed()) {
view.webContents.destroy();
}
} catch (err) {}
});
});
try {
if (!popupWindow.isDestroyed()) popupWindow.close();
} catch (err) {}
});
// Save state on close
win.on("close", () => saveState());
// Restore window state
if (restoreState) {
try { showPopup(win, "show-initial-loader"); } catch (e) {}
setTimeout(() => {
if (restoreState.isMaximized) win.maximize();
if (restoreState.isFullScreen) win.setFullScreen(true);
// Load URLs and apply zoom for this window only
let pending = win.pageTabs[win.currentPage] || 4;
Object.keys(win.pageViews).forEach(pageId => {
const savedUrls = restoreState.tabUrls?.[pageId] || [];
const tabCount = win.pageTabs[pageId] || 4;
const startPage = `file://${__dirname}/start.html`;
win.pageViews[pageId].forEach((view, index) => {
try {
if (view.webContents && !view.webContents.isDestroyed()) {
if (index < tabCount) {
const url = savedUrls[index] || startPage;
try { view.webContents.setZoomFactor(globalZoomLevel / 100); } catch (e) {}
view.webContents.loadURL(url);
view.webContents.once('did-finish-load', () => {
try {
if (!view.webContents.isDestroyed()) {
view.webContents.setZoomFactor(globalZoomLevel / 100);
}
if (pageId == win.currentPage && pending > 0) {
pending = Math.max(0, pending - 1);
if (pending === 0) {
try { win.popupWindow.webContents.send("hide-initial-loader"); } catch (e) {}
try { win.popupWindow.hide(); } catch (e) {}
}
}
} catch (err) {}
});
}
}
} catch (err) {}
});
});
setTimeout(() => {
try { win.popupWindow.webContents.send("hide-initial-loader"); } catch (e) {}
try { win.popupWindow.hide(); } catch (e) {}
}, 2000);
}, 200);
} else {
// Load default start pages
try { showPopup(win, "show-initial-loader"); } catch (e) {}
setTimeout(() => {
const startPage = `file://${__dirname}/start.html`;
let pending = win.pageTabs[win.currentPage] || 4;
Object.keys(win.pageViews).forEach(pageId => {
const tabCount = win.pageTabs[pageId] || 4;
win.pageViews[pageId].forEach((view, index) => {
try {
if (index < tabCount && view.webContents && !view.webContents.isDestroyed()) {
try { view.webContents.setZoomFactor(globalZoomLevel / 100); } catch (e) {}
view.webContents.loadURL(startPage);
if (pageId == win.currentPage && index < pending) {
view.webContents.once("did-finish-load", () => {
try {
pending = Math.max(0, pending - 1);
if (pending === 0) {
try { win.popupWindow.webContents.send("hide-initial-loader"); } catch (e) {}
try { win.popupWindow.hide(); } catch (e) {}
}
} catch (e) {}
});
}
}
} catch (err) {}
});
});
setTimeout(() => {
try { win.popupWindow.webContents.send("hide-initial-loader"); } catch (e) {}
try { win.popupWindow.hide(); } catch (e) {}
}, 2000);
}, 200);
}
return win;
}
// App initialization
app.whenReady().then(() => {
const savedState = loadState();
if (savedState) {
if (savedState.pages && savedState.pages.length > 0) {
pages = savedState.pages;
nextPageId = savedState.nextPageId || pages.length + 1;
deletedPageNumbers = savedState.deletedPageNumbers || [];
}
// Restore global zoom level
if (savedState.globalZoomLevel) {
globalZoomLevel = savedState.globalZoomLevel;
}
if (savedState.settings) {
settings = savedState.settings;
}
try {