-
Notifications
You must be signed in to change notification settings - Fork 471
/
main.js
executable file
·425 lines (386 loc) · 11.9 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
require('@electron/remote/main').initialize()
const os = require('os')
const electron = require('electron')
const nconf = require('nconf')
const windowStateKeeper = require('electron-window-state')
const electronLocalshortcut = require('electron-localshortcut')
const Menu = electron.Menu
const app = electron.app
const dialog = electron.dialog
const Tray = electron.Tray
const ipcMain = electron.ipcMain
const BrowserWindow = electron.BrowserWindow
let willQuitApp = false
// http://electron.rocks/sharing-between-main-and-renderer-process/
// Set up the logger
const logger = require('winston')
const path = require('path')
const fs = require('fs')
const isDev = require('electron-is-dev')
const defaultConfig = require('./configs/defaultConfig')
const appInfo = require('./package.json')
const { autoUpdater } = require("electron-updater")
autoUpdater.logger = logger
autoUpdater.autoDownload = nconf.get('autoUpdate')
initGlobalConfigs()
initGlobalLogger()
logger.info(`\n\n----- ${appInfo.name} v${appInfo.version} ${os.platform()}-----\n`)
logger.info(`[conf] Looking for .leptonrc at ${getConfigPath()}`)
logger.info('[conf] The resolved configuration is ...')
for (const key of Object.getOwnPropertyNames(defaultConfig)) {
logger.info(`"${key}": ${JSON.stringify(nconf.get(key))}`)
}
let mainWindow = null
let miniWindow = null
let operationType = 0;
const shortcuts = nconf.get('shortcuts')
function getConfigPath() {
if (process && process.env && process.env.XDG_CONFIG_HOME) {
return path.join(process.env.XDG_CONFIG_HOME, '.leptonrc'
} else {
return path.join(app.getPath('home'), '.leptonrc')
}
}
function createWindowAndAutoLogin () {
createWindow(true)
}
function createWindow (autoLogin) {
console.time('init')
// Load the previous state with fallback to defaults
let mainWindowState = windowStateKeeper({
defaultWidth: 1100,
defaultHeight: 800
})
const webPreferences = {
nodeIntegration: true,
enableRemoteModule: true,
// https://github.com/electron/electron/blob/main/docs/tutorial/context-isolation.md
// TODO: migrate and enable context isolation
contextIsolation: false
}
mainWindow = new BrowserWindow({
width: mainWindowState.width,
height: mainWindowState.height,
x: mainWindowState.x,
y: mainWindowState.y,
minWidth: 636,
minHeight: 609,
// titleBarStyle: 'hidden',
backgroundColor: '#808080',
show: false,
icon: path.join(__dirname, '/icon/icon.png'),
webPreferences
})
if (autoLogin) {
logger.debug('-----> registering login-page-ready listener')
// Set up a one-time listener for 'login-page-ready'
ipcMain.on('login-page-ready', () => {
logger.info('[signal] sending auto-login signal')
mainWindow.webContents.send('auto-login')
ipcMain.removeAllListeners('login-page-ready')
})
}
ipcMain.on('session-ready', () => {
setUpTouchBar()
})
ipcMain.on('session-destroyed', () => {
mainWindow.setTouchBar(null)
})
// 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);
mainWindow.webContents.on('will-navigate', (e, url) => {
e.preventDefault()
electron.shell.openExternal(url)
})
mainWindow.once('ready-to-show', () => {
mainWindow.show()
console.timeEnd('init')
autoUpdater.on('error', data => {
logger.debug('[autoUpdater] error ' + JSON.stringify(data))
})
autoUpdater.on('update-not-available', () => {
logger.debug('[autoUpdater] update-not-available')
})
autoUpdater.on('update-available', (info) => {
logger.debug('[autoUpdater] update-available. ' + mainWindow)
global.newVersionInfo = info
mainWindow && mainWindow.webContents.send('update-available')
})
//Only run auto update checker in production.
if (!isDev && !appInfo.version.includes('alpha')) {
autoUpdater.checkForUpdates()
}
})
mainWindow.on('close', (e) => {
if (operationType == 0) {
const choice = dialog.showMessageBoxSync(mainWindow, {
type: 'info',
title: 'Quit',
defaultId: 0,
cancelId: 0,
message: 'Are you sure?',
buttons: ['Nerver Mind', 'Minimize to disk', 'Quit']
})
if (choice === 1) {
if (miniWindow) {
mainWindow.hide() // 调用 最小化实例方法
} else {
setTray(app, mainWindow)
}
e.preventDefault()
operationType = 1
} else if (choice === 2) {
if (os.platform() === 'darwin' && !willQuitApp) {
// Hide the window when users close the window on macOS
e.preventDefault()
mainWindow.hide()
} else {
mainWindow = null
}
operationType = 2
} else {
e.preventDefault()
}
}
if (operationType == 1) {
if (miniWindow) {
mainWindow.hide() // 调用 最小化实例方法
} else {
setTray(app, mainWindow)
}
e.preventDefault()
}
if (operationType == 2) {
if (os.platform() === 'darwin' && !willQuitApp) {
// Hide the window when users close the window on macOS
e.preventDefault()
mainWindow.hide()
} else {
mainWindow = null
}
}
});
const ContextMenu = require('electron-context-menu')
ContextMenu({
prepend: (params, mainWindow) => []
})
mainWindow.loadURL(`file://${__dirname}/index.html`)
setUpApplicationMenu()
// mainWindow.webContents.openDevTools()
global.mainWindow = mainWindow
}
app.on('ready', () => {
// createWindow()
autoUpdater.checkForUpdatesAndNotify()
createWindowAndAutoLogin()
})
app.on('window-all-closed', () => {
logger.info('The app window is closed')
if (process.platform !== 'darwin') app.quit()
mainWindow = null
})
/* 'before-quit' is emitted when Electron receives
* the signal to exit and wants to start closing windows */
app.on('before-quit', (event) => {
if (operationType == 2) {
willQuitApp = true
try {
// If we launch the app and close it quickly, we might run into a
// situation where electronLocalshortcut is not initialized.
if (mainWindow && electronLocalshortcut) {
electronLocalshortcut.unregisterAll(mainWindow)
}
} catch (e) {
logger.error(e)
}
}else{
event.preventDefault()
}
})
// 'activate' is emitted when the user clicks the Dock icon (OS X).
// It is a macOS specific signal mapped to 'applicationShouldHandleReopen' event
app.on('activate', () => mainWindow && mainWindow.show())
function setUpApplicationMenu () {
// Create the Application's main menu
let { mainMenuTemplate } = require('./app/utilities/menu/mainMenu')
let gistMenu = {
label: 'Gist',
submenu: [
{
label: 'New Gist',
accelerator: shortcuts.keyNewGist,
click: (item, mainWindow) => mainWindow && mainWindow.send('new-gist')
},
{
label: 'Edit Gist',
accelerator: shortcuts.keyEditGist,
click: (item, mainWindow) => mainWindow && mainWindow.send('edit-gist')
},
{
label: 'Delete Gist',
accelerator: shortcuts.keyDeleteGist,
click: (item, mainWindow) => mainWindow && mainWindow.send('delete-gist-check')
},
{
label: 'Submit Gist',
accelerator: shortcuts.keySubmitGist,
click: (item, mainWindow) => mainWindow && mainWindow.send('submit-gist')
},
{
label: 'Sync Gist',
accelerator: shortcuts.keySyncGists,
click: (item, mainWindow) => mainWindow && mainWindow.send('sync-gists')
},
{
label: 'Exit Editor',
accelerator: shortcuts.keyEditorExit,
click: (item, mainWindow) => mainWindow && mainWindow.send('exit-editor')
},
{
label: 'Immersive Mode',
accelerator: shortcuts.keyImmersiveMode,
click: (item, mainWindow) => mainWindow && mainWindow.send('immersive-mode')
},
{
label: 'Back to Normal Mode',
accelerator: 'Escape',
click: (item, mainWindow) => mainWindow && mainWindow.send('back-to-normal-mode')
},
{
label: 'Dashboard',
accelerator: shortcuts.keyDashboard,
click: (item, mainWindow) => mainWindow && mainWindow.send('dashboard')
},
{
label: 'About',
accelerator: shortcuts.keyAboutPage,
click: (item, mainWindow) => mainWindow && mainWindow.send('about-page')
},
{
label: 'Search',
accelerator: shortcuts.keyShortcutForSearch,
click: (item, mainWindow) => mainWindow && mainWindow.send('search-gist')
}
]
}
let template = [...mainMenuTemplate, gistMenu]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
}
function setUpTouchBar() {
const makeIcon = name => {
return electron.nativeImage
.createFromPath(path.join(__dirname, `/build/touchbar/${name}.png`))
.resize({
width: 16,
height: 16
})
}
const { TouchBar } = electron
const { TouchBarButton, TouchBarSpacer, TouchBarGroup } = TouchBar
const touchBar = new TouchBar({
items: [
new TouchBarButton({
label: "Immersive",
icon: makeIcon("immersive"),
iconPosition: "left",
click: () => mainWindow.send("immersive-mode")
}),
new TouchBarButton({
label: "Sync",
icon: makeIcon("sync"),
iconPosition: "left",
click: () => mainWindow.send("sync-gists")
}),
new TouchBarButton({
label: "Search",
icon: makeIcon("search"),
iconPosition: "left",
click: () => mainWindow.send("search-gist")
}),
new TouchBarSpacer({
size: "flexible"
}),
new TouchBarButton({
label: "New",
icon: makeIcon("new"),
iconPosition: "left",
click: () => mainWindow.send("new-gist")
}),
new TouchBarButton({
label: "Edit",
icon: makeIcon("edit"),
iconPosition: "left",
click: () => mainWindow.send("edit-gist")
})
]
})
mainWindow.setTouchBar(touchBar)
}
function initGlobalConfigs () {
const configFilePath = getConfigPath()
logger.info(`[conf] Looking for .leptonrc at ${configFilePath}`)
nconf.argv().env()
try {
nconf.file({ file: configFilePath })
} catch (error) {
logger.error('[.leptonrc] Please correct the mistakes in your configuration file: [%s].\n' + error, configFilePath)
}
nconf.defaults(defaultConfig)
global.conf = nconf
global.configFilePath = configFilePath
}
function initGlobalLogger () {
logger.level = nconf.get('logger:level')
const appFolder = app.getPath('userData')
if (!fs.existsSync(appFolder)) {
fs.mkdirSync(appFolder)
}
const logFolder = path.join(app.getPath('userData'), 'logs')
if (!fs.existsSync(logFolder)) {
fs.mkdirSync(logFolder)
}
const logFile = new Date().toISOString().replace(/:/g, '.') + '.log'
const logFilePath = path.join(logFolder, logFile)
logger.add(logger.transports.File, {
json: false,
exitOnError: false,
filename: logFilePath,
timestamp: true })
global.logger = logger
global.logFilePath = logFilePath
}
function setTray(app, mainWindow) {
if (miniWindow) {
mainWindow.hide()
return
}
const trayMenuTemplate = [
{
label: 'Open Window',
click: () => {
mainWindow.show()
}
},
{
label: 'Quit',
click: () => {
operationType = 2
if (process.platform !== 'darwin') app.quit()
mainWindow = null
}
}
]
const iconPath = path.join(__dirname, 'build/icon/icon.png')
miniWindow = new Tray(iconPath)
const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)
mainWindow.hide()
miniWindow.setToolTip('Lepton')
miniWindow.setContextMenu(contextMenu)
miniWindow.on('double-click', () => {
mainWindow.show()
})
return miniWindow
}