-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathmain.ts
326 lines (270 loc) · 10.9 KB
/
main.ts
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
import { app, BrowserWindow, ipcMain, Menu, shell } from 'electron';
// Logging needs to be imported in main.ts also. Otherwise it just doesn't work anywhere else.
// See post by megahertz: https://github.com/megahertz/electron-log/issues/60
// "You need to import electron-log in the main process. Without it, electron-log doesn't works in a renderer process."
import log from 'electron-log';
import * as Store from 'electron-store';
import * as windowStateKeeper from 'electron-window-state';
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import * as url from 'url';
app.commandLine.appendSwitch('disable-color-correct-rendering');
log.create('main');
log.transports.file.resolvePath = () => path.join(app.getPath('userData'), 'logs', 'Knowte.log');
let mainWindow, serve;
const args = process.argv.slice(1);
serve = args.some((val) => val === '--serve');
// Workaround: Global does not allow setting custom properties.
// We need to cast it to "any" first.
const globalAny: any = global;
// Static folder is not detected correctly in production
if (process.env.NODE_ENV !== 'development') {
globalAny.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\');
}
// Workaround to send messages between Electron windows
const EventEmitter = require('events');
class GlobalEventEmitter extends EventEmitter {}
globalAny.globalEmitter = new GlobalEventEmitter();
// By default, electron-log logs only to file starting from level 'warn'. We also want 'info'.
log.transports.file.level = 'info';
const remoteMain = require('@electron/remote/main');
remoteMain.initialize();
function createMainWindow(): void {
const gotTheLock: boolean = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.focus();
}
});
Menu.setApplicationMenu(undefined);
// Load the previous state with fallback to defaults
const mainWindowState = windowStateKeeper({
defaultWidth: 850,
defaultHeight: 600,
});
// Create the window using the state information
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
backgroundColor: '#fff',
frame: windowhasFrame(),
icon: path.join(globalAny.__static, os.platform() === 'win32' ? 'icons/icon.ico' : 'icons/64x64.png'),
webPreferences: {
webSecurity: false,
nodeIntegration: true,
contextIsolation: false,
spellcheck: false,
},
show: false,
});
remoteMain.enable(mainWindow.webContents);
globalAny.windowHasFrame = windowhasFrame();
// Let us register listeners on the window, so we can update the state
// automatically (the listeners will be removed when the window is closed)
// and restore the maximized or full screen state
mainWindowState.manage(mainWindow);
if (serve) {
require('electron-reload')(__dirname, {
electron: require(`${__dirname}/node_modules/electron`),
});
mainWindow.loadURL('http://localhost:4200');
} else {
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, 'dist/index.html'),
protocol: 'file:',
slashes: true,
})
);
}
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store window
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = undefined;
// When the main window is closed, quit the app (This also closes all other windows)
app.quit();
});
// 'ready-to-show' doesn't fire on Windows in dev mode. In prod it seems to work.
// See: https://github.com/electron/electron/issues/7779
mainWindow.on('ready-to-show', () => {
mainWindow.show();
mainWindow.focus();
});
// Makes links open in external browser
const handleRedirect = (e: any, localUrl: string) => {
// Check that the requested url is not the current page
if (localUrl !== mainWindow.webContents.getURL()) {
e.preventDefault();
require('electron').shell.openExternal(localUrl);
}
};
mainWindow.webContents.on('will-navigate', handleRedirect);
mainWindow.webContents.on('new-window', handleRedirect);
mainWindow.webContents.on('before-input-event', (event, input) => {
if (input.key.toLowerCase() === 'f12') {
if (serve) {
mainWindow.webContents.toggleDevTools();
}
event.preventDefault();
}
});
}
}
function windowhasFrame(): boolean {
const settings: Store<any> = new Store();
if (!settings.has('useCustomTitleBar')) {
if (os.platform() === 'win32') {
settings.set('useCustomTitleBar', true);
} else {
settings.set('useCustomTitleBar', false);
}
}
return !settings.get('useCustomTitleBar');
}
function createNoteWindow(notePath: string, noteId: string, windowHasFrame: boolean): void {
const settings: Store<any> = new Store();
// Load the previous state with fallback to defaults
const noteWindowState = windowStateKeeper({
defaultWidth: 620,
defaultHeight: 400,
path: notePath,
file: `${noteId}.state`,
});
// Create the window using the state information
const noteWindow: BrowserWindow = new BrowserWindow({
x: noteWindowState.x,
y: noteWindowState.y,
width: noteWindowState.width,
height: noteWindowState.height,
backgroundColor: '#fff',
frame: windowHasFrame,
icon: path.join(globalAny.__static, os.platform() === 'win32' ? 'icons/icon.ico' : 'icons/64x64.png'),
webPreferences: {
webSecurity: false,
nodeIntegration: true,
contextIsolation: false,
spellcheck: settings.get('enableSpellChecker'),
},
show: true,
});
remoteMain.enable(noteWindow.webContents);
globalAny.windowHasFrame = windowHasFrame;
// noteWindow.webContents.openDevTools();
// Let us register listeners on the window, so we can update the state
// automatically (the listeners will be removed when the window is closed)
// and restore the maximized or full screen state
noteWindowState.manage(noteWindow);
if (serve) {
require('electron-reload')(__dirname, {
electron: require(`${__dirname}/node_modules/electron`),
});
noteWindow.loadURL(`http://localhost:4200#/note?id=${noteId}`);
} else {
noteWindow.loadURL(`file://${__dirname}/dist/index.html#/note?id=${noteId}`);
}
noteWindow.on('page-title-updated', (e) => {
// Prevents overwriting the window title by the title which is set in index.html
e.preventDefault();
});
noteWindow.on('ready-to-show', () => {
noteWindow.show();
noteWindow.focus();
});
// Makes links open in external browser
const handleRedirect = (e: any, localUrl: string) => {
// Check that the requested url is not the current page
if (localUrl !== noteWindow.webContents.getURL()) {
e.preventDefault();
require('electron').shell.openExternal(localUrl);
}
};
noteWindow.webContents.on('will-navigate', handleRedirect);
noteWindow.webContents.on('new-window', handleRedirect);
noteWindow.webContents.on('before-input-event', (event, input) => {
if (input.key.toLowerCase() === 'f12') {
if (serve) {
noteWindow.webContents.toggleDevTools();
}
event.preventDefault();
}
});
}
try {
log.info('[App] [main] +++ Starting +++');
// Open note windows
ipcMain.on('open-note-window', (event: any, arg: any) => {
createNoteWindow(arg.notePath, arg.noteId, arg.windowHasFrame);
});
// Print
ipcMain.on('print', (event: any, data: any) => {
const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
spellcheck: false,
},
});
win.loadURL(`file://${data.printHtmlFilePath}`);
win.webContents.on('did-finish-load', () => {
win.webContents.print({ silent: false, printBackground: true });
});
});
// PrintPDF
ipcMain.on('printToPDF', (event: any, data: any) => {
const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
spellcheck: false,
},
});
win.loadURL(`file://${data.printHtmlFilePath}`);
win.webContents.on('did-finish-load', async () => {
const pdfData: Buffer = await win.webContents.printToPDF({});
try {
await fs.writeFile(data.pdfFilePath, pdfData);
console.log('PDF generated successfully.');
shell.showItemInFolder(data.pdfFilePath);
} catch (error) {
console.log(`PDF generation failed. Error: ${error.message}`);
}
});
});
// 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', createMainWindow);
// Quit when all windows are closed.
app.on('window-all-closed', () => {
log.info('[App] [window-all-closed] +++ Stopping +++');
// On OS X 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.quit();
});
app.on('activate', () => {
// On OS X 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) {
createMainWindow();
}
});
} catch (error) {
// Catch Error
// throw error;
}