Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
868 lines (799 loc) · 28.1 KB
/
Copy pathmain.js
File metadata and controls
868 lines (799 loc) · 28.1 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
const {
app,
BrowserWindow,
ipcMain,
Menu,
Notification,
Tray,
nativeImage,
nativeTheme,
net,
screen,
session,
} = require('electron');
const path = require('path');
const os = require('os');
const fs = require('fs');
// ---------- Config persistence ----------
const CONFIG_PATH = path.join(app.getPath('userData'), 'config.json');
function loadConfig() {
try {
// Strip a leading BOM if present so JSON.parse doesn't choke.
const raw = fs.readFileSync(CONFIG_PATH, 'utf8').replace(/^/, '');
return JSON.parse(raw);
} catch {
return {};
}
}
function saveConfig(cfg) {
try {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf8');
} catch (e) {
console.error('Failed to save config:', e);
}
}
let config = loadConfig();
const WIN_WIDTH = 260;
const WIN_HEIGHT = 74;
const POPOVER_WIDTH = 260;
const POPOVER_HEIGHT = 84;
// Taskbar overlay widget footprint and spacing (DIP).
const TASKBAR_WIDGET_WIDTH = 210; // initial width before the renderer reports its content size
const TASKBAR_MIN_WIDTH = 110; // never shrink below this (keeps "Loading…" / short text readable)
const TASKBAR_MAX_WIDTH = 320; // beyond this the location text ellipsizes instead of growing
const TASKBAR_LEFT_MARGIN = 6; // gap from the taskbar's left edge when no weather button
const TASKBAR_GAP = 8; // gap from the weather button / system tray
const ICON_PATH = path.join(__dirname, 'assets', 'icon.png');
const MAC_TRAY_ICON_PATH = path.join(__dirname, 'assets', 'trayTemplate.png');
// ---------- Display mode ----------
// taskbar -> Windows 11 (embed widget into the taskbar)
// menubar -> macOS (title in the menu bar + click notification)
// floating -> Windows 10 and below, Linux (original desktop card)
function detectMode() {
if (process.platform === 'darwin') return 'menubar';
if (process.platform === 'win32') {
const build = parseInt(os.release().split('.')[2], 10);
if (Number.isFinite(build) && build >= 22000) return 'taskbar';
}
return 'floating';
}
let mode = detectMode();
// taskbar-win.js pulls in a native FFI dependency, so only load it on Windows.
const taskbarWin = mode === 'taskbar' ? require('./taskbar-win') : null;
// ---------- i18n ----------
// Detect the OS UI language. Chinese locales use Chinese; everything else
// falls back to English.
const STRINGS = {
zh: {
apiLang: 'zh-CN',
trayShow: '显示面板',
trayRefresh: '立即刷新',
trayQuit: '退出',
trayFieldIp: '菜单栏显示 IP',
trayFieldLoc: '菜单栏显示位置',
trayFieldIsp: '菜单栏显示运营商',
tooltip: 'IPWindow',
ipLoading: '获取中…',
labelIp: 'IP',
labelLoc: '位置',
labelIsp: '运营商',
closeTitle: '退出',
unknownLoc: '未知位置',
updatePrefix: '更新 ',
queryFailed: '查询失败',
networkError: '网络错误',
},
en: {
apiLang: 'en',
trayShow: 'Show Panel',
trayRefresh: 'Refresh Now',
trayQuit: 'Quit',
trayFieldIp: 'Menu bar: IP',
trayFieldLoc: 'Menu bar: Location',
trayFieldIsp: 'Menu bar: ISP',
tooltip: 'IPWindow',
ipLoading: 'Loading…',
labelIp: 'IP',
labelLoc: 'Location',
labelIsp: 'ISP',
closeTitle: 'Quit',
unknownLoc: 'Unknown location',
updatePrefix: 'Updated ',
queryFailed: 'Lookup failed',
networkError: 'Network error',
},
};
let t = STRINGS.en; // resolved in app.whenReady once the locale is available.
let win = null; // primary window: floating card or taskbar overlay widget
let popover = null; // hover detail popover (Windows taskbar mode)
let tray = null;
let refreshTimer = null;
let popoverHideTimer = null;
let lastInfo = null; // most recent successful lookup
let detailNotification = null;
let detailNotificationTimer = null;
let refreshInFlight = null; // shared by every manual, scheduled, and network-triggered refresh
// ---------- Taskbar overlay state (Windows 11) ----------
let taskbarHwnd = null; // BigInt HWND of our overlay window
let taskbarTimer = null; // periodic reposition / z-order assert
let fullscreenTimer = null; // quick fullscreen polling (same app can enter F11 without a focus event)
let taskbarTick = 0;
let reassertTimer = null; // delayed z-order re-assert after a foreground change
let dragTimer = null; // active while the user drags the widget
let dragSafetyTimer = null; // hard stop so a missed mouse-up can't wedge the drag
let draggingTaskbar = false;
let dragGrabDX = 0; // cursor-x minus window-x at drag start
let taskbarWidgetWidth = TASKBAR_WIDGET_WIDTH; // current width (DIP), driven by content
let taskbarHiddenForFullscreen = false;
// ---------- IP lookup ----------
// ip-api.com (free, no key). Returns the public IP of the requester + geo info.
// Chinese localization via lang=zh-CN.
function fetchIpInfo() {
return new Promise((resolve, reject) => {
const url =
'http://ip-api.com/json/?fields=status,message,country,regionName,city,query,isp&lang=' +
t.apiLang;
// Electron's net module goes through Chromium's network stack, so it
// honors the system proxy settings — the lookup reflects the proxy exit IP.
const req = net.request({ url, useSessionCookies: false });
let data = '';
let settled = false;
const fail = (e) => {
if (settled) return;
settled = true;
reject(e);
};
const timer = setTimeout(() => {
try {
req.abort();
} catch {}
fail(new Error('timeout'));
}, 10000);
req.on('response', (res) => {
res.on('data', (chunk) => (data += chunk));
res.on('end', () => {
clearTimeout(timer);
if (settled) return;
settled = true;
try {
const json = JSON.parse(data);
if (json.status === 'success') {
resolve({
ip: json.query,
location: [json.country, json.regionName, json.city]
.filter(Boolean)
.join(' '),
isp: json.isp || '',
});
} else {
reject(new Error(json.message || 'lookup failed'));
}
} catch (e) {
reject(e);
}
});
res.on('error', (e) => {
clearTimeout(timer);
fail(e);
});
});
req.on('error', (e) => {
clearTimeout(timer);
fail(e);
});
req.end();
});
}
// Send a message to every live renderer (primary window + popover).
function broadcast(channel, payload) {
for (const w of [win, popover]) {
if (w && !w.isDestroyed()) w.webContents.send(channel, payload);
}
}
function refreshAndSend() {
// The refresh button, timer, network watcher, and startup path can all fire
// at nearly the same time. Share one request so they cannot accumulate
// pending sockets and response buffers (or let an older response win).
if (refreshInFlight) return refreshInFlight;
refreshInFlight = (async () => {
broadcast('ip:loading');
try {
const info = await fetchIpInfo();
lastInfo = { ...info, time: Date.now() };
broadcast('ip:update', lastInfo);
updateTrayTitle();
} catch (e) {
broadcast('ip:error', { message: e.message, time: Date.now() });
} finally {
refreshInFlight = null;
}
})();
return refreshInFlight;
}
// ---------- Network-change auto refresh ----------
// Watch for local network transitions (link up/down, VPN/TUN adapters coming
// and going, system proxy toggled on/off) and trigger a single refresh shortly
// after things settle. We don't have a reliable cross-platform "network
// changed" event in the main process, so we poll a cheap signature instead.
let lastNetSig = null; // null = baseline not established yet
let netWatchTimer = null;
let netChangeDebounce = null;
let netSigInFlight = false;
// Signature of every non-internal interface address. Captures connect /
// disconnect and proxy adapters (Clash/V2Ray TUN etc.) appearing or vanishing.
function netInterfaceSig() {
const ifaces = os.networkInterfaces();
const parts = [];
for (const name of Object.keys(ifaces).sort()) {
for (const ni of ifaces[name] || []) {
if (ni.internal) continue;
parts.push(`${name}:${ni.family}:${ni.address}`);
}
}
return parts.join('|');
}
// Combine the interface signature with the proxy Chromium would use for the
// lookup, so flipping the *system proxy* (no adapter change) is also caught.
async function computeNetSig() {
let proxy = '';
try {
proxy = await session.defaultSession.resolveProxy('http://ip-api.com');
} catch {}
return netInterfaceSig() + '##' + proxy;
}
function onNetSig(sig) {
if (lastNetSig === null) {
lastNetSig = sig; // first observation is just the baseline, no refresh
return;
}
if (sig === lastNetSig) return;
lastNetSig = sig;
// A single transition emits several intermediate states (address dropped,
// then re-acquired, proxy re-resolved); coalesce them into one refresh.
if (netChangeDebounce) clearTimeout(netChangeDebounce);
netChangeDebounce = setTimeout(() => {
netChangeDebounce = null;
refreshAndSend();
}, 1500);
}
function startNetworkWatch() {
const tick = async () => {
// Proxy/PAC resolution can take longer than the polling cadence. Never
// queue another resolver while the current one still owns native resources.
if (netSigInFlight) return;
netSigInFlight = true;
try {
onNetSig(await computeNetSig());
} catch {}
finally {
netSigInFlight = false;
}
};
tick(); // establish the baseline now
netWatchTimer = setInterval(tick, 3000);
}
function sendI18n(target) {
if (!target || target.isDestroyed()) return;
target.webContents.send('i18n', {
ipLoading: t.ipLoading,
labelLoc: t.labelLoc,
closeTitle: t.closeTitle,
unknownLoc: t.unknownLoc,
updatePrefix: t.updatePrefix,
queryFailed: t.queryFailed,
networkError: t.networkError,
});
}
function currentTheme() {
return nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
}
// ---------- Windows ----------
function createFloatingWindow() {
const saved = config.bounds || {};
win = new BrowserWindow({
width: WIN_WIDTH,
height: WIN_HEIGHT,
x: typeof saved.x === 'number' ? saved.x : undefined,
y: typeof saved.y === 'number' ? saved.y : undefined,
icon: ICON_PATH,
frame: false,
transparent: true,
resizable: false,
alwaysOnTop: true,
skipTaskbar: true,
hasShadow: false,
fullscreenable: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
});
win.setAlwaysOnTop(true, 'screen-saver');
win.loadFile('index.html');
// Persist position after the user drags the window.
let saveDebounce = null;
const persistBounds = () => {
if (!win || win.isDestroyed()) return;
const b = win.getBounds();
config.bounds = { x: b.x, y: b.y };
if (saveDebounce) clearTimeout(saveDebounce);
saveDebounce = setTimeout(() => saveConfig(config), 300);
};
win.on('moved', persistBounds);
win.webContents.on('did-finish-load', () => {
sendI18n(win);
refreshAndSend();
});
}
function createTaskbarWindow() {
taskbarHwnd = null;
taskbarHiddenForFullscreen = false;
win = new BrowserWindow({
width: taskbarWidgetWidth,
height: 48,
icon: ICON_PATH,
frame: false,
transparent: true, // -> WS_EX_LAYERED, blends into the taskbar
backgroundColor: '#00000000',
resizable: false,
focusable: false, // -> WS_EX_NOACTIVATE, clicking it never steals focus
skipTaskbar: true, // -> tool window, no taskbar button / Alt-Tab entry
alwaysOnTop: true,
show: false,
hasShadow: false,
fullscreenable: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
// The window may be considered occluded by the taskbar; keep painting.
backgroundThrottling: false,
},
});
// 'screen-saver' is a z-band above the (topmost) taskbar.
win.setAlwaysOnTop(true, 'screen-saver');
win.loadFile('taskbar.html');
win.webContents.on('did-finish-load', () => {
sendI18n(win);
win.webContents.send('theme', currentTheme());
const hb = win.getNativeWindowHandle();
taskbarHwnd = hb.length >= 8 ? hb.readBigUInt64LE(0) : BigInt(hb.readUInt32LE(0));
// Place it over the taskbar before showing. If the taskbar can't be found,
// fall back to the regular floating card so the app stays usable.
if (!positionTaskbarWidget()) {
console.error('[main] taskbar not found, falling back to floating');
mode = 'floating';
destroyPopover();
win.destroy();
win = null;
createFloatingWindow();
return;
}
syncTaskbarFullscreenVisibility();
if (!taskbarHiddenForFullscreen) win.showInactive();
taskbarWin.refreshWidgetsButton();
// Re-assert placement + z-order every second to follow taskbar resize / DPI
// / theme / explorer restarts.
taskbarTimer = setInterval(onTaskbarTick, 1000);
fullscreenTimer = setInterval(syncTaskbarFullscreenVisibility, 250);
// Activating another app reshuffles the z-order and lets the (topmost)
// taskbar paint over our (also-topmost) overlay. Re-assert immediately on
// every foreground change so the widget doesn't blink out until the next
// tick.
taskbarWin.startForegroundWatch(reassertTaskbarTopmost);
refreshAndSend();
});
}
function taskbarSide() {
return config.taskbarSide === 'right' ? 'right' : 'left';
}
// Win32 RECT (in physical px) -> {x,y,width,height}.
function rectXYWH(r) {
return { x: r.left, y: r.top, width: r.right - r.left, height: r.bottom - r.top };
}
// Compute the widget's bounds (DIP) for the configured side, anchored to the
// right of the weather button (left side) or the left of the system tray
// (right side). Returns null if the taskbar can't be located.
function computeTaskbarBounds() {
const layout = taskbarWin.getLayout();
if (!layout) return null;
const tb = screen.screenToDipRect(null, rectXYWH(layout.taskbarRect));
const W = taskbarWidgetWidth;
let x;
if (taskbarSide() === 'right' && layout.trayRect) {
const tray = screen.screenToDipRect(null, rectXYWH(layout.trayRect));
x = tray.x - W - TASKBAR_GAP;
} else if (layout.widgetsRight != null) {
x = screen.screenToDipPoint({ x: layout.widgetsRight, y: layout.taskbarRect.top }).x + TASKBAR_GAP;
} else {
x = tb.x + TASKBAR_LEFT_MARGIN;
}
// Keep it within the taskbar horizontally.
x = Math.max(tb.x, Math.min(x, tb.x + tb.width - W));
return { x: Math.round(x), y: Math.round(tb.y), width: W, height: Math.round(tb.height) };
}
function positionTaskbarWidget() {
if (!win || win.isDestroyed()) return false;
const b = computeTaskbarBounds();
if (!b) return false;
win.setBounds(b);
return true;
}
// The renderer measures its content and reports the width the widget needs. We
// clamp it to a sane range, then resize + reposition so the refresh button hugs
// the text (no fixed-width gap) while staying anchored to its taskbar side.
function setTaskbarWidth(width) {
if (mode !== 'taskbar' || !win || win.isDestroyed()) return;
const w = Math.max(TASKBAR_MIN_WIDTH, Math.min(TASKBAR_MAX_WIDTH, Math.round(width || 0)));
if (w === taskbarWidgetWidth) return;
taskbarWidgetWidth = w;
// Don't fight an in-progress drag; the next reposition picks up the new width.
if (!draggingTaskbar) positionTaskbarWidget();
}
// Our overlay normally sits in a topmost z-band so it remains visible above
// the taskbar. Suppress it while another application owns a fullscreen monitor,
// then restore it as soon as that application leaves fullscreen or loses focus.
function syncTaskbarFullscreenVisibility() {
if (!win || win.isDestroyed() || !taskbarHwnd) return;
const shouldHide = taskbarWin.hasFullscreenForeground(taskbarHwnd);
if (shouldHide === taskbarHiddenForFullscreen) return;
taskbarHiddenForFullscreen = shouldHide;
if (shouldHide) {
if (popover && !popover.isDestroyed()) popover.hide();
win.hide();
return;
}
if (positionTaskbarWidget()) win.showInactive();
}
function onTaskbarTick() {
if (!win || win.isDestroyed() || draggingTaskbar) return;
syncTaskbarFullscreenVisibility();
if (taskbarHiddenForFullscreen) return;
positionTaskbarWidget();
if (taskbarHwnd) taskbarWin.assertTopmost(taskbarHwnd);
// Re-check the weather button every ~10s (it appears/disappears or changes
// width when Widgets is toggled or the forecast text changes).
if (++taskbarTick % 10 === 0) taskbarWin.refreshWidgetsButton();
}
// Fired by the foreground-change hook. Re-assert z-order at once, then once more
// shortly after — the new window's activation finishes restacking slightly after
// the event, so a single immediate call can lose the race.
function reassertTaskbarTopmost() {
if (!win || win.isDestroyed() || draggingTaskbar || !taskbarHwnd) return;
syncTaskbarFullscreenVisibility();
if (taskbarHiddenForFullscreen) return;
taskbarWin.assertTopmost(taskbarHwnd);
if (reassertTimer) clearTimeout(reassertTimer);
reassertTimer = setTimeout(() => {
reassertTimer = null;
if (win && !win.isDestroyed() && !draggingTaskbar && taskbarHwnd) {
syncTaskbarFullscreenVisibility();
if (taskbarHiddenForFullscreen) return;
taskbarWin.assertTopmost(taskbarHwnd);
}
}, 50);
}
// ---------- Drag to reposition (snaps to the nearer side) ----------
function startTaskbarDrag() {
if (mode !== 'taskbar' || !win || win.isDestroyed()) return;
// Self-healing: always clear any prior drag state first. If a previous drag
// ever failed to detect mouse-up (e.g. the poll was skipped across a
// sleep/resume or a throttled timer), `draggingTaskbar` would otherwise stay
// stuck true and silently block every future drag.
clearDragTimers();
const cur = screen.getCursorScreenPoint();
dragGrabDX = cur.x - win.getBounds().x;
draggingTaskbar = true;
if (popover && !popover.isDestroyed()) popover.hide();
dragTimer = setInterval(onTaskbarDrag, 16);
// Backstop: even if mouse-up detection fails entirely, never stay in drag mode
// longer than this (a single drag is always far shorter).
dragSafetyTimer = setTimeout(() => stopTaskbarDrag(true), 15000);
}
function clearDragTimers() {
if (dragTimer) {
clearInterval(dragTimer);
dragTimer = null;
}
if (dragSafetyTimer) {
clearTimeout(dragSafetyTimer);
dragSafetyTimer = null;
}
}
function onTaskbarDrag() {
if (!win || win.isDestroyed()) return stopTaskbarDrag(false);
// The renderer can't report mouseup once the cursor leaves our non-activating
// window, so we poll the physical button state instead.
if (!taskbarWin.isLeftMouseDown()) return stopTaskbarDrag(true);
const layout = taskbarWin.getLayout();
const b = win.getBounds();
let x = screen.getCursorScreenPoint().x - dragGrabDX;
if (layout) {
const tb = screen.screenToDipRect(null, rectXYWH(layout.taskbarRect));
x = Math.max(tb.x, Math.min(x, tb.x + tb.width - b.width));
}
win.setBounds({ x: Math.round(x), y: b.y, width: b.width, height: b.height });
if (taskbarHwnd) taskbarWin.assertTopmost(taskbarHwnd);
}
function stopTaskbarDrag(snap) {
if (!draggingTaskbar) {
clearDragTimers();
return;
}
clearDragTimers();
draggingTaskbar = false;
if (!snap || !win || win.isDestroyed()) return;
// Choose the side from the widget's center relative to the taskbar center,
// persist it, then snap to that side's anchor.
const layout = taskbarWin.getLayout();
if (layout) {
const tb = screen.screenToDipRect(null, rectXYWH(layout.taskbarRect));
const b = win.getBounds();
config.taskbarSide = b.x + b.width / 2 < tb.x + tb.width / 2 ? 'left' : 'right';
saveConfig(config);
}
positionTaskbarWidget();
}
function createPopover() {
popover = new BrowserWindow({
width: POPOVER_WIDTH,
height: POPOVER_HEIGHT,
frame: false,
transparent: true,
resizable: false,
show: false,
focusable: false,
skipTaskbar: true,
alwaysOnTop: true,
hasShadow: false,
fullscreenable: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
});
popover.setAlwaysOnTop(true, 'screen-saver');
popover.loadFile('popover.html');
popover.webContents.on('did-finish-load', () => {
sendI18n(popover);
// menubar mode has no primary window, so the popover kicks off the first
// lookup once it has loaded.
if (mode === 'menubar') refreshAndSend();
});
}
function destroyPopover() {
if (popover && !popover.isDestroyed()) popover.destroy();
popover = null;
}
// ---------- Hover popover ----------
function positionPopover() {
if (!popover || popover.isDestroyed()) return;
const pb = popover.getBounds();
if (mode === 'taskbar') {
// The widget is now a normal window we position ourselves, so anchor the
// popover directly above its current bounds.
if (!win || win.isDestroyed()) return;
const wb = win.getBounds();
popover.setBounds({
x: Math.round(wb.x),
y: Math.round(wb.y) - pb.height - 6,
width: pb.width,
height: pb.height,
});
} else if (mode === 'menubar' && tray) {
const b = tray.getBounds();
popover.setBounds({
x: Math.round(b.x + b.width / 2 - pb.width / 2),
y: Math.round(b.y + b.height + 4),
width: pb.width,
height: pb.height,
});
}
}
function showPopover() {
if (!popover || popover.isDestroyed()) return;
if (draggingTaskbar) return; // don't pop the detail card mid-drag
if (popoverHideTimer) {
clearTimeout(popoverHideTimer);
popoverHideTimer = null;
}
positionPopover();
if (lastInfo) popover.webContents.send('ip:update', lastInfo);
popover.showInactive();
}
function hidePopover() {
if (popoverHideTimer) clearTimeout(popoverHideTimer);
// Small delay so moving the cursor between the widget and the popover (or
// within either) doesn't make it flicker.
popoverHideTimer = setTimeout(() => {
if (popover && !popover.isDestroyed()) popover.hide();
}, 220);
}
// ---------- Tray ----------
function updateTrayTitle() {
if (mode !== 'menubar' || !tray) return;
const field = config.menubarField || 'loc';
let text = t.ipLoading;
if (lastInfo) {
text =
field === 'ip'
? lastInfo.ip
: field === 'isp'
? lastInfo.isp || lastInfo.location
: lastInfo.location;
}
tray.setTitle(' ' + (text || ''));
}
function closeDetailNotification() {
if (detailNotificationTimer) {
clearTimeout(detailNotificationTimer);
detailNotificationTimer = null;
}
if (detailNotification) {
detailNotification.close();
detailNotification = null;
}
}
function detailNotificationBody() {
if (!lastInfo) return t.ipLoading;
const lines = [
`${t.labelIp}: ${lastInfo.ip}`,
`${t.labelLoc}: ${lastInfo.location || t.unknownLoc}`,
];
if (lastInfo.isp) lines.push(`${t.labelIsp}: ${lastInfo.isp}`);
if (lastInfo.time) lines.push(`${t.updatePrefix}${new Date(lastInfo.time).toLocaleTimeString()}`);
return lines.join('\n');
}
async function showTrayDetailNotification() {
if (mode !== 'menubar' || !Notification.isSupported()) return;
if (!lastInfo) await refreshAndSend();
closeDetailNotification();
detailNotification = new Notification({
title: t.tooltip,
body: detailNotificationBody(),
silent: true,
});
const notification = detailNotification;
detailNotification.on('close', () => {
if (detailNotification !== notification) return;
detailNotification = null;
if (detailNotificationTimer) {
clearTimeout(detailNotificationTimer);
detailNotificationTimer = null;
}
});
detailNotification.show();
detailNotificationTimer = setTimeout(closeDetailNotification, 6000);
}
function buildTrayMenu(showWindow) {
const items = [];
if (mode === 'floating') items.push({ label: t.trayShow, click: showWindow });
items.push({ label: t.trayRefresh, click: () => refreshAndSend() });
if (mode === 'menubar') {
const field = config.menubarField || 'loc';
const setField = (f) => {
config.menubarField = f;
saveConfig(config);
updateTrayTitle();
if (mode !== 'menubar') tray.setContextMenu(buildTrayMenu(showWindow));
};
items.push({ type: 'separator' });
items.push({
label: t.trayFieldLoc,
type: 'radio',
checked: field === 'loc',
click: () => setField('loc'),
});
items.push({
label: t.trayFieldIp,
type: 'radio',
checked: field === 'ip',
click: () => setField('ip'),
});
items.push({
label: t.trayFieldIsp,
type: 'radio',
checked: field === 'isp',
click: () => setField('isp'),
});
}
items.push({ type: 'separator' });
items.push({ label: t.trayQuit, click: () => app.quit() });
return Menu.buildFromTemplate(items);
}
function createTray() {
const iconPath = mode === 'menubar' ? MAC_TRAY_ICON_PATH : ICON_PATH;
let icon = nativeImage.createFromPath(iconPath);
if (!icon.isEmpty()) {
// Tray icons are tiny; scale the master image down so it renders crisply.
icon = icon.resize({ width: mode === 'menubar' ? 18 : 32, height: mode === 'menubar' ? 18 : 32 });
if (mode === 'menubar') icon.setTemplateImage(true);
}
try {
tray = new Tray(icon);
} catch {
return;
}
const showWindow = () => {
if (!win || win.isDestroyed()) return;
if (win.isMinimized()) win.restore();
if (mode === 'taskbar') {
syncTaskbarFullscreenVisibility();
if (taskbarHiddenForFullscreen) return;
}
win.show();
win.setAlwaysOnTop(true, 'screen-saver');
};
if (mode === 'menubar') {
updateTrayTitle();
tray.setIgnoreDoubleClickEvents(true);
tray.on('click', (event) => {
if (event && event.ctrlKey) {
tray.popUpContextMenu(buildTrayMenu(showWindow));
} else {
showTrayDetailNotification();
}
});
tray.on('right-click', () => tray.popUpContextMenu(buildTrayMenu(showWindow)));
} else {
// Double-clicking the tray icon also brings the widget back.
tray.on('double-click', showWindow);
}
tray.setToolTip(t.tooltip);
tray.setContextMenu(mode === 'menubar' ? null : buildTrayMenu(showWindow));
}
// ---------- IPC ----------
ipcMain.on('ip:refresh', () => refreshAndSend());
ipcMain.on('app:quit', () => app.quit());
ipcMain.on('popover:enter', showPopover);
ipcMain.on('popover:leave', hidePopover);
ipcMain.on('taskbar:dragStart', startTaskbarDrag);
ipcMain.on('taskbar:dragEnd', () => stopTaskbarDrag(true));
ipcMain.on('taskbar:resize', (_e, width) => setTaskbarWidth(width));
app.whenReady().then(() => {
// Resolve UI language from the OS locale (Chinese → zh, otherwise English).
t = app.getLocale().toLowerCase().startsWith('zh') ? STRINGS.zh : STRINGS.en;
// Follow the OS proxy configuration so the IP lookup reflects the proxy.
session.defaultSession.setProxy({ mode: 'system' }).catch(() => {});
if (mode === 'taskbar') {
createTaskbarWindow();
createPopover();
} else if (mode === 'floating') {
createFloatingWindow();
}
createTray();
if (mode === 'menubar') refreshAndSend();
// Keep the embedded taskbar widget legible when the OS theme flips.
nativeTheme.on('updated', () => {
if (mode === 'taskbar' && win && !win.isDestroyed()) {
win.webContents.send('theme', currentTheme());
}
});
// Refresh every 5 minutes.
refreshTimer = setInterval(refreshAndSend, 5 * 60 * 1000);
// Also refresh once whenever the local network changes (connect / disconnect,
// proxy started, VPN adapter up/down).
startNetworkWatch();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
if (mode === 'taskbar') createTaskbarWindow();
else if (mode === 'floating') createFloatingWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('before-quit', () => {
if (refreshTimer) clearInterval(refreshTimer);
if (netWatchTimer) clearInterval(netWatchTimer);
if (netChangeDebounce) clearTimeout(netChangeDebounce);
if (taskbarTimer) clearInterval(taskbarTimer);
if (fullscreenTimer) clearInterval(fullscreenTimer);
closeDetailNotification();
clearDragTimers();
if (reassertTimer) clearTimeout(reassertTimer);
if (taskbarWin) taskbarWin.stopForegroundWatch();
});