Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
2525 lines (2361 loc) · 107 KB
/
Copy pathmain.js
File metadata and controls
2525 lines (2361 loc) · 107 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
// EQL Overlay - main process
// Creates a transparent, frameless, always-on-top overlay window that can be
// toggled between Edit mode (interactive) and Locked mode (click-through).
const { app, BrowserWindow, globalShortcut, ipcMain, Tray, Menu, screen, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const spelldb = require('./spelldb.js');
// ---------------------------------------------------------------------------
// Settings persistence
// ---------------------------------------------------------------------------
const settingsPath = () => path.join(app.getPath('userData'), 'overlay-settings.json');
const DEFAULT_SETTINGS = {
bounds: { x: 100, y: 100, width: 480, height: 320 },
opacity: 0.85, // background panel opacity (0..1)
fontFamily: 'Segoe UI',
fontColor: '#ffd766',
baseFontSize: 22, // px at base design size; scales with window
keepAspectRatio: true,
locked: false,
showNotes: false,
logPath: '',
lastZone: '',
autoZoneUpdate: false,
autoClearLog: false,
autoRun: false, // zoning starts a run automatically (End run stays manual)
archiveOnClear: true,
alertFlash: true,
alertSound: true,
alertVolume: 60,
mergePets: true,
buffAlerts: true,
mutedAlerts: [],
spellTimers: '',
posClasses: [], // Plane of Sky quest tracker: classes shown (max 3)
updateRepo: 'RealMaeel/seqo', // GitHub "user/repo" to check Releases for updates
autoCheckUpdates: true, // check for a new release at launch
autoDataCheck: true, // weekly: did the wiki pages behind Epics/Unlocks change?
buffWatch: 'Clarity = Your thoughts slow.\nSpirit of Wolf = You feel your feet slow.\nLevitate = You feel your feet touch the ground.',
wikiUser: '',
wikiPass: '',
bisFlag: false, // BiS drops flagged in toasts/verdicts (opt-in, own class only)
textScale: 'normal', // 'normal' | 'large' — fine-print size across overlay + docks
loginReminder: true, // once-per-login "/outputfile ..." reminder toast
needsPanelOpen: false, // zone-needs panel: restore open state across restarts
needsPanelMin: false, // ... and its minimized state
text: 'Notes: click to edit.'
};
function loadSettings() {
try {
const raw = fs.readFileSync(settingsPath(), 'utf8');
return { ...DEFAULT_SETTINGS, ...JSON.parse(raw) };
} catch {
return { ...DEFAULT_SETTINGS };
}
}
function saveSettings(s) {
try {
fs.mkdirSync(path.dirname(settingsPath()), { recursive: true });
fs.writeFileSync(settingsPath(), JSON.stringify(s, null, 2));
} catch (e) {
console.error('Failed to save settings:', e);
}
}
let settings = null;
let win = null;
let tray = null;
// Base design size: content is authored against this size and uniformly
// scaled up/down as the window is resized, preserving its internal ratio.
const BASE_W = 480;
const BASE_H = 320;
// ---------------------------------------------------------------------------
// Overlay window
// ---------------------------------------------------------------------------
function clampToScreen(bounds) {
const display = screen.getDisplayMatching(bounds) || screen.getPrimaryDisplay();
const wa = display.workArea;
const width = Math.min(bounds.width, wa.width);
const height = Math.min(bounds.height, wa.height);
const x = Math.min(Math.max(bounds.x, wa.x), wa.x + wa.width - width);
const y = Math.min(Math.max(bounds.y, wa.y), wa.y + wa.height - height);
return { x, y, width, height };
}
function createWindow() {
const b = clampToScreen(settings.bounds);
win = new BrowserWindow({
...b,
minWidth: 180,
minHeight: 120,
frame: false,
transparent: true,
resizable: true,
hasShadow: false,
skipTaskbar: true,
// 'screen-saver' is the highest always-on-top level - needed to stay
// above borderless-fullscreen games.
alwaysOnTop: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
win.setAlwaysOnTop(true, 'screen-saver');
win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
if (settings.keepAspectRatio) {
win.setAspectRatio(BASE_W / BASE_H);
}
win.loadFile('overlay.html');
win.webContents.on('did-finish-load', () => {
win.webContents.send('settings', settings);
applyLockState();
if (settings.logPath) startTail(settings.logPath);
else sendLogStatus();
// Dev-only: replay a log file through the meter (EQL_REPLAY=/path/to/log)
if (process.env.EQL_REPLAY) {
try {
const lines = fs.readFileSync(process.env.EQL_REPLAY, 'latin1')
.split(/\r?\n/).filter(l => l.length);
setTimeout(() => {
for (let i = 0; i < lines.length; i += 2000) {
win.webContents.send('log-lines', lines.slice(i, i + 2000));
}
}, 500);
} catch (e) { console.error('Replay failed:', e.message); }
}
// Headless smoke-test hook (dev only): EQL_TEST=1 captures screenshots.
if (process.env.EQL_TEST) {
win.webContents.on('console-message', (_e, _lvl, msg) => console.log('[renderer]', msg));
const shot = async (name) => {
const img = await win.webContents.capturePage();
fs.writeFileSync('/tmp/overlay-' + name + '.png', img.toPNG());
};
win.webContents.executeJavaScript('window.__EQLTEST = true; true').catch(() => {});
setTimeout(async () => {
try {
const tabs = (process.env.EQL_TEST_TABS ||
'meter;breakdown;loot;lookup;item:Flowing Black Silk Sash;export').split(';');
const wait = +(process.env.EQL_TEST_WAIT || 700);
for (let i = 0; i < tabs.length; i++) {
if (tabs[i] === 'syncdemo') { // dev-only: sync status with a pull from "another computer"
settings.dataDir = '/tmp/eqshare';
settings.syncFiles = ['/tmp/eqfake/Maeel_neriak_LO1.ini'];
fs.mkdirSync('/tmp/eqshare/gamefiles', { recursive: true });
fs.writeFileSync('/tmp/eqshare/gamefiles/sync-marker.json',
JSON.stringify({ host: 'ED-DESKTOP', at: Date.now() - 20 * 60000 }));
fs.writeFileSync('/tmp/eqfake/Maeel_neriak_LO1.ini', 'local version');
await new Promise(r => setTimeout(r, 2100)); // mtime gap > the 2s tolerance
fs.writeFileSync('/tmp/eqshare/gamefiles/Maeel_neriak_LO1.ini', 'shared newer version');
const res = syncGameFiles();
console.log('SYNCVERIFY|' + JSON.stringify(res.summary) + '|' + (res.results || []).join(' ~ '));
if (win) win.webContents.send('gamefiles-synced', res);
await win.webContents.executeJavaScript(
'document.body.classList.add("settings-open");' +
'[...document.querySelectorAll("#settings details")].forEach((d,x)=>d.open=x===3);true');
await new Promise(r => setTimeout(r, wait));
await shot(String(i + 1).padStart(2, '0') + '-sync');
continue;
}
if (tabs[i].startsWith('needshot')) { // dev-only: open + screenshot the zone-needs panel ('needshot' or 'needshot:min')
openNeeds();
await new Promise(r => setTimeout(r, wait + 1200));
if (tabs[i] === 'needshot:min') {
settings.needsPanelMin = true;
if (needsWin && !needsWin.isDestroyed()) needsWin.webContents.send('needs-min', true);
snapDock();
await new Promise(r => setTimeout(r, 500));
}
if (needsWin && !needsWin.isDestroyed()) {
const img = await needsWin.webContents.capturePage();
fs.writeFileSync('/tmp/overlay-' + String(i + 1).padStart(2, '0') + '-needs.png', img.toPNG());
}
continue;
}
if (tabs[i].startsWith('slydock:')) { // dev-only: Slayer route read-out in the dock
win.webContents.send('test-tab', 'slyroute:' + tabs[i].slice(8));
await new Promise(r => setTimeout(r, wait + 1500));
if (dockWin && !dockWin.isDestroyed()) {
const img = await dockWin.webContents.capturePage();
fs.writeFileSync('/tmp/overlay-' + String(i + 1).padStart(2, '0') + '-slydock.png', img.toPNG());
}
continue;
}
if (tabs[i].startsWith('dockshot')) { // dev-only: open + screenshot the dock ('dockshot', 'dockshot:item:Name', 'dockshot:help', 'dockshot:helptopic:N', 'dockshot:guide:Title[:Anchor]')
const spec = tabs[i].slice(9);
if (spec.startsWith('item:')) openDock('item', { name: spec.slice(5) });
else if (spec === 'help') openDock('help');
else if (spec.startsWith('helptopic:')) {
openDock('help');
await new Promise(r => setTimeout(r, 1000));
if (dockWin && !dockWin.isDestroyed())
await dockWin.webContents.executeJavaScript('showHelpTopic(' + (+spec.slice(10) || 0) + ');true');
}
else if (spec.startsWith('guide:')) {
const [t, a] = spec.slice(6).split('|');
// the sandboxed test env has no network: seed a cached page
gameDB.guidePages = gameDB.guidePages || {};
if (!gameDB.guidePages[t]) gameDB.guidePages[t] = {
pageTitle: t, revid: 1, updated: Date.now(),
wikitext: '== Dwarf ==\n=== Requirements ===\n* Get maximum faction with [[Storm Guard]]\n' +
'=== Recommended Method ===\n# Brew \'\'\'Tumpy Tonics\'\'\' from 800 [[Kiola Nut]]s and Flasks of Water.\n' +
'# Hand them to Trantor Everhot in [[South Kaladim]] four at a time.\n' +
'{| class="wikitable"\n! Item !! Total\n|-\n| Tumpy Tonic || 800\n|}\n'
};
openDock('guide', { title: t, anchor: a || undefined, label: t });
}
else openDock('cleanup');
await new Promise(r => setTimeout(r, wait + 1800));
if (spec.startsWith('filter:') && dockWin && !dockWin.isDestroyed()) {
await dockWin.webContents.executeJavaScript(
'document.getElementById("filter").value=' + JSON.stringify(spec.slice(7)) +
';document.getElementById("filter").dispatchEvent(new Event("input"));true');
await new Promise(r => setTimeout(r, 400));
}
if (spec.startsWith('chip:') && dockWin && !dockWin.isDestroyed()) {
await dockWin.webContents.executeJavaScript(
'pileFilter=' + JSON.stringify(spec.slice(5)) + ';render();true');
await new Promise(r => setTimeout(r, 400));
}
if (dockWin && !dockWin.isDestroyed()) {
const img = await dockWin.webContents.capturePage();
fs.writeFileSync('/tmp/overlay-' + String(i + 1).padStart(2, '0') + '-dock.png', img.toPNG());
}
continue;
}
win.webContents.send('test-tab', tabs[i]);
await new Promise(r => setTimeout(r, wait));
await shot(String(i + 1).padStart(2, '0') + '-' + (tabs[i].split(':')[0].replace(/[^a-z]/gi, '') || 'tab'));
}
app.quit();
} catch (e) { console.error(e); app.exit(1); }
}, 3000);
}
});
const rememberBounds = () => {
if (!win) return;
settings.bounds = win.getBounds();
saveSettings(settings);
snapDock(); // the dock rides along under the overlay
};
win.on('moved', rememberBounds);
win.on('resized', rememberBounds);
win.on('move', () => snapDock());
win.on('restore', () => { // back from taskbar: overlay mode again
win.setSkipTaskbar(true);
win.setAlwaysOnTop(true, 'screen-saver');
});
win.on('closed', () => { win = null; });
}
function applyLockState() {
if (!win) return;
if (settings.locked) {
// Click-through: mouse events pass to the game underneath.
win.setIgnoreMouseEvents(true, { forward: true });
} else {
win.setIgnoreMouseEvents(false);
}
win.webContents.send('lock-state', settings.locked);
// the attached windows (needs panel, dock) follow the same rules: locked =
// click-through with hover-to-interact (their renderers drive it), unlocked
// = ordinary windows
for (const w of [needsWin, dockWin]) {
if (!w || w.isDestroyed()) continue;
if (settings.locked) w.setIgnoreMouseEvents(true, { forward: true });
else w.setIgnoreMouseEvents(false);
w.webContents.send('lock-state', settings.locked);
}
snapDock(); // the drawn panel shifts between edit/locked — children follow
updateTrayMenu();
}
function toggleLock() {
settings.locked = !settings.locked;
saveSettings(settings);
applyLockState();
}
function toggleVisibility() {
if (!win) return;
if (win.isVisible()) win.hide();
else win.show();
updateTrayMenu();
}
// ---------------------------------------------------------------------------
// Tray icon
// ---------------------------------------------------------------------------
function updateTrayMenu() {
if (!tray) return;
tray.setContextMenu(Menu.buildFromTemplate([
{ label: settings.locked ? 'Unlock (edit mode) Ctrl+Alt+O' : 'Lock (click-through) Ctrl+Alt+O', click: toggleLock },
{ label: (win && win.isVisible()) ? 'Hide overlay Ctrl+Alt+H' : 'Show overlay Ctrl+Alt+H', click: toggleVisibility },
{ type: 'separator' },
{ label: 'Reset position', click: () => { if (win) win.setBounds({ x: 100, y: 100, width: BASE_W, height: BASE_H }); } },
{ type: 'separator' },
{ label: 'Quit SEQO', click: () => app.quit() }
]));
}
function createTray() {
try {
tray = new Tray(path.join(__dirname, 'assets', 'icon.png'));
tray.setToolTip('SEQO — Simple EQ Overlay');
tray.on('click', toggleVisibility); // single-click tray = show/hide
updateTrayMenu();
} catch (e) {
console.error('Tray icon unavailable:', e);
}
}
// ---------------------------------------------------------------------------
// Game database (zone/item lookup cache, populated from the wiki on demand)
// ---------------------------------------------------------------------------
const updater = require('./updater.js');
// Shareable databases (loot + game data) live in the data folder, which can
// be pointed at a Dropbox / Google Drive / OneDrive folder to sync between
// computers. Machine-specific settings always stay in the local profile.
function dataDir() {
return (settings && settings.dataDir) || app.getPath('userData');
}
const gameDbPath = () => path.join(dataDir(), 'gamedb.json');
let gameDB = { zones: {}, items: {} };
let gameSaveTimer = null;
function loadGameDB() {
try { gameDB = JSON.parse(fs.readFileSync(gameDbPath(), 'utf8')); } catch { gameDB = { zones: {}, items: {} }; }
gameDB.zones = gameDB.zones || {};
gameDB.items = gameDB.items || {};
delete gameDB.charmSpells; // v1.1.1: purge poisoned auto-learned "charm spells"
pruneGameDB(); // v2.5.0: keep the DB lean — it loads, saves and syncs whole
}
// Months of play grow two caches without bound: item-knowledge (every junk
// drop ever judged) and opened guide pages. Prune what hasn't been touched in
// a long while — anything pruned that's still wanted re-fetches cheaply (the
// cleanup scan bulk-checks existence 50 names per request).
function pruneGameDB() {
try {
let dropped = 0;
const ik = gameDB.itemKnowledge || {};
const entries = Object.entries(ik);
if (entries.length > 1500) { // cap: keep the 1500 most recently checked
entries.sort((a, b) => (b[1].checkedAt || 0) - (a[1].checkedAt || 0));
for (const [k] of entries.slice(1500)) { delete ik[k]; dropped++; }
}
const gp = gameDB.guidePages || {};
const cutoff = Date.now() - 60 * 864e5; // a guide untouched for 60 days re-fetches on next open
for (const [t, p] of Object.entries(gp))
if (!p || (p.updated || 0) < cutoff) { delete gp[t]; dropped++; }
if (dropped) saveGameDBSoon();
} catch { /* never let housekeeping break startup */ }
}
function saveGameDBSoon() {
clearTimeout(gameSaveTimer);
gameSaveTimer = setTimeout(() => {
try { lastDbWrite = Date.now(); fs.writeFileSync(gameDbPath(), JSON.stringify(gameDB)); } catch (e) { console.error(e); }
}, 1000);
}
// ---------------------------------------------------------------------------
// Shared data folder: choose, migrate, and watch for changes synced in from
// another computer (Dropbox/Drive writes the file; we reload and re-push).
// ---------------------------------------------------------------------------
ipcMain.handle('choose-data-folder', async () => {
const res = await dialog.showOpenDialog(win, {
title: 'Select shared data folder (e.g. a folder inside Dropbox or Google Drive)',
properties: ['openDirectory', 'createDirectory']
});
if (res.canceled || !res.filePaths.length) return { dir: dataDir(), changed: false };
const newDir = res.filePaths[0];
// migrate: if the shared folder doesn't have DBs yet, seed it with ours;
// if it does, the shared copies win (that's the point of sharing)
try {
for (const f of ['lootdb.json', 'gamedb.json']) {
const src = path.join(dataDir(), f);
const dst = path.join(newDir, f);
if (!fs.existsSync(dst) && fs.existsSync(src)) fs.copyFileSync(src, dst);
}
} catch (e) { return { error: e.message }; }
settings.dataDir = newDir;
saveSettings(settings);
app.relaunch();
app.exit(0);
});
ipcMain.handle('data-dir-status', () => ({
dir: dataDir(),
shared: !!settings.dataDir
}));
// ---------------------------------------------------------------------------
// Synced game files: user-chosen files (character loadouts like
// Maeel_neriak_LO1.ini, UI layouts, etc.) mirrored through the shared folder.
// Newest copy wins; the overwritten side gets a .seqo.bak backup first.
// Local paths are per-machine (installs differ); the shared side is keyed
// by filename under <dataDir>/gamefiles/.
// ---------------------------------------------------------------------------
const gamefilesDir = () => path.join(dataDir(), 'gamefiles');
function copyPreservingTime(src, dst) {
fs.copyFileSync(src, dst);
const st = fs.statSync(src);
fs.utimesSync(dst, st.atime, st.mtime); // keep mtimes equal so sync converges
}
function syncOnePair(local, shared, label, results) {
try {
const le = fs.existsSync(local), se = fs.existsSync(shared);
if (le && se) {
const lm = fs.statSync(local).mtimeMs, sm = fs.statSync(shared).mtimeMs;
if (Math.abs(lm - sm) < 2000) { results.push(label + ': in sync'); return; }
if (lm > sm) {
copyPreservingTime(local, shared);
results.push(label + ': → shared (local was newer)');
} else {
fs.copyFileSync(local, local + '.seqo.bak');
copyPreservingTime(shared, local);
results.push(label + ': ← shared (backup kept)');
}
} else if (le) {
fs.mkdirSync(path.dirname(shared), { recursive: true });
copyPreservingTime(local, shared);
results.push(label + ': seeded to shared');
} else if (se) {
fs.mkdirSync(path.dirname(local), { recursive: true });
copyPreservingTime(shared, local);
results.push(label + ': pulled from shared');
} else {
results.push(label + ': ⚠ missing on both sides');
}
} catch (e) {
results.push(label + ': ⚠ ' + e.message);
}
}
// list files (relative paths) under dir, up to `depth` levels down
function listFilesRel(dir, depth, prefix = '') {
const out = [];
let entries = [];
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
for (const e of entries) {
if (e.name.endsWith('.seqo.bak')) continue;
if (e.isDirectory()) {
if (depth > 0) out.push(...listFilesRel(path.join(dir, e.name), depth - 1, path.join(prefix, e.name)));
} else {
out.push(path.join(prefix, e.name));
}
}
return out;
}
function syncGameFiles() {
if (!settings.dataDir) return { error: 'Set a shared data folder first' };
const results = [];
try { fs.mkdirSync(gamefilesDir(), { recursive: true }); } catch (e) { return { error: e.message }; }
for (const local of settings.syncFiles || []) {
const base = path.basename(local);
let isDir = false;
try { isDir = fs.statSync(local).isDirectory(); } catch { /* may only exist on shared side */ }
const sharedFolder = path.join(gamefilesDir(), 'folders', base);
if (isDir || fs.existsSync(sharedFolder)) {
// whole-folder sync (e.g. a custom UI skin folder): newest-wins per file,
// union of both sides so files added later on either machine are picked up
const rels = new Set([...listFilesRel(local, 3), ...listFilesRel(sharedFolder, 3)]);
const sub = [];
for (const rel of rels) syncOnePair(path.join(local, rel), path.join(sharedFolder, rel), rel, sub);
const changed = sub.filter(r => !r.includes('in sync'));
results.push('📁 ' + base + ': ' + (changed.length ? changed.length + ' of ' + rels.size + ' files updated' : rels.size + ' files in sync'));
for (const c of changed.slice(0, 6)) results.push(' ' + c);
} else {
syncOnePair(local, path.join(gamefilesDir(), base), base, results);
}
}
// sync status (v2.4): a persistent record of what just happened, plus a
// marker in the shared folder saying WHICH COMPUTER wrote last — so after
// switching machines you can see at a glance whether the other side's data
// actually arrived or you forgot to sync before leaving it.
const host = (() => { try { return require('os').hostname(); } catch { return 'this computer'; } })();
let otherHost = null, otherAt = 0;
const markerPath = path.join(gamefilesDir(), 'sync-marker.json');
try {
const m = JSON.parse(fs.readFileSync(markerPath, 'utf8'));
if (m && m.host && m.host !== host) { otherHost = m.host; otherAt = m.at || 0; }
} catch { /* first sync ever, or marker unreadable */ }
const pulled = results.filter(r => /← shared|pulled from shared/.test(r)).length;
const pushed = results.filter(r => /→ shared|seeded to shared/.test(r)).length;
const failed = results.filter(r => r.includes('⚠'));
const summary = {
at: Date.now(), host, pulled, pushed,
failed: failed.slice(0, 4),
inSync: results.filter(r => r.includes('in sync')).length,
from: pulled && otherHost ? { host: otherHost, at: otherAt } : null
};
settings.lastSync = summary;
saveSettings(settings);
try { fs.writeFileSync(markerPath, JSON.stringify({ host, at: Date.now() })); } catch { /* read-only share */ }
return { results, summary };
}
let gamefileWatchers = [];
function watchGameFiles() {
for (const p of gamefileWatchers) fs.unwatchFile(p);
gamefileWatchers = [];
if (!settings.dataDir) return;
for (const local of settings.syncFiles || []) {
const shared = path.join(gamefilesDir(), path.basename(local));
gamefileWatchers.push(shared);
fs.watchFile(shared, { interval: 5000 }, (curr, prev) => {
if (curr.mtimeMs === prev.mtimeMs) return;
const res = syncGameFiles();
if (win && res.results) win.webContents.send('gamefiles-synced', res);
});
}
}
ipcMain.handle('get-sync-files', () => settings.syncFiles || []);
ipcMain.handle('add-sync-file', async () => {
const res = await dialog.showOpenDialog(win, {
title: 'Choose game file(s) to sync (e.g. your _LO1 loadout file)',
properties: ['openFile', 'multiSelections']
});
if (!res.canceled && res.filePaths.length) {
settings.syncFiles = [...new Set([...(settings.syncFiles || []), ...res.filePaths])];
saveSettings(settings);
watchGameFiles();
return { files: settings.syncFiles, ...syncGameFiles() };
}
return { files: settings.syncFiles || [] };
});
ipcMain.handle('add-sync-folder', async () => {
const res = await dialog.showOpenDialog(win, {
title: 'Choose a folder to sync (e.g. your custom UI skin in uifiles\\<skinname>)',
properties: ['openDirectory']
});
if (!res.canceled && res.filePaths.length) {
settings.syncFiles = [...new Set([...(settings.syncFiles || []), ...res.filePaths])];
saveSettings(settings);
watchGameFiles();
return { files: settings.syncFiles, ...syncGameFiles() };
}
return { files: settings.syncFiles || [] };
});
ipcMain.on('remove-sync-file', (_e, p) => {
settings.syncFiles = (settings.syncFiles || []).filter(f => f !== p);
saveSettings(settings);
watchGameFiles();
});
ipcMain.handle('sync-game-files', () => syncGameFiles());
function watchSharedDBs() {
if (!settings.dataDir) return; // only needed when sharing
for (const p of [lootDbPath(), gameDbPath()]) {
fs.watchFile(p, { interval: 3000 }, (curr, prev) => {
if (curr.mtimeMs === prev.mtimeMs) return;
if (Date.now() - lastDbWrite < 4000) return; // our own write, not a sync
loadLootDB();
loadGameDB();
if (win) {
win.webContents.send('loot-db', lootDB);
win.webContents.send('shared-reload');
}
});
}
}
ipcMain.handle('get-zone-data', (_e, zone) => gameDB.zones[zone] || null);
ipcMain.handle('update-zone-data', async (_e, zone, aliases) => {
try {
const data = await updater.fetchZoneData(zone, aliases || []);
gameDB.zones[zone] = data;
saveGameDBSoon();
return data;
} catch (err) {
return { error: err.message };
}
});
ipcMain.handle('get-item-data', (_e, name) => gameDB.items[name.toLowerCase()] || null);
// eqlegendstools' data pages are JavaScript-rendered, so plain fetches see
// empty shells. SEQO is a browser: render each page in a hidden window and
// read the finished text. Used only on cache refresh (weekly), politely.
function scrapeRenderedText(url) {
return new Promise((resolve) => {
let w = null;
let settled = false;
const done = (txt) => {
if (settled) return;
settled = true;
try { if (w && !w.isDestroyed()) w.destroy(); } catch {}
resolve(String(txt || ''));
};
try {
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, images: false } });
w.webContents.once('did-finish-load', async () => {
await new Promise(r => setTimeout(r, 3500)); // let the JS render
try { done(await w.webContents.executeJavaScript('document.body.innerText', true)); }
catch { done(''); }
});
w.webContents.once('did-fail-load', () => done(''));
w.loadURL(url).catch(() => done(''));
setTimeout(() => done(''), 25000); // hard cap
} catch { done(''); }
});
}
// Re-scrape the live BiS gear table from eqlegendstools.com (one hidden
// window, selecting each class in turn). Result is stored in gameDB.bisData
// and overrides the static seed in bis.js. Credit: eqlegendstools.com.
const BIS_CLASSES = ['Bard', 'Beastlord', 'Berserker', 'Cleric', 'Druid', 'Enchanter',
'Magician', 'Monk', 'Necromancer', 'Paladin', 'Ranger', 'Rogue', 'Shadow Knight',
'Shaman', 'Warrior', 'Wizard'];
function scrapeBisData() {
return new Promise((resolve) => {
let w = null, settled = false;
const done = (v) => {
if (settled) return;
settled = true;
try { if (w && !w.isDestroyed()) w.destroy(); } catch { /* ok */ }
resolve(v);
};
try {
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, images: false } });
w.webContents.once('did-finish-load', async () => {
try {
await new Promise(r => setTimeout(r, 3000));
const script = `(async () => {
const s1 = document.getElementById('gearClassSelect1');
const s2 = document.getElementById('gearClassSelect2');
const s3 = document.getElementById('gearClassSelect3');
if (!s1) return null;
const fire = (el) => el.dispatchEvent(new Event('change', { bubbles: true }));
s2.value = ''; fire(s2); s3.value = ''; fire(s3);
const allSlots = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === 'All Slots');
if (allSlots) allSlots.click();
const num = (v) => { const n = parseInt(v, 10); return isNaN(n) ? 0 : n; };
// map columns by header text so new site columns (e.g. Accuracy)
// don't break the scrape or get missed
const findCols = () => {
const ths = [...document.querySelectorAll('table thead th, table tr th')]
.map(th => th.textContent.trim().toLowerCase());
const at = (...names) => ths.findIndex(h => names.some(n => h === n || h.startsWith(n)));
const idx = {
name: at('name', 'item'), slot: at('slot'), ac: at('ac'),
hp: at('hp'), mana: at('mana'), acc: at('accuracy', 'acc'),
sp: at('special', 'effect'), src: at('source', 'drops', 'from')
};
// fall back to the known layout if headers aren't found
if (idx.name < 0) Object.assign(idx, { name: 1, slot: 2, ac: 3, hp: 4, mana: 5, acc: -1, sp: 19, src: 20 });
return idx;
};
const out = {};
for (const cls of ${JSON.stringify(BIS_CLASSES)}) {
s1.value = cls; fire(s1);
await new Promise(r => setTimeout(r, 700));
const col = findCols();
const bySlot = {};
for (const tr of document.querySelectorAll('table tbody tr')) {
const c = [...tr.cells].map(td => td.textContent.trim());
const g = (i) => (i >= 0 && c[i] !== undefined) ? c[i] : '';
const slot = g(col.slot);
if (!g(col.name) || !slot) continue;
const row = { n: g(col.name), ac: num(g(col.ac)), hp: num(g(col.hp)), mana: num(g(col.mana)), sp: g(col.sp) || undefined, src: g(col.src) || '' };
const acc = num(g(col.acc));
if (acc) row.acc = acc;
(bySlot[slot] = bySlot[slot] || []).push(row);
}
// keep top entries per slot: 6 by AC + 4 by HP + 4 by mana
const trimmed = {};
for (const [slot, rs] of Object.entries(bySlot)) {
const pick = new Set();
for (const r of [...rs].sort((a, b) => b.ac - a.ac).slice(0, 6)) pick.add(r);
for (const r of [...rs].sort((a, b) => b.hp - a.hp).slice(0, 4)) pick.add(r);
for (const r of [...rs].sort((a, b) => b.mana - a.mana).slice(0, 4)) pick.add(r);
trimmed[slot] = [...pick];
}
out[cls] = trimmed;
}
return out;
})()`;
const data = await w.webContents.executeJavaScript(script, true);
done(data && Object.keys(data).length === BIS_CLASSES.length ? data : null);
} catch { done(null); }
});
w.webContents.once('did-fail-load', () => done(null));
w.loadURL('https://eqlegendstools.com/bis-gear/').catch(() => done(null));
setTimeout(() => done(null), 60000);
} catch { done(null); }
});
}
ipcMain.handle('update-bis', async () => {
const data = await scrapeBisData();
if (!data) return { error: 'Could not read the live BiS table — try again later (the built-in list still works).' };
gameDB.bisData = { data, updated: Date.now() };
saveGameDBSoon();
return { classes: Object.keys(data).length, updated: gameDB.bisData.updated };
});
ipcMain.handle('get-bisdata', () => gameDB.bisData || null);
// "not a rare" list: mobs the wiki lists with drops (so they land in the
// zone's named set) that the player says aren't rares — e.g. haunted chests.
ipcMain.on('set-not-rare', (_e, { zone, mob, ignored }) => {
if (!mob) return;
gameDB.notRares = gameDB.notRares || {};
const arr = new Set(gameDB.notRares[zone || ''] || []);
if (ignored) arr.add(mob); else arr.delete(mob);
if (arr.size) gameDB.notRares[zone || ''] = [...arr];
else delete gameDB.notRares[zone || ''];
saveGameDBSoon();
});
ipcMain.handle('get-not-rares', () => gameDB.notRares || {});
// epic checklist manual tick-offs ('cls|item' -> true): turn-ins the
// inventory file can't see. Synced with the game DB like everything else.
ipcMain.on('set-epic-tick', (_e, { key, on }) => {
if (!key) return;
gameDB.epicTicks = gameDB.epicTicks || {};
if (on) gameDB.epicTicks[key] = true; else delete gameDB.epicTicks[key];
saveGameDBSoon();
});
ipcMain.handle('get-epic-ticks', () => gameDB.epicTicks || {});
// free-form notes — plain text, synced with the rest of the game database
ipcMain.on('set-notes', (_e, text) => {
gameDB.notes = String(text || '').slice(0, 200000);
saveGameDBSoon();
});
ipcMain.handle('get-notes', () => gameDB.notes || '');
// ---------------------------------------------------------------------------
// Cleanup window: a separate resizable window listing every bag/bank item
// with a keep/toss verdict. The OVERLAY renderer owns all the logic and data;
// this window is a dumb view — main just relays rows one way, commands back.
// ---------------------------------------------------------------------------
// The dock: one always-on-top panel that SNAPS TO THE OVERLAY'S BOTTOM EDGE
// and follows it around — the roomy place for anything that needs space
// (Cleanup, item details). Closable from inside; height is remembered;
// 📌 detaches it into a free-floating window.
let dockWin = null;
let dockDetached = false;
let needsWin = null; // zone-needs strip: its own slim window
let needsDetached = false;
const NEEDS_MIN_H = 32; // minimized: one summary line
function needsHeight() {
return settings.needsPanelMin ? NEEDS_MIN_H : Math.max(90, settings.needsHeight || 150);
}
// attached windows sit at ~the overlay's opacity (floored so they stay usable)
const childOpacity = () => Math.max(0.3, Math.min(1, settings.opacity !== undefined ? settings.opacity : 0.95));
function applyChildOpacity() {
for (const w of [dockWin, needsWin])
if (w && !w.isDestroyed()) { try { w.setOpacity(childOpacity()); } catch { /* ok */ } }
}
// The overlay DRAWS its panel centered inside the window (480×290 design,
// uniformly scaled; the 30px toolbar strip only exists in edit mode). Snapping
// children to the WINDOW bottom leaves a gap in locked mode — snap to the
// drawn panel instead. Mirrors rescale() in overlay.html exactly.
function panelRect() {
const b = win.getBounds();
const tb = settings.locked ? 0 : 30;
const availW = b.width, availH = b.height - tb;
const s = Math.min(availW / 480, availH / 290);
const w = Math.round(480 * s), h = Math.round(290 * s);
return {
x: b.x + Math.round((availW - w) / 2),
bottom: b.y + tb + Math.round((availH + h) / 2),
w
};
}
function snapDock() {
if (!win) return;
const r = panelRect();
const width = Math.max(320, r.w);
let y = r.bottom;
// the zone-needs strip rides directly under the overlay's drawn panel…
if (needsWin && !needsWin.isDestroyed() && !needsDetached) {
const h = needsHeight();
needsWin.setBounds({ x: r.x, y, width, height: h });
y += h;
}
// …and the dock stacks under whatever is above it
if (dockWin && !dockWin.isDestroyed() && !dockDetached) {
const h = Math.max(160, settings.dockHeight || 300);
dockWin.setBounds({ x: r.x, y, width, height: h });
}
}
function openDock(mode, payload) {
if (!dockWin || dockWin.isDestroyed()) {
dockWin = new BrowserWindow({
width: 480, height: Math.max(160, settings.dockHeight || 300),
minWidth: 320, minHeight: 160,
frame: false, transparent: false, backgroundColor: '#16161d',
skipTaskbar: true, resizable: true, alwaysOnTop: true,
webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, nodeIntegration: false }
});
dockWin.setAlwaysOnTop(true, 'screen-saver'); // same layer as the overlay
dockWin.loadFile('dock.html');
dockWin.on('closed', () => {
dockWin = null;
if (win) win.webContents.send('cleanup-state', false);
});
dockWin.on('resized', () => { // user dragged: keep the height, re-snap position/width
if (!dockWin || dockWin.isDestroyed()) return;
settings.dockHeight = dockWin.getBounds().height;
saveSettings(settings);
snapDock();
});
dockWin.webContents.once('did-finish-load', () => {
snapDock();
applyChildOpacity();
dockWin.webContents.send('ui-scale', settings.textScale || 'normal');
if (settings.locked) { // born locked: click-through with hover-to-interact
dockWin.setIgnoreMouseEvents(true, { forward: true });
dockWin.webContents.send('lock-state', true);
}
dockWin.webContents.send('dock-mode', { mode, payload });
if (win && mode === 'cleanup') win.webContents.send('cleanup-state', true);
});
return;
}
snapDock();
dockWin.focus();
dockWin.webContents.send('dock-mode', { mode, payload });
if (win && mode === 'cleanup') win.webContents.send('cleanup-state', true);
}
ipcMain.on('open-dock', (_e, { mode, payload }) => openDock(mode, payload));
ipcMain.on('open-cleanup', () => openDock('cleanup'));
ipcMain.on('close-dock', () => { if (dockWin && !dockWin.isDestroyed()) dockWin.close(); });
ipcMain.on('dock-detach', (_e, detached) => {
dockDetached = !!detached;
if (!dockDetached) snapDock();
else if (dockWin && !dockWin.isDestroyed()) dockWin.setResizable(true);
});
// overlay → dock (cleanup rows / scan progress)
ipcMain.on('cleanup-data', (_e, payload) => {
if (dockWin && !dockWin.isDestroyed()) dockWin.webContents.send('cleanup-data', payload);
});
// dock → overlay (commands: scan / junk / refresh / lookup / exaltview / wish)
ipcMain.on('cleanup-cmd', (_e, cmd) => {
if (win) win.webContents.send('cleanup-cmd', cmd);
});
// ---------------------------------------------------------------------------
// Zone-needs panel: a slim, PERSISTENT, minimizable strip glued under the
// overlay listing what you still need from the current zone. Its own window,
// so the dock (Cleanup / item details) can be open at the same time — the
// dock simply stacks below it. Open state and size survive restarts.
// ---------------------------------------------------------------------------
function openNeeds() {
if (needsWin && !needsWin.isDestroyed()) { snapDock(); needsWin.focus(); return; }
needsWin = new BrowserWindow({
width: 480, height: needsHeight(), minWidth: 320, minHeight: NEEDS_MIN_H,
frame: false, transparent: false, backgroundColor: '#14141c',
skipTaskbar: true, resizable: !settings.needsPanelMin, alwaysOnTop: true,
webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, nodeIntegration: false }
});
needsWin.setAlwaysOnTop(true, 'screen-saver');
needsWin.loadFile('needs.html');
needsWin.on('closed', () => {
needsWin = null;
settings.needsPanelOpen = false;
saveSettings(settings);
if (win) win.webContents.send('needs-state', false);
snapDock();
});
needsWin.on('resized', () => {
if (!needsWin || needsWin.isDestroyed()) return;
if (!settings.needsPanelMin) {
settings.needsHeight = needsWin.getBounds().height;
saveSettings(settings);
}
snapDock();
});
needsWin.webContents.once('did-finish-load', () => {
snapDock();
applyChildOpacity();
needsWin.webContents.send('ui-scale', settings.textScale || 'normal');
needsWin.webContents.send('needs-min', !!settings.needsPanelMin);
if (settings.locked) { // born locked: click-through with hover-to-interact
needsWin.setIgnoreMouseEvents(true, { forward: true });
needsWin.webContents.send('lock-state', true);
}
if (win) win.webContents.send('needs-state', true);
});
settings.needsPanelOpen = true;
saveSettings(settings);
}
ipcMain.on('open-needs', () => openNeeds());
ipcMain.on('close-needs', () => { if (needsWin && !needsWin.isDestroyed()) needsWin.close(); });
ipcMain.on('needs-detach', (_e, detached) => {
needsDetached = !!detached;
if (!needsDetached) snapDock();
});
ipcMain.on('needs-minimize', (_e, minimized) => {
settings.needsPanelMin = !!minimized;
saveSettings(settings);
if (needsWin && !needsWin.isDestroyed()) {
needsWin.setResizable(!settings.needsPanelMin);
needsWin.webContents.send('needs-min', settings.needsPanelMin);
}
snapDock();
});
// overlay → needs panel (rows) · needs panel → overlay (commands)
ipcMain.on('needs-data', (_e, payload) => {
if (needsWin && !needsWin.isDestroyed()) needsWin.webContents.send('needs-data', payload);
});
ipcMain.on('needs-cmd', (_e, cmd) => { if (win) win.webContents.send('needs-cmd', cmd); });
// ---------------------------------------------------------------------------
// Exaltations browser: effect index (per exaltation type) + per-effect item
// lists, pulled read-only from the wiki and cached in the game DB.
// ---------------------------------------------------------------------------
ipcMain.handle('get-exalt-index', () => gameDB.exaltIndex || null);
ipcMain.handle('update-exalt-index', async () => {
try {
gameDB.exaltIndex = await updater.fetchExaltIndex();
saveGameDBSoon();
return gameDB.exaltIndex;
} catch (e) { return { error: e.message }; }
});
ipcMain.handle('get-effect-items', async (_e, name) => {
gameDB.effects = gameDB.effects || {};
if (gameDB.effects[name]) return gameDB.effects[name];
try {
const data = await updater.fetchEffectItems(name);
gameDB.effects[name] = data;
saveGameDBSoon();
return data;
} catch (e) { return { error: e.message }; }
});
// permanent item knowledge (what each item is for), synced with the game DB
ipcMain.on('set-item-knowledge', (_e, { key, entry }) => {
if (!key) return;
gameDB.itemKnowledge = gameDB.itemKnowledge || {};
gameDB.itemKnowledge[key] = entry;
saveGameDBSoon();
});
ipcMain.handle('get-item-knowledge', () => gameDB.itemKnowledge || {});
// ---- spell database from the game's own files (spelldb.js) ----
// Parsed once per game patch, cached locally (machine-specific — NEVER in the
// shared/synced folder). The renderer gets the compact maps in one shot.
let spellDbBuilding = null;
ipcMain.handle('get-spell-db', async () => {
const root = settings.logPath ? gameRootFromLog(settings.logPath) : null;
if (!root) return { error: 'pick your log file first — the spell data lives next to it' };
try {
if (!spellDbBuilding) spellDbBuilding = spelldb.getSpellDB(root, app.getPath('userData'));
const db = await spellDbBuilding;
spellDbBuilding = null;
return db || { error: 'no spells_us.txt next to your Logs folder — is the log inside the game folder?' };
} catch (e) {
spellDbBuilding = null;
return { error: e.message || String(e) };
}
});
// bulk wiki existence pre-check for the cleanup scan: one query per 50 titles
// instead of parse + search fallbacks per missing item
ipcMain.handle('check-pages-exist', async (_e, titles) => {
try {
return await updater.pagesExist((titles || []).filter(Boolean).slice(0, 400));
} catch (e) {
return { error: e.message || String(e) };
}
});