-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
401 lines (341 loc) · 12.3 KB
/
Copy pathmain.js
File metadata and controls
401 lines (341 loc) · 12.3 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
const { app, BrowserWindow, ipcMain, dialog, Menu } = require('electron');
const path = require('path');
const fs = require('fs/promises');
const { existsSync } = require('fs');
const { autoUpdater } = require('electron-updater');
const cacheDir = path.join(app.getPath('userData'), 'cache');
app.commandLine.appendSwitch('disk-cache-dir', cacheDir);
app.commandLine.appendSwitch('media-cache-dir', cacheDir);
const APP_NAME = 'LabLog Generator';
const SETTINGS_FILE_NAME = 'settings.json';
let mainWindow = null;
function getDefaultSettings() {
const currentYear = new Date().getFullYear();
return {
Author: 'Jie Hua',
Email: 'Jie.Hua@lmu.de',
SelectedCategory: 'Experimental log',
Categories: [
{
name: 'Experimental log',
content:
"[toc]\n\n## To-do list\n\n- [ ] \n\n## Experiments\n\n## Other things\n\n<button type='button' data-path='./' style='border-radius: 15px; padding: 4px 12px; border: 1px solid #9ca3af; cursor: pointer'>📁 File Path</button>"
},
{
name: 'Discussion',
content:
"[toc]\n\n## Content\n\n<button type='button' data-path='./' style='border-radius: 15px; padding: 4px 12px; border: 1px solid #9ca3af; cursor: pointer'>📁 File Path</button>"
},
{
name: 'Reading',
content:
"[toc]\n\n## Basic Information\n\n**Title:**\n\n**DOI:**\n\n**URL:**\n\n**Published:**\n\n**Journal:**\n\n## Notes\n\n<button type='button' data-path='./' style='border-radius: 15px; padding: 4px 12px; border: 1px solid #9ca3af; cursor: pointer'>📁 File Path</button>"
},
{
name: 'Inspiration',
content:
"[toc]\n\n## Content\n\n<button type='button' data-path='./' style='border-radius: 15px; padding: 4px 12px; border: 1px solid #9ca3af; cursor: pointer'>📁 File Path</button>"
}
],
Theme: 'corporate',
Updates: {
mode: 'manual',
checkOnStartup: true
},
Copyright: {
owner: 'Jie Hua',
year: currentYear,
license: 'MIT'
}
};
}
function normalizeLegacyToc(markdown) {
if (typeof markdown !== 'string') {
return '';
}
const pathButton = "<button type='button' data-path='./' style='border-radius: 15px; padding: 4px 12px; border: 1px solid #9ca3af; cursor: pointer'>📁 File Path</button>";
return markdown
.replace(/(^|\n)##\s*目录(?=\n|$)/g, '$1[toc]')
.replace(/(^|\n)\[toc\](?=\n|$)/gi, '$1[toc]')
.replace(/\[File\s*Path\]\(\.\/\)/gi, pathButton)
.replace(/<button[^>]*>\s*\[:?file_folder:?\s*File\s*Path\]\(\.\/\)\s*<\/button>/gi, pathButton)
.replace(/<button[^>]*>\s*\[📁\s*File\s*Path\]\(\.\/\)\s*<\/button>/gi, pathButton);
}
function sanitizeSettings(incoming) {
const defaults = getDefaultSettings();
const settings = { ...defaults, ...(incoming || {}) };
if (!Array.isArray(settings.Categories) || settings.Categories.length === 0) {
settings.Categories = defaults.Categories;
}
settings.Categories = settings.Categories
.filter((item) => item && typeof item.name === 'string')
.map((item) => ({
name: item.name.trim() || 'Untitled',
content: normalizeLegacyToc(item.content)
}));
// Keep bundled templates available even if an older settings file removed them.
const existingNames = new Set(settings.Categories.map((item) => item.name));
defaults.Categories.forEach((template) => {
if (!existingNames.has(template.name)) {
settings.Categories.push({ ...template });
}
});
if (!settings.Categories.some((c) => c.name === settings.SelectedCategory)) {
settings.SelectedCategory = settings.Categories[0].name;
}
if (typeof settings.Theme !== 'string' || !settings.Theme.trim()) {
settings.Theme = defaults.Theme;
}
if (!settings.Updates || typeof settings.Updates !== 'object') {
settings.Updates = defaults.Updates;
}
if (!['manual', 'auto'].includes(settings.Updates.mode)) {
settings.Updates.mode = 'manual';
}
if (typeof settings.Updates.checkOnStartup !== 'boolean') {
settings.Updates.checkOnStartup = true;
}
if (!settings.Copyright || typeof settings.Copyright !== 'object') {
settings.Copyright = defaults.Copyright;
}
if (typeof settings.Copyright.owner !== 'string' || !settings.Copyright.owner.trim()) {
settings.Copyright.owner = defaults.Copyright.owner;
}
if (!Number.isInteger(settings.Copyright.year)) {
settings.Copyright.year = defaults.Copyright.year;
}
if (typeof settings.Copyright.license !== 'string' || !settings.Copyright.license.trim()) {
settings.Copyright.license = defaults.Copyright.license;
}
return settings;
}
function getSettingsPath() {
return path.join(app.getPath('userData'), SETTINGS_FILE_NAME);
}
async function ensureSettingsFile() {
const settingsPath = getSettingsPath();
if (!existsSync(settingsPath)) {
const defaultPath = path.join(__dirname, SETTINGS_FILE_NAME);
if (existsSync(defaultPath)) {
const data = await fs.readFile(defaultPath, 'utf8');
const merged = sanitizeSettings(JSON.parse(data));
await fs.writeFile(settingsPath, JSON.stringify(merged, null, 2), 'utf8');
return;
}
await fs.writeFile(settingsPath, JSON.stringify(getDefaultSettings(), null, 2), 'utf8');
}
const current = await fs.readFile(settingsPath, 'utf8');
const merged = sanitizeSettings(JSON.parse(current));
await fs.writeFile(settingsPath, JSON.stringify(merged, null, 2), 'utf8');
}
async function readSettings() {
const settingsPath = getSettingsPath();
const raw = await fs.readFile(settingsPath, 'utf8');
return sanitizeSettings(JSON.parse(raw));
}
async function writeSettings(settings) {
const clean = sanitizeSettings(settings);
await fs.writeFile(getSettingsPath(), JSON.stringify(clean, null, 2), 'utf8');
return clean;
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1180,
height: 780,
minWidth: 760,
minHeight: 620,
show: false,
frame: false,
transparent: false,
roundedCorners: true,
backgroundColor: '#111111',
title: APP_NAME,
icon: path.join(__dirname, 'build/icon.ico'),
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
spellcheck: false
}
});
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
mainWindow.on('maximize', () => {
mainWindow?.webContents.send('window:maximize-state', true);
});
mainWindow.on('unmaximize', () => {
mainWindow?.webContents.send('window:maximize-state', false);
});
mainWindow.setMenuBarVisibility(false);
Menu.setApplicationMenu(null);
mainWindow.loadFile('index.html');
}
function bindAutoUpdaterEvents() {
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = true;
autoUpdater.on('checking-for-update', () => {
mainWindow?.webContents.send('updates:status', {
state: 'checking',
message: 'Checking for updates...'
});
});
autoUpdater.on('update-available', (info) => {
mainWindow?.webContents.send('updates:status', {
state: 'available',
version: info.version,
message: `New version ${info.version} is available.`
});
});
autoUpdater.on('update-not-available', () => {
mainWindow?.webContents.send('updates:status', {
state: 'not-available',
message: 'You are using the latest version.'
});
});
autoUpdater.on('download-progress', (progress) => {
mainWindow?.webContents.send('updates:status', {
state: 'downloading',
message: `Downloading update ${Math.round(progress.percent)}%`,
percent: progress.percent
});
});
autoUpdater.on('update-downloaded', (info) => {
mainWindow?.webContents.send('updates:status', {
state: 'downloaded',
version: info.version,
message: `Update ${info.version} downloaded. Restart to install.`
});
});
autoUpdater.on('error', (error) => {
mainWindow?.webContents.send('updates:status', {
state: 'error',
message: `Update failed: ${error?.message || 'Unknown error'}`
});
});
}
async function checkUpdatesOnStartup() {
try {
const settings = await readSettings();
if (!settings.Updates?.checkOnStartup) {
return;
}
autoUpdater.autoDownload = settings.Updates.mode === 'auto';
await autoUpdater.checkForUpdates();
} catch (error) {
console.error('Update check on startup failed:', error);
}
}
app.whenReady().then(() => {
ensureSettingsFile().catch((error) => {
console.error('Failed to ensure settings file:', error);
});
bindAutoUpdaterEvents();
createWindow();
setTimeout(() => {
checkUpdatesOnStartup().catch((error) => {
console.error('Startup update check error:', error);
});
}, 1800);
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
ipcMain.handle('settings:get-path', () => {
return getSettingsPath();
});
ipcMain.on('window:minimize', () => {
mainWindow?.minimize();
});
ipcMain.on('window:toggle-maximize', () => {
if (!mainWindow) {
return;
}
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow.maximize();
}
});
ipcMain.on('window:close', () => {
mainWindow?.close();
});
ipcMain.handle('window:is-maximized', () => {
return mainWindow?.isMaximized() || false;
});
ipcMain.handle('settings:get', async () => {
await ensureSettingsFile();
return readSettings();
});
ipcMain.handle('settings:save', async (_, newSettings) => {
return writeSettings(newSettings);
});
ipcMain.handle('updates:check', async () => {
const settings = await readSettings();
autoUpdater.autoDownload = settings.Updates.mode === 'auto';
return autoUpdater.checkForUpdates();
});
ipcMain.handle('updates:download', async () => {
return autoUpdater.downloadUpdate();
});
ipcMain.handle('updates:install', () => {
autoUpdater.quitAndInstall();
return true;
});
ipcMain.on('save-markdown', (event, content, fileName) => {
dialog.showSaveDialog({
title: 'Save Markdown File',
defaultPath: path.join(app.getPath('userData'), fileName || 'defaultFileName.md'),
filters: [
{ name: 'Markdown Files', extensions: ['md'] },
{ name: 'All Files', extensions: ['*'] }
]
}).then(file => {
if (!file.canceled && file.filePath) {
const savedPath = file.filePath.toString();
fs.writeFile(savedPath, content, 'utf8')
.then(() => {
event.sender.send('save-markdown-reply', { message: 'File saved successfully.', filePath: savedPath });
})
.catch((err) => {
console.error('Failed to write markdown file:', err);
event.sender.send('save-markdown-reply', { message: 'Failed to save file.', error: err?.message || String(err) });
});
} else {
event.sender.send('save-markdown-reply', { message: 'Save canceled.' });
console.error('File path is undefined or saving was canceled');
}
}).catch(err => {
console.error('Failed to save the file:', err);
try {
// Notify renderer about failure with error details when possible
event.sender.send('save-markdown-reply', { message: 'Failed to save file.', error: err?.message || String(err) });
} catch (e) {
// ignore if event.sender is not available
}
});
});
ipcMain.handle('open-file', async (_, filePath) => {
try {
if (!filePath) return { success: false, error: 'No file path provided' };
const { shell } = require('electron');
const result = await shell.openPath(filePath);
// shell.openPath returns an empty string on success, or an error message on failure
if (typeof result === 'string' && result.length > 0) {
return { success: false, error: result };
}
return { success: true };
} catch (err) {
console.error('Failed to open file:', err);
return { success: false, error: err?.message || String(err) };
}
});