Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
944 lines (866 loc) · 34.6 KB
/
Copy pathmain.js
File metadata and controls
944 lines (866 loc) · 34.6 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
// NEO — main process
// Owns the window and all file-system access. The renderer talks to this
// through the IPC handlers below (see preload.js for the exposed API).
const { app, BrowserWindow, ipcMain, dialog, Menu, MenuItem } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
// macOS Chromium's "smart delete" also removes whitespace around a deleted
// selection, and that pass can duplicate characters. Deletes stay literal.
app.commandLine.appendSwitch('blink-settings', 'smartInsertDeleteEnabled=false');
// ---------------------------------------------------------------------------
// Library location: a folder of plain files the user can inspect, sync, back up.
// ---------------------------------------------------------------------------
// Resolved properly at startup via app.getPath('documents') — this default
// covers any early access and non-redirected setups.
let LIBRARY_DIR = path.join(os.homedir(), 'Documents', 'NEO Library');
let LIBRARY_FILE = path.join(LIBRARY_DIR, 'library.json');
function ensureLibrary() {
if (!fs.existsSync(LIBRARY_DIR)) fs.mkdirSync(LIBRARY_DIR, { recursive: true });
if (!fs.existsSync(LIBRARY_FILE)) {
const seed = {
authorName: '',
penNames: [],
firstRunDone: false,
pageTheme: 'night',
shelves: [{ id: 'shelf-1', name: 'Works in Progress', bookIds: [] }]
};
fs.writeFileSync(LIBRARY_FILE, JSON.stringify(seed, null, 2));
}
}
function bookDir(bookId) {
return path.join(LIBRARY_DIR, bookId);
}
// A human-readable map of the library, regenerated on every change:
// which folder is which book, and what shelf it lives on. Sorts to the
// top of the folder so browsing writers can always find their way.
function writeCatalog() {
try {
const lib = readJSON(LIBRARY_FILE, { shelves: [] });
const onShelf = {};
for (const s of lib.shelves || []) {
for (const id of s.bookIds) onShelf[id] = s.name;
}
const lines = [];
for (const d of fs.readdirSync(LIBRARY_DIR)) {
if (!d.startsWith('book-')) continue;
try {
const m = JSON.parse(fs.readFileSync(path.join(LIBRARY_DIR, d, 'book.json'), 'utf8'));
lines.push(`${m.title || 'Untitled'} — ${d} — shelf: ${onShelf[m.id] || '(none — removed from shelves)'}`);
} catch { /* not a valid book folder */ }
}
lines.sort((a, b) => a.localeCompare(b));
fs.writeFileSync(path.join(LIBRARY_DIR, '_catalog.txt'),
'NEO LIBRARY CATALOG — which folder is which book\n' +
'(regenerated automatically; edits here do nothing)\n\n' +
lines.join('\n') + '\n');
} catch (err) {
logError('catalog', err);
}
}
function readJSON(file, fallback) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'));
} catch {
return fallback;
}
}
function writeJSON(file, data) {
const tmp = file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, file); // atomic-ish: never leave a half-written file
}
// ---------------------------------------------------------------------------
// IPC — the renderer's whole view of the disk
// ---------------------------------------------------------------------------
ipcMain.handle('library:read', () => {
ensureLibrary();
return readJSON(LIBRARY_FILE, null);
});
ipcMain.handle('library:write', (_e, data) => {
ensureLibrary();
writeJSON(LIBRARY_FILE, data);
writeCatalog();
return true;
});
// A book is a folder: book.json + chapters/*.html + notes.html + outline.html + darlings.json
ipcMain.handle('book:create', (_e, meta) => {
ensureLibrary();
// folders carry a slug of the title when it's known at creation (imports),
// so the library reads like a bookshelf in Finder too
const slug = String(meta.title || '').toLowerCase()
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 30);
const id = 'book-' + (slug ? slug + '-' : '') +
Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7);
const dir = bookDir(id);
fs.mkdirSync(path.join(dir, 'chapters'), { recursive: true });
const book = {
id,
title: meta.title || 'Untitled',
subtitle: '',
series: '',
author: meta.author || 'Anonymous',
wordGoal: 0,
created: new Date().toISOString(),
modified: new Date().toISOString(),
chapterOrder: [],
tabNames: { notes: 'Notes', outline: 'Outline' }
};
writeJSON(path.join(dir, 'book.json'), book);
fs.writeFileSync(path.join(dir, 'notes.html'), '');
fs.writeFileSync(path.join(dir, 'outline.html'), '');
writeJSON(path.join(dir, 'darlings.json'), []);
writeJSON(path.join(dir, 'stickies.json'), []);
return book;
});
ipcMain.handle('book:readMeta', (_e, bookId) => {
return readJSON(path.join(bookDir(bookId), 'book.json'), null);
});
ipcMain.handle('book:writeMeta', (_e, bookId, meta) => {
meta.modified = new Date().toISOString();
writeJSON(path.join(bookDir(bookId), 'book.json'), meta);
writeCatalog();
return true;
});
ipcMain.handle('chapter:read', (_e, bookId, chapterId) => {
const file = path.join(bookDir(bookId), 'chapters', chapterId + '.html');
try {
return fs.readFileSync(file, 'utf8');
} catch {
return '';
}
});
ipcMain.handle('chapter:write', (_e, bookId, chapterId, html) => {
const dir = path.join(bookDir(bookId), 'chapters');
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, chapterId + '.html'), html);
return true;
});
ipcMain.handle('chapter:delete', (_e, bookId, chapterId) => {
const file = path.join(bookDir(bookId), 'chapters', chapterId + '.html');
if (fs.existsSync(file)) fs.unlinkSync(file);
return true;
});
ipcMain.handle('aux:read', (_e, bookId, name) => {
// name: 'notes' | 'outline'
const file = path.join(bookDir(bookId), name + '.html');
try {
return fs.readFileSync(file, 'utf8');
} catch {
return '';
}
});
ipcMain.handle('aux:write', (_e, bookId, name, html) => {
fs.writeFileSync(path.join(bookDir(bookId), name + '.html'), html);
return true;
});
ipcMain.handle('json:read', (_e, bookId, name, fallback) => {
return readJSON(path.join(bookDir(bookId), name + '.json'), fallback);
});
ipcMain.handle('json:write', (_e, bookId, name, data) => {
writeJSON(path.join(bookDir(bookId), name + '.json'), data);
return true;
});
ipcMain.handle('book:delete', async (_e, bookId, title) => {
const win = BrowserWindow.getFocusedWindow();
const { response } = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Cancel', process.platform === 'win32' ? 'Move to Recycle Bin' : 'Move to Trash'],
defaultId: 0,
cancelId: 0,
message: `Move “${title}” to the ${process.platform === 'win32' ? 'Recycle Bin' : 'Trash'}?`,
detail: 'The book folder goes to your system trash, so you can recover it.'
});
if (response === 1) {
const { shell } = require('electron');
try {
await shell.trashItem(bookDir(bookId));
return true;
} catch (err) {
// Some filesystems have no Trash (network mounts, odd drives).
// Words are never lost: leave the book alone and show the writer where it lives.
logError('trash', err);
shell.showItemInFolder(bookDir(bookId));
dialog.showMessageBox(win, {
message: 'NEO couldn’t move that folder to the Trash.',
detail: 'The book is untouched. Its folder is highlighted so you can deal with it yourself.'
});
return false;
}
}
return false;
});
// ---------------------------------------------------------------------------
// Cover art: images live inside the book's folder, so covers travel with
// the library. Timestamped filenames sidestep every caching gremlin.
// ---------------------------------------------------------------------------
const COVER_EXTS = ['png', 'jpg', 'jpeg', 'webp'];
ipcMain.handle('library:path', () => LIBRARY_DIR);
ipcMain.handle('cover:pick', async () => {
const win = BrowserWindow.getFocusedWindow();
const { canceled, filePaths } = await dialog.showOpenDialog(win, {
title: 'Choose cover art',
properties: ['openFile'],
filters: [{ name: 'Images', extensions: COVER_EXTS }]
});
return canceled || !filePaths.length ? null : filePaths[0];
});
function clearCovers(dir) {
for (const f of fs.readdirSync(dir)) {
if (/^cover-\d+\./.test(f)) fs.unlinkSync(path.join(dir, f));
}
}
ipcMain.handle('cover:set', (_e, bookId, srcPath) => {
const ext = path.extname(srcPath).toLowerCase().replace('.', '');
if (!COVER_EXTS.includes(ext)) return null;
const dir = bookDir(bookId);
if (!fs.existsSync(dir)) return null;
clearCovers(dir);
const fname = 'cover-' + Date.now() + '.' + (ext === 'jpeg' ? 'jpg' : ext);
fs.copyFileSync(srcPath, path.join(dir, fname));
return fname;
});
ipcMain.handle('cover:remove', (_e, bookId) => {
const dir = bookDir(bookId);
if (fs.existsSync(dir)) clearCovers(dir);
return true;
});
ipcMain.handle('cover:read', (_e, bookId, fname) => {
try {
if (!/^cover-\d+\.(png|jpg|webp)$/.test(fname)) return null;
const buf = fs.readFileSync(path.join(bookDir(bookId), fname));
const ext = path.extname(fname).slice(1);
const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg';
return { base64: buf.toString('base64'), mime, ext };
} catch {
return null;
}
});
// ---------------------------------------------------------------------------
// Fullscreen
// ---------------------------------------------------------------------------
// ⌘Enter / Ctrl+Enter toggles fullscreen
ipcMain.handle('fullscreen:toggle', (e) => {
const win = BrowserWindow.fromWebContents(e.sender);
if (win) win.setFullScreen(!win.isFullScreen());
return true;
});
// Regular fullscreen: Esc walks you out like any civilized app
ipcMain.handle('fullscreen:escape', (e) => {
const win = BrowserWindow.fromWebContents(e.sender);
if (win && win.isFullScreen()) {
win.setFullScreen(false);
return true;
}
return false;
});
// ---------------------------------------------------------------------------
// Export + email
// ---------------------------------------------------------------------------
async function renderPDF(html) {
const pdfWin = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
// Letter is a North American habit; most of the world prints A4.
const letterCountries = ['US', 'CA', 'MX', 'PH'];
try {
await pdfWin.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(html));
return await pdfWin.webContents.printToPDF({
pageSize: letterCountries.includes(app.getLocaleCountryCode()) ? 'Letter' : 'A4',
margins: { top: 1, bottom: 1, left: 1, right: 1 },
printBackground: false
});
} finally {
pdfWin.destroy();
}
}
// zipEntries: [{path, content, base64?, store?}] — order matters (EPUB mimetype first)
async function buildZip(zipEntries) {
const JSZip = require('jszip');
const zip = new JSZip();
for (const e of zipEntries) {
zip.file(e.path, e.base64 ? Buffer.from(e.content, 'base64') : e.content, {
compression: e.store ? 'STORE' : 'DEFLATE'
});
}
return zip.generateAsync({
type: 'nodebuffer',
compression: 'DEFLATE',
mimeType: 'application/epub+zip'
});
}
ipcMain.handle('export:save', async (_e, { format, defaultName, content, zipEntries }) => {
const win = BrowserWindow.getFocusedWindow();
const { canceled, filePath } = await dialog.showSaveDialog(win, {
defaultPath: path.join(os.homedir(), 'Documents', defaultName + '.' + format),
filters: [{ name: format.toUpperCase(), extensions: [format] }]
});
if (canceled || !filePath) return null;
if (zipEntries) {
fs.writeFileSync(filePath, await buildZip(zipEntries));
} else if (format === 'pdf') {
fs.writeFileSync(filePath, await renderPDF(content));
} else {
fs.writeFileSync(filePath, content, 'utf8');
}
return filePath;
});
// Writes a timestamped snapshot to the library's Exports folder, then hands it
// to your email — an outside-the-machine paper trail for provenance.
ipcMain.handle('email:draft', async (_e, { to, subject, body, html, defaultName, method }) => {
const { shell } = require('electron');
const exportsDir = path.join(LIBRARY_DIR, 'Exports');
if (!fs.existsSync(exportsDir)) fs.mkdirSync(exportsDir, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const file = path.join(exportsDir, `${defaultName}-${stamp}.pdf`);
fs.writeFileSync(file, await renderPDF(html));
if (method === 'gmail') {
// Gmail compose in the browser can't take an attachment from outside,
// so open the draft pre-filled and reveal the PDF right next to it to drag in.
const url = 'https://mail.google.com/mail/?view=cm&fs=1'
+ '&to=' + encodeURIComponent(to)
+ '&su=' + encodeURIComponent(subject)
+ '&body=' + encodeURIComponent(body);
await shell.openExternal(url);
shell.showItemInFolder(file);
return { ok: true, method: 'gmail', file };
}
const esc = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
const script = `
tell application "Mail"
set msg to make new outgoing message with properties {subject:"${esc(subject)}", content:"${esc(body)}" & return & return, visible:true}
tell msg to make new to recipient at end of to recipients with properties {address:"${esc(to)}"}
tell msg to make new attachment with properties {file name:(POSIX file "${esc(file)}")} at after the last paragraph of content
activate
end tell`;
return new Promise((resolve) => {
require('child_process').execFile('osascript', ['-e', script], (err) => {
if (err) {
// Mail not available — at least reveal the snapshot we saved
shell.showItemInFolder(file);
resolve({ ok: false, file });
} else {
resolve({ ok: true, method: 'mail', file });
}
});
});
});
// ---------------------------------------------------------------------------
// Import: .docx / .txt / .md → chapters
// ---------------------------------------------------------------------------
const decodeEntities = (s) => s
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, "'");
async function importFile(fp) {
const name = path.basename(fp).replace(/\.[^.]+$/, '');
const ext = path.extname(fp).toLowerCase();
let paras = [];
if (ext === '.docx') {
const JSZip = require('jszip');
const zip = await JSZip.loadAsync(fs.readFileSync(fp));
const docFile = zip.file('word/document.xml');
if (!docFile) throw new Error('Not a valid .docx: ' + fp);
const xml = await docFile.async('string');
paras = [...xml.matchAll(/<w:p[ >][\s\S]*?<\/w:p>/g)].map((m) => {
const p = m[0];
// <w:t> or <w:t attr...> ONLY — never <w:tab>/<w:tabs>, which share
// the same first letters and once leaked raw XML into a manuscript
const text = [...p.matchAll(/<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g)]
.map((t) => decodeEntities(t[1])).join('');
const pageBreak = /<w:br [^>]*w:type="page"/.test(p) || /<w:pageBreakBefore/.test(p);
return { text: text.trim(), pageBreak };
});
} else {
const raw = fs.readFileSync(fp, 'utf8');
paras = raw.split(/\r?\n\s*\r?\n/)
.map((b) => ({ text: b.replace(/\s*\r?\n\s*/g, ' ').trim(), pageBreak: false }))
.filter((p) => p.text);
}
// Chapterize: page breaks and heading lines start new chapters. Headings
// include "Chapter N" styles plus bare chapter numbers — "7", "VII",
// "Seven" — which get stripped so NEO's own numbering doesn't duplicate them.
const SPELLED = /^(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)\.?$/i;
const isNumeralish = (t) => /^\d{1,3}\.?$/.test(t) || /^[IVXLC]{1,7}\.?$/.test(t) || SPELLED.test(t);
// Bare numbers only count as chapter markers when there's a ladder of them —
// a story that merely OPENS with "Seven." keeps its seven.
const numeralMode = paras.filter((p) => p.text && isNumeralish(p.text.trim())).length >= 2;
const isHeading = (t) => t && (
(/^(chapter|prologue|epilogue|part)\b/i.test(t) && t.length < 60) ||
(numeralMode && isNumeralish(t))
);
const isBreak = (t) => /^\s*([*#•~⁂—–-]\s*){1,7}$/.test(t || '');
const chapterize = (usePageBreaks) => {
const chapters = [];
let cur = [];
for (const p of paras) {
const brk = usePageBreaks && p.pageBreak;
if (!p.text && !brk) continue;
if ((brk || isHeading(p.text)) && cur.length) {
chapters.push(cur);
cur = [];
}
if (isHeading(p.text)) continue; // the heading line itself is replaced by NEO's numbering
if (isBreak(p.text)) { cur.push({ scene: true }); continue; }
if (p.text) cur.push({ text: p.text });
}
if (cur.length) chapters.push(cur);
return chapters;
};
const countAllWords = (list) =>
list.reduce((n, ch) => n + ch.reduce((m, p) => m + (p.text ? p.text.trim().split(/\s+/).length : 0), 0), 0);
// First pass trusts page breaks. Some word processors sprinkle page-break
// formatting on every paragraph, exploding a story into confetti — if the
// result is absurd (lots of tiny "chapters"), re-run trusting headings only.
let chapters = chapterize(true);
if (chapters.length > 6 && countAllWords(chapters) / chapters.length < 250) {
chapters = chapterize(false);
}
if (!chapters.length) chapters.push([{ text: '' }]);
// Front matter: a short title line and a "by Author" line belong on the
// title page, not in the body. Detect, harvest, and remove them.
let title = null;
let author = null;
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
const first = chapters[0];
if (first && first.length) {
const t0 = (first[0].text || '').trim();
const t1 = first.length > 1 ? (first[1].text || '').trim() : '';
const titleish = t0 && t0.length < 90 && !/[.!?]$/.test(t0) && (
(norm(t0).length > 3 && norm(name).includes(norm(t0))) ||
/^by\s+\S/i.test(t1) ||
(t0 === t0.toUpperCase() && /[A-Z].*[A-Z]/.test(t0) && t0.length < 60)
);
if (titleish) {
title = t0;
first.shift();
}
const bl = first.length ? (first[0].text || '').trim().match(/^by\s+(.{2,60})$/i) : null;
if (bl) {
author = bl[1].trim();
first.shift();
}
if (!first.length) chapters.shift();
if (!chapters.length) chapters.push([{ text: '' }]);
}
return { name, title, author, chapters };
}
// Same parsing as the picker, but for files dropped from Finder/Explorer
ipcMain.handle('import:files', async (_e, paths) => {
const out = [];
for (const fp of paths || []) {
if (!/\.(docx|txt|md)$/i.test(fp)) continue;
try {
out.push(await importFile(fp));
} catch (err) {
logError('import', err);
out.push({ name: path.basename(fp), error: String(err.message || err) });
}
}
return out;
});
ipcMain.handle('import:pick', async () => {
const win = BrowserWindow.getFocusedWindow();
const { canceled, filePaths } = await dialog.showOpenDialog(win, {
title: 'Bring your manuscripts home',
properties: ['openFile', 'multiSelections'],
filters: [{ name: 'Manuscripts', extensions: ['docx', 'txt', 'md'] }]
});
if (canceled || !filePaths.length) return [];
const out = [];
for (const fp of filePaths) {
try {
out.push(await importFile(fp));
} catch (err) {
logError('import', err);
out.push({ name: path.basename(fp), error: String(err.message || err) });
}
}
return out;
});
// ---------------------------------------------------------------------------
// Robustness: error log, daily backups, single instance
// ---------------------------------------------------------------------------
const ERROR_LOG = () => path.join(LIBRARY_DIR, 'neo-errors.log');
function logError(source, err) {
try {
ensureLibrary();
const line = `[${new Date().toISOString()}] [${source}] ${err && err.stack ? err.stack : String(err)}\n`;
fs.appendFileSync(ERROR_LOG(), line);
} catch { /* never let logging crash the app */ }
}
process.on('uncaughtException', (err) => logError('main', err));
process.on('unhandledRejection', (err) => logError('main-promise', err));
ipcMain.handle('log:error', (_e, msg) => logError('renderer', msg));
// One zip of the whole library per day, keeping the last 14. Cheap insurance.
async function dailyBackup() {
try {
ensureLibrary();
const backupsDir = path.join(LIBRARY_DIR, 'Backups');
if (!fs.existsSync(backupsDir)) fs.mkdirSync(backupsDir, { recursive: true });
const today = new Date().toISOString().slice(0, 10);
const target = path.join(backupsDir, `neo-backup-${today}.zip`);
if (fs.existsSync(target)) return;
const JSZip = require('jszip');
const zip = new JSZip();
const skip = new Set(['Backups', 'Exports']);
const walk = (dir, rel) => {
for (const name of fs.readdirSync(dir)) {
if (rel === '' && skip.has(name)) continue;
const full = path.join(dir, name);
const relPath = rel ? rel + '/' + name : name;
const stat = fs.statSync(full);
if (stat.isDirectory()) walk(full, relPath);
else zip.file(relPath, fs.readFileSync(full));
}
};
walk(LIBRARY_DIR, '');
fs.writeFileSync(target, await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }));
// prune old backups
const backups = fs.readdirSync(backupsDir).filter((f) => f.startsWith('neo-backup-')).sort();
while (backups.length > 14) fs.unlinkSync(path.join(backupsDir, backups.shift()));
} catch (err) {
logError('backup', err);
}
}
// ---------------------------------------------------------------------------
// Window
// ---------------------------------------------------------------------------
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
titleBarStyle: 'hiddenInset',
backgroundColor: '#191919',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
// The engine is available, but every editable element starts with
// spellcheck="false" — NEO never nags. A spellcheck pass is a
// deliberate act (Edit → Spellcheck Pass), not a klaxon.
spellcheck: true
}
});
win.loadFile('index.html');
// NEO does its own spellchecking (see spell:* handlers) — the engine's
// checker proved unreliable at scanning existing text, so it stays off
win.webContents.session.setSpellCheckerEnabled(false);
}
// ---------------------------------------------------------------------------
// Spellcheck: NEO's own dictionary (Hunspell en-US via nspell), identical on
// every platform. The renderer paints the squiggles and asks for suggestions.
// ---------------------------------------------------------------------------
let neoSpell = null;
function initSpell() {
try {
const nspell = require('nspell');
require('dictionary-en-us')((err, dict) => {
if (err) { logError('spell', err); return; }
neoSpell = nspell(dict);
try {
const lib = readJSON(LIBRARY_FILE, {});
for (const w of lib.customWords || []) neoSpell.add(w);
} catch { /* custom words are a nicety */ }
});
} catch (err) {
logError('spell', err);
}
}
ipcMain.handle('spell:check', (_e, words) => {
const out = {};
// dictionary still loading: report everything correct rather than crying wolf
for (const w of words) out[w] = neoSpell ? neoSpell.correct(w) : true;
return out;
});
ipcMain.handle('spell:suggest', (_e, word) => (neoSpell ? neoSpell.suggest(word).slice(0, 6) : []));
ipcMain.handle('spell:learn', (_e, word) => {
if (neoSpell && typeof word === 'string') neoSpell.add(word);
return true;
});
// ---------------------------------------------------------------------------
// Application menu — Help and Format live here, out of the writing room
// ---------------------------------------------------------------------------
function sendToWindow(msg) {
const w = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
if (w) w.webContents.send('menu', msg);
}
function buildMenu() {
const isMac = process.platform === 'darwin';
const bodyFonts = isMac
? ['Georgia', 'Palatino', 'Baskerville', 'Hoefler Text', 'Iowan Old Style']
: ['Georgia', 'Palatino', 'Baskerville', 'Cambria', 'Constantia'];
const template = [
// appMenu exists only on macOS — including it on Windows throws,
// which is exactly what kept NEO from ever opening a window there
...(isMac ? [{ role: 'appMenu' }] : []),
{
label: 'File',
submenu: [
{
label: 'Export',
submenu: [
{ label: 'Plain Text (.txt)', click: () => sendToWindow({ type: 'export', format: 'txt' }) },
{ label: 'Markdown (.md)', click: () => sendToWindow({ type: 'export', format: 'md' }) },
{ label: 'Web Page (.html)', click: () => sendToWindow({ type: 'export', format: 'html' }) },
{ label: 'PDF (.pdf)', click: () => sendToWindow({ type: 'export', format: 'pdf' }) },
{ label: 'Word (.docx)', click: () => sendToWindow({ type: 'export', format: 'docx' }) },
{ label: 'EPUB (.epub)', click: () => sendToWindow({ type: 'export', format: 'epub' }) }
]
},
{ type: 'separator' },
{
label: 'Email Draft to Myself',
accelerator: 'CmdOrCtrl+E',
click: () => sendToWindow({ type: 'emailDraft' })
},
{ label: 'Email Settings…', click: () => sendToWindow({ type: 'emailSettings' }) },
{
label: isMac ? 'Goals & Settings…' : 'Goals && Settings…',
accelerator: 'CmdOrCtrl+,',
click: () => sendToWindow({ type: 'stats' })
},
{ type: 'separator' },
{
label: 'Import Manuscripts…',
accelerator: 'CmdOrCtrl+Shift+I',
click: () => sendToWindow({ type: 'import' })
},
{ type: 'separator' },
...(isMac ? [{ role: 'close' }] : [{ role: 'quit' }])
]
},
{
label: 'Edit',
submenu: [
{ role: 'undo' }, { role: 'redo' },
{ type: 'separator' },
{ role: 'cut' }, { role: 'copy' }, { role: 'paste' },
{ role: 'pasteAndMatchStyle' }, { role: 'selectAll' },
{ type: 'separator' },
{
label: isMac ? 'Find & Replace' : 'Find && Replace',
accelerator: 'CmdOrCtrl+F',
click: () => sendToWindow({ type: 'find' })
},
{
label: 'Spellcheck Pass',
accelerator: 'CmdOrCtrl+;',
click: () => sendToWindow({ type: 'spellcheck' })
}
]
},
{
label: 'Format',
submenu: [
{
label: 'Body Font',
submenu: bodyFonts.map((f) => ({
label: f,
click: () => sendToWindow({ type: 'bodyFont', value: f })
}))
},
{
label: 'Drop Cap Style',
submenu: [
{ label: 'Literary', click: () => sendToWindow({ type: 'dropCap', value: 'literary' }) },
{ label: 'Fantasy', click: () => sendToWindow({ type: 'dropCap', value: 'fantasy' }) },
{ label: 'Sci-Fi', click: () => sendToWindow({ type: 'dropCap', value: 'scifi' }) }
]
},
{
label: 'Align Paragraph',
submenu: [
{ label: 'Left', click: () => sendToWindow({ type: 'align', value: 'left' }) },
{ label: 'Center', click: () => sendToWindow({ type: 'align', value: 'center' }) },
{ label: 'Right', click: () => sendToWindow({ type: 'align', value: 'right' }) },
{ label: 'Justify', click: () => sendToWindow({ type: 'align', value: 'justify' }) }
]
},
{ type: 'separator' },
{ label: 'Larger Text', accelerator: 'CmdOrCtrl+=', click: () => sendToWindow({ type: 'fontSize', value: 1 }) },
{ label: 'Smaller Text', accelerator: 'CmdOrCtrl+-', click: () => sendToWindow({ type: 'fontSize', value: -1 }) },
{ label: 'Reset Text Size', accelerator: 'CmdOrCtrl+0', click: () => sendToWindow({ type: 'fontSize', value: 0 }) },
{ type: 'separator' },
{
label: 'Typewriter Scrolling',
accelerator: 'CmdOrCtrl+Shift+T',
click: () => sendToWindow({ type: 'typewriter' })
}
]
},
{
label: 'View',
submenu: [
{
label: 'Full Screen',
accelerator: 'CmdOrCtrl+Shift+F',
click: () => {
const w = BrowserWindow.getFocusedWindow();
if (w) w.setFullScreen(!w.isFullScreen());
}
},
{ type: 'separator' },
{
label: 'Page',
submenu: [
{ label: 'Night', click: () => sendToWindow({ type: 'pageTheme', value: 'night' }) },
{ label: 'Paper', click: () => sendToWindow({ type: 'pageTheme', value: 'paper' }) }
]
},
{
label: 'Brighter Interface',
click: () => sendToWindow({ type: 'uiBright' })
}
]
},
{ role: 'windowMenu' },
{
label: 'Help',
submenu: [
{
label: 'NEO Shortcuts',
accelerator: 'CmdOrCtrl+/',
click: () => sendToWindow({ type: 'help' })
},
{ type: 'separator' },
{
label: 'About NEO',
click: () => sendToWindow({ type: 'about' })
},
{
label: 'Check for Update…',
click: () => sendToWindow({ type: 'checkUpdate' })
}
]
}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
// Manual update check (Help → Check for Update…): a direct GitHub Releases
// lookup, separate from the silent auto-updater. Works in dev builds too.
let lastReleaseUrl = null;
function compareVersions(a, b) {
const pa = a.split('.').map(Number);
const pb = b.split('.').map(Number);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const na = pa[i] || 0, nb = pb[i] || 0;
if (na !== nb) return na - nb;
}
return 0;
}
// toggling at the session level forces the engine to re-scan visible text —
// newer Chromium ignores attribute changes on text it has already looked at
ipcMain.handle('app:version', () => app.getVersion());
ipcMain.handle('update:check', async () => {
try {
const res = await fetch('https://api.github.com/repos/hughhowey/neo/releases/latest', {
headers: { 'User-Agent': 'NEO-App' }
});
if (!res.ok) throw new Error('GitHub API returned ' + res.status);
const data = await res.json();
const latestVersion = String(data.tag_name || '').replace(/^v/, '');
const currentVersion = app.getVersion();
lastReleaseUrl = data.html_url || null;
return {
hasUpdate: !!latestVersion && compareVersions(latestVersion, currentVersion) > 0,
latestVersion,
currentVersion
};
} catch (err) {
logError('update', err);
return { error: true };
}
});
// the renderer may only open the release page fetched above — never arbitrary URLs
ipcMain.handle('update:openRelease', () => {
if (lastReleaseUrl && /^https:\/\/github\.com\//.test(lastReleaseUrl)) {
require('electron').shell.openExternal(lastReleaseUrl);
}
return true;
});
// Two copies of NEO editing the same library is how words get eaten
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on('second-instance', () => {
const win = BrowserWindow.getAllWindows()[0];
if (win) {
if (win.isMinimized()) win.restore();
win.focus();
}
});
}
// Auto-update from GitHub releases. Deliberately defensive: any failure is
// logged and swallowed, so an unsigned build or offline machine never notices.
// (macOS auto-update only works once the app is code-signed.)
function checkForUpdates() {
if (!app.isPackaged) return;
try {
const { autoUpdater } = require('electron-updater');
autoUpdater.logger = null;
autoUpdater.on('error', (err) => logError('updater', err));
autoUpdater.checkForUpdatesAndNotify().catch((err) => logError('updater', err));
} catch (err) {
logError('updater', err);
}
}
app.whenReady().then(() => {
// Packaged builds get name/icon from electron-builder; this covers `npm start`.
try {
const devIcon = path.join(__dirname, 'build', 'icon.png');
if (process.platform === 'darwin' && fs.existsSync(devIcon)) {
if (app.dock) app.dock.setIcon(devIcon);
app.setAboutPanelOptions({
applicationName: 'NEO',
applicationVersion: app.getVersion(),
iconPath: devIcon
});
}
} catch { /* cosmetic only */ }
// Startup discipline: the window is created first, and every other step is
// individually guarded so no single failure can leave the app running
// invisibly with no window.
try {
// the real Documents folder (handles OneDrive-redirected Windows setups)
try {
LIBRARY_DIR = path.join(app.getPath('documents'), 'NEO Library');
LIBRARY_FILE = path.join(LIBRARY_DIR, 'library.json');
} catch (err) {
logError('paths', err);
}
// macOS press-and-hold accent picker can open invisibly inside Chromium
// and re-emit swallowed keys as phantom repeated letters. Within NEO,
// held keys simply repeat — which is what writers expect anyway.
if (process.platform === 'darwin') {
try {
const { systemPreferences } = require('electron');
systemPreferences.setUserDefault('ApplePressAndHoldEnabled', 'boolean', false);
// macOS injects its own items into any menu named "Edit" —
// these two official switches remove the ones writers can't use here
systemPreferences.setUserDefault('NSDisabledDictationMenuItem', 'boolean', true);
systemPreferences.setUserDefault('NSDisabledCharacterPaletteMenuItem', 'boolean', true);
} catch (err) {
logError('prefs', err);
}
}
try { ensureLibrary(); } catch (err) { logError('library', err); }
createWindow();
try { initSpell(); } catch (err) { logError('spell', err); }
try { buildMenu(); } catch (err) { logError('menu', err); }
try { dailyBackup(); } catch (err) { logError('backup', err); }
try { checkForUpdates(); } catch (err) { logError('updater', err); }
} catch (err) {
// catastrophic: tell the human instead of dying in silence
logError('startup', err);
try {
dialog.showErrorBox('NEO failed to start',
'Please report this at github.com/hughhowey/neo/issues:\n\n' + String((err && err.stack) || err));
} catch { /* nothing left to try */ }
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});