Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
400 lines (383 loc) · 12.4 KB
/
Copy pathmain.js
File metadata and controls
400 lines (383 loc) · 12.4 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
const {
app,
BrowserWindow,
ipcMain,
dialog,
Menu,
screen,
shell,
} = require("electron");
const path = require("path");
const fs = require("fs");
const demoMode = process.argv.includes("--demo");
// Keep the original profile when changing the visible product name to Todo.
const legacyProfile = path.join(app.getPath("appData"), "todotree");
fs.mkdirSync(legacyProfile, { recursive: true });
app.setPath("userData", legacyProfile);
if (demoMode) {
const demoData = path.join(app.getPath("temp"), "TodoTree-demo");
fs.mkdirSync(demoData, { recursive: true });
app.setPath("userData", demoData);
}
// 状态变量必须先于单实例锁声明:second-instance 事件可能在
// requestSingleInstanceLock 同步执行期间投递(并发启动竞态),
// 若声明在锁检查之后会触发 TDZ(Cannot access before initialization)
let currentFilePath = path.join(app.getPath("desktop"), "TODOTREE.md");
if (demoMode)
currentFilePath = path.join(app.getPath("userData"), "演示任务.md");
let configPath = path.join(app.getPath("userData"), "config.json");
let mainWindow;
let isPinned = !demoMode;
let expectQuit = false;
let transientEdit = false;
let recreateCount = 0;
let windowBounds = { x: undefined, y: undefined, width: 520, height: 740 };
// 单实例锁:重复启动时直接退出,避免两个窗口叠在桌面层
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
let desktopLayer = {
attach: () => {
throw new Error("desktop-layer unavailable");
},
detach: () => {},
ensureAttached: () => "unattached",
};
try {
desktopLayer = require("./desktop-layer");
} catch (e) {
console.error("[desktop-layer] load failed:", e.message);
}
const fileStore = require("./lib/file-store");
const seed = demoMode
? fs.readFileSync(path.join(__dirname, "examples", "demo.md"), "utf8")
: "# Todo\n\n## 目标\n\n## 待完成\n\n## 已完成\n\n## 放弃\n";
app.on("second-instance", () => {
if (mainWindow && !mainWindow.isDestroyed()) {
isPinned = false;
transientEdit = false;
applyPinState();
mainWindow.show();
mainWindow.focus();
}
});
function loadConfig() {
try {
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
if (
typeof config.filePath === "string" &&
path.isAbsolute(config.filePath)
)
currentFilePath = config.filePath;
for (const key of ["x", "y", "width", "height"])
if (Number.isFinite(config.bounds?.[key]))
windowBounds[key] = config.bounds[key];
isPinned = demoMode ? false : config.pinned !== false;
}
} catch (_) {}
}
function saveConfig(patch = {}) {
try {
let existing = {};
try {
existing = JSON.parse(fs.readFileSync(configPath, "utf8"));
} catch (_) {}
fs.mkdirSync(path.dirname(configPath), { recursive: true });
const temp = configPath + ".tmp";
fs.writeFileSync(
temp,
JSON.stringify(
{
...existing,
filePath: currentFilePath,
bounds: windowBounds,
pinned: isPinned,
...patch,
},
null,
2,
),
"utf8",
);
fs.renameSync(temp, configPath);
} catch (_) {}
}
loadConfig();
function applyPinState(sendEvent = true) {
if (!mainWindow) return;
if (isPinned) {
mainWindow.setAlwaysOnTop(false);
mainWindow.setSkipTaskbar(true);
// 锁定模式下仍允许拉伸窗口边缘(横向拉宽等),只禁拖动
mainWindow.setResizable(true);
mainWindow.setMovable(false);
try {
desktopLayer.attach(mainWindow);
mainWindow.setFocusable(false);
} catch (e) {
// 环境不支持桌面层时回退为普通窗口
console.error("[desktop-layer] attach failed:", e.message);
isPinned = false;
mainWindow.setFocusable(true);
mainWindow.setSkipTaskbar(false);
mainWindow.setMovable(true);
}
} else {
mainWindow.setAlwaysOnTop(false);
try {
desktopLayer.detach(mainWindow);
} catch (e) {
console.error("[desktop-layer] detach failed:", e.message);
}
mainWindow.setFocusable(true);
mainWindow.setSkipTaskbar(false);
mainWindow.setResizable(true);
mainWindow.setMovable(true);
}
if (sendEvent) mainWindow.webContents.send("pin-state-changed", isPinned);
}
function createWindow() {
{
const hasPosition =
Number.isFinite(windowBounds.x) && Number.isFinite(windowBounds.y);
const area = hasPosition
? screen.getDisplayMatching(windowBounds).workArea
: screen.getPrimaryDisplay().workArea;
windowBounds.width = Math.min(
Math.max(320, windowBounds.width),
area.width,
);
windowBounds.height = Math.min(
Math.max(400, windowBounds.height),
area.height,
);
if (hasPosition)
windowBounds.x = Math.max(
area.x,
Math.min(windowBounds.x, area.x + area.width - windowBounds.width),
);
if (hasPosition)
windowBounds.y = Math.max(
area.y,
Math.min(windowBounds.y, area.y + area.height - windowBounds.height),
);
}
mainWindow = new BrowserWindow({
x: windowBounds.x,
y: windowBounds.y,
width: windowBounds.width,
height: windowBounds.height,
minWidth: 320,
minHeight: 400,
resizable: true,
frame: false,
transparent: true,
focusable: false,
skipTaskbar: true,
alwaysOnTop: false,
show: false,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
},
});
Menu.setApplicationMenu(null);
mainWindow.loadFile(path.join(__dirname, "renderer", "index.html"));
mainWindow.setMenu(null);
mainWindow.on("blur", () => {
// 临时输入结束(点击了其他窗口):自动回到桌面层
if (isPinned && transientEdit) {
transientEdit = false;
applyPinState();
}
});
mainWindow.on("ready-to-show", () => {
mainWindow.show();
applyPinState();
});
mainWindow.on("close", (event) => {
if (!expectQuit) {
event.preventDefault();
mainWindow.webContents.send("close-requested");
}
});
let saveBoundsTimer = null;
let snapping = false;
const onBoundsChange = () => {
if (snapping) return;
if (saveBoundsTimer) clearTimeout(saveBoundsTimer);
saveBoundsTimer = setTimeout(() => {
if (!mainWindow || mainWindow.isDestroyed()) return;
let b = mainWindow.getBounds();
// 浮动解锁模式下拖近屏幕工作区边缘(15px 内)自动磁吸对齐
if (!isPinned && typeof mainWindow.setBounds === "function") {
const area = screen.getDisplayMatching(b).workArea;
const SNAP = 15;
let nx = b.x;
let ny = b.y;
if (Math.abs(b.x - area.x) <= SNAP) nx = area.x;
else if (Math.abs(b.x + b.width - (area.x + area.width)) <= SNAP)
nx = area.x + area.width - b.width;
if (Math.abs(b.y - area.y) <= SNAP) ny = area.y;
else if (Math.abs(b.y + b.height - (area.y + area.height)) <= SNAP)
ny = area.y + area.height - b.height;
if (nx !== b.x || ny !== b.y) {
snapping = true;
try {
b = { x: nx, y: ny, width: b.width, height: b.height };
mainWindow.setBounds(b);
} finally {
snapping = false;
}
}
}
windowBounds = { x: b.x, y: b.y, width: b.width, height: b.height };
saveConfig();
}, 300);
};
mainWindow.on("resize", onBoundsChange);
mainWindow.on("move", onBoundsChange);
}
ipcMain.handle("load-todo", () => {
return { ...fileStore.read(currentFilePath, seed), pinned: isPinned };
});
ipcMain.handle("save-todo", (_event, request) =>
fileStore.save(
currentFilePath,
request,
path.join(app.getPath("userData"), "backups"),
),
);
ipcMain.handle("save-copy", async (_event, content) => {
const result = await dialog.showSaveDialog(mainWindow, {
title: "保留当前任务副本",
defaultPath: currentFilePath.replace(/\.(md|txt)$/i, "") + "-副本.md",
filters: [{ name: "Markdown", extensions: ["md"] }],
});
if (result.canceled || !result.filePath) return null;
if (
path.resolve(result.filePath).toLowerCase() ===
path.resolve(currentFilePath).toLowerCase()
)
return { success: false, error: "请选择其他文件名,以保留外部修改" };
const disk = fileStore.read(result.filePath);
if (!disk.success) return disk;
return {
...fileStore.save(result.filePath, {
content,
filePath: result.filePath,
revision: disk.revision,
}),
filePath: result.filePath,
};
});
ipcMain.handle("open-backups", () => {
const dir = fileStore.backupFolder(
currentFilePath,
path.join(app.getPath("userData"), "backups"),
);
fs.mkdirSync(dir, { recursive: true });
return shell.openPath(dir);
});
ipcMain.handle("change-file", async () => {
const result = await dialog.showOpenDialog(mainWindow, {
title: "选择 TODOTREE 文件",
filters: [
{ name: "Markdown", extensions: ["md", "txt"] },
{ name: "All Files", extensions: ["*"] },
],
properties: ["openFile"],
});
if (!result.canceled && result.filePaths.length > 0) {
const loaded = fileStore.read(result.filePaths[0]);
if (!loaded.success) return loaded;
currentFilePath = result.filePaths[0];
saveConfig();
return loaded;
}
return null;
});
ipcMain.handle("get-file-path", () => currentFilePath);
ipcMain.handle("toggle-pin", () => {
isPinned = !isPinned;
transientEdit = false;
applyPinState();
saveConfig();
return isPinned;
});
// 锁定模式下点击输入框:临时摘回普通窗口拿键盘焦点,失焦后自动回到桌面层
ipcMain.handle("begin-transient-edit", () => {
if (!isPinned || !mainWindow) return false;
try {
desktopLayer.detach(mainWindow);
mainWindow.setFocusable(true);
transientEdit = true;
mainWindow.focus();
return true;
} catch (e) {
console.error("[desktop-layer] transient edit failed:", e.message);
return false;
}
});
ipcMain.handle("close-app", () => {
expectQuit = true;
app.quit();
});
ipcMain.handle("get-zone-heights", () => {
try {
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
return config.zoneHeights || {};
}
} catch (_) {}
return {};
});
ipcMain.handle("save-zone-heights", async (_event, heights) => {
saveConfig({ zoneHeights: heights });
});
ipcMain.handle("get-auto-start", () => {
return app.getLoginItemSettings().openAtLogin;
});
ipcMain.handle("toggle-auto-start", () => {
const current = app.getLoginItemSettings().openAtLogin;
const settings = { openAtLogin: !current, name: "TodoTree" };
// 开发模式跑的是 electron.exe,必须带上项目路径参数,否则开机弹出 Electron 默认页
if (!app.isPackaged) settings.args = [__dirname];
app.setLoginItemSettings(settings);
return !current;
});
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", () => {
// 挂在桌面树里的窗口会被 explorer 重启连带销毁:非用户主动关闭时自动重建
if (process.platform !== "darwin" && !expectQuit && recreateCount < 3) {
recreateCount += 1;
setTimeout(() => {
try {
createWindow();
} catch (e) {
console.error("recreate failed:", e.message);
}
}, 1000);
return;
}
app.quit();
});
// 桌面层看门狗:explorer 重启等意外后自动恢复
setInterval(() => {
if (!mainWindow || !isPinned || transientEdit) return;
try {
const result = desktopLayer.ensureAttached(mainWindow);
if (result === "container-lost") {
isPinned = false;
applyPinState();
}
} catch (_) {}
}, 5000);
}