Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1632 lines (1479 loc) · 49.3 KB
/
Copy pathapp.js
File metadata and controls
1632 lines (1479 loc) · 49.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
const electron = require('electron');
const { autoUpdater } = require('electron-updater');
const log = require('electron-log');
const express = require('express');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const portfinder = require('portfinder');
const i18n = require('i18next');
const i18nBackend = require('i18next-node-fs-backend');
const os = require('os');
const fetch = require('node-fetch');
const remote = require('@electron/remote/main');
// eslint-disable-next-line import/no-unresolved
const aptabase = require('@aptabase/electron/main');
const Sentry = require('@sentry/electron/main');
require('dotenv').config();
remote.initialize();
const expressApp = express();
/* eslint-disable import/order */
const httpBase = require('http').Server(expressApp);
const http = require('http-shutdown')(httpBase);
const io = require('socket.io')(http);
/* eslint-enable */
const prodConfig = require('./config.prod.json');
const defaultPrefs = require('./www/configs/defaults.json');
const themes = require('./www/configs/themes.json');
const Analytics = require('./analytics');
const { styles } = require('./resetViewerStyles');
// Are we packaging for a platform's app store?
const appstore = false;
const maxChangeLogSeenCount = 5;
/* eslint-disable import/no-unresolved, import/extensions */
const Store = require('./www/js/store');
const {
savedSettingsCamelCase,
} = require('./www/js/common/store/user-settings/get-saved-user-settings');
/* eslint-enable */
const savedSettings = savedSettingsCamelCase();
const platform = os.platform();
let isUnsupportedWindow = false;
if (platform === 'win32') {
const version = /\d+\.\d/.exec(os.release())[0];
if (version !== '6.3' && version !== '10.0') {
isUnsupportedWindow = true;
}
}
// Configuring the i18n
i18n.use(i18nBackend);
i18n.init({
backend: {
loadPath: path.join(__dirname, './www/locales/{{lng}}.json'),
jsonIndent: 2,
},
fallbackLng: 'en',
});
expressApp.use(express.static(path.join(__dirname, 'www', 'obs')));
expressApp.use(express.json());
const {
app,
webContents,
BrowserWindow,
dialog,
ipcMain,
safeStorage,
globalShortcut,
systemPreferences,
shell,
} = electron;
const store = new Store({
configName: 'user-preferences',
defaults: defaultPrefs,
});
const appVersion = app.getVersion();
const overlayCast = true;
// Reset to default theme if theme not found
const currentTheme = themes.find((theme) => theme.key === store.getUserPref('app.theme'));
if (currentTheme === undefined) {
store.setUserPref('app.theme', themes[0].key);
}
let mainWindow;
let viewerWindow = false;
let projectionWindow = false;
/** Embedded controller <webview> (in-app preview) — kept separate from external BrowserWindows */
let embeddedViewerWebContents = null;
let projectionViewport = null;
let projectionRange = null;
/** WebContents of a Display 2 window that has loaded but is not yet projectionWindow. */
let pendingProjectionWebContents = null;
/** @type {{ channel: string, data: any } | null} Last IPC payload for classic Display 1 restore after recreate */
let lastPresenterIpc = null;
/** Pinned external display ids — never reassigned from getAllDisplays() order alone */
let pinnedPresenterDisplayId = null;
let pinnedProjectionDisplayId = null;
let startChangelogOpenTimer;
let endChangelogOpenTimer;
app.setAsDefaultProtocolClient('sttm-desktop');
// Initialize Aptabase with key from appropriate source
let aptabaseKey;
let sentryDsn;
if (process.env.NODE_ENV === 'development') {
aptabaseKey = process.env.APTABASE_KEY;
sentryDsn = process.env.SENTRY_DSN;
} else {
try {
aptabaseKey = prodConfig.APTABASE_KEY;
sentryDsn = prodConfig.SENTRY_DSN;
} catch (error) {
console.error('Failed to load production config:', error);
}
}
if (aptabaseKey) {
aptabase.initialize(aptabaseKey);
}
if (sentryDsn) {
Sentry.init({
dsn: sentryDsn,
});
}
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient('sttm-desktop', process.execPath, [path.resolve(process.argv[1])]);
}
const secondaryWindows = {
changelogWindow: {
obj: false,
url: `file://${__dirname}/www/changelog.html`,
onClose: () => {
const count = store.get('changelog-seen-count');
endChangelogOpenTimer = new Date().getTime();
store.set('changelog-seen', appVersion);
store.set('changelog-seen-count', count + 1);
global.analytics.trackEvent({
category: 'changelog',
action: 'closed',
label: 'changelog',
value: (endChangelogOpenTimer - startChangelogOpenTimer) / 1000.0,
});
},
show: () => {
startChangelogOpenTimer = new Date().getTime();
},
},
helpWindow: {
obj: false,
url: `file://${__dirname}/www/help.html`,
},
overlayWindow: {
obj: false,
url: `file://${__dirname}/www/overlay.html`,
},
shortcutLegend: {
obj: false,
url: `file://${__dirname}/www/legend.html`,
},
};
let manualUpdate = false;
let lastLine;
function openSecondaryWindow(windowName) {
const window = secondaryWindows[windowName];
const openWindow = BrowserWindow.getAllWindows().filter((item) => item.getURL() === window.url);
if (openWindow.length > 0) {
openWindow[0].show();
} else {
window.obj = new BrowserWindow({
width: 1366,
height: 768,
show: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
nodeIntegrationInWorker: true,
media: true,
},
});
remote.enable(window.obj.webContents);
window.obj.setMenu(null);
window.obj.webContents.on('did-finish-load', () => {
window.obj.show();
window.obj.focus();
if (window.show) {
window.show();
}
if (window.focus) {
window.focus();
}
});
window.obj.loadURL(window.url);
window.obj.on('close', () => {
window.obj = false;
if (window.onClose) {
window.onClose();
}
});
}
}
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
expressApp.post('/api/bani-control', (req, res) => {
const data = req.body;
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('bani-controller-data', data);
}
res.json({ success: true });
});
// autoUpdater events
autoUpdater.on('checking-for-update', () => {
if (!isUnsupportedWindow) {
mainWindow.webContents.send('checking-for-update');
}
});
autoUpdater.on('update-available', () => {
if (!isUnsupportedWindow) {
mainWindow.webContents.send('update-available');
}
});
autoUpdater.on('update-not-available', () => {
if (!isUnsupportedWindow) {
mainWindow.webContents.send('update-not-available');
if (manualUpdate) {
dialog.showMessageBox({
type: 'info',
buttons: [i18n.t('OK')],
defaultId: 0,
title: i18n.t('NO_UPDATE_AVAILABLE'),
message: i18n.t('NO_UPDATE_AVAILABLE'),
detail: i18n.t('LATEST_VERSION', { appVersion }),
});
}
}
});
autoUpdater.on('update-downloaded', () => {
if (!isUnsupportedWindow) {
mainWindow.webContents.send('update-downloaded');
dialog
.showMessageBox({
type: 'info',
buttons: [i18n.t('DISMISS'), i18n.t('INSTALL_N_RESTART')],
defaultId: 1,
title: i18n.t('UPDATE_AVAILABLE'),
message: i18n.t('UPDATE_AVAILABLE'),
detail: i18n.t('UPDATE_DOWNLOADED'),
cancelId: 0,
})
.then(({ response }) => {
if (response === 1 || response === '1') {
autoUpdater.quitAndInstall();
}
global.analytics.trackEvent({
category: 'menu',
action: 'install-restart',
label: 'from-update-dialog',
value: response,
});
});
}
});
autoUpdater.on('error', () => {
if (!isUnsupportedWindow) {
if (manualUpdate) {
dialog.showMessageBox({
type: 'error',
buttons: [i18n.t('OK')],
defaultId: 0,
title: i18n.t('SOMETHING_WENT_WRONG_UPDATE_TITLE'),
message: i18n.t('SOMETHING_WENT_WRONG_UPDATE_BODY'),
detail: i18n.t('CURRENT_VERSION', { appVersion }),
});
}
}
});
function checkForUpdates(manual = false) {
if (process.env.NODE_ENV !== 'development') {
if (manual) {
manualUpdate = true;
}
if (!isUnsupportedWindow) {
autoUpdater.checkForUpdatesAndNotify();
}
}
}
function saveToken(token) {
if (!safeStorage.isEncryptionAvailable()) {
throw new Error('Encryption is not available on this system');
}
const userDataPath = app.getPath('userData');
const encryptedToken = safeStorage.encryptString(token);
const tokenPath = path.join(userDataPath, 'userToken.enc');
fs.writeFileSync(tokenPath, encryptedToken);
}
function retrieveToken() {
const userDataPath = app.getPath('userData');
const tokenPath = path.join(userDataPath, 'userToken.enc');
if (fs.existsSync(tokenPath)) {
const encryptedToken = fs.readFileSync(tokenPath);
if (!safeStorage.isEncryptionAvailable()) {
throw new Error('Decryption is not available on this system');
}
return safeStorage.decryptString(encryptedToken);
}
return null;
}
function deleteToken() {
const userDataPath = app.getPath('userData');
const tokenPath = path.join(userDataPath, 'userToken.enc');
fs.unlink(tokenPath, () => {
// eslint-disable-next-line no-console
console.log('token deleted');
});
}
let display2Connected = false;
function trackDisplay(action) {
if (!global.analytics) return;
global.analytics.trackEvent({
category: 'display',
action,
label: '',
value: '',
});
}
function getExternalDisplays() {
const primaryDisplayId = electron.screen.getPrimaryDisplay().id;
return electron.screen.getAllDisplays().filter((display) => display.id !== primaryDisplayId);
}
function trackDisplay2Connection() {
const connected = getExternalDisplays().length >= 2;
if (connected === display2Connected) return;
display2Connected = connected;
trackDisplay(connected ? 'display-2-connected' : 'display-2-disconnected');
}
/** Stable sort so first-time bootstrap is deterministic, not API enumeration order. */
function sortDisplaysStable(displays) {
return displays.slice().sort((a, b) => {
if (a.bounds.x !== b.bounds.x) return a.bounds.x - b.bounds.x;
if (a.bounds.y !== b.bounds.y) return a.bounds.y - b.bounds.y;
return a.id - b.id;
});
}
/**
* Display 1 (classic slide) = one external, pinned by id.
* Display 2 (teleprompter) = optional second external, pinned by id.
* Controller stays on OS primary. Never thrash on getAllDisplays() index.
*/
function resolveDisplayRoles() {
const externals = sortDisplaysStable(getExternalDisplays());
const byId = new Map(externals.map((display) => [display.id, display]));
let presenterDisplay = null;
if (pinnedPresenterDisplayId != null && byId.has(pinnedPresenterDisplayId)) {
presenterDisplay = byId.get(pinnedPresenterDisplayId);
} else if (
viewerWindow &&
!viewerWindow.isDestroyed() &&
viewerWindow.displayId != null &&
byId.has(viewerWindow.displayId)
) {
presenterDisplay = byId.get(viewerWindow.displayId);
pinnedPresenterDisplayId = presenterDisplay.id;
} else if (externals.length > 0) {
[presenterDisplay] = externals;
pinnedPresenterDisplayId = presenterDisplay.id;
} else {
pinnedPresenterDisplayId = null;
}
const remaining = externals.filter(
(display) => !presenterDisplay || display.id !== presenterDisplay.id,
);
const remainingById = new Map(remaining.map((display) => [display.id, display]));
let projectionDisplay = null;
if (pinnedProjectionDisplayId != null && remainingById.has(pinnedProjectionDisplayId)) {
projectionDisplay = remainingById.get(pinnedProjectionDisplayId);
} else if (
projectionWindow &&
!projectionWindow.isDestroyed() &&
projectionWindow.displayId != null &&
remainingById.has(projectionWindow.displayId)
) {
projectionDisplay = remainingById.get(projectionWindow.displayId);
pinnedProjectionDisplayId = projectionDisplay.id;
} else if (remaining.length > 0) {
[projectionDisplay] = remaining;
pinnedProjectionDisplayId = projectionDisplay.id;
} else {
pinnedProjectionDisplayId = null;
}
if (presenterDisplay) {
pinnedPresenterDisplayId = presenterDisplay.id;
}
if (projectionDisplay) {
pinnedProjectionDisplayId = projectionDisplay.id;
} else {
pinnedProjectionDisplayId = null;
}
return { presenterDisplay, projectionDisplay };
}
/**
* Same cover as upstream STTM desktop dev createViewer (D1 golden, no menu):
* show → setFullScreen(true) → focus controller.
* setBounds first so dual-external windows land on the correct display.
*/
function presentOnExternalDisplay(browserWindow, display) {
if (!browserWindow || browserWindow.isDestroyed() || !display) return;
const { x, y, width, height } = display.bounds;
try {
browserWindow.setBounds({ x, y, width, height }, false);
browserWindow.show();
browserWindow.setFullScreen(true);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.focus();
}
} catch (err) {
log.error(`[display] presentOnExternalDisplay failed: ${err.message}`);
}
}
/** Display 2 — identical fullscreen path as Display 1. */
function coverProjectionDisplay(browserWindow, display) {
presentOnExternalDisplay(browserWindow, display);
}
// Pending placement timer per window, so a new move cancels the previous one
const placeDisplayTimers = new WeakMap();
function placeWindowOnDisplay(browserWindow, display) {
if (!browserWindow || browserWindow.isDestroyed() || !display) return;
clearTimeout(placeDisplayTimers.get(browserWindow));
placeDisplayTimers.delete(browserWindow);
const isProjection = browserWindow === projectionWindow;
let label = 'window';
if (browserWindow === viewerWindow) {
label = 'presenter';
} else if (isProjection) {
label = 'projection';
}
const { x, y, width, height } = display.bounds;
const targetId = display.id;
// eslint-disable-next-line no-param-reassign
browserWindow.displayId = targetId;
// Exit any FS mode so bounds can change, then re-apply the right cover.
try {
if (
typeof browserWindow.setSimpleFullScreen === 'function' &&
browserWindow.isSimpleFullScreen()
) {
browserWindow.setSimpleFullScreen(false);
}
if (browserWindow.isFullScreen()) {
browserWindow.setFullScreen(false);
}
browserWindow.setAlwaysOnTop(false);
} catch (err) {
log.warn(`[display] ${label} pre-move exit failed: ${err.message}`);
}
const placeTimer = setTimeout(() => {
placeDisplayTimers.delete(browserWindow);
if (browserWindow.isDestroyed()) return;
if (isProjection) {
coverProjectionDisplay(browserWindow, display);
} else {
presentOnExternalDisplay(browserWindow, display);
}
// eslint-disable-next-line no-param-reassign
browserWindow.displayId = targetId;
const bounds = browserWindow.getBounds();
const onTarget =
Math.abs(bounds.x - x) < 80 &&
Math.abs(bounds.y - y) < 80 &&
Math.abs(bounds.width - width) < 80;
log.info(
`[display] ${label} → id=${targetId} target=(${x},${y} ${width}x${height}) ` +
`actual=(${bounds.x},${bounds.y} ${bounds.width}x${bounds.height}) ok=${onTarget}`,
);
if (!onTarget) {
setTimeout(() => {
if (browserWindow.isDestroyed()) return;
if (isProjection) {
coverProjectionDisplay(browserWindow, display);
} else {
presentOnExternalDisplay(browserWindow, display);
}
const retry = browserWindow.getBounds();
log.info(
`[display] ${label} retry actual=(${retry.x},${retry.y} ${retry.width}x${retry.height})`,
);
}, 100);
}
}, 50);
placeDisplayTimers.set(browserWindow, placeTimer);
}
function replayLastPresenterIpc(targetWindow) {
if (!targetWindow || targetWindow.isDestroyed() || !lastPresenterIpc) return;
targetWindow.webContents.send(lastPresenterIpc.channel, lastPresenterIpc.data);
}
function sendToViewerWindows(channel, ...args) {
[viewerWindow, projectionWindow].forEach((window) => {
if (window && !window.isDestroyed()) window.webContents.send(channel, ...args);
});
// Always keep the in-app controller preview in sync (single-monitor / Presentation).
if (embeddedViewerWebContents && !embeddedViewerWebContents.isDestroyed()) {
try {
embeddedViewerWebContents.send(channel, ...args);
} catch (err) {
log.warn(`[preview] Failed to send ${channel} to embedded webview: ${err.message}`);
}
}
}
function showChangelog() {
const lastSeen = store.get('changelog-seen');
const lastSeenCount = store.get('changelog-seen-count');
const { limitChangeLog } = savedSettings;
return lastSeen !== appVersion || (lastSeenCount < maxChangeLogSeenCount && !limitChangeLog);
}
function createViewer(ipcData, display) {
if (viewerWindow && !viewerWindow.isDestroyed()) return;
const targetDisplay = display || resolveDisplayRoles().presenterDisplay;
if (!targetDisplay) return;
if (ipcData && ipcData.send) {
lastPresenterIpc = { channel: ipcData.send, data: ipcData.data };
}
const presenterWindow = new BrowserWindow({
width: targetDisplay.size.width,
height: targetDisplay.size.height,
x: targetDisplay.bounds.x,
y: targetDisplay.bounds.y,
autoHideMenuBar: true,
show: false,
titleBarStyle: 'hidden',
frame: false,
backgroundColor: '#000000',
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
nodeIntegrationInWorker: true,
media: true,
},
});
viewerWindow = presenterWindow;
presenterWindow.displayId = targetDisplay.id;
pinnedPresenterDisplayId = targetDisplay.id;
// Do NOT assign global.webview here. That ref is reserved for the controller's
// embedded <webview> (set in ViewerContent). Overwriting it with the external
// BrowserWindow breaks in-app preview updates (update-viewer-setting).
presenterWindow.loadURL(`file://${__dirname}/www/viewer.html`);
remote.enable(presenterWindow.webContents);
// Upstream dev golden: insertCSS → show → focus → setFullScreen(true) → IPC
presenterWindow.webContents.on('did-finish-load', () => {
presenterWindow.webContents.insertCSS(styles);
presenterWindow.show();
const [width, height] = presenterWindow.getSize();
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('external-display', JSON.stringify({ width, height }));
mainWindow.focus();
if (showChangelog() && secondaryWindows.changelogWindow.obj) {
secondaryWindows.changelogWindow.obj.focus();
}
}
presenterWindow.setFullScreen(true);
presenterWindow.webContents.send('wc-webview-enabled');
presenterWindow.webContents.send('update-settings');
if (ipcData) {
presenterWindow.webContents.send(ipcData.send, ipcData.data);
} else {
replayLastPresenterIpc(presenterWindow);
}
// ShabadDeck renders from the store, not from show-line, and a swap starts it
// empty. Pull the current snapshot so the line + read ticks + home show at
// once instead of only after the next line change.
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('projection-state-request');
}
});
presenterWindow.on('enter-full-screen', () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.focus();
if (showChangelog() && secondaryWindows.changelogWindow.obj) {
secondaryWindows.changelogWindow.obj.focus();
}
}
});
presenterWindow.on('closed', () => {
if (viewerWindow === presenterWindow) {
viewerWindow = false;
// Keep global.webview — it points at the controller embedded preview, not this window.
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('remove-external-display');
}
}
});
presenterWindow.on('resize', () => {
if (mainWindow && !mainWindow.isDestroyed()) {
const [width, height] = presenterWindow.getSize();
mainWindow.webContents.send('external-display', JSON.stringify({ width, height }));
}
});
}
function createProjection(display) {
if (!display || (projectionWindow && !projectionWindow.isDestroyed())) return;
const paneWindow = new BrowserWindow({
width: display.size.width,
height: display.size.height,
x: display.bounds.x,
y: display.bounds.y,
autoHideMenuBar: true,
show: false,
// Match createViewer (Display 1) so native FS covers menu bar the same way.
titleBarStyle: 'hidden',
frame: false,
backgroundColor: '#000000',
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
nodeIntegrationInWorker: true,
media: true,
},
});
projectionWindow = paneWindow;
paneWindow.displayId = display.id;
pinnedProjectionDisplayId = display.id;
paneWindow.loadURL(`file://${__dirname}/www/viewer.html?paneProjection=1`);
// Keep a reference: paneWindow.webContents can't be read once the window is destroyed
const paneWebContents = paneWindow.webContents;
pendingProjectionWebContents = paneWebContents;
remote.enable(paneWindow.webContents);
paneWindow.webContents.on('did-fail-load', (_event, code, description, url) => {
log.error(`[projection] Load failed (${code}): ${description} ${url}`);
});
paneWindow.webContents.on('render-process-gone', (_event, details) => {
log.error(`[projection] Renderer exited: ${details.reason} ${details.exitCode}`);
});
paneWindow.webContents.on('did-finish-load', () => {
// Same golden path as createViewer / upstream D1 (no menu).
paneWindow.webContents.insertCSS(styles);
paneWindow.show();
paneWindow.setFullScreen(true);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.focus();
}
paneWindow.webContents.send('wc-webview-enabled');
// Recreate (swap) starts with an empty viewer store. Ask the controller for
// the current shabad/pane snapshot so Display 2 is not a blank white screen.
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('projection-state-request');
}
});
paneWindow.on('enter-full-screen', () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.focus();
}
});
paneWindow.on('closed', () => {
if (pendingProjectionWebContents === paneWebContents) {
pendingProjectionWebContents = null;
}
if (projectionWindow === paneWindow) {
projectionWindow = false;
}
});
}
ipcMain.on('viewer-render-start', (event, url) => {
if (event.sender === projectionWindow?.webContents) {
log.info(`[projection] Viewer entry loaded: ${url}`);
}
});
ipcMain.on('viewer-boot-error', (event, message) => {
if (event.sender === projectionWindow?.webContents) {
log.error(`[projection] Viewer boot failed: ${message}`);
}
});
ipcMain.on('viewer-runtime-error', (event, message) => {
if (event.sender === projectionWindow?.webContents) {
log.error(`[projection] Viewer runtime failed: ${message}`);
}
});
ipcMain.on('projection-render-state', (event, state) => {
if (event.sender === projectionWindow?.webContents) {
log.info(`[projection] React state: ${JSON.stringify(state)}`);
}
});
/** Tell controller whether Swap Displays is available (2+ externals). */
function notifyDualDisplayState() {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('dual-display-state', {
canSwap: getExternalDisplays().length >= 2,
});
}
/**
* Reconcile classic (Display 1) + optional teleprompter (Display 2) windows.
* Prefer move-in-place over destroy/recreate so Display 1 does not blank.
* Call on display topology changes — not on every show-line.
* Swap uses swapDisplayRoles() instead (native FS move is broken on virtuals).
*/
function syncViewerWindows() {
const { presenterDisplay, projectionDisplay } = resolveDisplayRoles();
log.info(
`[display] sync roles presenter=${presenterDisplay ? presenterDisplay.id : 'none'} ` +
`projection=${projectionDisplay ? projectionDisplay.id : 'none'} ` +
`viewerWin=${viewerWindow && !viewerWindow.isDestroyed() ? viewerWindow.displayId : 'none'} ` +
`projWin=${projectionWindow && !projectionWindow.isDestroyed() ? projectionWindow.displayId : 'none'}`,
);
const movePresenter =
presenterDisplay &&
viewerWindow &&
!viewerWindow.isDestroyed() &&
viewerWindow.displayId !== presenterDisplay.id;
const moveProjection =
projectionDisplay &&
projectionWindow &&
!projectionWindow.isDestroyed() &&
projectionWindow.displayId !== projectionDisplay.id;
if (!presenterDisplay) {
if (viewerWindow && !viewerWindow.isDestroyed()) {
const previousPresenterWindow = viewerWindow;
viewerWindow = false;
previousPresenterWindow.close();
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('remove-external-display');
}
}
} else if (movePresenter) {
placeWindowOnDisplay(viewerWindow, presenterDisplay);
} else if (!viewerWindow || viewerWindow.isDestroyed()) {
createViewer(
lastPresenterIpc
? { send: lastPresenterIpc.channel, data: lastPresenterIpc.data }
: undefined,
presenterDisplay,
);
}
if (!projectionDisplay) {
if (projectionWindow && !projectionWindow.isDestroyed()) {
const previousProjectionWindow = projectionWindow;
projectionWindow = false;
previousProjectionWindow.close();
}
} else if (moveProjection) {
const projWin = projectionWindow;
const projDisplay = projectionDisplay;
const delayMs = movePresenter ? 100 : 0;
setTimeout(() => {
if (!projWin || projWin.isDestroyed()) return;
placeWindowOnDisplay(projWin, projDisplay);
}, delayMs);
} else if (!projectionWindow || projectionWindow.isDestroyed()) {
createProjection(projectionDisplay);
}
notifyDualDisplayState();
trackDisplay2Connection();
}
/**
* Swap = flip pins, create NEW windows (same path as initial load), then close old.
* Do NOT: close-then-create (menu bar), or in-place loadURL (blank first swap).
*/
function swapDisplayRoles() {
const externals = sortDisplaysStable(getExternalDisplays());
if (externals.length < 2) {
log.warn(
`[display] swap ignored — need 2+ externals, got ${externals.length} ` +
`(ids=${externals.map((d) => d.id).join(',')})`,
);
notifyDualDisplayState();
return;
}
const previousPresenterId = pinnedPresenterDisplayId;
const previousProjectionId = pinnedProjectionDisplayId;
if (
previousPresenterId != null &&
previousProjectionId != null &&
previousPresenterId !== previousProjectionId
) {
pinnedPresenterDisplayId = previousProjectionId;
pinnedProjectionDisplayId = previousPresenterId;
} else {
pinnedPresenterDisplayId = externals[1].id;
pinnedProjectionDisplayId = externals[0].id;
}
log.info(
`[display] swap pins ${previousPresenterId}/${previousProjectionId} → ` +
`${pinnedPresenterDisplayId}/${pinnedProjectionDisplayId}; ` +
`externals=${externals.map((d) => `${d.id}@(${d.bounds.x},${d.bounds.y})`).join(' ')}`,
);
const { presenterDisplay, projectionDisplay } = resolveDisplayRoles();
const presenterIpc = lastPresenterIpc
? { send: lastPresenterIpc.channel, data: lastPresenterIpc.data }
: undefined;
const oldViewer = viewerWindow && !viewerWindow.isDestroyed() ? viewerWindow : null;
const oldProjection =
projectionWindow && !projectionWindow.isDestroyed() ? projectionWindow : null;
// Detach globals so create* can run; keep old windows alive until new ones are up.
viewerWindow = false;
projectionWindow = false;
if (oldViewer) {
oldViewer.removeAllListeners('closed');
}
if (oldProjection) {
oldProjection.removeAllListeners('closed');
}
if (presenterDisplay) {
createViewer(presenterIpc, presenterDisplay);
}
if (projectionDisplay) {
createProjection(projectionDisplay);
}
const createdViewer = viewerWindow;
const createdProjection = projectionWindow;
const closeOld = (win) => {
if (!win || win.isDestroyed()) return;
try {
win.close();
} catch (err) {
/* ignore */
}
};
// After old FS windows leave the displays, re-assert cover so macOS menu bar stays hidden.
const recoverFullscreenAfterSwap = () => {
setTimeout(() => {
if (viewerWindow && !viewerWindow.isDestroyed() && presenterDisplay) {
presentOnExternalDisplay(viewerWindow, presenterDisplay);
}
if (projectionWindow && !projectionWindow.isDestroyed() && projectionDisplay) {
coverProjectionDisplay(projectionWindow, projectionDisplay);
}
}, 50);
};
// Close previous pair after new windows finish their first load (FS already applied).
let pending = (presenterDisplay ? 1 : 0) + (projectionDisplay ? 1 : 0);
let settled = false;
let safetyTimer = null;
const finishSwap = () => {
if (settled) return;
settled = true;
clearTimeout(safetyTimer);
closeOld(oldViewer);
closeOld(oldProjection);
recoverFullscreenAfterSwap();
};
const onNewReady = () => {
pending -= 1;
if (pending > 0) return;
finishSwap();
};
if (viewerWindow && !viewerWindow.isDestroyed()) {
viewerWindow.webContents.once('did-finish-load', onNewReady);
}
if (projectionWindow && !projectionWindow.isDestroyed()) {
projectionWindow.webContents.once('did-finish-load', onNewReady);
}
if (pending === 0) {
finishSwap();
}
// Safety: if load hangs, still tear down old windows and recover FS.
// Skip once both windows have loaded, or if a newer swap already replaced them.
safetyTimer = setTimeout(() => {
if (
(presenterDisplay && viewerWindow !== createdViewer) ||
(projectionDisplay && projectionWindow !== createdProjection)
) {
return;
}
finishSwap();
}, 4000);
notifyDualDisplayState();
}
ipcMain.on('projection-state-request', (event) => {
const fromCurrentProjection =
projectionWindow &&
!projectionWindow.isDestroyed() &&
event.sender === projectionWindow.webContents;
const fromPendingProjection = event.sender === pendingProjectionWebContents;
if (
(!fromCurrentProjection && !fromPendingProjection) ||
!mainWindow ||
mainWindow.isDestroyed()
) {
log.warn('[projection] Ignored state request from an unexpected renderer');
return;
}
log.info('[projection] State request received from display renderer');
mainWindow.webContents.send('projection-state-request');
});
ipcMain.on('projection-state-response', (event, state) => {
if (event.sender !== mainWindow?.webContents) {
log.warn('[projection] Ignored state response from an unexpected renderer');
return;
}
const target = projectionWindow && !projectionWindow.isDestroyed() ? projectionWindow : null;
const hasProjectionTarget =
target || (pendingProjectionWebContents && !pendingProjectionWebContents.isDestroyed());
const hasViewerTarget = viewerWindow && !viewerWindow.isDestroyed();
if (!hasProjectionTarget && !hasViewerTarget) {
log.warn('[projection] Ignored state response; no display window');
return;
}
const payload = {
...state,
viewport: projectionViewport,
range: projectionRange,
};
log.info(`[projection] State response received; viewport=${Boolean(projectionViewport?.width)}`);
// Display 2 (pane projection) needs the scaled viewport; Display 1 (ShabadDeck)
// hydrates its store from the same snapshot so a swap isn't blank.
if (target) {
target.webContents.send('projection-state', payload);
} else if (pendingProjectionWebContents && !pendingProjectionWebContents.isDestroyed()) {
pendingProjectionWebContents.send('projection-state', payload);