-
Notifications
You must be signed in to change notification settings - Fork 29.2k
/
workbench.ts
470 lines (379 loc) · 18 KB
/
workbench.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/workbench/browser/style';
import { localize } from 'vs/nls';
import { Event, Emitter, setGlobalLeakWarningThreshold } from 'vs/base/common/event';
import { addClasses, addClass, removeClasses } from 'vs/base/browser/dom';
import { runWhenIdle } from 'vs/base/common/async';
import { getZoomLevel, isFirefox, isSafari, isChrome } from 'vs/base/browser/browser';
import { mark } from 'vs/base/common/performance';
import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
import { Registry } from 'vs/platform/registry/common/platform';
import { isWindows, isLinux, isWeb, isNative, isMacintosh } from 'vs/base/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { IEditorInputFactoryRegistry, Extensions as EditorExtensions } from 'vs/workbench/common/editor';
import { IActionBarRegistry, Extensions as ActionBarExtensions } from 'vs/workbench/browser/actions';
import { getSingletonServiceDescriptors } from 'vs/platform/instantiation/common/extensions';
import { Position, Parts, IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IStorageService, WillSaveStateReason, StorageScope } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { LifecyclePhase, ILifecycleService, WillShutdownEvent, BeforeShutdownEvent } from 'vs/platform/lifecycle/common/lifecycle';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { NotificationService } from 'vs/workbench/services/notification/common/notificationService';
import { NotificationsCenter } from 'vs/workbench/browser/parts/notifications/notificationsCenter';
import { NotificationsAlerts } from 'vs/workbench/browser/parts/notifications/notificationsAlerts';
import { NotificationsStatus } from 'vs/workbench/browser/parts/notifications/notificationsStatus';
import { registerNotificationCommands } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { NotificationsToasts } from 'vs/workbench/browser/parts/notifications/notificationsToasts';
import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { setARIAContainer } from 'vs/base/browser/ui/aria/aria';
import { readFontInfo, restoreFontInfo, serializeFontInfo } from 'vs/editor/browser/config/configuration';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { ILogService } from 'vs/platform/log/common/log';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { WorkbenchContextKeysHandler } from 'vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
export class Workbench extends Layout {
private readonly _onBeforeShutdown = this._register(new Emitter<BeforeShutdownEvent>());
readonly onBeforeShutdown: Event<BeforeShutdownEvent> = this._onBeforeShutdown.event;
private readonly _onWillShutdown = this._register(new Emitter<WillShutdownEvent>());
readonly onWillShutdown: Event<WillShutdownEvent> = this._onWillShutdown.event;
private readonly _onShutdown = this._register(new Emitter<void>());
readonly onShutdown: Event<void> = this._onShutdown.event;
constructor(
parent: HTMLElement,
private readonly serviceCollection: ServiceCollection,
logService: ILogService
) {
super(parent);
this.registerErrorHandler(logService);
}
private registerErrorHandler(logService: ILogService): void {
// Listen on unhandled rejection events
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
// See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
onUnexpectedError(event.reason);
// Prevent the printing of this event to the console
event.preventDefault();
});
// Install handler for unexpected errors
setUnexpectedErrorHandler(error => this.handleUnexpectedError(error, logService));
// Inform user about loading issues from the loader
interface AnnotatedLoadingError extends Error {
phase: 'loading';
moduleId: string;
neededBy: string[];
}
interface AnnotatedFactoryError extends Error {
phase: 'factory';
moduleId: string;
}
interface AnnotatedValidationError extends Error {
phase: 'configuration';
}
type AnnotatedError = AnnotatedLoadingError | AnnotatedFactoryError | AnnotatedValidationError;
(<any>window).require.config({
onError: (err: AnnotatedError) => {
if (err.phase === 'loading') {
onUnexpectedError(new Error(localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err))));
}
console.error(err);
}
});
}
private previousUnexpectedError: { message: string | undefined, time: number } = { message: undefined, time: 0 };
private handleUnexpectedError(error: unknown, logService: ILogService): void {
const message = toErrorMessage(error, true);
if (!message) {
return;
}
const now = Date.now();
if (message === this.previousUnexpectedError.message && now - this.previousUnexpectedError.time <= 1000) {
return; // Return if error message identical to previous and shorter than 1 second
}
this.previousUnexpectedError.time = now;
this.previousUnexpectedError.message = message;
// Log it
logService.error(message);
}
startup(): IInstantiationService {
try {
// Configure emitter leak warning threshold
setGlobalLeakWarningThreshold(175);
// ARIA
setARIAContainer(document.body);
// Services
const instantiationService = this.initServices(this.serviceCollection);
instantiationService.invokeFunction(async accessor => {
const lifecycleService = accessor.get(ILifecycleService);
const storageService = accessor.get(IStorageService);
const configurationService = accessor.get(IConfigurationService);
// Layout
this.initLayout(accessor);
// Registries
this.startRegistries(accessor);
// Context Keys
this._register(instantiationService.createInstance(WorkbenchContextKeysHandler));
// Register Listeners
this.registerListeners(lifecycleService, storageService, configurationService);
// Render Workbench
this.renderWorkbench(instantiationService, accessor.get(INotificationService) as NotificationService, storageService, configurationService);
// Workbench Layout
this.createWorkbenchLayout();
// Layout
this.layout();
// Restore
try {
await this.restoreWorkbench(accessor.get(IEditorService), accessor.get(IEditorGroupsService), accessor.get(IViewletService), accessor.get(IPanelService), accessor.get(ILogService), lifecycleService);
} catch (error) {
onUnexpectedError(error);
}
});
return instantiationService;
} catch (error) {
onUnexpectedError(error);
throw error; // rethrow because this is a critical issue we cannot handle properly here
}
}
private initServices(serviceCollection: ServiceCollection): IInstantiationService {
// Layout Service
serviceCollection.set(IWorkbenchLayoutService, this);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// NOTE: DO NOT ADD ANY OTHER SERVICE INTO THE COLLECTION HERE.
// CONTRIBUTE IT VIA WORKBENCH.DESKTOP.MAIN.TS AND registerSingleton().
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// All Contributed Services
const contributedServices = getSingletonServiceDescriptors();
for (let [id, descriptor] of contributedServices) {
serviceCollection.set(id, descriptor);
}
const instantiationService = new InstantiationService(serviceCollection, true);
// Wrap up
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
// TODO@Sandeep debt around cyclic dependencies
const configurationService = accessor.get(IConfigurationService) as any;
if (typeof configurationService.acquireInstantiationService === 'function') {
setTimeout(() => {
configurationService.acquireInstantiationService(instantiationService);
}, 0);
}
// Signal to lifecycle that services are set
lifecycleService.phase = LifecyclePhase.Ready;
});
return instantiationService;
}
private startRegistries(accessor: ServicesAccessor): void {
Registry.as<IActionBarRegistry>(ActionBarExtensions.Actionbar).start(accessor);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).start(accessor);
Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).start(accessor);
}
private registerListeners(
lifecycleService: ILifecycleService,
storageService: IStorageService,
configurationService: IConfigurationService
): void {
// Configuration changes
this._register(configurationService.onDidChangeConfiguration(() => this.setFontAliasing(configurationService)));
// Font Info
if (isNative) {
this._register(storageService.onWillSaveState(e => {
if (e.reason === WillSaveStateReason.SHUTDOWN) {
this.storeFontInfo(storageService);
}
}));
} else {
this._register(lifecycleService.onWillShutdown(() => this.storeFontInfo(storageService)));
}
// Lifecycle
this._register(lifecycleService.onBeforeShutdown(event => this._onBeforeShutdown.fire(event)));
this._register(lifecycleService.onWillShutdown(event => this._onWillShutdown.fire(event)));
this._register(lifecycleService.onShutdown(() => {
this._onShutdown.fire();
this.dispose();
}));
}
private fontAliasing: 'default' | 'antialiased' | 'none' | 'auto' | undefined;
private setFontAliasing(configurationService: IConfigurationService) {
if (!isMacintosh) {
return; // macOS only
}
const aliasing = configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>('workbench.fontAliasing');
if (this.fontAliasing === aliasing) {
return;
}
this.fontAliasing = aliasing;
// Remove all
const fontAliasingValues: (typeof aliasing)[] = ['antialiased', 'none', 'auto'];
removeClasses(this.container, ...fontAliasingValues.map(value => `monaco-font-aliasing-${value}`));
// Add specific
if (fontAliasingValues.some(option => option === aliasing)) {
addClass(this.container, `monaco-font-aliasing-${aliasing}`);
}
}
private restoreFontInfo(storageService: IStorageService, configurationService: IConfigurationService): void {
// Restore (native: use storage service, web: use browser specific local storage)
const storedFontInfoRaw = isNative ? storageService.get('editorFontInfo', StorageScope.GLOBAL) : window.localStorage.getItem('vscode.editorFontInfo');
if (storedFontInfoRaw) {
try {
const storedFontInfo = JSON.parse(storedFontInfoRaw);
if (Array.isArray(storedFontInfo)) {
restoreFontInfo(storedFontInfo);
}
} catch (err) {
/* ignore */
}
}
readFontInfo(BareFontInfo.createFromRawSettings(configurationService.getValue('editor'), getZoomLevel()));
}
private storeFontInfo(storageService: IStorageService): void {
const serializedFontInfo = serializeFontInfo();
if (serializedFontInfo) {
const serializedFontInfoRaw = JSON.stringify(serializedFontInfo);
// Font info is very specific to the machine the workbench runs
// on. As such, in the web, we prefer to store this info in
// local storage and not global storage because it would not make
// much sense to synchronize to other machines.
if (isNative) {
storageService.store('editorFontInfo', serializedFontInfoRaw, StorageScope.GLOBAL);
} else {
window.localStorage.setItem('vscode.editorFontInfo', serializedFontInfoRaw);
}
}
}
private renderWorkbench(instantiationService: IInstantiationService, notificationService: NotificationService, storageService: IStorageService, configurationService: IConfigurationService): void {
// State specific classes
const platformClass = isWindows ? 'windows' : isLinux ? 'linux' : 'mac';
const workbenchClasses = coalesce([
'monaco-workbench',
platformClass,
isWeb ? 'web' : undefined,
isChrome ? 'chromium' : isFirefox ? 'firefox' : isSafari ? 'safari' : undefined,
...this.getLayoutClasses()
]);
addClasses(this.container, ...workbenchClasses);
addClass(document.body, platformClass); // used by our fonts
if (isWeb) {
addClass(document.body, 'web');
}
// Apply font aliasing
this.setFontAliasing(configurationService);
// Warm up font cache information before building up too many dom elements
this.restoreFontInfo(storageService, configurationService);
// Create Parts
[
{ id: Parts.TITLEBAR_PART, role: 'contentinfo', classes: ['titlebar'] },
{ id: Parts.ACTIVITYBAR_PART, role: 'navigation', classes: ['activitybar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] },
{ id: Parts.SIDEBAR_PART, role: 'complementary', classes: ['sidebar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] },
{ id: Parts.EDITOR_PART, role: 'main', classes: ['editor'], options: { restorePreviousState: this.state.editor.restoreEditors } },
{ id: Parts.PANEL_PART, role: 'complementary', classes: ['panel', this.state.panel.position === Position.BOTTOM ? 'bottom' : 'right'] },
{ id: Parts.STATUSBAR_PART, role: 'contentinfo', classes: ['statusbar'] }
].forEach(({ id, role, classes, options }) => {
const partContainer = this.createPart(id, role, classes);
this.getPart(id).create(partContainer, options);
});
// Notification Handlers
this.createNotificationsHandlers(instantiationService, notificationService);
// Add Workbench to DOM
this.parent.appendChild(this.container);
}
private createPart(id: string, role: string, classes: string[]): HTMLElement {
const part = document.createElement('div');
addClasses(part, 'part', ...classes);
part.id = id;
part.setAttribute('role', role);
return part;
}
private createNotificationsHandlers(instantiationService: IInstantiationService, notificationService: NotificationService): void {
// Instantiate Notification components
const notificationsCenter = this._register(instantiationService.createInstance(NotificationsCenter, this.container, notificationService.model));
const notificationsToasts = this._register(instantiationService.createInstance(NotificationsToasts, this.container, notificationService.model));
this._register(instantiationService.createInstance(NotificationsAlerts, notificationService.model));
const notificationsStatus = instantiationService.createInstance(NotificationsStatus, notificationService.model);
// Visibility
this._register(notificationsCenter.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible);
notificationsToasts.update(notificationsCenter.isVisible);
}));
// Register Commands
registerNotificationCommands(notificationsCenter, notificationsToasts);
}
private async restoreWorkbench(
editorService: IEditorService,
editorGroupService: IEditorGroupsService,
viewletService: IViewletService,
panelService: IPanelService,
logService: ILogService,
lifecycleService: ILifecycleService
): Promise<void> {
const restorePromises: Promise<void>[] = [];
// Restore editors
restorePromises.push((async () => {
mark('willRestoreEditors');
// first ensure the editor part is restored
await editorGroupService.whenRestored;
// then see for editors to open as instructed
let editors: IResourceEditor[];
if (Array.isArray(this.state.editor.editorsToOpen)) {
editors = this.state.editor.editorsToOpen;
} else {
editors = await this.state.editor.editorsToOpen;
}
if (editors.length) {
await editorService.openEditors(editors);
}
mark('didRestoreEditors');
})());
// Restore Sidebar
if (this.state.sideBar.viewletToRestore) {
restorePromises.push((async () => {
mark('willRestoreViewlet');
const viewlet = await viewletService.openViewlet(this.state.sideBar.viewletToRestore);
if (!viewlet) {
await viewletService.openViewlet(viewletService.getDefaultViewletId()); // fallback to default viewlet as needed
}
mark('didRestoreViewlet');
})());
}
// Restore Panel
if (this.state.panel.panelToRestore) {
mark('willRestorePanel');
panelService.openPanel(this.state.panel.panelToRestore);
mark('didRestorePanel');
}
// Restore Zen Mode
if (this.state.zenMode.restore) {
this.toggleZenMode(false, true);
}
// Restore Editor Center Mode
if (this.state.editor.restoreCentered) {
this.centerEditorLayout(true, true);
}
// Emit a warning after 10s if restore does not complete
const restoreTimeoutHandle = setTimeout(() => logService.warn('Workbench did not finish loading in 10 seconds, that might be a problem that should be reported.'), 10000);
try {
await Promise.all(restorePromises);
clearTimeout(restoreTimeoutHandle);
} catch (error) {
onUnexpectedError(error);
} finally {
// Set lifecycle phase to `Restored`
lifecycleService.phase = LifecyclePhase.Restored;
// Set lifecycle phase to `Eventually` after a short delay and when idle (min 2.5sec, max 5sec)
setTimeout(() => {
this._register(runWhenIdle(() => lifecycleService.phase = LifecyclePhase.Eventually, 2500));
}, 2500);
// Telemetry: startup metrics
mark('didStartWorkbench');
}
}
}