-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
408 lines (369 loc) · 12.7 KB
/
main.js
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
// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain, dialog, Menu, MenuItem} = require('electron')
const path = require('path')
const fs = require('fs')
const {platform} = require('os')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let isChangesSaved = true; // Default to true when the app starts
function forceRelaunch() {
app.relaunch()
app.quit()
}
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1000,
height: 800,
minHeight: 600,
minWidth: 800,
webPreferences: {
nodeIntegration: true,
contextIsolation: false // This is the default value anyway
},
icon: path.join(__dirname, 'brand/PBC_LOGO.ico'),
// No Menu
autoHideMenuBar: true,
// No Header
frame: false
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Comment out this area to enable DevTools
/////////////DEVTOOLS//////////////////////
//mainWindow.setMenu(null)
///////////////////////////////////////////
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
// is JSON, like this {"width": 800, "height": 600}
ipcMain.on('window-dimensions', (event, dimensions) => {
mainWindow.setSize(dimensions.width, dimensions.height)
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// Handle IPC messages from renderer process
ipcMain.on('message', (event, arg) => {
switch (arg) {
case 'open':
openFile()
break
case 'save':
saveFile()
break
case 'save-as':
saveFileAs()
break
case 'save-as-and-exit':
saveFileAsAndExit()
break
case 'exit':
if (isChangesSaved) {
app.quit()
} else {
exitApp()
}
break
case 'minimize':
mainWindow.minimize()
break
case 'maximize':
mainWindow.maximize()
break
case 'unmaximize':
mainWindow.unmaximize()
break
default:
console.log(arg)
// If contains "run-py|||path/to/file.py", run the python script
if (arg.includes('run-py|||')) {
let command = arg.split('|||')[1]
command = "python " + command
openPowerShellAndRunCommand(command)
} else if (arg.includes('run-node|||')) {
let command = arg.split('|||')[1]
command = "node " + command
openPowerShellAndRunCommand(command)
} else if (arg.includes('run-ruby|||')) {
let command = arg.split('|||')[1]
command = "ruby " + command
openPowerShellAndRunCommand(command)
} else if (arg.includes('run-java|||')) {
let command = arg.split('|||')[1]
command = "javac " + command + " && java " + command.split('.')[0]
openPowerShellAndRunCommand(command)
} else if (arg.includes('run-custom|||')) {
let command = arg.split('|||')[1]
openPowerShellAndRunCommand(command)
} else {
console.log('Unknown message: ' + arg)
}
}
})
// Open a file and send its content to the renderer process
function openFile() {
dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{name: 'Text Files', extensions: ['txt']},
{name: 'All Files', extensions: ['*']}
]
}).then(result => {
if (!result.canceled) {
let filePath = result.filePaths[0]
let fileName = path.basename(filePath)
let fileContent = fs.readFileSync(filePath, 'utf8')
mainWindow.webContents.send('file-opened', fileName, fileContent, filePath)
}
}).catch(err => {
console.log(err)
})
}
// exit application after user approves the options are either Save or Discard or cancel
function exitApp() {
const confirmSave = dialog.showMessageBoxSync(mainWindow, {
type: 'question',
buttons: ['Save', 'Discard', 'Cancel'],
defaultId: 0,
title: 'Save Changes',
message: 'Do you want to save changes before exiting?',
});
if (confirmSave === 0) {
// User clicked "Save", trigger the save process
saveFileAndExit()
} else if (confirmSave === 1) {
app.quit()
} else {
// User clicked "Cancel", do nothing or handle accordingly
console.log('Cancelled save');
}
}
// Save the current file
function saveFile() {
mainWindow.webContents.send('file-save')
}
function saveFileAndExit() {
mainWindow.webContents.send('file-save-and-exit')
}
// Save the current file as a new file
function saveFileAs() {
dialog.showSaveDialog(mainWindow, {
filters: [
{name: 'Text Files', extensions: ['txt']},
{name: 'All Files', extensions: ['*']}
]
}).then(result => {
if (!result.canceled) {
let filePath = result.filePath
mainWindow.webContents.send('file-save-as', filePath)
}
}).catch(err => {
console.log(err)
})
}
function saveFileAsAndExit() {
dialog.showSaveDialog(mainWindow, {
filters: [
{name: 'Text Files', extensions: ['txt']},
{name: 'All Files', extensions: ['*']}
]
}).then(result => {
if (!result.canceled) {
let filePath = result.filePath
mainWindow.webContents.send('file-save-as-and-exit', filePath)
}
}).catch(err => {
console.log(err)
})
}
// Receive the file content from the renderer process and write it to the file
ipcMain.on('file-content', (event, filePath, fileContent,saved) => {
fs.writeFile(filePath, fileContent, (err) => {
if (err) {
console.log(err)
} else {
console.log(saved);
isChangesSaved=saved;
console.log('File saved: ' + filePath)
console.log(isChangesSaved);
}
})
})
// Receive the file content from the renderer process and write it to the file then exit
ipcMain.on('file-content-and-exit', (event, filePath, fileContent) => {
fs.writeFile(filePath, fileContent, (err) => {
if (err) {
console.log(err)
} else {
console.log('File saved: ' + filePath)
app.quit()
}
})
})
ipcMain.on('editor-content-changed', (event, changedSaved) => {
// Editor content changed, set saved state to false
isChangesSaved = changedSaved;
console.log(changedSaved);
});
function openPowerShellAndRunCommand(command) {
const {exec} = require('child_process');
if (platform() === 'darwin') {
command = `osascript -e 'tell application "Terminal" to do script "${command}"'`;
} else if (platform() === 'win32') {
command = `start powershell.exe -NoExit -Command "${command}"`;
} else if (platform() === 'linux') {
command = `gnome-terminal -- bash -c "${command}; exec bash"`;
} else {
console.log('Unknown platform: ' + platform());
return;
}
const powershellProcess = exec(command, (err, stdout, stderr) => {});
powershellProcess.stdout.on('data', (data) => {
console.log(data.toString());
});
powershellProcess.stderr.on('data', (data) => {
console.error(data.toString());
});
powershellProcess.on('exit', (code) => {
console.log(`PowerShell process exited with code ${code}`);
});
}
async function tempWindow(htmlstring) {
let tempWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false // This is the default value anyway
},
icon: path.join(__dirname, 'brand/PBC_LOGO.ico')
})
var template = [
{
label: "Tools",
submenu: [
{
label: "Reload",
accelerator: "CmdOrCtrl+R",
click: function (item, focusedWindow) {
if (focusedWindow) {
// on reload, start fresh and close any old
// open secondary windows
if (focusedWindow.id === 1) {
BrowserWindow.getAllWindows().forEach(function (win) {
if (win.id > 1) {
win.close()
}
})
}
focusedWindow.reload()
}
}
},
{
label: "Toggle Full Screen",
accelerator: (function () {
if (process.platform === "darwin") {
return "Ctrl+Command+F"
} else {
return "F11"
}
})(),
click: function (item, focusedWindow) {
if (focusedWindow) {
focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
}
}
},
{
label: "Toggle Developer Tools",
accelerator: (function () {
if (process.platform === "darwin") {
return "Alt+Command+I"
} else {
return "Ctrl+Shift+I"
}
})(),
click: function (item, focusedWindow) {
if (focusedWindow) {
focusedWindow.toggleDevTools()
}
}
},
{
label: "Quit",
accelerator: "CmdOrCtrl+Q",
click: function () {
// Only close the temp window
tempWindow.close()
}
}
]
}
]
// function notifyEditorContentChanged() {
// ipcRenderer.send('editor-content-changed');
// }
// editor.on('change', () => {
// // Notify the main process about the content change
// notifyEditorContentChanged();
// });
Menu.setApplicationMenu(Menu.buildFromTemplate(template))
// If temp.html exists, delete it
if (fs.existsSync('temp.html')) {
fs.unlink('temp.html', (err) => {
if (err) {
console.log(err)
} else {
console.log('Deleted temp.html')
}
})
}
// Save the htmlstring to a temp file
fs.writeFileSync('temp.html', htmlstring)
// Load the temp file
tempWindow.loadFile('temp.html')
tempWindow.on('closed', function () {
tempWindow = null
})
}
// previewinwindow event, must run in async mode
ipcMain.on('previewinwindow', async (event, htmlstring) => {
tempWindow(htmlstring)
})
ipcMain.on('clear-preferences', (event) => {
// Delete preferences.json from the local directory
fs.unlink('preferences.json', (err) => {
if (err) {
console.log(err)
} else {
console.log('Deleted preferences.json')
}
})
forceRelaunch()
})