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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { app, BrowserWindow } from 'electron';
import { validatedIpcMain } from 'vs/base/parts/ipc/electron-main/ipcMain';
import { Barrier, Promises, timeout } from 'vs/base/common/async';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { isMacintosh, isWindows } from 'vs/base/common/platform';
import { cwd } from 'vs/base/common/process';
import { assertIsDefined } from 'vs/base/common/types';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IStateMainService } from 'vs/platform/state/electron-main/state';
import { ICodeWindow, LoadReason, UnloadReason } from 'vs/platform/window/electron-main/window';
import { ISingleFolderWorkspaceIdentifier, IWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace';
export const ILifecycleMainService = createDecorator<ILifecycleMainService>('lifecycleMainService');
interface WindowLoadEvent {
/**
* The window that is loaded to a new workspace.
*/
window: ICodeWindow;
/**
* The workspace the window is loaded into.
*/
workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | undefined;
/**
* More details why the window loads to a new workspace.
*/
reason: LoadReason;
}
export const enum ShutdownReason {
/**
* The application exits normally.
*/
QUIT = 1,
/**
* The application exits abnormally and is being
* killed with an exit code (e.g. from integration
* test run)
*/
KILL
}
export interface ShutdownEvent {
/**
* More details why the application is shutting down.
*/
reason: ShutdownReason;
/**
* Allows to join the shutdown. The promise can be a long running operation but it
* will block the application from closing.
*/
join(promise: Promise<void>): void;
}
export interface ILifecycleMainService {
readonly _serviceBrand: undefined;
/**
* Will be true if the program was restarted (e.g. due to explicit request or update).
*/
readonly wasRestarted: boolean;
/**
* Will be true if the program was requested to quit.
*/
readonly quitRequested: boolean;
/**
* A flag indicating in what phase of the lifecycle we currently are.
*/
phase: LifecycleMainPhase;
/**
* An event that fires when the application is about to shutdown before any window is closed.
* The shutdown can still be prevented by any window that vetos this event.
*/
readonly onBeforeShutdown: Event<void>;
/**
* An event that fires after the onBeforeShutdown event has been fired and after no window has
* vetoed the shutdown sequence. At this point listeners are ensured that the application will
* quit without veto.
*/
readonly onWillShutdown: Event<ShutdownEvent>;
/**
* An event that fires when a window is loading. This can either be a window opening for the
* first time or a window reloading or changing to another URL.
*/
readonly onWillLoadWindow: Event<WindowLoadEvent>;
/**
* An event that fires before a window closes. This event is fired after any veto has been dealt
* with so that listeners know for sure that the window will close without veto.
*/
readonly onBeforeCloseWindow: Event<ICodeWindow>;
/**
* Make a `ICodeWindow` known to the lifecycle main service.
*/
registerWindow(window: ICodeWindow): void;
/**
* Reload a window. All lifecycle event handlers are triggered.
*/
reload(window: ICodeWindow, cli?: NativeParsedArgs): Promise<void>;
/**
* Unload a window for the provided reason. All lifecycle event handlers are triggered.
*/
unload(window: ICodeWindow, reason: UnloadReason): Promise<boolean /* veto */>;
/**
* Restart the application with optional arguments (CLI). All lifecycle event handlers are triggered.
*/
relaunch(options?: { addArgs?: string[]; removeArgs?: string[] }): Promise<void>;
/**
* Shutdown the application normally. All lifecycle event handlers are triggered.
*/
quit(willRestart?: boolean): Promise<boolean /* veto */>;
/**
* Forcefully shutdown the application and optionally set an exit code.
*
* This method should only be used in rare situations where it is important
* to set an exit code (e.g. running tests) or when the application is
* not in a healthy state and should terminate asap.
*
* This method does not fire the normal lifecycle events to the windows,
* that normally can be vetoed. Windows are destroyed without a chance
* of components to participate. The only lifecycle event handler that
* is triggered is `onWillShutdown` in the main process.
*/
kill(code?: number): Promise<void>;
/**
* Returns a promise that resolves when a certain lifecycle phase
* has started.
*/
when(phase: LifecycleMainPhase): Promise<void>;
}
export const enum LifecycleMainPhase {
/**
* The first phase signals that we are about to startup.
*/
Starting = 1,
/**
* Services are ready and first window is about to open.
*/
Ready = 2,
/**
* This phase signals a point in time after the window has opened
* and is typically the best place to do work that is not required
* for the window to open.
*/
AfterWindowOpen = 3
}
export class LifecycleMainService extends Disposable implements ILifecycleMainService {
declare readonly _serviceBrand: undefined;
private static readonly QUIT_AND_RESTART_KEY = 'lifecycle.quitAndRestart';
private readonly _onBeforeShutdown = this._register(new Emitter<void>());
readonly onBeforeShutdown = this._onBeforeShutdown.event;
private readonly _onWillShutdown = this._register(new Emitter<ShutdownEvent>());
readonly onWillShutdown = this._onWillShutdown.event;
private readonly _onWillLoadWindow = this._register(new Emitter<WindowLoadEvent>());
readonly onWillLoadWindow = this._onWillLoadWindow.event;
private readonly _onBeforeCloseWindow = this._register(new Emitter<ICodeWindow>());
readonly onBeforeCloseWindow = this._onBeforeCloseWindow.event;
private _quitRequested = false;
get quitRequested(): boolean { return this._quitRequested; }
private _wasRestarted: boolean = false;
get wasRestarted(): boolean { return this._wasRestarted; }
private _phase = LifecycleMainPhase.Starting;
get phase(): LifecycleMainPhase { return this._phase; }
private readonly windowToCloseRequest = new Set<number>();
private oneTimeListenerTokenGenerator = 0;
private windowCounter = 0;
private pendingQuitPromise: Promise<boolean> | undefined = undefined;
private pendingQuitPromiseResolve: { (veto: boolean): void } | undefined = undefined;
private pendingWillShutdownPromise: Promise<void> | undefined = undefined;
private readonly mapWindowIdToPendingUnload = new Map<number, Promise<boolean>>();
private readonly phaseWhen = new Map<LifecycleMainPhase, Barrier>();
constructor(
@ILogService private readonly logService: ILogService,
@IStateMainService private readonly stateMainService: IStateMainService
) {
super();
this.resolveRestarted();
this.when(LifecycleMainPhase.Ready).then(() => this.registerListeners());
}
private resolveRestarted(): void {
this._wasRestarted = !!this.stateMainService.getItem(LifecycleMainService.QUIT_AND_RESTART_KEY);
if (this._wasRestarted) {
// remove the marker right after if found
this.stateMainService.removeItem(LifecycleMainService.QUIT_AND_RESTART_KEY);
}
}
private registerListeners(): void {
// before-quit: an event that is fired if application quit was
// requested but before any window was closed.
const beforeQuitListener = () => {
if (this._quitRequested) {
return;
}
this.logService.trace('Lifecycle#app.on(before-quit)');
this._quitRequested = true;
// Emit event to indicate that we are about to shutdown
this.logService.trace('Lifecycle#onBeforeShutdown.fire()');
this._onBeforeShutdown.fire();
// macOS: can run without any window open. in that case we fire
// the onWillShutdown() event directly because there is no veto
// to be expected.
if (isMacintosh && this.windowCounter === 0) {
this.fireOnWillShutdown(ShutdownReason.QUIT);
}
};
app.addListener('before-quit', beforeQuitListener);
// window-all-closed: an event that only fires when the last window
// was closed. We override this event to be in charge if app.quit()
// should be called or not.
const windowAllClosedListener = () => {
this.logService.trace('Lifecycle#app.on(window-all-closed)');
// Windows/Linux: we quit when all windows have closed
// Mac: we only quit when quit was requested
if (this._quitRequested || !isMacintosh) {
app.quit();
}
};
app.addListener('window-all-closed', windowAllClosedListener);
// will-quit: an event that is fired after all windows have been
// closed, but before actually quitting.
app.once('will-quit', e => {
this.logService.trace('Lifecycle#app.on(will-quit)');
// Prevent the quit until the shutdown promise was resolved
e.preventDefault();
// Start shutdown sequence
const shutdownPromise = this.fireOnWillShutdown(ShutdownReason.QUIT);
// Wait until shutdown is signaled to be complete
shutdownPromise.finally(() => {
// Resolve pending quit promise now without veto
this.resolvePendingQuitPromise(false /* no veto */);
// Quit again, this time do not prevent this, since our
// will-quit listener is only installed "once". Also
// remove any listener we have that is no longer needed
app.removeListener('before-quit', beforeQuitListener);
app.removeListener('window-all-closed', windowAllClosedListener);
app.quit();
});
});
}
private fireOnWillShutdown(reason: ShutdownReason): Promise<void> {
if (this.pendingWillShutdownPromise) {
return this.pendingWillShutdownPromise; // shutdown is already running
}
this.logService.trace('Lifecycle#onWillShutdown.fire()');
const joiners: Promise<void>[] = [];
this._onWillShutdown.fire({
reason,
join(promise) {
joiners.push(promise);
}
});
this.pendingWillShutdownPromise = (async () => {
// Settle all shutdown event joiners
try {
await Promises.settled(joiners);
} catch (error) {
this.logService.error(error);
}
// Then, always make sure at the end
// the state service is flushed.
try {
await this.stateMainService.close();
} catch (error) {
this.logService.error(error);
}
})();
return this.pendingWillShutdownPromise;
}
set phase(value: LifecycleMainPhase) {
if (value < this.phase) {
throw new Error('Lifecycle cannot go backwards');
}
if (this._phase === value) {
return;
}
this.logService.trace(`lifecycle (main): phase changed (value: ${value})`);
this._phase = value;
const barrier = this.phaseWhen.get(this._phase);
if (barrier) {
barrier.open();
this.phaseWhen.delete(this._phase);
}
}
async when(phase: LifecycleMainPhase): Promise<void> {
if (phase <= this._phase) {
return;
}
let barrier = this.phaseWhen.get(phase);
if (!barrier) {
barrier = new Barrier();
this.phaseWhen.set(phase, barrier);
}
await barrier.wait();
}
registerWindow(window: ICodeWindow): void {
const windowListeners = new DisposableStore();
// track window count
this.windowCounter++;
// Window Will Load
windowListeners.add(window.onWillLoad(e => this._onWillLoadWindow.fire({ window, workspace: e.workspace, reason: e.reason })));
// Window Before Closing: Main -> Renderer
const win = assertIsDefined(window.win);
win.on('close', e => {
// The window already acknowledged to be closed
const windowId = window.id;
if (this.windowToCloseRequest.has(windowId)) {
this.windowToCloseRequest.delete(windowId);
return;
}
this.logService.trace(`Lifecycle#window.on('close') - window ID ${window.id}`);
// Otherwise prevent unload and handle it from window
e.preventDefault();
this.unload(window, UnloadReason.CLOSE).then(veto => {
if (veto) {
this.windowToCloseRequest.delete(windowId);
return;
}
this.windowToCloseRequest.add(windowId);
// Fire onBeforeCloseWindow before actually closing
this.logService.trace(`Lifecycle#onBeforeCloseWindow.fire() - window ID ${windowId}`);
this._onBeforeCloseWindow.fire(window);
// No veto, close window now
window.close();
});
});
// Window After Closing
win.on('closed', () => {
this.logService.trace(`Lifecycle#window.on('closed') - window ID ${window.id}`);
// update window count
this.windowCounter--;
// clear window listeners
windowListeners.dispose();
// if there are no more code windows opened, fire the onWillShutdown event, unless
// we are on macOS where it is perfectly fine to close the last window and
// the application continues running (unless quit was actually requested)
if (this.windowCounter === 0 && (!isMacintosh || this._quitRequested)) {
this.fireOnWillShutdown(ShutdownReason.QUIT);
}
});
}
async reload(window: ICodeWindow, cli?: NativeParsedArgs): Promise<void> {
// Only reload when the window has not vetoed this
const veto = await this.unload(window, UnloadReason.RELOAD);
if (!veto) {
window.reload(cli);
}
}
unload(window: ICodeWindow, reason: UnloadReason): Promise<boolean /* veto */> {
// Ensure there is only 1 unload running at the same time
const pendingUnloadPromise = this.mapWindowIdToPendingUnload.get(window.id);
if (pendingUnloadPromise) {
return pendingUnloadPromise;
}
// Start unload and remember in map until finished
const unloadPromise = this.doUnload(window, reason).finally(() => {
this.mapWindowIdToPendingUnload.delete(window.id);
});
this.mapWindowIdToPendingUnload.set(window.id, unloadPromise);
return unloadPromise;
}
private async doUnload(window: ICodeWindow, reason: UnloadReason): Promise<boolean /* veto */> {
// Always allow to unload a window that is not yet ready
if (!window.isReady) {
return false;
}
this.logService.trace(`Lifecycle#unload() - window ID ${window.id}`);
// first ask the window itself if it vetos the unload
const windowUnloadReason = this._quitRequested ? UnloadReason.QUIT : reason;
let veto = await this.onBeforeUnloadWindowInRenderer(window, windowUnloadReason);
if (veto) {
this.logService.trace(`Lifecycle#unload() - veto in renderer (window ID ${window.id})`);
return this.handleWindowUnloadVeto(veto);
}
// finally if there are no vetos, unload the renderer
await this.onWillUnloadWindowInRenderer(window, windowUnloadReason);
return false;
}
private handleWindowUnloadVeto(veto: boolean): boolean {
if (!veto) {
return false; // no veto
}
// a veto resolves any pending quit with veto
this.resolvePendingQuitPromise(true /* veto */);
// a veto resets the pending quit request flag
this._quitRequested = false;
return true; // veto
}
private resolvePendingQuitPromise(veto: boolean): void {
if (this.pendingQuitPromiseResolve) {
this.pendingQuitPromiseResolve(veto);
this.pendingQuitPromiseResolve = undefined;
this.pendingQuitPromise = undefined;
}
}
private onBeforeUnloadWindowInRenderer(window: ICodeWindow, reason: UnloadReason): Promise<boolean /* veto */> {
return new Promise<boolean>(resolve => {
const oneTimeEventToken = this.oneTimeListenerTokenGenerator++;
const okChannel = `vscode:ok${oneTimeEventToken}`;
const cancelChannel = `vscode:cancel${oneTimeEventToken}`;
validatedIpcMain.once(okChannel, () => {
resolve(false); // no veto
});
validatedIpcMain.once(cancelChannel, () => {
resolve(true); // veto
});
window.send('vscode:onBeforeUnload', { okChannel, cancelChannel, reason });
});
}
private onWillUnloadWindowInRenderer(window: ICodeWindow, reason: UnloadReason): Promise<void> {
return new Promise<void>(resolve => {
const oneTimeEventToken = this.oneTimeListenerTokenGenerator++;
const replyChannel = `vscode:reply${oneTimeEventToken}`;
validatedIpcMain.once(replyChannel, () => resolve());
window.send('vscode:onWillUnload', { replyChannel, reason });
});
}
quit(willRestart?: boolean): Promise<boolean /* veto */> {
if (this.pendingQuitPromise) {
return this.pendingQuitPromise;
}
this.logService.trace(`Lifecycle#quit() - will restart: ${willRestart}`);
// Remember if we are about to restart
if (willRestart) {
this.stateMainService.setItem(LifecycleMainService.QUIT_AND_RESTART_KEY, true);
}
this.pendingQuitPromise = new Promise(resolve => {
// Store as field to access it from a window cancellation
this.pendingQuitPromiseResolve = resolve;
// Calling app.quit() will trigger the close handlers of each opened window
// and only if no window vetoed the shutdown, we will get the will-quit event
this.logService.trace('Lifecycle#quit() - calling app.quit()');
app.quit();
});
return this.pendingQuitPromise;
}
async relaunch(options?: { addArgs?: string[]; removeArgs?: string[] }): Promise<void> {
this.logService.trace('Lifecycle#relaunch()');
const args = process.argv.slice(1);
if (options?.addArgs) {
args.push(...options.addArgs);
}
if (options?.removeArgs) {
for (const a of options.removeArgs) {
const idx = args.indexOf(a);
if (idx >= 0) {
args.splice(idx, 1);
}
}
}
const quitListener = () => {
// Windows: we are about to restart and as such we need to restore the original
// current working directory we had on startup to get the exact same startup
// behaviour. As such, we briefly change back to that directory and then when
// Code starts it will set it back to the installation directory again.
try {
if (isWindows) {
const currentWorkingDir = cwd();
if (currentWorkingDir !== process.cwd()) {
process.chdir(currentWorkingDir);
}
}
} catch (err) {
this.logService.error(err);
}
// relaunch after we are sure there is no veto
this.logService.trace('Lifecycle#relaunch() - calling app.relaunch()');
app.relaunch({ args });
};
app.once('quit', quitListener);
// `app.relaunch()` does not quit automatically, so we quit first,
// check for vetoes and then relaunch from the `app.on('quit')` event
const veto = await this.quit(true /* will restart */);
if (veto) {
app.removeListener('quit', quitListener);
}
}
async kill(code?: number): Promise<void> {
this.logService.trace('Lifecycle#kill()');
// Give main process participants a chance to orderly shutdown
await this.fireOnWillShutdown(ShutdownReason.KILL);
// From extension tests we have seen issues where calling app.exit()
// with an opened window can lead to native crashes (Linux). As such,
// we should make sure to destroy any opened window before calling
// `app.exit()`.
//
// Note: Electron implements a similar logic here:
// https://github.com/electron/electron/blob/fe5318d753637c3903e23fc1ed1b263025887b6a/spec-main/window-helpers.ts#L5
await Promise.race([
// Still do not block more than 1s
timeout(1000),
// Destroy any opened window: we do not unload windows here because
// there is a chance that the unload is veto'd or long running due
// to a participant within the window. this is not wanted when we
// are asked to kill the application.
(async () => {
for (const window of BrowserWindow.getAllWindows()) {
if (window && !window.isDestroyed()) {
let whenWindowClosed: Promise<void>;
if (window.webContents && !window.webContents.isDestroyed()) {
whenWindowClosed = new Promise(resolve => window.once('closed', resolve));
} else {
whenWindowClosed = Promise.resolve();
}
window.destroy();
await whenWindowClosed;
}
}
})()
]);
// Now exit either after 1s or all windows destroyed
app.exit(code);
}
}
|