-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipc-register-app-state.ts
More file actions
266 lines (237 loc) · 9.13 KB
/
Copy pathipc-register-app-state.ts
File metadata and controls
266 lines (237 loc) · 9.13 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
/**
* ipc-register-app-state.ts — Register app-state and file-picker IPC handlers.
*
* Responsibilities:
* - Register config/theme/code-cell/menu/file-picker IPC handlers.
* - Hydrate in-memory theme/code-cell caches from disk.
*
* Non-responsibilities:
* - Kernel lifecycle, project, tree, or modules IPC handling.
* - Push forwarding between comm router and renderer.
*/
import { app, dialog, ipcMain, shell, type BrowserWindow } from "electron";
import * as fs from "fs/promises";
import * as fsSync from "fs";
import * as path from "path";
import type { ConfigStore, PDVConfig } from "./config";
import type { Theme, WindowChromeInfo, WindowChromePlatform } from "./ipc";
import { IPC } from "./ipc";
import { getTopLevelMenuModel, popupTopLevelMenu, updateMenuEnabled, updateRecentProjectsMenu } from "./menu";
import { initAutoUpdater, checkForUpdates, downloadUpdate, installUpdate, openReleasesPage, getUpdateStatus } from "./auto-updater";
import { isQuitting } from "./app";
let savedThemes: Theme[] = [];
interface RegisterAppStateIpcHandlersOptions {
win: BrowserWindow;
configStore: ConfigStore;
readConfig: (configStore: ConfigStore) => PDVConfig;
themesDir: string;
stateDir: string;
/** Flips the close-guard flag in `app.ts` so the next `win.close()` proceeds. */
setAllowClose: (allow: boolean) => void;
/** Called after config:set with the old and new config values. */
onConfigChanged?: (prev: PDVConfig, next: PDVConfig) => void;
}
function getWindowChromePlatform(): WindowChromePlatform {
if (process.platform === "darwin") return "macos";
if (process.platform === "linux") return "linux";
return "windows";
}
function buildWindowChromeInfo(win: BrowserWindow): WindowChromeInfo {
const platform = getWindowChromePlatform();
return {
platform,
showCustomTitleBar: platform === "macos" || platform === "linux",
showMenuBar: platform === "linux",
showWindowControls: platform === "linux",
isMaximized: win.isMaximized() || win.isFullScreen(),
};
}
function loadThemesFromDisk(themesDir: string): void {
if (savedThemes.length > 0) {
return;
}
if (!fsSync.existsSync(themesDir)) {
try {
fsSync.mkdirSync(themesDir, { recursive: true });
console.log(`[ipc-register-app-state] No themes directory found, created ${themesDir}`);
} catch (mkdirErr) {
console.warn(`[ipc-register-app-state] Unable to create themes directory: ${themesDir}`, mkdirErr);
}
return;
}
try {
const entries = fsSync.readdirSync(themesDir);
for (const entry of entries) {
if (!entry.endsWith(".json")) continue;
try {
const raw = fsSync.readFileSync(path.join(themesDir, entry), "utf8");
const parsed = JSON.parse(raw) as unknown;
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
const obj = parsed as Record<string, unknown>;
if (typeof obj.name === "string" && obj.colors && typeof obj.colors === "object") {
savedThemes.push({ name: obj.name, colors: obj.colors as Record<string, string> });
}
}
} catch (error) {
console.warn(
`[ipc-register-app-state] Skipping unreadable theme file: ${entry}`,
error
);
}
}
} catch (error) {
console.warn(
`[ipc-register-app-state] Unable to read themes directory: ${themesDir}`,
error
);
}
}
/**
* Register app-state IPC handlers (config/themes/code-cells/menu/files).
*
* @param options - Handler dependencies and local state paths.
* @returns Nothing.
* @throws {Error} Propagates filesystem or dialog errors from handler execution.
*/
export function registerAppStateIpcHandlers(
options: RegisterAppStateIpcHandlersOptions
): void {
const { win, configStore, readConfig, themesDir, stateDir, setAllowClose, onConfigChanged } = options;
fs.mkdir(themesDir, { recursive: true }).catch((error) => {
console.warn(
`[ipc-register-app-state] Unable to create themes directory: ${themesDir}`,
error
);
});
fs.mkdir(stateDir, { recursive: true }).catch((error) => {
console.warn(
`[ipc-register-app-state] Unable to create state directory: ${stateDir}`,
error
);
});
loadThemesFromDisk(themesDir);
const pushWindowChromeState = (): void => {
if (win.isDestroyed()) {
return;
}
win.webContents.send(IPC.push.chromeStateChanged, buildWindowChromeInfo(win));
};
win.on("maximize", pushWindowChromeState);
win.on("unmaximize", pushWindowChromeState);
win.on("enter-full-screen", pushWindowChromeState);
win.on("leave-full-screen", pushWindowChromeState);
ipcMain.handle(IPC.config.get, async () => readConfig(configStore));
ipcMain.handle(IPC.about.getVersion, () => app.getVersion());
// Auto-updater
initAutoUpdater(win, configStore);
ipcMain.handle(IPC.updater.checkForUpdates, async () => { await checkForUpdates(configStore); });
ipcMain.handle(IPC.updater.downloadUpdate, async () => { await downloadUpdate(); });
ipcMain.handle(IPC.updater.installUpdate, async () => { installUpdate(); });
ipcMain.handle(IPC.updater.openReleasesPage, async () => { await openReleasesPage(); });
ipcMain.handle(IPC.updater.getStatus, async () => getUpdateStatus());
ipcMain.handle(IPC.config.set, async (_event, updates: Partial<PDVConfig>) => {
const prev = readConfig(configStore);
const merged: PDVConfig = { ...prev, ...updates };
for (const key of Object.keys(updates) as Array<keyof PDVConfig>) {
const value = updates[key];
if (value !== undefined) {
configStore.set(key, value);
}
}
const next = { ...merged, ...configStore.getAll() };
onConfigChanged?.(prev, next);
return next;
});
ipcMain.handle(IPC.themes.get, async () => savedThemes);
ipcMain.handle(IPC.themes.save, async (_event, theme: Theme) => {
const existing = savedThemes.findIndex((entry) => entry.name === theme.name);
if (existing >= 0) {
savedThemes[existing] = theme;
} else {
savedThemes = [...savedThemes, theme];
}
const safeName = theme.name.replace(/[^a-zA-Z0-9_\-. ]/g, "_");
const filePath = path.join(themesDir, `${safeName}.json`);
await fs.writeFile(filePath, JSON.stringify(theme, null, 2), "utf8");
return true;
});
ipcMain.handle(IPC.themes.openDir, async () => {
await fs.mkdir(themesDir, { recursive: true });
return shell.openPath(themesDir);
});
ipcMain.handle(IPC.menu.updateRecentProjects, async (_event, paths: string[]) => {
updateRecentProjectsMenu(Array.isArray(paths) ? paths : []);
return true;
});
ipcMain.handle(IPC.menu.updateEnabled, async (_event, state: Record<string, boolean>) => {
updateMenuEnabled(state);
return true;
});
ipcMain.handle(IPC.menu.getModel, async () => getTopLevelMenuModel());
ipcMain.handle(IPC.menu.popup, async (_event, menuId: "file" | "edit" | "view" | "window", x: number, y: number) =>
popupTopLevelMenu(menuId, x, y)
);
ipcMain.handle(IPC.chrome.getInfo, async () => buildWindowChromeInfo(win));
ipcMain.handle(IPC.chrome.minimize, async () => {
win.minimize();
return true;
});
ipcMain.handle(IPC.chrome.toggleMaximize, async () => {
if (win.isMaximized()) {
win.unmaximize();
} else {
win.maximize();
}
return win.isMaximized();
});
ipcMain.handle(IPC.chrome.close, async () => {
// Route through the same close-confirmation flow as the OS-level close
// (`win.on('close')` in app.ts) so the title-bar X also prompts about
// unsaved changes. The renderer will call `IPC.app.confirmClose` once
// the user resolves the prompt.
if (!win.isDestroyed()) {
win.webContents.send(IPC.push.requestClose);
}
return true;
});
ipcMain.handle(IPC.app.confirmClose, async () => {
setAllowClose(true);
// During a real quit (Cmd+Q, autoUpdater restart, OS logout), call
// app.quit() instead of win.close(). app.quit() will close the window
// itself (the close handler passes through because allowClose is set),
// then will-quit runs kernel cleanup. Calling both win.close() and
// app.quit() in the same tick re-enters the quit machinery and breaks
// electron-updater on macOS.
if (isQuitting()) {
app.quit();
return;
}
if (!win.isDestroyed()) {
win.close();
}
});
ipcMain.handle(IPC.files.pickExecutable, async () => {
const result = await dialog.showOpenDialog({ properties: ["openFile"] });
if (result.canceled || result.filePaths.length === 0) {
return null;
}
return result.filePaths[0] ?? null;
});
ipcMain.handle(IPC.files.pickFile, async () => {
const result = await dialog.showOpenDialog({ properties: ["openFile"] });
if (result.canceled || result.filePaths.length === 0) {
return null;
}
return result.filePaths[0] ?? null;
});
ipcMain.handle(IPC.files.pickDirectory, async (_event, defaultPath?: string) => {
const result = await dialog.showOpenDialog({
properties: ["openDirectory", "createDirectory"],
defaultPath: defaultPath || undefined,
});
if (result.canceled || result.filePaths.length === 0) {
return null;
}
return result.filePaths[0] ?? null;
});
}