-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
437 lines (396 loc) · 14.1 KB
/
Copy pathmain.js
File metadata and controls
437 lines (396 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
const { app, BrowserWindow, dialog, ipcMain, Menu } = require('electron');
const path = require('path');
const { pathToFileURL } = require('url');
const os = require('os');
const fs = require('fs/promises');
const LOCALES = require('./locales');
const MD_EXTS = ['.md', '.markdown', '.txt'];
let mainWindow = null;
let pendingOpenPath = null; // 窗口就绪前收到的待打开文件(双击关联文件)
let isDirty = false;
let closingAfterSave = false;
let currentLang = 'en';
const t = () => LOCALES[currentLang] || LOCALES.en;
// ---- 最近打开的文件 ----
let recentFiles = [];
const RECENT_MAX = 10;
const recentStorePath = () => path.join(app.getPath('userData'), 'recent.json');
async function loadRecent() {
try {
const arr = JSON.parse(await fs.readFile(recentStorePath(), 'utf-8'));
if (Array.isArray(arr)) recentFiles = arr.filter((p) => typeof p === 'string');
} catch {
// 首次运行没有该文件,或内容损坏,忽略即可
}
}
function saveRecent() {
fs.writeFile(recentStorePath(), JSON.stringify(recentFiles), 'utf-8').catch(() => {});
}
function addRecent(filePath) {
if (!filePath) return;
recentFiles = recentFiles.filter((p) => p !== filePath); // 已存在则提到最前
recentFiles.unshift(filePath);
if (recentFiles.length > RECENT_MAX) recentFiles.length = RECENT_MAX;
saveRecent();
buildMenu();
}
function removeRecent(filePath) {
const before = recentFiles.length;
recentFiles = recentFiles.filter((p) => p !== filePath);
if (recentFiles.length !== before) {
saveRecent();
buildMenu();
}
}
function clearRecent() {
recentFiles = [];
saveRecent();
buildMenu();
}
function fileFromArgv(argv) {
// 跳过可执行文件本身和 electron 开发模式下的 "."
for (const arg of argv.slice(1)) {
if (arg.startsWith('-') || arg === '.') continue;
if (MD_EXTS.includes(path.extname(arg).toLowerCase())) return arg;
}
return null;
}
async function loadFileIntoWindow(filePath) {
if (!mainWindow) {
pendingOpenPath = filePath;
return;
}
try {
const content = await fs.readFile(filePath, 'utf-8');
mainWindow.webContents.send('doc:load', { filePath, content });
addRecent(filePath);
} catch (err) {
dialog.showErrorBox(t().dialog.openFailed, `${filePath}\n${err.message}`);
removeRecent(filePath); // 文件已被移动/删除,从最近列表清掉
}
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 600,
minHeight: 400,
icon: path.join(__dirname, 'build', 'icon.png'), // 开发模式下的任务栏图标;打包后用 exe 内嵌图标
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
// preload 需要 require('highlight.js'),沙箱模式下不允许加载 npm 模块
sandbox: false
}
});
mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
mainWindow.webContents.on('did-finish-load', () => {
if (pendingOpenPath) {
loadFileIntoWindow(pendingOpenPath);
pendingOpenPath = null;
}
});
mainWindow.on('close', (e) => {
if (!isDirty || closingAfterSave) return;
const d = t().dialog;
const choice = dialog.showMessageBoxSync(mainWindow, {
type: 'warning',
buttons: [d.save, d.dontSave, d.cancel],
defaultId: 0,
cancelId: 2,
message: d.unsaved
});
if (choice === 2) {
e.preventDefault();
} else if (choice === 0) {
e.preventDefault();
mainWindow.webContents.send('app:save-then-close');
}
// choice === 1:直接关闭
});
mainWindow.on('closed', () => {
mainWindow = null;
});
}
function buildRecentSubmenu() {
const m = t().menu;
if (recentFiles.length === 0) {
return [{ label: m.noRecent, enabled: false }];
}
const items = recentFiles.map((filePath) => ({
label: filePath,
click: () => loadFileIntoWindow(filePath)
}));
items.push({ type: 'separator' });
items.push({ label: m.clearRecent, click: () => clearRecent() });
return items;
}
function buildMenu() {
const m = t().menu;
const send = (action) => mainWindow && mainWindow.webContents.send('menu', action);
const template = [
{
label: m.file,
submenu: [
{ label: m.new, accelerator: 'CmdOrCtrl+N', click: () => send('new') },
{ label: m.open, accelerator: 'CmdOrCtrl+O', click: () => send('open') },
{ label: m.openRecent, submenu: buildRecentSubmenu() },
{ type: 'separator' },
{ label: m.save, accelerator: 'CmdOrCtrl+S', click: () => send('save') },
{ label: m.saveAs, accelerator: 'CmdOrCtrl+Shift+S', click: () => send('save-as') },
{ type: 'separator' },
{ label: m.exportHtml, accelerator: 'CmdOrCtrl+E', click: () => send('export-html') },
{ label: m.exportPdf, accelerator: 'CmdOrCtrl+Shift+E', click: () => send('export-pdf') },
{ type: 'separator' },
{ label: m.print, accelerator: 'CmdOrCtrl+P', click: () => send('print') },
{ type: 'separator' },
{ role: 'quit', label: m.quit }
]
},
{
label: m.edit,
submenu: [
// 撤销/重做/全选交给 CodeMirror 处理,不能用系统 role(会作用在隐藏 textarea 上)
{ label: m.undo, accelerator: 'CmdOrCtrl+Z', click: () => send('undo') },
{ label: m.redo, accelerator: 'CmdOrCtrl+Shift+Z', click: () => send('redo') },
{ type: 'separator' },
{ role: 'cut', label: m.cut },
{ role: 'copy', label: m.copy },
{ role: 'paste', label: m.paste },
{ label: m.selectAll, accelerator: 'CmdOrCtrl+A', click: () => send('select-all') }
]
},
{
label: m.view,
submenu: [
{ label: m.editOnly, accelerator: 'CmdOrCtrl+1', click: () => send('view-edit') },
{ label: m.split, accelerator: 'CmdOrCtrl+2', click: () => send('view-split') },
{ label: m.previewOnly, accelerator: 'CmdOrCtrl+3', click: () => send('view-preview') },
{ type: 'separator' },
{ role: 'togglefullscreen', label: m.fullscreen }
]
}
];
if (process.platform === 'darwin') {
template.unshift({ role: 'appMenu' });
}
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
// ---- 单实例:再次双击 .md 文件时复用已打开的窗口 ----
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
app.on('second-instance', (event, argv) => {
const file = fileFromArgv(argv);
if (file) loadFileIntoWindow(file);
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
// macOS:Finder 中双击 .md 文件触发
app.on('open-file', (event, filePath) => {
event.preventDefault();
loadFileIntoWindow(filePath);
});
// Windows:首次启动时文件路径在命令行参数里
pendingOpenPath = fileFromArgv(process.argv);
app.whenReady().then(async () => {
await loadRecent();
createWindow();
buildMenu();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
}
// ---- 导出 ----
function escapeHtml(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
// 打印预览窗口顶部的工具条(打印 / 关闭按钮 + Ctrl+P / Esc 快捷键),打印时通过 @media print 隐藏
function printPreviewChrome() {
const ui = t().ui;
return `<style>
#print-bar{position:fixed;top:0;left:0;right:0;z-index:1000;display:flex;gap:8px;justify-content:flex-end;
padding:8px 16px;background:#f6f8fa;border-bottom:1px solid #d0d7de;
font-family:-apple-system,"Segoe UI","Microsoft YaHei",sans-serif;}
#print-bar button{padding:6px 18px;font-size:14px;border:1px solid #d0d7de;border-radius:6px;
background:#fff;color:#24292f;cursor:pointer;}
#print-bar button:hover{background:#eaecef;}
#print-bar .primary{background:#0969da;border-color:#0969da;color:#fff;}
body.markdown-body{padding-top:60px;}
@media print{#print-bar{display:none;}body.markdown-body{padding-top:0;}}
</style>
<div id="print-bar">
<button class="primary" onclick="window.print()">${escapeHtml(ui.print)}</button>
<button onclick="window.close()">${escapeHtml(ui.close)}</button>
</div>
<script>
document.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && (e.key === 'p' || e.key === 'P')) { e.preventDefault(); window.print(); }
else if (e.key === 'Escape') { window.close(); }
});
</script>`;
}
async function buildExportHtml(bodyHtml, title, previewChrome = false) {
const katexDir = path.join(__dirname, 'node_modules', 'katex', 'dist');
const [mdCss, hljsCss, katexCssRaw] = await Promise.all([
fs.readFile(path.join(__dirname, 'renderer', 'export.css'), 'utf-8'),
fs.readFile(path.join(__dirname, 'node_modules', 'highlight.js', 'styles', 'github.css'), 'utf-8'),
fs.readFile(path.join(katexDir, 'katex.min.css'), 'utf-8')
]);
// KaTeX 字体在样式里是相对路径 url(fonts/...),导出的 HTML 不在 katex 目录下,
// 改写成指向 node_modules 的绝对 file:// 路径,PDF/HTML 才能加载字体
const fontsUrl = pathToFileURL(path.join(katexDir, 'fonts')).href;
const katexCss = katexCssRaw.replace(/url\(fonts\//g, `url(${fontsUrl}/`);
return `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>${escapeHtml(title)}</title>
<style>
${hljsCss}
${katexCss}
${mdCss}
</style>
</head>
<body class="markdown-body">
${previewChrome ? printPreviewChrome() : ''}
${bodyHtml}
</body>
</html>`;
}
ipcMain.handle('export:html', async (event, bodyHtml, title, suggestedName) => {
const result = await dialog.showSaveDialog(mainWindow, {
defaultPath: suggestedName,
filters: [{ name: 'HTML', extensions: ['html'] }]
});
if (result.canceled || !result.filePath) return null;
try {
await fs.writeFile(result.filePath, await buildExportHtml(bodyHtml, title), 'utf-8');
return result.filePath;
} catch (err) {
dialog.showErrorBox(t().dialog.exportFailed, err.message);
return null;
}
});
ipcMain.handle('export:pdf', async (event, bodyHtml, title, suggestedName) => {
const result = await dialog.showSaveDialog(mainWindow, {
defaultPath: suggestedName,
filters: [{ name: 'PDF', extensions: ['pdf'] }]
});
if (result.canceled || !result.filePath) return null;
const tmpFile = path.join(os.tmpdir(), `md-export-${Date.now()}.html`);
let pdfWindow = null;
try {
await fs.writeFile(tmpFile, await buildExportHtml(bodyHtml, title), 'utf-8');
pdfWindow = new BrowserWindow({ show: false });
await pdfWindow.loadFile(tmpFile);
const pdfData = await pdfWindow.webContents.printToPDF({
printBackground: true,
pageSize: 'A4',
margins: { top: 0.6, bottom: 0.6, left: 0.6, right: 0.6 }
});
await fs.writeFile(result.filePath, pdfData);
return result.filePath;
} catch (err) {
dialog.showErrorBox(t().dialog.exportFailed, err.message);
return null;
} finally {
if (pdfWindow) pdfWindow.destroy();
fs.unlink(tmpFile).catch(() => {});
}
});
ipcMain.handle('doc:print', async (event, bodyHtml, title) => {
// 打开可见的预览窗口(与导出同一套排版),由页面内的"打印"按钮触发 window.print()。
// 这样用户能先预览,取消打印也不会报错。
const tmpFile = path.join(os.tmpdir(), `md-print-${Date.now()}.html`);
try {
await fs.writeFile(tmpFile, await buildExportHtml(bodyHtml, title, true), 'utf-8');
const previewWindow = new BrowserWindow({
width: 900,
height: 1000,
title,
autoHideMenuBar: true,
backgroundColor: '#ffffff'
});
previewWindow.setMenu(null); // 去掉本窗口的应用菜单,让 Ctrl+P 走页面内的处理而非主窗口
await previewWindow.loadFile(tmpFile);
fs.unlink(tmpFile).catch(() => {}); // 内容已载入内存,临时文件可删
return true;
} catch (err) {
dialog.showErrorBox(t().dialog.exportFailed, err.message);
fs.unlink(tmpFile).catch(() => {});
return false;
}
});
// ---- IPC ----
ipcMain.on('settings:lang', (event, lang) => {
if (LOCALES[lang]) {
currentLang = lang;
buildMenu();
}
});
ipcMain.handle('file:open', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Markdown', extensions: ['md', 'markdown'] },
{ name: '*', extensions: ['*'] }
]
});
if (result.canceled || result.filePaths.length === 0) return null;
const filePath = result.filePaths[0];
const content = await fs.readFile(filePath, 'utf-8');
addRecent(filePath);
return { filePath, content };
});
// 拖放打开:渲染进程拿到文件路径后读取内容(路径由 preload 的 webUtils 解析)
ipcMain.handle('file:read', async (event, filePath) => {
try {
const content = await fs.readFile(filePath, 'utf-8');
addRecent(filePath);
return { filePath, content };
} catch (err) {
dialog.showErrorBox(t().dialog.openFailed, `${filePath}\n${err.message}`);
return null;
}
});
ipcMain.handle('file:save', async (event, filePath, content) => {
await fs.writeFile(filePath, content, 'utf-8');
return true;
});
ipcMain.handle('file:save-as', async (event, content, suggestedName) => {
const result = await dialog.showSaveDialog(mainWindow, {
defaultPath: suggestedName,
filters: [{ name: 'Markdown', extensions: ['md'] }]
});
if (result.canceled || !result.filePath) return null;
await fs.writeFile(result.filePath, content, 'utf-8');
addRecent(result.filePath);
return result.filePath;
});
ipcMain.handle('dialog:confirm', async (event, message) => {
const d = t().dialog;
const result = await dialog.showMessageBox(mainWindow, {
type: 'warning',
buttons: [d.ok, d.cancel],
defaultId: 1,
cancelId: 1,
message
});
return result.response === 0;
});
ipcMain.on('doc:dirty-changed', (event, dirty) => {
isDirty = dirty;
});
ipcMain.on('app:close-after-save', () => {
closingAfterSave = true;
if (mainWindow) mainWindow.close();
});