Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
2249 lines (2093 loc) Β· 75.8 KB
/
Copy pathmain.js
File metadata and controls
2249 lines (2093 loc) Β· 75.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const {
app, BrowserWindow, shell, ipcMain, screen, Tray, Menu,
protocol, nativeImage, clipboard, dialog, globalShortcut
} = require('electron');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { pathToFileURL } = require('url');
const { Readable } = require('stream');
const { execFile, spawn } = require('child_process');
const {
cleanFsPath, toMediaUrl, createPathAllowlist, IMAGE_EXTS, mimeForPath,
isExistingImageFile
} = require('./lib/paths');
const { clearThumbCache, evictThumbCache } = require('./lib/thumb-cache');
const { clampWindowBounds, MIN_W, MIN_H } = require('./lib/window-bounds');
const { initUpdater, setAutoCheckEnabled } = require('./lib/updater');
const { buildBackup, parseBackup } = require('./lib/settings-backup');
const {
TRAY_HELP_URLS, buildTrayHelpModel, taskbarSettingsLaunch
} = require('./lib/tray-help');
const CVMedia = require('./js/media-helpers');
protocol.registerSchemesAsPrivileged([
{
scheme: 'cvlocal',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
stream: true,
corsEnabled: true,
bypassCSP: false
}
}
]);
const settingsPath = path.join(app.getPath('userData'), 'settings.json');
const menuI18n = JSON.parse(
fs.readFileSync(path.join(__dirname, 'i18n', 'menu.json'), 'utf8')
);
/** Matches the config placeholder. Empty/missing settings resolve to this. */
const DEFAULT_TOGGLE_HOTKEY = 'Alt+Shift+V';
function isToggleHotkeyDisabled(value) {
return value === 'disabled';
}
function resolveToggleHotkey(value) {
if (isToggleHotkeyDisabled(value)) return '';
const s = value == null ? '' : String(value).trim();
return s || DEFAULT_TOGGLE_HOTKEY;
}
const pathAllowlist = createPathAllowlist([__dirname]);
function getUiLang() {
try {
const s = loadSettings();
return (s.app && s.app.language) || 'en';
} catch (_) {
return 'en';
}
}
function tMenu(key, lang) {
const l = lang || getUiLang();
const pack = menuI18n[l] || menuI18n.en || {};
return pack[key] != null ? pack[key] : (menuI18n.en && menuI18n.en[key]) || key;
}
function loadSettings() {
try {
if (fs.existsSync(settingsPath)) {
const data = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
if (data && data.app) {
if (data.app.checkUpdatesOnStartup === undefined) {
data.app.checkUpdatesOnStartup = data.app.manualUpdateOnly === undefined
? true
: !data.app.manualUpdateOnly;
}
if (!data.app.updateNotify || typeof data.app.updateNotify !== 'object') {
data.app.updateNotify = {
lastNotifiedAvailable: null,
lastNotifiedDownloaded: null
};
}
if (data.app.toolbarOpen === undefined) data.app.toolbarOpen = true;
if (data.app.bannerAutoHide === undefined) data.app.bannerAutoHide = (data.app.hudAutoHide !== undefined ? data.app.hudAutoHide : true);
if (data.app.hudAutoHideDelay === undefined) data.app.hudAutoHideDelay = 2000;
if (data.app.disableTooltips === undefined) data.app.disableTooltips = false;
if (data.app.showShortcutGuide === undefined) data.app.showShortcutGuide = true;
if (data.app.alphaBackground === undefined) data.app.alphaBackground = 'checker-dark';
if (data.app.imageOutline === undefined) data.app.imageOutline = false;
if (!Array.isArray(data.app.recentFiles)) data.app.recentFiles = [];
if (!Array.isArray(data.app.recentFolders)) data.app.recentFolders = [];
if (data.app.slideshowIntervalMs === undefined) data.app.slideshowIntervalMs = 3000;
if (data.app.slideshowLoop === undefined) data.app.slideshowLoop = true;
if (data.app.slideshowEnterFullscreen === undefined) data.app.slideshowEnterFullscreen = true;
if (data.app.allowMultipleInstances === undefined) data.app.allowMultipleInstances = false;
if (data.app.showFileName === undefined) data.app.showFileName = true;
if (data.app.animateGifs === undefined) data.app.animateGifs = true;
if (data.app.dblClickAction === undefined) data.app.dblClickAction = 'fullscreen';
if (data.app.toggleHotkey === undefined || data.app.toggleHotkey === '') {
data.app.toggleHotkey = DEFAULT_TOGGLE_HOTKEY;
}
}
return data;
}
} catch (e) {
console.error('Error cargando settings:', e);
}
return {
window: { width: 1280, height: 800, maximized: true },
app: {
closeToTray: false,
closeImageOnTray: true,
trayRecentImages: true,
startMinimized: false,
autoStart: false,
accentColor: '#00d4ff',
sidebarOpen: false,
statusbarVisible: true,
preferredDisplayId: 'auto',
language: 'en',
contextMenuEnabled: false,
toggleHotkey: DEFAULT_TOGGLE_HOTKEY,
checkUpdatesOnStartup: true,
updateNotify: {
lastNotifiedAvailable: null,
lastNotifiedDownloaded: null
},
toolbarOpen: true,
bannerAutoHide: true,
hudAutoHideDelay: 2000,
disableTooltips: false,
showShortcutGuide: true,
alphaBackground: 'checker-dark',
imageOutline: false,
recentFiles: [],
recentFolders: [],
slideshowIntervalMs: 3000,
slideshowLoop: true,
slideshowEnterFullscreen: true,
allowMultipleInstances: false,
showFileName: true,
animateGifs: true,
dblClickAction: 'fullscreen',
navZoomMode: 'reset'
}
};
}
function saveSettings(data) {
try {
const current = loadSettings();
const merged = {
window: { ...current.window, ...(data.window || {}) },
app: { ...current.app, ...(data.app || {}) }
};
fs.writeFileSync(settingsPath, JSON.stringify(merged, null, 2));
} catch (e) {
console.error('Error guardando settings:', e);
}
}
function getFilePathFromArgs(args) {
for (let arg of args) {
arg = arg.replace(/^"(.*)"$/, '$1');
if (arg.match(/\.(jpg|jpeg|png|gif|webp|bmp|tiff|tif|ico|avif)$/i)) {
try {
if (fs.existsSync(arg)) {
const resolved = path.resolve(arg);
pathAllowlist.allow(resolved);
return resolved;
}
} catch (_) { /* ignore */ }
}
}
return null;
}
function resolveAllowedPath(rawPath) {
const abs = cleanFsPath(rawPath);
return pathAllowlist.assertAllowed(abs);
}
function registerMediaProtocol() {
protocol.handle('cvlocal', async (request) => {
try {
// Prefer ?p= absolute path β avoids Windows drive letters becoming URL hosts.
const abs = cleanFsPath(request.url);
if (!pathAllowlist.isAllowed(abs)) {
console.warn('cvlocal forbidden:', abs);
return new Response('Forbidden', { status: 403 });
}
let st;
try {
st = await fs.promises.stat(abs);
} catch (_) {
return new Response('Not Found', { status: 404 });
}
if (!st.isFile()) {
return new Response('Not Found', { status: 404 });
}
// Stream file bytes β avoids loading multi-MB images fully into RAM.
const nodeStream = fs.createReadStream(abs);
const webStream = Readable.toWeb(nodeStream);
const isThumb = abs.toLowerCase().includes(`${path.sep}thumb_cache${path.sep}`) ||
abs.toLowerCase().includes('/thumb_cache/');
return new Response(webStream, {
headers: {
'Content-Type': mimeForPath(abs),
'Content-Length': String(st.size),
'Cache-Control': isThumb ? 'private, max-age=86400' : 'no-cache, must-revalidate'
}
});
} catch (e) {
console.error('cvlocal protocol error:', e.message);
return new Response('Bad Request', { status: 400 });
}
});
}
let win;
let tray = null;
let isQuitting = false;
// Resolved once at launch from persisted settings + launch args (see lock section).
let allowMultipleInstances = false;
const initialFilePath = getFilePathFromArgs(process.argv);
const instanceHasInitialFile = !!initialFilePath;
// Tray/close-to-tray are reserved for the "resident" launch (no file arg).
// Instances opened with an image file are ephemeral windows under multi-instance:
// they get no tray icon and closing them quits that process (no duplicates).
function wantsTray() {
const s = loadSettings().app;
return !!s.closeToTray && !(allowMultipleInstances && instanceHasInitialFile);
}
function resolveStartupBounds(settings) {
const raw = settings.window && settings.window.bounds;
const clamped = clampWindowBounds(raw, {
displays: screen.getAllDisplays(),
primary: screen.getPrimaryDisplay(),
preferredDisplayId: settings.app && settings.app.preferredDisplayId,
// A normal close should reopen centered on the last/selected monitor.
// Maximized windows keep their native maximized restore behavior.
center: settings.window && settings.window.maximized === false
});
const inflated = !!(
raw &&
Number.isFinite(raw.width) &&
Number.isFinite(raw.height) &&
(raw.width > clamped.width + 32 || raw.height > clamped.height + 32)
);
return { ...clamped, inflated };
}
function persistWindowState() {
if (!win || win.isDestroyed()) return;
try {
// Do not persist exclusive-fullscreen metrics as normal window bounds
if (typeof win.isFullScreen === 'function' && win.isFullScreen()) return;
const isMax = win.isMaximized();
// Live bounds identify the monitor even while maximized
const live = win.getBounds();
const liveDisplay =
(typeof screen.getDisplayMatching === 'function' && screen.getDisplayMatching(live)) ||
screen.getDisplayNearestPoint({
x: Math.round(live.x + live.width / 2),
y: Math.round(live.y + live.height / 2)
});
// getNormalBounds avoids DPI-inflated maximized metrics on Windows
const raw = typeof win.getNormalBounds === 'function' ? win.getNormalBounds() : live;
const clamped = clampWindowBounds(raw, {
displays: screen.getAllDisplays(),
primary: screen.getPrimaryDisplay(),
preferredDisplayId: loadSettings().app.preferredDisplayId,
savedDisplayId: liveDisplay && liveDisplay.id
});
saveSettings({
window: {
maximized: isMax,
bounds: {
x: clamped.x,
y: clamped.y,
width: clamped.width,
height: clamped.height,
displayId: (liveDisplay && liveDisplay.id) || clamped.displayId
}
}
});
} catch (e) {
console.error('Error persisting window state:', e);
}
}
function createWindow() {
const settings = loadSettings();
const startup = resolveStartupBounds(settings);
// Prefer maximized when previously maximized, first-run, or saved size was DPI-inflated
const startMaximized =
settings.window.maximized === true ||
settings.window.maximized == null ||
startup.inflated;
win = new BrowserWindow({
x: startup.x,
y: startup.y,
width: startup.width,
height: startup.height,
minWidth: MIN_W,
minHeight: MIN_H,
title: 'CyberViewer',
backgroundColor: '#080a0e',
icon: path.join(__dirname, 'assets', 'icon.ico'),
frame: false,
titleBarStyle: 'hidden',
// Native rounded corners only on Windows 11 (build >= 22000). No effect on Win10.
roundedCorners: true,
thickFrame: true,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js'),
spellcheck: false,
enableWebSQL: false,
webSecurity: true
}
});
try {
win.setBackgroundColor('#080a0e');
} catch (_) { /* ignore */ }
// Debounce persistence β move/resize fire often and mixed-DPI getBounds is noisy
let persistTimer = null;
const schedulePersist = () => {
if (persistTimer) clearTimeout(persistTimer);
persistTimer = setTimeout(() => {
persistTimer = null;
if (!win || win.isDestroyed()) return;
if (win.isMaximized()) return;
if (typeof win.isFullScreen === 'function' && win.isFullScreen()) return;
persistWindowState();
}, 400);
};
win.on('move', schedulePersist);
win.on('resize', schedulePersist);
let shown = false;
const revealWindow = () => {
if (shown || !win || win.isDestroyed()) return;
shown = true;
const isStartupLaunch = process.argv.includes('--startup');
const shouldStartMinimized = settings.app.autoStart && isStartupLaunch;
if (shouldStartMinimized) {
if (!tray) createTray();
return;
}
// Last-resort flash mitigation: show at opacity 0, settle layout, then fade in
try { win.setOpacity(0); } catch (_) { /* ignore */ }
// Place on the resolved startup display (keeps last-used monitor)
try {
win.setBounds({
x: startup.x,
y: startup.y,
width: startup.width,
height: startup.height
});
} catch (_) { /* ignore */ }
win.show();
if (startMaximized) {
try {
// Nudge onto the target display before maximize if needed
const target =
screen.getDisplayNearestPoint({
x: startup.x + Math.floor(startup.width / 2),
y: startup.y + Math.floor(startup.height / 2)
});
const cur = win.getBounds();
const curDisp =
(typeof screen.getDisplayMatching === 'function' && screen.getDisplayMatching(cur)) ||
screen.getDisplayNearestPoint({
x: Math.round(cur.x + cur.width / 2),
y: Math.round(cur.y + cur.height / 2)
});
if (target && curDisp && target.id !== curDisp.id) {
const wa = target.workArea || target.bounds;
win.setBounds({
x: wa.x + 48,
y: wa.y + 48,
width: Math.min(startup.width, Math.max(800, wa.width - 96)),
height: Math.min(startup.height, Math.max(500, wa.height - 96))
});
}
if (!win.isMaximized()) win.maximize();
} catch (_) { /* ignore */ }
}
const fadeIn = () => {
if (!win || win.isDestroyed()) return;
try { win.setOpacity(1); } catch (_) { /* ignore */ }
};
// Two ticks: let Chromium/DWM composite the dark frame before becoming visible
setTimeout(fadeIn, 32);
};
// Register before loadURL to avoid missing a fast ui-ready
const onUiReady = () => {
ipcMain.removeListener('ui-ready', onUiReady);
revealWindow();
};
ipcMain.on('ui-ready', onUiReady);
win.once('ready-to-show', () => {
// Fallback if renderer never acks
setTimeout(() => revealWindow(), 1500);
});
win.on('closed', () => {
ipcMain.removeListener('ui-ready', onUiReady);
});
const htmlPath = path.join(__dirname, 'CyberViewer.html');
const loadUrl = !app.isPackaged
? pathToFileURL(htmlPath).href + '?v=' + Date.now()
: pathToFileURL(htmlPath).href;
win.loadURL(loadUrl);
win.on('close', (event) => {
if (!isQuitting && wantsTray()) {
event.preventDefault();
hideToTray();
return false;
}
persistWindowState();
});
win.on('show', () => updateTrayMenu());
win.on('hide', () => updateTrayMenu());
win.on('minimize', () => updateTrayMenu());
win.on('restore', () => updateTrayMenu());
win.on('blur', () => {
if (win && !win.isDestroyed()) win.webContents.send('window-blur');
});
win.on('maximize', () => {
win.webContents.send('win-state', 'maximized');
persistWindowState();
});
win.on('unmaximize', () => {
// Ignore transient unmaximize while entering exclusive fullscreen
if (typeof win.isFullScreen === 'function' && win.isFullScreen()) return;
win.webContents.send('win-state', 'normal');
// Re-clamp after unmaximize β Windows/DPI often restores oversized bounds
setTimeout(() => {
if (!win || win.isDestroyed() || win.isMaximized()) return;
if (typeof win.isFullScreen === 'function' && win.isFullScreen()) return;
try {
const raw = win.getBounds();
const clamped = clampWindowBounds(raw, {
displays: screen.getAllDisplays(),
primary: screen.getPrimaryDisplay(),
preferredDisplayId: loadSettings().app.preferredDisplayId
});
if (raw.width > clamped.width + 8 || raw.height > clamped.height + 8) {
win.setBounds({
x: clamped.x,
y: clamped.y,
width: clamped.width,
height: clamped.height
});
}
} catch (_) { /* ignore */ }
persistWindowState();
}, 0);
});
// OS exclusive fullscreen β renderer immersive (ghost) UI
win.on('enter-full-screen', () => {
if (!win || win.isDestroyed()) return;
win.webContents.send('fullscreen-changed', true);
});
win.on('leave-full-screen', () => {
if (!win || win.isDestroyed()) return;
win.webContents.send('fullscreen-changed', false);
// Restore maximize glyph after exclusive fullscreen ends
try {
win.webContents.send('win-state', win.isMaximized() ? 'maximized' : 'normal');
} catch (_) { /* ignore */ }
persistWindowState();
});
win.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
}
function hideToTray() {
if (!win || win.isDestroyed()) return;
persistWindowState();
// Optionally unload the open image when hiding to the tray, so reopening
// the window (manually or via Explorer) shows a clean state with no trace
// of the previous image β it stays only in the Recents history.
try {
const s = (loadSettings().app) || {};
if (s.closeImageOnTray !== false && win.webContents && !win.webContents.isDestroyed()) {
win.webContents.send('menu-action', { action: 'close-image' });
}
} catch (_) { /* ignore */ }
if (win.isVisible()) win.hide();
updateTrayMenu();
}
function showFromTray() {
if (!win || win.isDestroyed()) return;
if (win.isMinimized()) win.restore();
if (!win.isVisible()) win.show();
win.focus();
updateTrayMenu();
}
function isWindowShown() {
return !!(win && !win.isDestroyed() && win.isVisible() && !win.isMinimized());
}
// Windows may emit a normal click around the same right-click that opens the
// tray context menu. Defer the click and cancel it when the right-click wins.
let trayRightClickSeq = 0;
let lastTrayRightClickAt = 0;
let trayClickTimer = null;
function resolveOpenTaskbarSettingsExe() {
const candidates = [
// Packaged extraResources (outside asar β required to spawn).
path.join(process.resourcesPath || '', 'open-taskbar-settings.exe'),
// Development copy kept beside the helper source.
path.join(__dirname, 'electron', 'open-taskbar-settings.exe'),
path.join(app.getAppPath(), 'electron', 'open-taskbar-settings.exe'),
path.join(__dirname, 'open-taskbar-settings.exe')
];
return candidates.find((candidate) => {
try {
return fs.existsSync(candidate);
} catch (_) {
return false;
}
}) || null;
}
async function openTaskbarIconSettings() {
const helperPath = resolveOpenTaskbarSettingsExe();
const launch = taskbarSettingsLaunch(process.platform, !!helperPath);
if (process.platform === 'win32') {
if (launch.method === 'native') {
try {
const child = spawn(helperPath, [], {
detached: true,
stdio: 'ignore',
windowsHide: true
});
child.once('error', (error) => {
console.warn('Taskbar settings helper failed; opening Windows Settings:', error.message);
void shell.openExternal(launch.uri);
});
child.unref();
return { success: true, method: 'native' };
} catch (error) {
console.warn('Taskbar settings helper unavailable; using Windows Settings:', error.message);
}
}
}
await shell.openExternal(launch.uri);
return { success: true, method: 'uri' };
}
function openTrayHelpUrl(key) {
const url = TRAY_HELP_URLS[key];
if (url) void shell.openExternal(url);
}
// Windows owns the lifecycle of native tray menus and their submenu flyouts.
// Keep the menu object stable while it is open; replacing it during a hover can
// make Windows redraw the menu or crash older Electron/Windows combinations.
let trayContextMenuOpen = false;
let trayContextMenuRebuildPending = false;
let trayContextMenuCloseFallback = null;
let pendingTrayAction = null;
function executePendingTrayAction() {
const action = pendingTrayAction;
pendingTrayAction = null;
if (!action) return;
if (action === 'quit') {
isQuitting = true;
app.quit();
return;
}
if (action === 'hide') {
hideToTray();
return;
}
if (action === 'show') {
showFromTray();
return;
}
if (action === 'settings') {
showFromTray();
if (win && !win.isDestroyed()) win.webContents.send('open-settings');
return;
}
if (action === 'about') {
showFromTray();
if (win && !win.isDestroyed()) win.webContents.send('menu-action', { action: 'show-about' });
return;
}
if (action === 'help-pin') {
showFromTray();
if (win && !win.isDestroyed()) win.webContents.send('menu-action', { action: 'show-tray-pin-reminder' });
return;
}
if (action === 'help-check-updates') {
showFromTray();
if (win && !win.isDestroyed()) win.webContents.send('menu-action', { action: 'check-updates' });
return;
}
if (action && typeof action === 'object' && action.type === 'open-file') {
showFromTray();
if (win && !win.isDestroyed()) {
try {
pathAllowlist.allow(action.filePath);
} catch (_) {}
win.webContents.send('open-file', action.filePath);
}
return;
}
if (action === 'clear-recent') {
clearRecentFilesFromMain();
return;
}
}
function clearRecentFilesFromMain() {
const current = loadSettings();
const appSettings = { ...(current.app || {}), recentFiles: [] };
saveSettings({ app: appSettings });
updateTrayMenu();
if (win && !win.isDestroyed()) {
win.webContents.send('recent-files-cleared');
}
}
function onTrayContextMenuClosed() {
if (!trayContextMenuOpen) return;
trayContextMenuOpen = false;
if (trayContextMenuCloseFallback) {
clearTimeout(trayContextMenuCloseFallback);
trayContextMenuCloseFallback = null;
}
// Windows can emit menu-will-close before the item click. Give the click
// callback a short window to populate pendingTrayAction, as CyberLauncher
// does for the same native menu lifecycle.
setTimeout(() => {
executePendingTrayAction();
if (trayContextMenuRebuildPending) {
trayContextMenuRebuildPending = false;
rebuildTrayContextMenu();
}
}, 50);
}
function loadTrayMenuIcon(name) {
const iconPath = path.join(__dirname, 'assets', 'menu-icons', name);
try {
if (!fs.existsSync(iconPath)) return null;
const image = nativeImage.createFromPath(iconPath);
return image.isEmpty() ? null : image;
} catch (_) {
return null;
}
}
function loadTrayBrandIcon() {
const iconPath = path.join(__dirname, 'assets', 'icon.ico');
try {
if (!fs.existsSync(iconPath)) return null;
const image = nativeImage.createFromPath(iconPath);
return image.isEmpty() ? null : image.resize({ width: 16, height: 16 });
} catch (_) {
return null;
}
}
function buildTrayContextMenuTemplate() {
const lang = getUiLang();
const t = menuI18n[lang] || menuI18n.en;
const settings = loadSettings();
const visible = isWindowShown();
const shortcut = resolveToggleHotkey(settings.app && settings.app.toggleHotkey);
const help = buildTrayHelpModel(t);
const iconBrand = loadTrayBrandIcon();
const iconShow = loadTrayMenuIcon('show-hide.png');
const iconRecent = loadTrayMenuIcon('recent-images.png');
const iconSettings = loadTrayMenuIcon('settings.png');
const iconHelp = loadTrayMenuIcon('help.png');
const iconFaq = loadTrayMenuIcon('faq.png');
const iconChangelog = loadTrayMenuIcon('changelog.png');
const iconHome = loadTrayMenuIcon('homepage.png');
const iconDonate = loadTrayMenuIcon('donate.png');
const iconAbout = loadTrayMenuIcon('about.png');
const iconUpdate = loadTrayMenuIcon('update.png');
const iconQuit = loadTrayMenuIcon('quit.png');
const recentFiles = (settings.app && Array.isArray(settings.app.recentFiles)) ? settings.app.recentFiles : [];
const showTrayRecents = !settings.app || settings.app.trayRecentImages !== false;
let recentItem = null;
if (showTrayRecents) {
const validRecents = recentFiles.filter((p) => p && typeof p === 'string').slice(0, 10);
const recentSubmenu = [];
if (validRecents.length === 0) {
recentSubmenu.push({
label: t.tray_no_recent || 'No recent images',
enabled: false
});
} else {
validRecents.forEach((filePath) => {
const name = (path.basename(filePath) || filePath).replace(/&/g, '&&');
recentSubmenu.push({
label: name,
click: () => {
pendingTrayAction = { type: 'open-file', filePath };
}
});
});
recentSubmenu.push({ type: 'separator' });
recentSubmenu.push({
label: t.tray_clear_recent || 'Clear recent list',
click: () => {
pendingTrayAction = 'clear-recent';
}
});
}
recentItem = {
label: t.tray_recent_images || 'Recent images',
...(iconRecent ? { icon: iconRecent } : {}),
submenu: recentSubmenu
};
}
return [
{
label: 'CyberViewer v' + app.getVersion(),
...(iconBrand ? { icon: iconBrand } : {}),
click: () => { pendingTrayAction = 'about'; }
},
{ type: 'separator' },
{
label: visible ? t.tray_hide : t.tray_show,
...(iconShow ? { icon: iconShow } : {}),
accelerator: shortcut || undefined,
click: () => { pendingTrayAction = visible ? 'hide' : 'show'; }
},
...(recentItem ? [recentItem] : []),
{
label: t.tray_settings,
...(iconSettings ? { icon: iconSettings } : {}),
click: () => { pendingTrayAction = 'settings'; }
},
{
label: help.label,
...(iconHelp ? { icon: iconHelp } : {}),
submenu: [
{
label: help.pinLabel,
...(iconSettings ? { icon: iconSettings } : {}),
click: () => { pendingTrayAction = 'help-pin'; }
},
{ type: 'separator' },
{
label: help.docsLabel,
...(iconHelp ? { icon: iconHelp } : {}),
click: () => openTrayHelpUrl('docs')
},
{
label: help.faqLabel,
...(iconFaq ? { icon: iconFaq } : {}),
click: () => openTrayHelpUrl('faq')
},
{
label: help.changelogLabel,
...(iconChangelog ? { icon: iconChangelog } : {}),
click: () => openTrayHelpUrl('changelog')
},
{
label: help.websiteLabel,
...(iconHome ? { icon: iconHome } : {}),
click: () => openTrayHelpUrl('website')
},
{
label: help.donateLabel,
...(iconDonate ? { icon: iconDonate } : {}),
click: () => openTrayHelpUrl('donate')
},
{ type: 'separator' },
{
label: help.aboutLabel,
...(iconAbout ? { icon: iconAbout } : {}),
click: () => { pendingTrayAction = 'about'; }
},
{
label: help.updatesLabel,
...(iconUpdate ? { icon: iconUpdate } : {}),
click: () => { pendingTrayAction = 'help-check-updates'; }
}
]
},
{ type: 'separator' },
{
label: t.tray_exit,
...(iconQuit ? { icon: iconQuit } : {}),
click: () => { pendingTrayAction = 'quit'; }
}
];
}
function rebuildTrayContextMenu() {
if (!tray) return;
if (trayContextMenuOpen) {
trayContextMenuRebuildPending = true;
return;
}
trayContextMenuRebuildPending = false;
const menu = Menu.buildFromTemplate(buildTrayContextMenuTemplate());
menu.on('menu-will-show', () => {
trayContextMenuOpen = true;
pendingTrayAction = null;
if (trayContextMenuCloseFallback) clearTimeout(trayContextMenuCloseFallback);
trayContextMenuCloseFallback = setTimeout(() => {
if (trayContextMenuOpen) onTrayContextMenuClosed();
}, 15000);
});
menu.on('menu-will-close', onTrayContextMenuClosed);
tray.setContextMenu(menu);
}
function updateTrayMenu() {
if (!tray) return;
tray.setToolTip('CyberViewer v' + app.getVersion());
rebuildTrayContextMenu();
}
function createTray() {
if (tray) return;
tray = new Tray(path.join(__dirname, 'assets', 'icon.ico'));
tray.setToolTip('CyberViewer v' + app.getVersion());
rebuildTrayContextMenu();
tray.on('click', () => {
if (process.platform === 'win32') {
const clickSeq = trayRightClickSeq;
if (trayClickTimer) clearTimeout(trayClickTimer);
trayClickTimer = setTimeout(() => {
trayClickTimer = null;
// A right-click can arrive before or after this deferred click.
// Ignore both event orderings so opening the context menu cannot also
// toggle the main window underneath it.
if (trayRightClickSeq !== clickSeq || Date.now() - lastTrayRightClickAt < 400) return;
if (trayContextMenuOpen) return;
if (!win || win.isDestroyed()) return;
if (isWindowShown()) hideToTray();
else showFromTray();
}, 120);
return;
}
if (!win || win.isDestroyed()) return;
if (isWindowShown()) hideToTray();
else showFromTray();
});
tray.on('right-click', (_event, _bounds) => {
trayRightClickSeq += 1;
lastTrayRightClickAt = Date.now();
});
}
// ββ Global toggle hotkey βββββββββββββββββββββββββββββββββββββββββββββ
// When the user sets an accelerator (e.g. "Alt+Shift+V") we register it globally
// so CyberViewer can be shown/hidden from anywhere. "disabled" (or a resolved
// empty value) unregisters the shortcut. Missing/blank settings use Alt+Shift+V.
function applyToggleHotkey(accelerator) {
try { globalShortcut.unregisterAll(); } catch (_) { /* not registered yet */ }
const acc = resolveToggleHotkey(accelerator);
if (!acc) return { success: true }; // disabled by design
try {
globalShortcut.register(acc, () => {
if (!win || win.isDestroyed()) return;
if (isWindowShown()) hideToTray();
else showFromTray();
});
if (!globalShortcut.isRegistered(acc)) {
return { success: false, error: 'accelerator-in-use' };
}
return { success: true };
} catch (e) {
return { success: false, error: e.message || 'invalid-accelerator' };
}
}
app.on('will-quit', () => {
try { globalShortcut.unregisterAll(); } catch (_) { /* nothing registered */ }
});
ipcMain.handle('open-taskbar-settings', async () => {
try {
return await openTaskbarIconSettings();
} catch (error) {
console.error('Failed to open Windows tray icon settings:', error);
return { success: false, error: error && error.message ? error.message : String(error) };
}
});
// ββ IPC ββ
ipcMain.on('win-minimize', () => win.minimize());
ipcMain.on('win-maximize', () => {
if (!win || win.isDestroyed()) return;
// Leave exclusive fullscreen before toggle maximize/restore
if (typeof win.isFullScreen === 'function' && win.isFullScreen()) {
win.setFullScreen(false);
}
if (win.isMaximized()) win.unmaximize();
else win.maximize();
});
ipcMain.on('win-close', () => win.close());
ipcMain.on('win-devtools', () => {
// DevTools only outside packaged builds
if (!app.isPackaged && win && !win.isDestroyed()) {
win.webContents.openDevTools();
}
});
ipcMain.handle('win-set-fullscreen', (event, flag) => {
if (!win || win.isDestroyed()) return false;
const want = !!flag;
try {
if (win.isFullScreen() === want) return want;
win.setFullScreen(want);
return win.isFullScreen();
} catch (e) {
console.error('setFullScreen failed:', e);
return false;
}
});
ipcMain.handle('win-is-fullscreen', () => {
if (!win || win.isDestroyed()) return false;
try {
return !!win.isFullScreen();
} catch (_) {
return false;
}
});
ipcMain.handle('open-file-dialog', async () => {
const lang = getUiLang();
const result = await dialog.showOpenDialog(win, {
title: tMenu('dialog_open_title', lang),
filters: [
{
name: tMenu('dialog_open_filter_images', lang),
extensions: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tiff', 'tif', 'ico', 'avif']
},
{ name: tMenu('dialog_open_filter_all', lang), extensions: ['*'] }
],
properties: ['openFile']
});
if (result.canceled || !result.filePaths.length) return null;
const filePath = result.filePaths[0];
pathAllowlist.allow(filePath);
return filePath;
});
/**
* Resolve first image in a directory (natural sort) and allowlist it.