-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathoverlayManager.ts
More file actions
1040 lines (906 loc) · 33.3 KB
/
Copy pathoverlayManager.ts
File metadata and controls
1040 lines (906 loc) · 33.3 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
import {
app,
BrowserWindow,
BrowserWindowConstructorOptions,
screen,
} from 'electron';
import type { DashboardLayout, ContainerBoundsInfo } from '@irdashies/types';
import path from 'node:path';
import { Notification } from 'electron';
import { readData, writeData } from './storage/storage';
import { getDashboard } from './storage/dashboards';
import { getChromiumFlags, parseCustomSwitches } from './storage/chromiumFlags';
import {
markCorrectedBounds,
trackSettingsWindowMovement,
} from './trackWindowMovement';
import { sanitizeWindowBounds } from './windowBounds';
import logger from './logger';
import { createRendererPerfArguments } from './perfRendererArguments';
type RendererDataStream = 'sessionData' | 'telemetryInspector';
interface RendererDataSubscriptions {
has(rendererId: number, stream: RendererDataStream): boolean;
hasAny(stream: RendererDataStream): boolean;
}
// used for Hot Module Replacement
declare const MAIN_WINDOW_VITE_DEV_SERVER_URL: string;
declare const MAIN_WINDOW_VITE_NAME: string;
declare const APP_GIT_HASH: string;
// Hosts allowed to attach as <webview> guests (Heart Rate widget only).
// Used by both will-attach-webview and will-redirect so the allowlist
// can't drift apart.
const HYPERATE_HOST_RE = /(^|\.)hyperate\.io$/i;
const isAllowedGuestHost = (urlStr: string): boolean => {
try {
return HYPERATE_HOST_RE.test(new URL(urlStr).hostname);
} catch {
return false;
}
};
function getIconPath(): string {
const isDev = !!MAIN_WINDOW_VITE_DEV_SERVER_URL;
const basePath = isDev
? path.join(__dirname, '../../docs/assets/icons')
: path.join(process.resourcesPath, 'icons');
return path.join(basePath, 'logo.png');
}
export class OverlayManager {
private displayWindows = new Map<number, BrowserWindow>();
private displayBoundsInfo = new Map<number, ContainerBoundsInfo>();
private displayFullBounds = new Map<number, Electron.Rectangle>();
private currentSettingsWindow: BrowserWindow | undefined;
private currentDashboard: DashboardLayout | undefined;
private isLocked = true;
private isQuitting = false;
private skipTaskbar = true;
private overlayAlwaysOnTop = true;
private hasSingleInstanceLock = false;
private onWindowReadyCallbacks = new Set<(windowId: string) => void>();
private rendererDataSubscriptions?: RendererDataSubscriptions;
/** Padding around the widget bounding box when shrink-wrapping */
private static readonly SHRINK_WRAP_PADDING = 20;
public getVersion(): string {
const version = app.getVersion();
const gitHash = typeof APP_GIT_HASH !== 'undefined' ? APP_GIT_HASH : 'dev';
return `${version}+${gitHash}`;
}
/**
* Get all display overlay windows
*/
public getOverlays(): { window: BrowserWindow }[] {
const result: { window: BrowserWindow }[] = [];
for (const win of this.displayWindows.values()) {
if (!win.isDestroyed()) {
result.push({ window: win });
}
}
return result;
}
/**
* Create one overlay window per display
*/
public createOverlays(
dashboardLayout: DashboardLayout,
options: { createSettingsWindow?: boolean } = {}
): void {
this.currentDashboard = dashboardLayout;
const { generalSettings } = dashboardLayout;
this.skipTaskbar = generalSettings?.skipTaskbar ?? true;
this.overlayAlwaysOnTop = generalSettings?.overlayAlwaysOnTop ?? true;
const allDisplays = screen.getAllDisplays();
const primaryDisplay = screen.getPrimaryDisplay();
logger.info(`[OverlayManager] Found ${allDisplays.length} display(s):`);
for (const display of allDisplays) {
const isPrimary = display.id === primaryDisplay.id;
logger.info(
` Display ${display.id}${isPrimary ? ' (PRIMARY)' : ''}: bounds=${JSON.stringify(display.bounds)}`
);
}
// Determine which displays have widgets assigned (by center-point)
const displaysWithWidgets = new Set<number>();
for (const widget of dashboardLayout.widgets) {
if (!widget.enabled) continue;
const centerX = widget.layout.x + widget.layout.width / 2;
const centerY = widget.layout.y + widget.layout.height / 2;
for (const display of allDisplays) {
const { x, y, width, height } = display.bounds;
if (
centerX >= x &&
centerX < x + width &&
centerY >= y &&
centerY < y + height
) {
displaysWithWidgets.add(display.id);
break;
}
}
}
// Always create a window for the primary display (fallback for unmatched widgets)
displaysWithWidgets.add(primaryDisplay.id);
for (const display of allDisplays) {
if (!displaysWithWidgets.has(display.id)) {
logger.info(
`[OverlayManager] Skipping display ${display.id} — no widgets assigned`
);
continue;
}
const isPrimary = display.id === primaryDisplay.id;
this.createWindowForDisplay(display, isPrimary);
}
if (options.createSettingsWindow !== false) {
const startMinimized = generalSettings?.startMinimized ?? false;
this.createSettingsWindow(undefined, { startHidden: startMinimized });
}
}
/**
* Create a transparent overlay window sized exactly to one display
*/
private createWindowForDisplay(
display: Electron.Display,
isPrimary: boolean
): BrowserWindow {
const existing = this.displayWindows.get(display.id);
if (existing && !existing.isDestroyed()) {
return existing;
}
const expectedBounds = {
x: display.bounds.x,
y: display.bounds.y,
width: display.bounds.width,
height: display.bounds.height,
};
// Store full display bounds for shrink-wrap / expand toggling
this.displayFullBounds.set(display.id, { ...expectedBounds });
logger.info(
`[OverlayManager] Creating window for display ${display.id}${isPrimary ? ' (PRIMARY)' : ''}: x=${expectedBounds.x}, y=${expectedBounds.y}, ${expectedBounds.width}x${expectedBounds.height}`
);
const browserWindow = new BrowserWindow({
x: expectedBounds.x,
y: expectedBounds.y,
width: expectedBounds.width,
height: expectedBounds.height,
title: `irDashies - ${display.id}${isPrimary ? ' (Primary)' : ''})`,
transparent: true,
frame: false,
skipTaskbar: this.skipTaskbar,
focusable: true, // for OpenKneeboard/VR
resizable: false,
movable: false,
roundedCorners: false,
hasShadow: false,
show: false,
alwaysOnTop: true,
backgroundColor: '#00000000',
icon: getIconPath(),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
backgroundThrottling: false,
additionalArguments: createRendererPerfArguments(),
// Enables the <webview> used by the Heart Rate widget to embed
// HypeRate's overlay and inject transparent-background CSS (the same
// technique OBS uses). Global-by-design: webPreferences are fixed at
// window-creation and any widget can land on any display, so this is
// set on every overlay window. Attachable guests are constrained to
// hyperate.io by the will-attach-webview allowlist below, and guests
// run with sandbox + contextIsolation + no node integration + an
// isolated session partition (see HeartRateEmbed).
webviewTag: true,
},
});
browserWindow.setBounds(expectedBounds);
// Harden the <webview> used by the Heart Rate widget: keep the guest on
// secure defaults and only allow HypeRate hosts to attach.
browserWindow.webContents.on(
'will-attach-webview',
(event, webPreferences, params) => {
delete webPreferences.preload;
webPreferences.nodeIntegration = false;
webPreferences.contextIsolation = true;
webPreferences.sandbox = true;
if (!isAllowedGuestHost(params.src)) {
event.preventDefault();
}
}
);
// Contain the guest after attachment: no popups, no navigating away, and
// no cross-origin redirects (3xx fires will-redirect, not will-navigate).
browserWindow.webContents.on('did-attach-webview', (_event, guest) => {
guest.setWindowOpenHandler(() => ({ action: 'deny' }));
guest.on('will-navigate', (e, url) => {
if (!isAllowedGuestHost(url)) e.preventDefault();
});
guest.on('will-redirect', (e, url) => {
if (!isAllowedGuestHost(url)) e.preventDefault();
});
});
browserWindow.on('page-title-updated', (evt) => {
evt.preventDefault();
});
browserWindow.setIgnoreMouseEvents(this.isLocked);
browserWindow.setVisibleOnAllWorkspaces(true, {
visibleOnFullScreen: true,
});
if (this.overlayAlwaysOnTop) {
browserWindow.setAlwaysOnTop(true, 'screen-saver', 1);
}
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
browserWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
browserWindow.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`)
);
}
this.displayWindows.set(display.id, browserWindow);
browserWindow.on('closed', () => {
logger.info(`Display ${display.id} overlay window closed`);
this.displayWindows.delete(display.id);
this.displayBoundsInfo.delete(display.id);
});
browserWindow.webContents.on('render-process-gone', (_event, details) => {
logger.error(
`[OverlayManager] Renderer process gone for display ${display.id}${isPrimary ? ' (PRIMARY)' : ''}: reason=${details.reason}, exitCode=${details.exitCode}`
);
if (this.isQuitting) return;
// Clean up stale entry so recreate doesn't early-return
this.displayWindows.delete(display.id);
this.displayBoundsInfo.delete(display.id);
// Small delay so Electron can fully clean up before a new window is created
setTimeout(() => {
if (this.isQuitting) return;
logger.info(
`[OverlayManager] Recreating renderer for display ${display.id}`
);
this.createWindowForDisplay(display, isPrimary);
}, 1000);
});
browserWindow.on('unresponsive', () => {
logger.warn(
`[OverlayManager] Renderer unresponsive for display ${display.id}${isPrimary ? ' (PRIMARY)' : ''}`
);
});
browserWindow.on('responsive', () => {
logger.info(
`[OverlayManager] Renderer responsive again for display ${display.id}${isPrimary ? ' (PRIMARY)' : ''}`
);
});
// Track readiness of both events to avoid race condition
let boundsReady = false;
let pageLoaded = false;
const sendBoundsIfReady = () => {
if (!boundsReady || !pageLoaded) return;
if (browserWindow.isDestroyed()) return;
const boundsInfo = this.displayBoundsInfo.get(display.id);
browserWindow.webContents.send('containerBoundsInfo', boundsInfo);
this.onWindowReadyCallbacks.forEach((cb) => cb(`display-${display.id}`));
// Apply shrink-wrap after initial setup when not in edit mode
if (this.isLocked) {
this.updateOverlayBounds();
}
};
browserWindow.once('ready-to-show', () => {
if (browserWindow.isDestroyed()) return;
browserWindow.setPosition(expectedBounds.x, expectedBounds.y);
browserWindow.setSize(expectedBounds.width, expectedBounds.height);
browserWindow.show();
const actualBounds = browserWindow.getBounds();
const offset = {
x: actualBounds.x - expectedBounds.x,
y: actualBounds.y - expectedBounds.y,
};
const allDisplayBounds = screen
.getAllDisplays()
.map((d) => ({ ...d.bounds }));
const boundsInfo: ContainerBoundsInfo = {
expected: expectedBounds,
actual: actualBounds,
offset,
displayId: display.id,
isPrimary,
displayBounds: { ...expectedBounds },
allDisplayBounds,
};
this.displayBoundsInfo.set(display.id, boundsInfo);
logger.info(
`[OverlayManager] Display ${display.id} final bounds: x=${actualBounds.x}, y=${actualBounds.y}, ${actualBounds.width}x${actualBounds.height}`
);
if (offset.x !== 0 || offset.y !== 0) {
logger.warn(
`[OverlayManager] Display ${display.id} OS constrained position! Offset: (${offset.x}, ${offset.y})`
);
}
boundsReady = true;
sendBoundsIfReady();
});
browserWindow.webContents.on('did-finish-load', () => {
if (browserWindow.isDestroyed()) return;
if (!pageLoaded) {
// First load: coordinate with ready-to-show before sending bounds
pageLoaded = true;
sendBoundsIfReady();
} else {
// Subsequent reload (e.g., Vite HMR after a branch switch in dev mode).
// Re-send containerBoundsInfo and re-trigger ready callbacks so the SDK
// bridge re-sends runningState/telemetry/sessionData to the reloaded renderer.
const boundsInfo = this.displayBoundsInfo.get(display.id);
if (boundsInfo) {
browserWindow.webContents.send('containerBoundsInfo', boundsInfo);
}
this.onWindowReadyCallbacks.forEach((cb) =>
cb(`display-${display.id}`)
);
}
});
return browserWindow;
}
/**
* Get the primary display's bounds info (backward compatibility)
*/
public getContainerBoundsInfo(): ContainerBoundsInfo | null {
const primaryDisplay = screen.getPrimaryDisplay();
return this.displayBoundsInfo.get(primaryDisplay.id) ?? null;
}
/**
* Compute the bounding box of all enabled widgets assigned to a given display.
* Returns null if there are no widgets for the display.
*/
private computeWidgetBounds(
displayId: number,
dashboard: DashboardLayout,
displayBounds: Electron.Rectangle
): Electron.Rectangle | null {
const primaryDisplay = screen.getPrimaryDisplay();
const isPrimary = displayId === primaryDisplay.id;
const enabledWidgets = dashboard.widgets.filter((w) => w.enabled);
const widgetsForDisplay = enabledWidgets.filter((widget) => {
const centerX = widget.layout.x + widget.layout.width / 2;
const centerY = widget.layout.y + widget.layout.height / 2;
const inThisDisplay =
centerX >= displayBounds.x &&
centerX < displayBounds.x + displayBounds.width &&
centerY >= displayBounds.y &&
centerY < displayBounds.y + displayBounds.height;
return inThisDisplay || (!inThisDisplay && isPrimary);
});
if (widgetsForDisplay.length === 0) return null;
const pad = OverlayManager.SHRINK_WRAP_PADDING;
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const widget of widgetsForDisplay) {
minX = Math.min(minX, widget.layout.x);
minY = Math.min(minY, widget.layout.y);
maxX = Math.max(maxX, widget.layout.x + widget.layout.width);
maxY = Math.max(maxY, widget.layout.y + widget.layout.height);
}
// Clamp to display bounds
const x = Math.max(displayBounds.x, Math.floor(minX - pad));
const y = Math.max(displayBounds.y, Math.floor(minY - pad));
const right = Math.min(
displayBounds.x + displayBounds.width,
Math.ceil(maxX + pad)
);
const bottom = Math.min(
displayBounds.y + displayBounds.height,
Math.ceil(maxY + pad)
);
return { x, y, width: right - x, height: bottom - y };
}
/**
* Shrink-wrap or expand overlay windows based on edit mode.
* When locked (not editing), windows shrink to the bounding box of their widgets.
* When unlocked (editing), windows expand to full display bounds.
*/
public updateOverlayBounds(dashboard?: DashboardLayout): void {
if (dashboard) {
this.currentDashboard = dashboard;
}
if (!this.currentDashboard) return;
for (const [displayId, win] of this.displayWindows.entries()) {
if (win.isDestroyed()) continue;
const fullBounds = this.displayFullBounds.get(displayId);
if (!fullBounds) continue;
let targetBounds: Electron.Rectangle;
if (!this.isLocked) {
// Edit mode: expand to full display
targetBounds = fullBounds;
} else {
// Locked: shrink-wrap to widget bounding box
const widgetBounds = this.computeWidgetBounds(
displayId,
this.currentDashboard,
fullBounds
);
targetBounds = widgetBounds ?? fullBounds;
}
const currentBounds = win.getBounds();
if (
currentBounds.x === targetBounds.x &&
currentBounds.y === targetBounds.y &&
currentBounds.width === targetBounds.width &&
currentBounds.height === targetBounds.height
) {
continue;
}
win.setBounds(targetBounds);
const actualBounds = win.getBounds();
const boundsInfo = this.displayBoundsInfo.get(displayId);
if (boundsInfo) {
boundsInfo.expected = targetBounds;
boundsInfo.actual = actualBounds;
boundsInfo.offset = {
x: actualBounds.x - targetBounds.x,
y: actualBounds.y - targetBounds.y,
};
win.webContents.send('containerBoundsInfo', boundsInfo);
}
}
}
/**
* Toggle edit mode - enables/disables mouse interaction with overlays
*/
public toggleLockOverlays(): boolean {
this.isLocked = !this.isLocked;
if (!this.isLocked) {
this.updateOverlayBounds();
}
for (const win of this.displayWindows.values()) {
if (win.isDestroyed()) continue;
win.setIgnoreMouseEvents(this.isLocked);
win.webContents.send('editModeToggled', !this.isLocked);
if (!this.isLocked) {
win.focus();
}
}
if (this.isLocked) {
this.updateOverlayBounds();
}
// Raise settings window to layer 2 during edit mode so it appears above
// overlay windows (layer 1); revert to normal layering when not editing.
if (
this.currentSettingsWindow &&
!this.currentSettingsWindow.isDestroyed()
) {
if (!this.isLocked) {
this.currentSettingsWindow.setAlwaysOnTop(true, 'screen-saver', 2);
} else {
this.currentSettingsWindow.setAlwaysOnTop(false);
}
}
return this.isLocked;
}
/**
* Send a message to the container window and settings window
*/
// High-frequency messages that only the overlay container needs
private static readonly OVERLAY_ONLY_MESSAGES = new Set([
'telemetryInspector:telemetry',
'runningState',
]);
public publishMessage(key: string, value: unknown): void {
// Send to all display overlay windows
for (const win of this.displayWindows.values()) {
if (win.isDestroyed()) continue;
if (
(key === 'telemetryInspector:telemetry' || key === 'sessionData') &&
!win.isVisible()
) {
continue;
}
if (
(key === 'telemetryInspector:telemetry' || key === 'sessionData') &&
!this.rendererDataSubscriptions?.has(
win.webContents.id,
key === 'telemetryInspector:telemetry'
? 'telemetryInspector'
: 'sessionData'
)
) {
continue;
}
try {
win.webContents.send(key, value);
} catch (e) {
logger.error(`Failed to send message ${key} to overlay window`, e);
}
}
// Skip high-frequency telemetry messages for the settings window
if (OverlayManager.OVERLAY_ONLY_MESSAGES.has(key)) {
return;
}
// Send to settings window
if (
this.currentSettingsWindow &&
!this.currentSettingsWindow.isDestroyed()
) {
try {
this.currentSettingsWindow.webContents.send(key, value);
} catch (e) {
logger.error(`Failed to send message ${key} to settings window`, e);
}
}
}
public setRendererDataSubscriptions(
subscriptions: RendererDataSubscriptions
): void {
this.rendererDataSubscriptions = subscriptions;
}
public hasTelemetryInspectorSubscribers(): boolean {
return (
this.rendererDataSubscriptions?.hasAny('telemetryInspector') ?? false
);
}
/**
* Send a message to a specific overlay (for backwards compatibility)
* In container mode, this just sends to the container
*/
public publishMessageToOverlay(
_id: string,
key: string,
value: unknown
): void {
this.publishMessage(key, value);
}
public onOverlayReady(callback: (id: string) => void) {
this.onWindowReadyCallbacks.add(callback);
return () => this.onWindowReadyCallbacks.delete(callback);
}
/**
* Close all display overlay windows
*/
public closeAllOverlays(): void {
for (const win of this.displayWindows.values()) {
if (!win.isDestroyed()) {
win.close();
}
}
this.displayWindows.clear();
this.displayBoundsInfo.clear();
this.displayFullBounds.clear();
}
public markQuitting(): void {
this.isQuitting = true;
}
public quitApp(): void {
if (this.isQuitting) return;
this.isQuitting = true;
this.closeAllOverlays();
if (
this.currentSettingsWindow &&
!this.currentSettingsWindow.isDestroyed()
) {
this.currentSettingsWindow.destroy();
this.currentSettingsWindow = undefined;
}
app.quit();
}
/**
* Create windows for any displays that need them but don't have one yet.
* Uses widget center-point assignment (same logic as createOverlays) to
* determine which displays are required. Safe to call during drag operations
* since it never destroys existing windows.
*/
public ensureDisplayWindows(dashboardLayout: DashboardLayout): void {
this.currentDashboard = dashboardLayout;
const allDisplays = screen.getAllDisplays();
const primaryDisplay = screen.getPrimaryDisplay();
const displaysWithWidgets = new Set<number>();
for (const widget of dashboardLayout.widgets) {
if (!widget.enabled) continue;
const centerX = widget.layout.x + widget.layout.width / 2;
const centerY = widget.layout.y + widget.layout.height / 2;
for (const display of allDisplays) {
const { x, y, width, height } = display.bounds;
if (
centerX >= x &&
centerX < x + width &&
centerY >= y &&
centerY < y + height
) {
displaysWithWidgets.add(display.id);
break;
}
}
}
displaysWithWidgets.add(primaryDisplay.id);
for (const display of allDisplays) {
if (!displaysWithWidgets.has(display.id)) continue;
const existing = this.displayWindows.get(display.id);
if (existing && !existing.isDestroyed()) continue;
const isPrimary = display.id === primaryDisplay.id;
this.createWindowForDisplay(display, isPrimary);
}
// Shrink-wrap windows when not in edit mode
if (this.isLocked) {
this.updateOverlayBounds();
}
}
/**
* Ensure at least one overlay window exists per active display.
* Widget visibility is handled by the React OverlayContainer.
*/
public closeOrCreateWindows(dashboardLayout?: DashboardLayout): void {
if (dashboardLayout) {
this.ensureDisplayWindows(dashboardLayout);
return;
}
if (this.displayWindows.size === 0) {
const allDisplays = screen.getAllDisplays();
const primaryDisplay = screen.getPrimaryDisplay();
for (const display of allDisplays) {
const isPrimary = display.id === primaryDisplay.id;
this.createWindowForDisplay(display, isPrimary);
}
}
}
/**
* Force refresh by closing all overlay windows and recreating them
*/
public forceRefreshOverlays(dashboardLayout?: DashboardLayout): void {
this.closeAllOverlays();
if (dashboardLayout) {
this.createOverlays(dashboardLayout);
} else {
const allDisplays = screen.getAllDisplays();
const primaryDisplay = screen.getPrimaryDisplay();
for (const display of allDisplays) {
const isPrimary = display.id === primaryDisplay.id;
this.createWindowForDisplay(display, isPrimary);
}
}
}
public focusSettingsWindow(widgetType?: string): void {
if (
!this.currentSettingsWindow ||
this.currentSettingsWindow.isDestroyed()
) {
this.currentSettingsWindow = this.createSettingsWindow(widgetType);
return;
}
const win = this.currentSettingsWindow;
if (win.isMinimized()) {
win.restore();
}
win.show();
win.focus();
if (widgetType) {
win.webContents.send('navigateToSettings', widgetType);
}
}
/**
* Check dashboard settings and disable hardware acceleration if configured.
* Must be called before the app is ready.
*/
public setupHardwareAcceleration(): void {
const dashboard = getDashboard('default');
if (dashboard?.generalSettings?.disableHardwareAcceleration) {
app.disableHardwareAcceleration();
}
}
/**
* Apply user-configured Chromium command-line switches.
* Must be called before the app is ready, as Chromium reads switches
* during GPU process initialization.
*/
public setupChromiumFlags(): void {
const flags = getChromiumFlags();
const disableFeatures = new Set<string>(flags.disableFeatures ?? []);
if (flags.disableNativeWinOcclusion) {
disableFeatures.add('CalculateNativeWinOcclusion');
}
if (disableFeatures.size > 0) {
app.commandLine.appendSwitch(
'disable-features',
Array.from(disableFeatures).join(',')
);
}
const enableFeatures = flags.enableFeatures ?? [];
if (enableFeatures.length > 0) {
app.commandLine.appendSwitch('enable-features', enableFeatures.join(','));
}
if (flags.angleBackend && flags.angleBackend !== 'default') {
app.commandLine.appendSwitch('use-angle', flags.angleBackend);
}
if (flags.disableDirectComposition) {
app.commandLine.appendSwitch('disable-direct-composition');
}
// customSwitches is already allowlist-filtered in getChromiumFlags()
// (see docs/ARCHITECTURE_REVIEW.md finding S1). Anything unsafe was
// dropped at the storage normalisation step; parsing here is a clean,
// structural pass over the safe subset.
for (const { name, value } of parseCustomSwitches(
flags.customSwitches ?? ''
)) {
if (value === undefined) {
app.commandLine.appendSwitch(name);
} else {
app.commandLine.appendSwitch(name, value);
}
}
logger.info('[OverlayManager] Applied Chromium flags', flags);
}
public setupAutoStart(): void {
const dashboard = getDashboard('default');
app.setLoginItemSettings({
openAtLogin: dashboard?.generalSettings?.enableAutoStart ?? false,
});
}
private shouldCloseToTray(): boolean {
const dashboard = getDashboard('default');
return dashboard?.generalSettings?.closeToTray ?? true;
}
private notifyTrayAccessOnce(): void {
const trayNotificationShown = readData<boolean>('trayNotificationShown');
if (trayNotificationShown) return;
new Notification({
title: 'irDashies',
body: 'Settings window is still accessible via the system tray icon',
}).show();
writeData('trayNotificationShown', true);
}
/**
* Setup a single instance lock for the application. If the application is already running, it will quit the new instance.
* @returns true if the lock was obtained, false otherwise
*/
public setupSingleInstanceLock(): boolean {
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
logger.warn('[OverlayManager] Failed to get single instance lock.');
const isDev = !!MAIN_WINDOW_VITE_DEV_SERVER_URL;
if (!isDev) {
app.quit();
this.hasSingleInstanceLock = false;
return false;
}
// In dev mode, we allow it to continue because Forge might not have
// fully killed the previous process's lock yet.
logger.warn('[OverlayManager] Dev mode detected, continuing anyway...');
this.hasSingleInstanceLock = true;
return true;
}
this.hasSingleInstanceLock = true;
app.on('second-instance', () => {
this.focusSettingsWindow();
});
return true;
}
/**
* Check if the application has obtained the single instance lock.
* This should be checked before starting services that require exclusive access (like servers).
*/
public hasLock(): boolean {
return this.hasSingleInstanceLock;
}
public createSettingsWindow(
widgetType?: string,
options?: { startHidden?: boolean }
): BrowserWindow {
if (this.currentSettingsWindow) {
if (this.currentSettingsWindow.isMinimized()) {
this.currentSettingsWindow.restore();
}
this.currentSettingsWindow.show();
this.currentSettingsWindow.focus();
return this.currentSettingsWindow;
}
const startHidden = options?.startHidden ?? false;
// Load saved window bounds
const savedBounds = loadWindowBounds();
const defaultOptions: BrowserWindowConstructorOptions = {
title: `irDashies - Settings`,
frame: true,
width: 800,
height: 700,
autoHideMenuBar: true,
acceptFirstMouse: true,
icon: getIconPath(),
// Start hidden and reveal on ready-to-show (same pattern as overlay
// windows). This avoids a race where a window created with the default
// show:true is auto-shown by Electron on first paint even after an early
// hide() call — which is what broke the "Start minimized" setting.
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
backgroundThrottling: false,
},
};
// Create the browser window with saved bounds if available
const browserWindow = new BrowserWindow(
savedBounds ? { ...defaultOptions, ...savedBounds } : defaultOptions
);
this.currentSettingsWindow = browserWindow;
// Reveal the window once its content is ready, unless it should start
// minimized to the system tray (the "Start minimized" general setting).
browserWindow.once('ready-to-show', () => {
if (browserWindow.isDestroyed()) return;
// Runs before the startHidden check: a window that starts in the tray is
// shown later, and would otherwise be revealed somewhere unreachable.
ensureWindowOnScreen(browserWindow);
if (startHidden) return;
browserWindow.show();
browserWindow.focus();
});
// During edit mode, raise settings window above overlay windows (layer 1).
// Outside edit mode, use normal window layering.
if (!this.isLocked) {
browserWindow.setAlwaysOnTop(true, 'screen-saver', 2);
}
// Track window movement and resizing to save bounds
trackSettingsWindowMovement(browserWindow);
// and load the index.html of the app.
const hash = widgetType ? `/settings/${widgetType}` : `/settings`;
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
browserWindow.loadURL(`${MAIN_WINDOW_VITE_DEV_SERVER_URL}#${hash}`);
} else {
browserWindow.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
{ hash }
);
}
browserWindow.on('close', (event) => {
if (this.isQuitting) return;
if (this.shouldCloseToTray()) {
event.preventDefault();
browserWindow.hide();
this.notifyTrayAccessOnce();
return;
}
this.quitApp();
});
browserWindow.on('closed', () => {
this.currentSettingsWindow = undefined;
});
return browserWindow;
}
}
/**
* Correct a window that has ended up where no display covers it.
*
* Validating the saved bounds on the way in only guards the restore path. This
* checks where the window actually landed, so it also catches a window placed
* off-screen by something other than a stale saved position — Electron's own
* default placement, or a display set that was not fully enumerated when the
* window was created. #539 was reported on a freshly installed Windows with no
* saved bounds at all, which the restore-path check cannot explain, so the
* guard is deliberately cause-agnostic: it asks only whether the window can be
* reached, never why it could not be.
*/
function ensureWindowOnScreen(browserWindow: BrowserWindow): void {
const actual = browserWindow.getBounds();
const corrected = sanitizeWindowBounds(
actual,
screen.getAllDisplays().map((display) => display.workArea),
screen.getPrimaryDisplay().workArea