-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
3633 lines (3286 loc) · 113 KB
/
main.js
File metadata and controls
3633 lines (3286 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, Menu, dialog, ipcMain, shell, nativeImage, clipboard, crashReporter } = require('electron');
const os = require('os');
const path = require('path');
const fs = require('fs');
const https = require('https');
const log = require('electron-log/main');
const { openInFinder } = require('./finder-actions');
const agentServer = require('./agent-server');
// Configure electron-log: writes to ~/Library/Logs/OpenMarkdownReader/
log.initialize();
log.transports.file.level = 'info';
log.transports.console.level = 'debug';
// Redirect console to electron-log so all output is captured to file
Object.assign(console, log.functions);
// Native crash dumps for hard crashes (Electron itself dying, native code crashes,
// GPU/utility process hard crashes). These are minidumps written to:
// ~/Library/Application Support/OpenMarkdownReader/Crashpad/completed/
// Without this, hard crashes leave nothing behind except whatever macOS captured
// to ~/Library/Logs/DiagnosticReports/.
// uploadToServer:false keeps everything local — no telemetry sent anywhere.
crashReporter.start({
productName: 'OpenMarkdownReader',
companyName: 'jacobcole',
uploadToServer: false,
ignoreSystemCrashHandler: false,
rateLimit: false,
compress: true
});
// Global error handlers — catch anything that would silently kill the app
process.on('uncaughtException', (error) => {
console.error('[UNCAUGHT EXCEPTION]', error.stack || error);
});
process.on('unhandledRejection', (reason) => {
console.error('[UNHANDLED REJECTION]', reason);
});
// ── Crash diagnostics ───────────────────────────────────────────────────
// Translates Electron's terse exit codes/reasons into something a human or
// support engineer can act on. Used by render-process-gone and child-process-gone.
const CRASH_REASON_MAP = {
'clean-exit': 'Process exited cleanly',
'abnormal-exit': 'Process exited abnormally',
'killed': 'Process was killed (SIGTERM/SIGKILL — usually deliberate)',
'crashed': 'Process crashed (segfault, JS uncaught exception, etc.)',
'oom': 'Process ran out of memory',
'launch-failed': 'Process failed to launch',
'integrity-failure': 'Code signing integrity check failed'
};
const CRASH_EXIT_CODE_MAP = {
0: 'Clean exit',
9: 'SIGKILL (force-killed by OS or `kill -9`)',
11: 'SIGSEGV (segmentation fault)',
15: 'SIGTERM (deliberately stopped, e.g. `pkill`)',
'-1': 'Unknown'
};
function describeCrash(processType, details) {
const reasonText = CRASH_REASON_MAP[details.reason] || details.reason || 'unknown';
const exitText = CRASH_EXIT_CODE_MAP[details.exitCode] != null
? CRASH_EXIT_CODE_MAP[details.exitCode]
: `exit code ${details.exitCode}`;
return `${processType} process: ${reasonText} (${exitText})`;
}
function handleProcessCrash(processType, details, win) {
const summary = describeCrash(processType, details);
console.error(`[${processType.toUpperCase()} CRASHED] reason=${details.reason} exitCode=${details.exitCode}`);
// Build full diagnostic text the user can copy to a bug report
const logPath = log.transports.file.getFile().path;
const dumpDir = path.join(app.getPath('userData'), 'Crashpad', 'completed');
const diagnosticText = [
'OpenMarkdownReader crash report',
'─────────────────────────────',
`Time: ${new Date().toISOString()}`,
`Process: ${processType}`,
`Reason: ${details.reason}`,
`Exit code: ${details.exitCode}`,
`Description: ${summary}`,
'',
`App version: ${buildInfo.version} (build ${buildInfo.buildNumber}, ${buildInfo.gitHash})`,
`Platform: ${process.platform} ${os.release()}`,
`Electron: ${process.versions.electron}`,
`Node: ${process.versions.node}`,
`Arch: ${process.arch}`,
'',
`Log file: ${logPath}`,
`Crash dumps: ${dumpDir}`,
].join('\n');
// Don't show a dialog for renderer 'killed' on app quit — that's expected
// (the main process intentionally tears down renderers during shutdown).
if (details.reason === 'killed' && app.isQuittingForReal) {
return;
}
// Async dialog so we don't block the main thread; offers actionable buttons.
const dialogOptions = {
type: 'error',
title: 'OpenMarkdownReader crashed',
message: 'OpenMarkdownReader crashed',
detail: `${summary}\n\nThe app may continue to work, but you should restart it. If this keeps happening, share the diagnostic info with the developer.`,
buttons: ['Reload', 'Copy Diagnostics', 'Show Logs in Finder', 'Close'],
defaultId: 0,
cancelId: 3,
noLink: true
};
const targetWin = (win && !win.isDestroyed()) ? win : null;
const dialogPromise = targetWin
? dialog.showMessageBox(targetWin, dialogOptions)
: dialog.showMessageBox(dialogOptions);
dialogPromise.then(({ response }) => {
if (response === 0 && targetWin && !targetWin.isDestroyed()) {
// Reload — try to recover the renderer
try {
targetWin.webContents.reload();
} catch (err) {
console.error('Failed to reload after crash:', err);
}
} else if (response === 1) {
clipboard.writeText(diagnosticText);
} else if (response === 2) {
shell.showItemInFolder(logPath);
}
}).catch(err => {
console.error('Crash dialog error:', err);
});
}
// Catch GPU/utility/plugin process crashes (separate from renderer crashes).
// Without this, GPU process crashes silently fall through to a black window
// or graphics glitches with no logging.
app.on('child-process-gone', (event, details) => {
console.error(`[CHILD PROCESS GONE] type=${details.type} name=${details.name || 'n/a'} reason=${details.reason} exitCode=${details.exitCode}`);
// Only show dialog for serious crashes — clean exit and 'killed' during shutdown are normal.
if (details.reason === 'clean-exit' || details.reason === 'killed') return;
handleProcessCrash(details.type || 'child', details, null);
});
const { getFileIdentity, detectFileMove } = require('./file-watch-utils');
const {
findNameCollisionInDirectory
} = require('./file-creation-utils');
const {
moveFileToDirectory
} = require('./file-move-utils');
// Load build info (generated by scripts/generate-build-info.js)
let buildInfo = { version: '0.0.0', buildNumber: 0, gitHash: 'dev', buildDate: '' };
try {
const buildInfoPath = path.join(__dirname, 'build-info.json');
if (fs.existsSync(buildInfoPath)) {
buildInfo = JSON.parse(fs.readFileSync(buildInfoPath, 'utf8'));
}
} catch {
// Fall back to package.json version
try {
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
buildInfo.version = pkg.version;
} catch {}
}
const devTag = buildInfo.isDev ? ' [DEV]' : (buildInfo.channel ? ` [${buildInfo.channel}]` : '');
log.info(`OpenMarkdownReader starting — v${buildInfo.version} (build ${buildInfo.buildNumber}, ${buildInfo.gitHash})${devTag}`);
log.info(`Platform: ${process.platform} ${os.release()} | Electron: ${process.versions.electron} | Node: ${process.versions.node} | Arch: ${process.arch}`);
// Detect if running as Mac App Store (sandboxed) build
// MAS apps have a receipt file in the app bundle
function isMASBuild() {
if (process.platform !== 'darwin') return false;
try {
const receiptPath = path.join(app.getAppPath(), '..', '_MASReceipt', 'receipt');
return fs.existsSync(receiptPath);
} catch {
return false;
}
}
const windows = new Set();
let isReadOnlyMode = true; // Default to read-only
let watchFileMode = false; // Watch for external file changes
const fileWatchers = new Map(); // Track active file watchers
const fileWatchDebounceTimers = new Map(); // Track debounce timers per watcher
const fileWatchStates = new Map(); // Track watcher metadata (path/inode/search root)
// Track files received via open-file before app is ready (Finder double-click / Open With)
const pendingOpenFiles = [];
// Argument Parsing
function parseArgs(argv) {
const flags = {
watch: false,
edit: false,
theme: null,
noSession: false,
scratch: false,
ref: false,
monospace: null,
newFile: false,
files: []
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--watch' || arg === '-w') {
flags.watch = true;
} else if (arg === '--edit' || arg === '-e') {
flags.edit = true;
} else if (arg === '--scratch' || arg === '-s') {
flags.scratch = true;
} else if (arg === '--ref' || arg === '-r') {
flags.ref = true;
} else if (arg === '--new' || arg === '-n') {
flags.newFile = true;
} else if (arg === '--no-session') {
flags.noSession = true;
} else if (arg === '--monospace') {
flags.monospace = true;
} else if (arg === '--no-monospace') {
flags.monospace = false;
} else if (arg === '--theme' || arg === '-t') {
const next = argv[i + 1];
if (next && ['light', 'dark', 'system'].includes(next)) {
flags.theme = next;
i++;
}
} else if (arg === '--debug') {
flags.debug = true;
} else if (arg === '.') {
flags.files.push(process.cwd());
} else if (!arg.startsWith('-')) {
if (arg.includes('node_modules') ||
arg.includes('OpenMarkdownReader.app') ||
arg === 'main.js' ||
arg === '.') continue;
if (path.isAbsolute(arg) || arg.includes('/') || arg.includes('\\') || arg.endsWith('.md')) {
flags.files.push(arg);
}
}
}
return flags;
}
// Single Instance Lock
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', (event, argv, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
const win = getFocusedWindow();
if (win) {
if (win.isMinimized()) win.restore();
win.focus();
const args = parseArgs(argv);
// Apply flags to session
if (args.watch) {
watchFileMode = true;
windows.forEach(w => w.webContents.send('set-watch-mode', true));
}
if (args.theme) {
setTheme(args.theme);
}
if (args.monospace !== null) {
config.editorMonospace = args.monospace;
saveConfig();
broadcastSetting('editor-monospace', args.monospace);
}
// Open daily notes if requested
if (args.scratch) {
createDailyNote(win, 'scratch');
}
if (args.ref) {
createDailyNote(win, 'ref');
}
// Create new file if requested
if (args.newFile) {
win.webContents.send('new-file');
}
// Open any files passed
args.files.forEach(file => {
const fullPath = path.isAbsolute(file) ? file : path.join(workingDirectory, file);
openPathInWindow(win, fullPath, { forceEdit: args.edit });
});
setupMenu(); // Update menu checkmarks
}
});
}
// Configuration Management
const configPath = path.join(app.getPath('userData'), 'config.json');
let config = {
theme: 'system', // 'system', 'light', 'dark'
recentFiles: [], // Array of { path, type: 'file' | 'folder', timestamp }
maxRecentFiles: 10,
contentWidth: 900,
contentPadding: 20,
editorMonospace: false, // Use monospace font in editor
compactTables: false, // Compact table cells (nowrap + horizontal scroll)
restoreSession: true, // Whether to restore previous session on launch
session: null, // Saved session state: { windows: [{ tabs: [{filePath, fileName}], directory: dirPath }] }
cliCommandPath: null,
watchMode: false, // Watch for external file changes
dailyNotesFolder: null, // Path to folder for daily notes
dailyNotesFormat: 'YYYY-MM-DD', // Date format for filenames
dailyNotesTemplate: '', // Optional template for new daily notes
askedAboutDefaultApp: false // Whether we've asked to set as default
};
const CLI_COMMAND_NAMES = ['omr', 'openmd'];
const APP_BUNDLE_ID = 'com.jacobcole.openmarkdownreader';
// The CLI script is a thin wrapper that calls the main script inside the app bundle
// This way, CLI updates automatically when the app updates
function getCliScriptContents(commandName) {
return `#!/usr/bin/env bash
# OpenMarkdownReader CLI wrapper
# This script delegates to the CLI inside the app bundle for auto-updates
APP_PATH="/Applications/OpenMarkdownReader.app"
BUNDLED_CLI="$APP_PATH/Contents/Resources/cli.sh"
if [[ -x "$BUNDLED_CLI" ]]; then
exec "$BUNDLED_CLI" "$@"
else
# Fallback if app not in /Applications or cli.sh missing
APP_BUNDLE_ID="${APP_BUNDLE_ID}"
if [[ $# -eq 0 ]]; then
open -b "$APP_BUNDLE_ID" 2>/dev/null || open -a "OpenMarkdownReader"
else
open -b "$APP_BUNDLE_ID" --args "$@" 2>/dev/null || open -a "OpenMarkdownReader" --args "$@"
fi
fi
`;
}
// The actual CLI implementation that lives inside the app bundle
function getCliImplementation() {
return `#!/usr/bin/env bash
set -euo pipefail
APP_BUNDLE_ID="${APP_BUNDLE_ID}"
APP_NAME="OpenMarkdownReader"
APP_PATH="/Applications/OpenMarkdownReader.app"
VERSION="1.0.0"
# Get version from app's package.json if available
if [[ -f "$APP_PATH/Contents/Resources/app/package.json" ]]; then
DETECTED_VERSION=$(grep '"version"' "$APP_PATH/Contents/Resources/app/package.json" 2>/dev/null | head -1 | sed 's/.*"version": *"\\([^"]*\\)".*/\\1/' || echo "$VERSION")
VERSION="\${DETECTED_VERSION:-$VERSION}"
fi
if [[ "\${1:-}" == "--help" || "\${1:-}" == "-h" ]]; then
echo "OpenMarkdownReader v$VERSION - A beautiful Markdown reader and editor"
echo ""
echo "Usage: omr [options] [path ...]"
echo ""
echo "Options:"
echo " -e, --edit Open file(s) in edit mode"
echo " -w, --watch Watch for external file changes"
echo " -s, --scratch Open today's scratch note"
echo " -r, --ref Open today's reference note"
echo " -t, --theme <mode> Set theme (light, dark, system)"
echo " --monospace Use monospace font in editor"
echo " --no-monospace Use proportional font in editor"
echo " --no-session Don't restore previous session"
echo " -n, --new Create a new untitled file"
echo " -v, --version Show version"
echo " -h, --help Show this help message"
echo ""
echo "Examples:"
echo " omr Open app (restores last session)"
echo " omr . Open current directory in sidebar"
echo " omr README.md Open a specific file"
echo " omr -e README.md Open file in edit mode"
echo " omr -w README.md Open and watch for changes"
echo " omr -s Open today's scratch note"
echo " omr --theme dark Open with dark theme"
echo " omr -n Create new untitled file"
exit 0
fi
if [[ "\${1:-}" == "--version" || "\${1:-}" == "-v" ]]; then
echo "OpenMarkdownReader $VERSION"
exit 0
fi
if [[ $# -eq 0 ]]; then
open -b "$APP_BUNDLE_ID" 2>/dev/null || open -a "$APP_NAME"
exit 0
fi
# Use --args to pass flags to the Electron app
open -b "$APP_BUNDLE_ID" --args "$@" 2>/dev/null || open -a "$APP_NAME" --args "$@"
`;
}
function getCliInstallCandidates() {
const homeDir = os.homedir();
return [
'/opt/homebrew/bin',
'/usr/local/bin',
path.join(homeDir, '.local', 'bin'),
path.join(homeDir, 'bin')
];
}
function isDirInPath(dirPath) {
const envPath = process.env.PATH || '';
return envPath.split(':').includes(dirPath);
}
function ensureWritableDir(dirPath, { create } = { create: false }) {
if (!fs.existsSync(dirPath)) {
if (!create) return false;
try {
fs.mkdirSync(dirPath, { recursive: true });
} catch {
return false;
}
}
try {
fs.accessSync(dirPath, fs.constants.W_OK);
return true;
} catch {
return false;
}
}
async function installCliCommand() {
if (process.platform !== 'darwin') {
dialog.showMessageBox({
type: 'info',
message: 'Terminal command install is currently macOS-only.'
});
return;
}
const preferredCandidates = getCliInstallCandidates();
const candidatesInPath = preferredCandidates.filter(isDirInPath);
const orderedCandidates = [...candidatesInPath, ...preferredCandidates.filter(d => !candidatesInPath.includes(d))];
let installedPaths = [];
let lastError = null;
// Find a suitable directory for all commands
let selectedDir = null;
for (const dir of orderedCandidates) {
const isUserDir = dir.startsWith(os.homedir());
const ok = ensureWritableDir(dir, { create: isUserDir });
if (ok) {
selectedDir = dir;
break;
}
}
if (!selectedDir) {
dialog.showErrorBox('Install Failed', 'No writable install location found in your PATH.');
return;
}
for (const commandName of CLI_COMMAND_NAMES) {
const target = path.join(selectedDir, commandName);
const script = getCliScriptContents(commandName);
try {
if (fs.existsSync(target)) {
const choice = dialog.showMessageBoxSync({
type: 'question',
buttons: ['Replace', 'Cancel'],
defaultId: 0,
cancelId: 1,
message: `A '${commandName}' command already exists at:\n${target}\n\nReplace it?`
});
if (choice !== 0) continue;
}
fs.writeFileSync(target, script, { encoding: 'utf-8' });
fs.chmodSync(target, 0o755);
installedPaths.push(target);
} catch (err) {
lastError = err;
}
}
if (installedPaths.length === 0) {
dialog.showErrorBox(
'Install Failed',
`Could not install terminal commands.\n\n${lastError ? String(lastError.message || lastError) : ''}`
);
return;
}
config.cliCommandPath = installedPaths[0]; // Store one for reference
saveConfig();
setupMenu();
const inPath = isDirInPath(selectedDir);
const nextSteps = inPath
? `Try it in Terminal:\n ${CLI_COMMAND_NAMES[1]} README.md`
: `Add this to your shell PATH (zsh):\n echo 'export PATH=\"${selectedDir}:$PATH\"' >> ~/.zshrc\n source ~/.zshrc\n\nThen try:\n ${CLI_COMMAND_NAMES[1]} README.md`;
dialog.showMessageBox({
type: 'info',
message: `Installed terminal commands`,
detail: `Commands installed to: ${selectedDir}\n\nCommands: ${CLI_COMMAND_NAMES.join(', ')}\n\n${nextSteps}`
});
}
async function uninstallCliCommand() {
if (process.platform !== 'darwin') {
dialog.showMessageBox({
type: 'info',
message: 'Terminal command uninstall is currently macOS-only.'
});
return;
}
const existingPaths = [];
const candidates = getCliInstallCandidates();
for (const dir of candidates) {
for (const name of CLI_COMMAND_NAMES) {
const p = path.join(dir, name);
if (fs.existsSync(p)) existingPaths.push(p);
}
}
if (existingPaths.length === 0) {
dialog.showMessageBox({
type: 'info',
message: `No terminal commands found to uninstall.`
});
return;
}
const choice = dialog.showMessageBoxSync({
type: 'question',
buttons: ['Uninstall', 'Cancel'],
defaultId: 0,
cancelId: 1,
message: `Found terminal commands at:\n${existingPaths.join('\n')}\n\nUninstall them?`
});
if (choice === 0) {
let count = 0;
for (const p of existingPaths) {
try {
fs.unlinkSync(p);
count++;
} catch (err) {
console.error(`Failed to uninstall ${p}:`, err);
}
}
config.cliCommandPath = null;
saveConfig();
setupMenu();
dialog.showMessageBox({
type: 'info',
message: `Uninstalled ${count} command(s).`
});
}
}
function openPathInWindow(win, targetPath, options = {}) {
try {
const stats = fs.statSync(targetPath);
if (stats.isDirectory()) {
const files = getDirectoryContents(targetPath);
win.webContents.send('directory-loaded', { dirPath: targetPath, files });
addToRecent(targetPath, 'folder');
return;
}
loadMarkdownFile(win, targetPath, options);
} catch (err) {
dialog.showErrorBox('Error', `Could not open path: ${err.message}`);
}
}
function loadConfig() {
try {
if (fs.existsSync(configPath)) {
const data = fs.readFileSync(configPath, 'utf-8');
config = { ...config, ...JSON.parse(data) };
}
} catch (err) {
console.error('Error loading config:', err);
}
}
function saveConfig() {
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
} catch (err) {
console.error('Error saving config:', err);
}
}
// Review unsaved tabs one by one (standard macOS pattern)
// Shows a dialog for each unsaved document: Save / Don't Save / Cancel
// Returns 'close' if all documents were handled, 'cancel' if user cancelled
async function reviewUnsavedTabsOneByOne(win, unsavedTabs) {
for (let i = 0; i < unsavedTabs.length; i++) {
const tab = unsavedTabs[i];
if (win.isDestroyed()) return 'cancel';
const remaining = unsavedTabs.length - i;
const message = `Do you want to save the changes you made to "${tab.fileName}"?`;
const detail = remaining > 1
? `${remaining} documents with unsaved changes. Your changes will be lost if you don't save them.`
: 'Your changes will be lost if you don\'t save them.';
const choice = dialog.showMessageBoxSync(win, {
type: 'warning',
buttons: ['Save', "Don't Save", 'Cancel'],
defaultId: 0,
cancelId: 2,
message: message,
detail: detail
});
if (choice === 0) {
// Save - tell renderer to save this specific tab
const saved = await saveTabInRenderer(win, tab);
if (!saved) {
// Save was cancelled (e.g., user cancelled Save As dialog)
return 'cancel';
}
} else if (choice === 1) {
// Don't Save - continue to next tab
continue;
} else {
// Cancel - abort the close operation
return 'cancel';
}
}
return 'close';
}
// Helper to save a specific tab via IPC
function saveTabInRenderer(win, tabInfo) {
return new Promise((resolve) => {
if (win.isDestroyed()) {
resolve(false);
return;
}
let timeoutId = null;
const responseHandler = (event, data) => {
if (event.sender !== win.webContents) return;
if (timeoutId) clearTimeout(timeoutId);
ipcMain.removeListener('review-decision', responseHandler);
if (data.success) {
resolve(true);
} else if (data.cancelled) {
resolve(false); // User cancelled Save As dialog
} else {
resolve(true); // Error but continue anyway
}
};
ipcMain.on('review-decision', responseHandler);
win.webContents.send('review-unsaved-tab', tabInfo);
// Timeout in case renderer doesn't respond
timeoutId = setTimeout(() => {
ipcMain.removeListener('review-decision', responseHandler);
resolve(true); // Assume saved on timeout
}, 30000); // 30 second timeout for save operations
});
}
// Add a file/folder to recent list
function addToRecent(filePath, type = 'file') {
// Remove if already exists
config.recentFiles = config.recentFiles.filter(item => item.path !== filePath);
// Add to beginning
config.recentFiles.unshift({
path: filePath,
type: type,
timestamp: Date.now()
});
// Trim to max
if (config.recentFiles.length > config.maxRecentFiles) {
config.recentFiles = config.recentFiles.slice(0, config.maxRecentFiles);
}
saveConfig();
setupMenu(); // Rebuild menu to update recent files list
}
// Clear recent files
function clearRecentFiles() {
config.recentFiles = [];
saveConfig();
setupMenu();
}
// Load config on startup
loadConfig();
watchFileMode = config.watchMode || false;
function cleanupFileWatchersForWindow(winId) {
const prefix = `${winId}:`;
for (const [watchKey, watcher] of fileWatchers) {
if (!watchKey.startsWith(prefix)) continue;
try {
watcher.close();
} catch {}
fileWatchers.delete(watchKey);
const timer = fileWatchDebounceTimers.get(watchKey);
if (timer) clearTimeout(timer);
fileWatchDebounceTimers.delete(watchKey);
fileWatchStates.delete(watchKey);
}
}
function createWindow(filePath = null) {
const initialPath = filePath;
const win = new BrowserWindow({
width: 900,
height: 700,
minWidth: 400,
minHeight: 300,
titleBarStyle: 'hiddenInset',
// backgroundColor: '#ffffff', // Removed to respect system theme
icon: path.join(__dirname, 'build', 'icon.png'),
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // Allow preload to use Node modules like 'path'
preload: path.join(__dirname, 'preload.js')
}
});
const winId = win.id;
windows.add(win);
agentServer.emitEvent('window-created', { windowId: winId });
win.on('closed', () => {
cleanupFileWatchersForWindow(winId);
windows.delete(win);
agentServer.emitEvent('window-closed', { windowId: winId });
});
// Handle close with unsaved changes check
let forceClose = false;
win.on('close', async (e) => {
if (forceClose) return;
if (win.isDestroyed()) return;
e.preventDefault();
// Ask renderer if there are unsaved changes
return new Promise((resolve) => {
let responded = false;
let timeoutId = null;
const responseHandler = async (event, data) => {
if (win.isDestroyed()) {
ipcMain.removeListener('unsaved-state', responseHandler);
resolve();
return;
}
if (event.sender !== win.webContents) return;
responded = true;
if (timeoutId) clearTimeout(timeoutId);
ipcMain.removeListener('unsaved-state', responseHandler);
// Handle both boolean (legacy) and object responses
let hasUnsaved = false;
let unsavedTabs = [];
let sessionData = null;
if (typeof data === 'boolean') {
hasUnsaved = data;
} else if (typeof data === 'object' && data !== null) {
hasUnsaved = data.hasUnsaved;
unsavedTabs = data.unsavedTabs || [];
sessionData = data.sessionData;
}
// Save session state if available (keep schema consistent with restore)
if (config.restoreSession && sessionData) {
config.session = { windows: [sessionData] };
saveConfig();
}
if (hasUnsaved && unsavedTabs.length > 1) {
// Multiple unsaved documents - show summary dialog first (standard macOS pattern)
const fileList = unsavedTabs.map(t => t.fileName).join(', ');
const choice = dialog.showMessageBoxSync(win, {
type: 'warning',
buttons: ['Save All', 'Review Changes...', 'Discard Changes', 'Cancel'],
defaultId: 0,
cancelId: 3,
message: `You have ${unsavedTabs.length} documents with unsaved changes.`,
detail: `${fileList}\n\nYour changes will be lost if you discard them.`
});
if (choice === 0) {
// Save All - save all and close
if (!win.isDestroyed()) {
win.webContents.send('save-all');
setTimeout(() => {
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}, 1000);
}
} else if (choice === 1) {
// Review Changes - go through one by one
const result = await reviewUnsavedTabsOneByOne(win, unsavedTabs);
if (result === 'close') {
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}
} else if (choice === 2) {
// Discard Changes - close without saving any
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}
// Cancel (choice === 3) - do nothing, window stays open
} else if (hasUnsaved && unsavedTabs.length === 1) {
// Single unsaved document - show simple Save/Don't Save/Cancel
const tab = unsavedTabs[0];
const choice = dialog.showMessageBoxSync(win, {
type: 'warning',
buttons: ['Save', "Don't Save", 'Cancel'],
defaultId: 0,
cancelId: 2,
message: `Do you want to save the changes you made to "${tab.fileName}"?`,
detail: 'Your changes will be lost if you don\'t save them.'
});
if (choice === 0) {
// Save
const saved = await saveTabInRenderer(win, tab);
if (saved) {
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}
} else if (choice === 1) {
// Don't Save
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}
// Cancel - do nothing
} else if (hasUnsaved) {
// Legacy path - show the old dialog if we don't have unsavedTabs list
const choice = dialog.showMessageBoxSync(win, {
type: 'warning',
buttons: ['Save All', "Don't Save", 'Cancel'],
defaultId: 0,
cancelId: 2,
message: 'You have unsaved changes.',
detail: 'Do you want to save your changes before closing?'
});
if (choice === 0) {
// Save All - tell renderer to save all tabs, then close
if (!win.isDestroyed()) {
win.webContents.send('save-all');
// Give it a moment to save all
setTimeout(() => {
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}, 1000);
}
} else if (choice === 1) {
// Don't Save - close without saving
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}
// Cancel (choice === 2) - do nothing, window stays open
} else {
forceClose = true;
if (!win.isDestroyed()) {
win.close();
}
}
resolve();
};
ipcMain.on('unsaved-state', responseHandler);
if (!win.isDestroyed()) {
win.webContents.send('check-unsaved');
}
// Timeout in case renderer doesn't respond
timeoutId = setTimeout(() => {
if (responded) return; // Already handled
ipcMain.removeListener('unsaved-state', responseHandler);
forceClose = true;
// Check if window still exists before trying to close
if (!win.isDestroyed()) {
win.close();
}
resolve();
}, 2000);
});
});
win.loadFile('index.html');
// ── White-screen / crash diagnostics ──
win.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error(`[LOAD FAIL] code=${errorCode} desc="${errorDescription}" url=${validatedURL}`);
});
win.webContents.on('render-process-gone', (event, details) => {
handleProcessCrash('renderer', details, win);
});
win.webContents.on('unresponsive', () => {
console.error('[UNRESPONSIVE] Window became unresponsive');
});
win.webContents.on('responsive', () => {
console.log('[RESPONSIVE] Window recovered');
});
win.webContents.on('console-message', (event, level, message, line, sourceId) => {
if (level >= 2) { // errors only
console.error(`[Renderer ERROR] ${message} (${sourceId}:${line})`);
}
});
// Native text/edit context menu parity (Copy/Paste/Look Up/Speech, etc.).
win.webContents.on('context-menu', (event, params) => {
const template = [];
const hasSelection = Boolean(params.selectionText && params.selectionText.trim());
const canPaste = Boolean(params.editFlags && params.editFlags.canPaste);
if (params.isEditable) {
template.push(
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste', enabled: canPaste },
{ role: 'selectAll' }
);
} else if (hasSelection) {
template.push({ role: 'copy' });
}
if (hasSelection && process.platform === 'darwin') {
if (template.length > 0) template.push({ type: 'separator' });
template.push(
{ role: 'lookUpSelection' },
{ role: 'startSpeaking' },
{ role: 'stopSpeaking' }
);
}
if (template.length === 0) return;
const menu = Menu.buildFromTemplate(template);
menu.popup({ window: win });
});