'use strict'; const { app, BrowserWindow, ipcMain, dialog, Menu, net, nativeTheme } = require('electron'); const path = require('path'); const fs = require('fs'); const fsp = fs.promises; const wikiapi = require('./wikiapi'); const spell = require('./spell'); const wordnet = require('./wordnet'); const exporter = require('./exporter'); const os = require('os'); let win = null; let cfgPath = ''; let cfg = null; const NOTE_EXT = /\.(wiki|mediawiki|txt)$/i; function defaults() { return { version: 1, notesDir: '', profiles: [], active: null, swapped: false, sidebar: true, split: 0.5, spellLang: 'en-US', underline: true, dict: [], exportDir: '', css: {}, lastNote: '', bounds: { width: 1280, height: 800 } }; } function loadConfig() { let data = {}; try { data = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch (e) { data = {}; } return Object.assign(defaults(), data); } function saveConfig() { try { fs.mkdirSync(path.dirname(cfgPath), { recursive: true }); fs.writeFileSync(cfgPath, JSON.stringify(cfg, null, 2)); } catch (e) { /* settings are best effort */ } } function ensureNotesDir() { try { fs.mkdirSync(cfg.notesDir, { recursive: true }); } catch (e) { /* reported when listing */ } } function cleanTitle(t) { let s = String(t || '') .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '') .replace(/\s+/g, ' ') .trim() .replace(/[. ]+$/, '') .slice(0, 120); if (/^(con|prn|aux|nul|com\d|lpt\d)$/i.test(s)) s = '_' + s; return s; } function notePath(file) { const base = path.basename(String(file || '')); if (!NOTE_EXT.test(base)) throw new Error('Not a note file'); const full = path.join(cfg.notesDir, base); if (path.resolve(path.dirname(full)) !== path.resolve(cfg.notesDir)) throw new Error('Bad path'); return full; } const fetchFn = (url, init) => net.fetch(url, init); function cleanProfiles(list) { if (!Array.isArray(list)) return []; return list .filter((p) => p && typeof p.id === 'string' && typeof p.url === 'string') .map((p) => ({ id: p.id, name: String(p.name || '').slice(0, 80), url: p.url.slice(0, 500) })); } ipcMain.handle('config:get', () => cfg); ipcMain.handle('config:set', (e, patch) => { patch = patch || {}; if ('profiles' in patch) cfg.profiles = cleanProfiles(patch.profiles); if ('active' in patch) cfg.active = patch.active ? String(patch.active) : null; if ('swapped' in patch) cfg.swapped = !!patch.swapped; if ('sidebar' in patch) cfg.sidebar = !!patch.sidebar; if ('spellLang' in patch && /^en-(US|GB)$/.test(patch.spellLang)) cfg.spellLang = patch.spellLang; if ('underline' in patch) cfg.underline = !!patch.underline; if ('split' in patch) cfg.split = Math.max(0.15, Math.min(0.85, Number(patch.split) || 0.5)); if ('css' in patch && patch.css && typeof patch.css === 'object') { const css = {}; for (const k of Object.keys(patch.css)) { const v = patch.css[k] || {}; css[k] = { path: String(v.path || ''), on: !!v.on }; } cfg.css = css; } if ('lastNote' in patch) cfg.lastNote = String(patch.lastNote || ''); if ('notesDir' in patch && patch.notesDir) { cfg.notesDir = String(patch.notesDir); ensureNotesDir(); } saveConfig(); return cfg; }); ipcMain.handle('notes:list', async (e, query) => { ensureNotesDir(); const q = String(query || '').trim().toLowerCase(); let names = []; try { names = (await fsp.readdir(cfg.notesDir)).filter((f) => NOTE_EXT.test(f)); } catch (err) { return []; } const out = []; for (const f of names) { try { const full = path.join(cfg.notesDir, f); const st = await fsp.stat(full); if (!st.isFile()) continue; const title = f.replace(NOTE_EXT, ''); if (q) { let hit = title.toLowerCase().includes(q); if (!hit) hit = (await fsp.readFile(full, 'utf8')).toLowerCase().includes(q); if (!hit) continue; } out.push({ file: f, title, mtime: st.mtimeMs }); } catch (err) { /* skip unreadable file */ } } out.sort((a, b) => b.mtime - a.mtime); return out; }); ipcMain.handle('notes:read', async (e, file) => fsp.readFile(notePath(file), 'utf8')); ipcMain.handle('notes:write', async (e, file, text) => { await fsp.writeFile(notePath(file), String(text), 'utf8'); return true; }); ipcMain.on('notes:writeSync', (e, file, text) => { try { fs.writeFileSync(notePath(file), String(text), 'utf8'); e.returnValue = true; } catch (err) { e.returnValue = false; } }); ipcMain.handle('notes:create', async (e, base) => { ensureNotesDir(); const stem = cleanTitle(base) || 'Untitled'; let n = 1; let name = stem + '.wiki'; while (fs.existsSync(path.join(cfg.notesDir, name))) { n++; name = stem + ' ' + n + '.wiki'; } await fsp.writeFile(path.join(cfg.notesDir, name), '', 'utf8'); return { file: name, title: name.replace(NOTE_EXT, '') }; }); ipcMain.handle('notes:rename', async (e, file, newTitle) => { const from = notePath(file); const ext = path.extname(file); const stem = cleanTitle(newTitle); if (!stem) return { ok: false, error: 'empty' }; const toName = stem + ext; const to = path.join(cfg.notesDir, toName); if (toName === path.basename(file)) return { ok: true, file: toName }; if (fs.existsSync(to) && to.toLowerCase() !== from.toLowerCase()) return { ok: false, error: 'exists' }; await fsp.rename(from, to); return { ok: true, file: toName }; }); ipcMain.handle('notes:delete', async (e, file) => { await fsp.unlink(notePath(file)); return true; }); ipcMain.handle('dialog:pickFolder', async () => { const r = await dialog.showOpenDialog(win, { properties: ['openDirectory', 'createDirectory'] }); return r.canceled || !r.filePaths.length ? null : r.filePaths[0]; }); ipcMain.handle('dialog:pickCss', async () => { const r = await dialog.showOpenDialog(win, { properties: ['openFile'], filters: [{ name: 'Stylesheets', extensions: ['css', 'txt'] }, { name: 'All files', extensions: ['*'] }] }); return r.canceled || !r.filePaths.length ? null : r.filePaths[0]; }); ipcMain.handle('css:read', async (e, p) => { try { return { ok: true, text: await fsp.readFile(String(p), 'utf8') }; } catch (err) { return { ok: false, error: err.message }; } }); ipcMain.handle('wiki:connect', async (e, input) => { try { return await wikiapi.connect(input, fetchFn); } catch (err) { return { ok: false, kind: 'badurl', detail: err.message }; } }); ipcMain.handle('wiki:parse', async (e, req) => { try { const r = await wikiapi.parseWiki(fetchFn, req.api, req.text, req.title); if (!r.ok) return { ok: false, kind: r.kind, detail: wikiapi.explain(r, new URL(req.api)) }; return { ok: true, doc: wikiapi.buildLiveDoc(r.json, req.api, req.title) }; } catch (err) { return { ok: false, kind: 'unreachable', detail: err.message }; } }); /* ---------- spelling, thesaurus, export ---------- */ ipcMain.handle('spell:check', (e, text) => { try { return { ok: true, list: spell.check(String(text || ''), cfg.spellLang, cfg.dict) }; } catch (err) { return { ok: false, error: err.message }; } }); ipcMain.handle('spell:suggest', (e, word) => { try { return spell.suggest(String(word || ''), cfg.spellLang); } catch (err) { return []; } }); ipcMain.handle('spell:add', (e, word) => { word = String(word || '').trim(); if (word && cfg.dict.indexOf(word) < 0 && cfg.dict.length < 5000) { cfg.dict.push(word); saveConfig(); } return cfg.dict; }); ipcMain.handle('thes:lookup', (e, word) => { try { return Object.assign({ ok: true }, wordnet.lookup(word)); } catch (err) { return { ok: false, error: err.message }; } }); async function makePdf(html, paper) { const tmp = path.join(os.tmpdir(), 'swiftmark-export-' + Date.now() + '.html'); fs.writeFileSync(tmp, html, 'utf8'); const w = new BrowserWindow({ show: false, width: 900, height: 1200, webPreferences: { sandbox: true, javascript: false, contextIsolation: true, nodeIntegration: false, spellcheck: false } }); try { await w.loadFile(tmp); await new Promise((r) => setTimeout(r, 400)); return await w.webContents.printToPDF({ pageSize: paper === 'A4' ? 'A4' : 'Letter', printBackground: true, margins: { top: 0.6, bottom: 0.6, left: 0.6, right: 0.6 } }); } finally { w.destroy(); try { fs.unlinkSync(tmp); } catch (err) { /* ignore */ } } } ipcMain.handle('export:run', async (e, req) => { req = req || {}; const format = req.format; const title = String(req.title || 'Untitled'); const text = String(req.text || ''); const paper = req.paper === 'A4' ? 'A4' : 'Letter'; const markup = req.content === 'markup'; const ext = format === 'pdf' ? 'pdf' : (format === 'docx' ? 'docx' : 'wiki'); const filters = { pdf: [{ name: 'PDF document', extensions: ['pdf'] }], docx: [{ name: 'Word document', extensions: ['docx'] }], wiki: [{ name: 'Wikitext', extensions: ['wiki'] }, { name: 'Text', extensions: ['txt'] }] }[format]; if (!filters) return { ok: false, error: 'Unknown format' }; const safe = title.replace(/[\\/:*?"<>|]+/g, ' ').trim() || 'Untitled'; const dir = cfg.exportDir && fs.existsSync(cfg.exportDir) ? cfg.exportDir : app.getPath('documents'); const r = await dialog.showSaveDialog(win, { title: 'Export', defaultPath: path.join(dir, safe + '.' + ext), filters }); if (r.canceled || !r.filePath) return { ok: false, canceled: true }; try { let out; if (format === 'wiki') out = text; else if (format === 'pdf') out = await makePdf(markup ? exporter.markupPage(title, text) : String(req.html || ''), paper); else out = await exporter.toDocx(title, markup ? exporter.markupBody(title, text) : String(req.body || ''), paper); fs.writeFileSync(r.filePath, out); cfg.exportDir = path.dirname(r.filePath); saveConfig(); return { ok: true, path: r.filePath }; } catch (err) { return { ok: false, error: err.message }; } }); // Native right-click menu: copy and paste in the editor and the preview, plus spelling help. function buildContextTemplate(params, wc) { const t = []; if (params.misspelledWord) { (params.dictionarySuggestions || []).slice(0, 5).forEach((s) => { t.push({ label: s, click: () => wc.replaceMisspelling(s) }); }); if (!(params.dictionarySuggestions || []).length) t.push({ label: 'No suggestions', enabled: false }); t.push({ label: 'Add to dictionary', click: () => wc.session.addWordToSpellCheckerDictionary(params.misspelledWord) }); t.push({ type: 'separator' }); } if (params.isEditable) { const f = params.editFlags || {}; t.push({ label: 'Cut', role: 'cut', enabled: !!f.canCut }); t.push({ label: 'Copy', role: 'copy', enabled: !!f.canCopy }); t.push({ label: 'Paste', role: 'paste', enabled: !!f.canPaste }); t.push({ type: 'separator' }); t.push({ label: 'Select all', role: 'selectAll' }); } else { const has = !!(params.selectionText && params.selectionText.length); t.push({ label: 'Copy', enabled: has, click: () => { const f = params.frame; if (f && typeof f.copy === 'function') f.copy(); else wc.copy(); } }); t.push({ label: 'Select all', click: () => { const f = params.frame; if (f && typeof f.selectAll === 'function') f.selectAll(); else wc.selectAll(); } }); } return t; } module.exports = { buildContextTemplate }; function createWindow() { const b = cfg.bounds || {}; win = new BrowserWindow({ width: b.width || 1280, height: b.height || 800, x: b.x, y: b.y, minWidth: 760, minHeight: 480, title: 'Swiftmark', backgroundColor: nativeTheme.shouldUseDarkColors ? '#1b1c1f' : '#f3f3f3', autoHideMenuBar: true, webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, nodeIntegration: false, sandbox: true, spellcheck: true } }); win.setMenuBarVisibility(false); win.loadFile(path.join(__dirname, 'renderer', 'index.html')); win.webContents.on('context-menu', (e, params) => { const tpl = buildContextTemplate(params, win.webContents); if (tpl.length) Menu.buildFromTemplate(tpl).popup({ window: win }); }); win.webContents.on('will-navigate', (e) => e.preventDefault()); win.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); win.webContents.on('before-input-event', (e, input) => { if (input.type === 'keyDown' && (input.key === 'F12' || (input.control && input.shift && input.key.toLowerCase() === 'i'))) { win.webContents.toggleDevTools(); } }); win.on('close', () => { if (!win.isMaximized() && !win.isMinimized()) cfg.bounds = win.getBounds(); saveConfig(); }); win.on('closed', () => { win = null; }); } if (!app.requestSingleInstanceLock()) { app.quit(); } else { app.on('second-instance', () => { if (win) { if (win.isMinimized()) win.restore(); win.focus(); } }); app.whenReady().then(() => { cfgPath = path.join(app.getPath('userData'), 'config.json'); // The first build was called WikiNotes. Carry its settings over so wikis and the notes folder survive the rename. if (!fs.existsSync(cfgPath)) { const old = path.join(app.getPath('appData'), 'WikiNotes', 'config.json'); try { if (fs.existsSync(old)) { fs.mkdirSync(path.dirname(cfgPath), { recursive: true }); fs.copyFileSync(old, cfgPath); } } catch (e) { /* start fresh if the old settings cannot be copied */ } } cfg = loadConfig(); if (!cfg.notesDir) { const legacy = path.join(app.getPath('documents'), 'WikiNotes'); cfg.notesDir = fs.existsSync(legacy) ? legacy : path.join(app.getPath('documents'), 'Swiftmark'); } ensureNotesDir(); saveConfig(); Menu.setApplicationMenu(null); createWindow(); }); app.on('window-all-closed', () => app.quit()); }