-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
444 lines (385 loc) · 11.7 KB
/
main.js
File metadata and controls
444 lines (385 loc) · 11.7 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
438
439
440
441
442
443
444
const { app, BrowserWindow, ipcMain, dialog, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
const isDev = require('electron-is-dev');
// Initialize environment
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
app.allowRendererProcessReuse = true;
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
},
show: false,
backgroundColor: '#1e1e1e', // Dark background color
});
// Load the app
if (isDev) {
console.log('Running in development mode');
mainWindow.loadURL('http://localhost:3002');
} else {
// Production - load built files with a proper file URL format
const indexPath = path.join(__dirname, 'build', 'index.html');
const fileUrl = `file://${indexPath.replace(/\\/g, '/')}`;
console.log('Loading URL:', fileUrl);
mainWindow.loadURL(fileUrl);
}
mainWindow.on('ready-to-show', () => {
mainWindow.show();
});
mainWindow.on('closed', () => {
mainWindow = null;
});
// Create the application menu
const template = [
{
label: 'File',
submenu: [
{
label: 'Create New',
accelerator: 'CmdOrCtrl+N',
click: () => {
mainWindow.webContents.send('create-new-file');
}
},
{ type: 'separator' },
{
label: 'Open Folder',
accelerator: 'CmdOrCtrl+O',
click: async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (result.filePaths.length > 0) {
mainWindow.webContents.send('open-directory', result.filePaths[0]);
}
}
},
{ type: 'separator' },
{ role: 'quit' }
]
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' }
]
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
}
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
// Add event listeners for IPC events
ipcMain.on('open-directory-dialog', async (event) => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (result.filePaths.length > 0) {
mainWindow.webContents.send('open-directory', result.filePaths[0]);
}
});
ipcMain.on('create-new-file-request', (event, targetDir) => {
mainWindow.webContents.send('create-new-file-request', targetDir);
});
// Delete a directory recursively
function deleteFolderRecursive(directoryPath) {
if (fs.existsSync(directoryPath)) {
fs.readdirSync(directoryPath).forEach((file) => {
const curPath = path.join(directoryPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
// Recursive
deleteFolderRecursive(curPath);
} else {
// Delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(directoryPath);
}
}
// Normalize paths to handle Windows backslashes correctly
function normalizePath(filePath) {
// Convert Windows backslashes to forward slashes for consistent path handling
return filePath.replace(/\\/g, '/');
}
// Helper function to get all files in a directory recursively
function getAllFilesInDirectory(dirPath, allFiles = [], depth = 0) {
// Limit recursion depth to prevent excessive traversal
const MAX_DEPTH = 2;
if (!dirPath || dirPath === '' || !fs.existsSync(dirPath) || depth > MAX_DEPTH) {
return allFiles;
}
try {
const normalizedDirPath = normalizePath(dirPath);
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
entries.forEach(entry => {
const fullPath = path.join(dirPath, entry.name);
const normalizedFullPath = normalizePath(fullPath);
try {
const stats = fs.statSync(fullPath);
if (entry.isDirectory()) {
// Add this directory to our results
allFiles.push({
name: entry.name,
isDirectory: true,
path: normalizedFullPath,
extension: null,
lastModified: stats.mtime.getTime(),
size: stats.size,
children: [] // Add a children array to hold subdirectory contents
});
// Recursively get subdirectory contents if not at max depth
if (depth < MAX_DEPTH) {
const subFiles = getAllFilesInDirectory(fullPath, [], depth + 1);
// Store the subdirectory's contents in the children array
const dirIndex = allFiles.findIndex(item => item.path === normalizedFullPath);
if (dirIndex !== -1) {
allFiles[dirIndex].children = subFiles;
}
}
} else {
// Add the file
allFiles.push({
name: entry.name,
isDirectory: false,
path: normalizedFullPath,
extension: path.extname(entry.name),
lastModified: stats.mtime.getTime(),
size: stats.size
});
}
} catch (err) {
console.error(`Error processing ${fullPath}:`, err);
}
});
return allFiles;
} catch (error) {
console.error(`Error reading directory ${dirPath}:`, error);
return allFiles;
}
}
// File system operations
ipcMain.handle('open-directory-dialog', async () => {
try {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
return result.filePaths[0];
} catch (error) {
console.error('Error opening directory dialog:', error);
return null;
}
});
ipcMain.handle('read-directory', async (event, directoryPath) => {
try {
if (!directoryPath || directoryPath === '' || !fs.existsSync(directoryPath)) {
console.error(`Directory does not exist or is empty: ${directoryPath}`);
return [];
}
console.log(`Reading directory: ${directoryPath}`);
// Use our recursive function to get all files and folders
const allFiles = getAllFilesInDirectory(directoryPath, []);
console.log(`Found ${allFiles.length} files and folders in ${directoryPath}`);
return allFiles;
} catch (error) {
console.error('Error reading directory:', error);
return [];
}
});
ipcMain.handle('read-file', async (event, filePath) => {
try {
if (!filePath || !fs.existsSync(filePath)) {
throw new Error(`File does not exist: ${filePath}`);
}
console.log(`Reading file: ${filePath}`);
const content = fs.readFileSync(filePath, 'utf8');
return content;
} catch (error) {
console.error('Error reading file:', error);
return '';
}
});
ipcMain.handle('write-file', async (event, filePath, content) => {
try {
if (!filePath) {
throw new Error('No file path provided');
}
console.log(`Writing to file: ${filePath}`);
fs.writeFileSync(filePath, content, 'utf8');
return true;
} catch (error) {
console.error('Error writing file:', error);
return false;
}
});
ipcMain.handle('create-new-file', async (event, directoryPath, fileName) => {
try {
if (!directoryPath) {
throw new Error('No directory selected');
}
if (!fs.existsSync(directoryPath)) {
throw new Error(`Directory does not exist: ${directoryPath}`);
}
const filePath = path.join(directoryPath, fileName);
const normalizedPath = normalizePath(filePath);
console.log(`Creating new file: ${filePath}`);
// Check if file already exists
if (fs.existsSync(filePath)) {
throw new Error('File already exists');
}
// Create empty file
fs.writeFileSync(filePath, '', 'utf8');
return {
success: true,
filePath: normalizedPath
};
} catch (error) {
console.error('Error creating new file:', error);
return {
success: false,
error: error.message
};
}
});
// Create a new folder
ipcMain.handle('create-folder', async (event, parentPath, folderName) => {
try {
if (!parentPath) {
throw new Error('No parent directory specified');
}
if (!fs.existsSync(parentPath)) {
throw new Error(`Parent directory does not exist: ${parentPath}`);
}
const newFolderPath = path.join(parentPath, folderName);
const normalizedPath = normalizePath(newFolderPath);
console.log(`Creating new folder: ${newFolderPath}`);
// Check if folder already exists
if (fs.existsSync(newFolderPath)) {
throw new Error('Folder already exists');
}
// Create the folder
fs.mkdirSync(newFolderPath);
return {
success: true,
folderPath: normalizedPath
};
} catch (error) {
console.error('Error creating folder:', error);
return {
success: false,
error: error.message
};
}
});
// Delete a file
ipcMain.handle('delete-file', async (event, filePath) => {
try {
if (!filePath) {
throw new Error('No file path provided');
}
if (!fs.existsSync(filePath)) {
throw new Error(`File does not exist: ${filePath}`);
}
console.log(`Deleting file: ${filePath}`);
fs.unlinkSync(filePath);
return {
success: true
};
} catch (error) {
console.error('Error deleting file:', error);
return {
success: false,
error: error.message
};
}
});
// Delete a folder and all its contents
ipcMain.handle('delete-folder', async (event, folderPath) => {
try {
if (!folderPath) {
throw new Error('No folder path provided');
}
if (!fs.existsSync(folderPath)) {
throw new Error(`Folder does not exist: ${folderPath}`);
}
console.log(`Deleting folder: ${folderPath}`);
deleteFolderRecursive(folderPath);
return {
success: true
};
} catch (error) {
console.error('Error deleting folder:', error);
return {
success: false,
error: error.message
};
}
});
// Add a new handler to read a specific directory
ipcMain.handle('read-subdirectory', async (event, directoryPath) => {
try {
if (!directoryPath || directoryPath === '' || !fs.existsSync(directoryPath)) {
console.error(`Subdirectory does not exist or is empty: ${directoryPath}`);
return [];
}
console.log(`Reading subdirectory: ${directoryPath}`);
const files = [];
const entries = fs.readdirSync(directoryPath, { withFileTypes: true });
entries.forEach(entry => {
const fullPath = path.join(directoryPath, entry.name);
const normalizedFullPath = normalizePath(fullPath);
try {
const stats = fs.statSync(fullPath);
files.push({
name: entry.name,
isDirectory: entry.isDirectory(),
path: normalizedFullPath,
extension: entry.isDirectory() ? null : path.extname(entry.name),
lastModified: stats.mtime.getTime(),
size: stats.size
});
} catch (err) {
console.error(`Error processing ${fullPath}:`, err);
}
});
return files;
} catch (error) {
console.error('Error reading subdirectory:', error);
return [];
}
});