-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
main.ts
471 lines (403 loc) · 11.7 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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import '../lib/logging/main/install'
import { app, Menu, ipcMain, BrowserWindow, shell } from 'electron'
import * as Fs from 'fs'
import { AppWindow } from './app-window'
import { buildDefaultMenu, MenuEvent, findMenuItemByID } from './menu'
import { shellNeedsPatching, updateEnvironmentForProcess } from '../lib/shell'
import { parseAppURL } from '../lib/parse-app-url'
import { handleSquirrelEvent } from './squirrel-updater'
import { fatalError } from '../lib/fatal-error'
import { IMenuItemState } from '../lib/menu-update'
import { LogLevel } from '../lib/logging/log-level'
import { log as writeLog } from './log'
import { openDirectorySafe } from './shell'
import { reportError } from './exception-reporting'
import {
enableSourceMaps,
withSourceMappedStack,
} from '../lib/source-map-support'
import { now } from './now'
import { showUncaughtException } from './show-uncaught-exception'
import { IMenuItem } from '../lib/menu-item'
import { buildContextMenu } from './menu/build-context-menu'
enableSourceMaps()
let mainWindow: AppWindow | null = null
const launchTime = now()
let preventQuit = false
let readyTime: number | null = null
type OnDidLoadFn = (window: AppWindow) => void
/** See the `onDidLoad` function. */
let onDidLoadFns: Array<OnDidLoadFn> | null = []
function handleUncaughtException(error: Error) {
preventQuit = true
if (mainWindow) {
mainWindow.destroy()
mainWindow = null
}
const isLaunchError = !mainWindow
showUncaughtException(isLaunchError, error)
}
process.on('uncaughtException', (error: Error) => {
error = withSourceMappedStack(error)
reportError(error)
handleUncaughtException(error)
})
let handlingSquirrelEvent = false
if (__WIN32__ && process.argv.length > 1) {
const arg = process.argv[1]
const promise = handleSquirrelEvent(arg)
if (promise) {
handlingSquirrelEvent = true
promise
.catch(e => {
log.error(`Failed handling Squirrel event: ${arg}`, e)
})
.then(() => {
app.quit()
})
} else {
handlePossibleProtocolLauncherArgs(process.argv)
}
}
function handleAppURL(url: string) {
log.info('Processing protocol url')
const action = parseAppURL(url)
onDidLoad(window => {
// This manual focus call _shouldn't_ be necessary, but is for Chrome on
// macOS. See https://github.com/desktop/desktop/issues/973.
window.focus()
window.sendURLAction(action)
})
}
let isDuplicateInstance = false
// If we're handling a Squirrel event we don't want to enforce single instance.
// We want to let the updated instance launch and do its work. It will then quit
// once it's done.
if (!handlingSquirrelEvent) {
isDuplicateInstance = app.makeSingleInstance((args, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore()
}
if (!mainWindow.isVisible()) {
mainWindow.show()
}
mainWindow.focus()
}
handlePossibleProtocolLauncherArgs(args)
})
if (isDuplicateInstance) {
app.quit()
}
}
if (shellNeedsPatching(process)) {
updateEnvironmentForProcess()
}
app.on('will-finish-launching', () => {
// macOS only
app.on('open-url', (event, url) => {
event.preventDefault()
handleAppURL(url)
})
})
/**
* Attempt to detect and handle any protocol handler arguments passed
* either via the command line directly to the current process or through
* IPC from a duplicate instance (see makeSingleInstance)
*
* @param args Essentially process.argv, i.e. the first element is the exec
* path
*/
function handlePossibleProtocolLauncherArgs(args: ReadonlyArray<string>) {
log.info(`Received possible protocol arguments: ${args.length}`)
if (__WIN32__) {
// We register our protocol handler callback on Windows as
// [executable path] --protocol-launcher -- "%1" meaning that any
// url data comes after we've stopped processing arguments. We check
// for that exact scenario here before doing any processing. If there's
// more than 4 args because of a malformed url then we bail out.
if (
args.length === 4 &&
args[1] === '--protocol-launcher' &&
args[2] === '--'
) {
handleAppURL(args[3])
}
} else if (args.length > 1) {
handleAppURL(args[1])
}
}
/**
* Wrapper around app.setAsDefaultProtocolClient that adds our
* custom prefix command line switches on Windows that prevents
* command line argument parsing after the `--`.
*/
function setAsDefaultProtocolClient(protocol: string) {
if (__WIN32__) {
app.setAsDefaultProtocolClient(protocol, process.execPath, [
'--protocol-launcher',
'--',
])
} else {
app.setAsDefaultProtocolClient(protocol)
}
}
if (process.env.GITHUB_DESKTOP_DISABLE_HARDWARE_ACCELERATION) {
log.info(
`GITHUB_DESKTOP_DISABLE_HARDWARE_ACCELERATION environment variable set, disabling hardware acceleration`
)
app.disableHardwareAcceleration()
}
app.on('ready', () => {
if (isDuplicateInstance || handlingSquirrelEvent) {
return
}
readyTime = now() - launchTime
setAsDefaultProtocolClient('x-github-client')
if (__DEV__) {
setAsDefaultProtocolClient('x-github-desktop-dev-auth')
} else {
setAsDefaultProtocolClient('x-github-desktop-auth')
}
// Also support Desktop Classic's protocols.
if (__DARWIN__) {
setAsDefaultProtocolClient('github-mac')
} else if (__WIN32__) {
setAsDefaultProtocolClient('github-windows')
}
createWindow()
let menu = buildDefaultMenu()
Menu.setApplicationMenu(menu)
ipcMain.on(
'update-preferred-app-menu-item-labels',
(
event: Electron.IpcMessageEvent,
labels: { editor?: string; pullRequestLabel?: string; shell: string }
) => {
menu = buildDefaultMenu(
labels.editor,
labels.shell,
labels.pullRequestLabel
)
Menu.setApplicationMenu(menu)
if (mainWindow) {
mainWindow.sendAppMenu()
}
}
)
ipcMain.on('menu-event', (event: Electron.IpcMessageEvent, args: any[]) => {
const { name }: { name: MenuEvent } = event as any
if (mainWindow) {
mainWindow.sendMenuEvent(name)
}
})
/**
* An event sent by the renderer asking that the menu item with the given id
* is executed (ie clicked).
*/
ipcMain.on(
'execute-menu-item',
(event: Electron.IpcMessageEvent, { id }: { id: string }) => {
const menuItem = findMenuItemByID(menu, id)
if (menuItem) {
const window = BrowserWindow.fromWebContents(event.sender)
const fakeEvent = { preventDefault: () => {}, sender: event.sender }
menuItem.click(fakeEvent, window, event.sender)
}
}
)
ipcMain.on(
'update-menu-state',
(
event: Electron.IpcMessageEvent,
items: Array<{ id: string; state: IMenuItemState }>
) => {
let sendMenuChangedEvent = false
for (const item of items) {
const { id, state } = item
const menuItem = findMenuItemByID(menu, id)
if (menuItem) {
// Only send the updated app menu when the state actually changes
// or we might end up introducing a never ending loop between
// the renderer and the main process
if (
state.enabled !== undefined &&
menuItem.enabled !== state.enabled
) {
menuItem.enabled = state.enabled
sendMenuChangedEvent = true
}
} else {
fatalError(`Unknown menu id: ${id}`)
}
}
if (sendMenuChangedEvent && mainWindow) {
mainWindow.sendAppMenu()
}
}
)
ipcMain.on(
'show-contextual-menu',
(event: Electron.IpcMessageEvent, items: ReadonlyArray<IMenuItem>) => {
const menu = buildContextMenu(items, ix =>
event.sender.send('contextual-menu-action', ix)
)
const window = BrowserWindow.fromWebContents(event.sender)
menu.popup({ window })
}
)
/**
* An event sent by the renderer asking for a copy of the current
* application menu.
*/
ipcMain.on('get-app-menu', () => {
if (mainWindow) {
mainWindow.sendAppMenu()
}
})
ipcMain.on(
'show-certificate-trust-dialog',
(
event: Electron.IpcMessageEvent,
{
certificate,
message,
}: { certificate: Electron.Certificate; message: string }
) => {
// This API is only implemented for macOS and Windows right now.
if (__DARWIN__ || __WIN32__) {
onDidLoad(window => {
window.showCertificateTrustDialog(certificate, message)
})
}
}
)
ipcMain.on(
'log',
(event: Electron.IpcMessageEvent, level: LogLevel, message: string) => {
writeLog(level, message)
}
)
ipcMain.on(
'uncaught-exception',
(event: Electron.IpcMessageEvent, error: Error) => {
handleUncaughtException(error)
}
)
ipcMain.on(
'send-error-report',
(
event: Electron.IpcMessageEvent,
{ error, extra }: { error: Error; extra: { [key: string]: string } }
) => {
reportError(error, extra)
}
)
ipcMain.on(
'open-external',
(event: Electron.IpcMessageEvent, { path }: { path: string }) => {
const pathLowerCase = path.toLowerCase()
if (
pathLowerCase.startsWith('http://') ||
pathLowerCase.startsWith('https://')
) {
log.info(`opening in browser: ${path}`)
}
const result = shell.openExternal(path)
event.sender.send('open-external-result', { result })
}
)
ipcMain.on(
'show-item-in-folder',
(event: Electron.IpcMessageEvent, { path }: { path: string }) => {
Fs.stat(path, (err, stats) => {
if (err) {
log.error(`Unable to find file at '${path}'`, err)
return
}
if (stats.isDirectory()) {
openDirectorySafe(path)
} else {
shell.showItemInFolder(path)
}
})
}
)
})
app.on('activate', () => {
onDidLoad(window => {
window.show()
})
})
app.on('web-contents-created', (event, contents) => {
contents.on('new-window', (event, url) => {
// Prevent links or window.open from opening new windows
event.preventDefault()
log.warn(`Prevented new window to: ${url}`)
})
})
app.on(
'certificate-error',
(event, webContents, url, error, certificate, callback) => {
callback(false)
onDidLoad(window => {
window.sendCertificateError(certificate, error, url)
})
}
)
function createWindow() {
const window = new AppWindow()
if (__DEV__) {
const {
default: installExtension,
REACT_DEVELOPER_TOOLS,
REACT_PERF,
} = require('electron-devtools-installer')
require('electron-debug')({ showDevTools: true })
const ChromeLens = {
id: 'idikgljglpfilbhaboonnpnnincjhjkd',
electron: '>=1.2.1',
}
const extensions = [REACT_DEVELOPER_TOOLS, REACT_PERF, ChromeLens]
for (const extension of extensions) {
try {
installExtension(extension)
} catch (e) {}
}
}
window.onClose(() => {
mainWindow = null
if (!__DARWIN__ && !preventQuit) {
app.quit()
}
})
window.onDidLoad(() => {
window.show()
window.sendLaunchTimingStats({
mainReadyTime: readyTime!,
loadTime: window.loadTime!,
rendererReadyTime: window.rendererReadyTime!,
})
const fns = onDidLoadFns!
onDidLoadFns = null
for (const fn of fns) {
fn(window)
}
})
window.load()
mainWindow = window
}
/**
* Register a function to be called once the window has been loaded. If the
* window has already been loaded, the function will be called immediately.
*/
function onDidLoad(fn: OnDidLoadFn) {
if (onDidLoadFns) {
onDidLoadFns.push(fn)
} else {
if (mainWindow) {
fn(mainWindow)
}
}
}