Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
269 lines (222 loc) · 6.56 KB
/
Copy pathmain.js
File metadata and controls
269 lines (222 loc) · 6.56 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
const { app, BrowserWindow, dialog, ipcMain } = require("electron");
const chokidar = require("chokidar");
const fs = require("fs");
const path = require("path");
const pkg = require("./package.json");
const pdfModule = require("./src/modules/pdf/pdf.js");
// Updater
const setupUpdater = require("./src/modules/update");
// Disable sandbox only for AppImage builds
if (process.env.APPIMAGE) {
app.commandLine.appendSwitch("no-sandbox");
}
let workspaceWatcher = null;
let currentWorkspacePath = null;
let mainWindow;
let lastKnownDirtyState = false;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1100,
height: 800,
webPreferences: {
preload: path.join(__dirname, "src", "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
},
});
// Remove all menus
mainWindow.setMenu(null);
mainWindow.setMenuBarVisibility(false);
mainWindow.setAutoHideMenuBar(true);
// Block DevTools shortcuts
mainWindow.webContents.on("before-input-event", (event, input) => {
if (
(input.key === "I" && input.control && input.shift) ||
input.key === "F12"
) {
event.preventDefault();
}
});
// Unsaved changes / workspace dirty failsafe
mainWindow.on("close", (event) => {
// Ask renderer for dirty state
mainWindow.webContents.send("workspace:isDirty:request");
// Prevent the window from closing until we decide
event.preventDefault();
// Give the renderer a moment to respond
setTimeout(() => {
if (lastKnownDirtyState) {
const choice = dialog.showMessageBoxSync(mainWindow, {
type: "warning",
buttons: ["Cancel", "Discard Changes"],
defaultId: 0,
cancelId: 0,
title: "Unsaved Changes",
message: "You have unsaved changes. Close SnapDock anyway?",
});
if (choice === 1) {
// User chose "Discard Changes"
mainWindow.destroy();
}
} else {
// Clean workspace → safe to close
mainWindow.destroy();
}
}, 50);
});
mainWindow.loadFile("index.html");
setupUpdater(mainWindow);
}
app.whenReady().then(createWindow);
// -----------------------------
// FILE OPERATIONS
// -----------------------------
ipcMain.handle("open-file", async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ["openFile"],
filters: [{ name: "Markdown", extensions: ["md"] }],
});
if (canceled || filePaths.length === 0) return null;
const filePath = filePaths[0];
const content = fs.readFileSync(filePath, "utf-8");
return { content, filePath };
});
ipcMain.handle("open-folder", async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ["openDirectory"],
});
if (canceled || filePaths.length === 0) return null;
const workspacePath = filePaths[0];
// Close previous watcher if exists
if (workspaceWatcher) {
workspaceWatcher.close();
}
currentWorkspacePath = workspacePath;
workspaceWatcher = chokidar.watch(workspacePath, {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true,
});
let ready = false;
let refreshTimeout = null;
workspaceWatcher
.on("ready", () => {
ready = true;
})
.on("all", () => {
if (!ready) return; // ignore initial scan events
clearTimeout(refreshTimeout);
refreshTimeout = setTimeout(() => {
if (mainWindow) {
mainWindow.webContents.send("workspace-updated");
}
}, 100); // debounce to avoid double-refresh on Windows
});
return workspacePath;
});
ipcMain.handle("save-file", async (event, filePath, content, suggestedName) => {
try {
if (!filePath) {
const { canceled, filePath: newFilePath } = await dialog.showSaveDialog({
title: "Save File",
defaultPath: suggestedName || "untitled",
});
if (canceled || !newFilePath) return false;
let finalPath = newFilePath;
// If user didn't provide any extension, add .md
if (!path.extname(finalPath)) {
finalPath += ".md";
}
fs.writeFileSync(finalPath, content, "utf-8");
return { newFilePath: finalPath };
}
fs.writeFileSync(filePath, content, "utf-8");
return true;
} catch (err) {
console.error("Failed to save file:", err);
return false;
}
});
ipcMain.handle("open-recent-file", async (event, filePath) => {
try {
return fs.readFileSync(filePath, "utf-8");
} catch (err) {
console.error("Failed to open recent file:", err);
return null;
}
});
ipcMain.handle("list-files", async (event, dirPath) => {
if (!dirPath || typeof dirPath !== "string") {
console.error("list-files called without valid path");
return [];
}
try {
const files = fs.readdirSync(dirPath, { withFileTypes: true });
return files.map((f) => ({
name: f.name,
type: f.isDirectory() ? "folder" : "file",
fullPath: path.join(dirPath, f.name),
}));
} catch (err) {
console.error("Failed to list files:", err);
return [];
}
});
ipcMain.handle("open-file-by-path", async (_, pathArg) => {
try {
return await fs.promises.readFile(pathArg, "utf8");
} catch {
return null;
}
});
ipcMain.handle("confirm-tab-close", async (event, title) => {
const choice = await dialog.showMessageBox({
type: "warning",
buttons: ["Cancel", "Discard Changes"],
defaultId: 0,
cancelId: 0,
title: "Unsaved Changes",
message: `"${title}" has unsaved changes. Close anyway?`,
});
return choice.response === 1;
});
// -----------------------------
// HELP DOCUMENT
// -----------------------------
ipcMain.handle("dialog:openHelp", async () => {
try {
const helpPath = path.join(
__dirname,
"assets",
"resources",
"docs",
"user_guide.md",
);
return fs.readFileSync(helpPath, "utf-8");
} catch (err) {
console.error("Failed to load help doc:", err);
return "# Help file not found";
}
});
// -----------------------------
// VERSION INFO
// -----------------------------
ipcMain.handle("get-version", async () => {
return {
version: pkg.version,
stage: pkg.buildStage,
date: pkg.releaseDate,
};
});
// -----------------------------
// PDF EXPORT
// -----------------------------
ipcMain.handle("export-pdf", (event, htmlContent) => {
pdfModule.exportCurrentMarkdown(htmlContent);
});
// -----------------------------
// WORKSPACE DIRTY STATE IPC
// -----------------------------
ipcMain.on("workspace:isDirty:response", (event, isDirty) => {
lastKnownDirtyState = isDirty;
});