desktop.main.ts 18.1 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import * as fs from 'fs';
7
import * as gracefulFs from 'graceful-fs';
S
Sandeep Somavarapu 已提交
8 9 10
import { createHash } from 'crypto';
import { stat } from 'vs/base/node/pfs';
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
11
import { zoomLevelToZoomFactor } from 'vs/platform/windows/common/windows';
12
import { importEntries, mark } from 'vs/base/common/performance';
13
import { Workbench } from 'vs/workbench/browser/workbench';
14
import { NativeWindow } from 'vs/workbench/electron-sandbox/window';
15
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
16
import { domContentLoaded, addDisposableListener, EventType, scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';
17
import { onUnexpectedError } from 'vs/base/common/errors';
18
import { URI } from 'vs/base/common/uri';
19
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
20
import { NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService';
21
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
22
import { INativeWorkbenchConfiguration, INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
23
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
24
import { ISingleFolderWorkspaceIdentifier, IWorkspaceInitializationPayload, ISingleFolderWorkspaceInitializationPayload, reviveWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
25
import { ILogService } from 'vs/platform/log/common/log';
26
import { NativeStorageService } from 'vs/platform/storage/node/storageService';
27
import { Schemas } from 'vs/base/common/network';
B
Benjamin Pasero 已提交
28
import { sanitizeFilePath } from 'vs/base/common/extpath';
B
wip  
Benjamin Pasero 已提交
29
import { GlobalStorageDatabaseChannelClient } from 'vs/platform/storage/node/storageIpc';
B
Benjamin Pasero 已提交
30 31 32
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
33
import { Disposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
34
import { registerWindowDriver } from 'vs/platform/driver/electron-browser/driver';
35
import { IMainProcessService, MainProcessService } from 'vs/platform/ipc/electron-sandbox/mainProcessService';
36
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-sandbox/remoteAuthorityResolverService';
37 38 39
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-browser/remoteAgentServiceImpl';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
40
import { FileService } from 'vs/platform/files/common/fileService';
41
import { IFileService } from 'vs/platform/files/common/files';
42
import { DiskFileSystemProvider } from 'vs/platform/files/electron-browser/diskFileSystemProvider';
43
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
44
import { ConfigurationCache } from 'vs/workbench/services/configuration/electron-browser/configurationCache';
I
isidor 已提交
45 46
import { SignService } from 'vs/platform/sign/node/signService';
import { ISignService } from 'vs/platform/sign/common/sign';
S
Sandeep Somavarapu 已提交
47
import { FileUserDataProvider } from 'vs/workbench/services/userData/common/fileUserDataProvider';
48
import { basename } from 'vs/base/common/resources';
49
import { IProductService } from 'vs/platform/product/common/productService';
50
import product from 'vs/platform/product/common/product';
B
Benjamin Pasero 已提交
51
import { NativeLogService } from 'vs/workbench/services/log/electron-browser/logService';
52 53
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeHostService } from 'vs/platform/native/electron-sandbox/nativeHostService';
54 55
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
import { UriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentityService';
56 57
import { KeyboardLayoutService } from 'vs/workbench/services/keybinding/electron-sandbox/nativeKeyboardLayout';
import { IKeyboardLayoutService } from 'vs/platform/keyboardLayout/common/keyboardLayout';
J
Joao Moreno 已提交
58

B
Benjamin Pasero 已提交
59
class DesktopMain extends Disposable {
E
Erich Gamma 已提交
60

61 62
	private readonly productService: IProductService = { _serviceBrand: undefined, ...product };
	private readonly environmentService = new NativeWorkbenchEnvironmentService(this.configuration, this.productService);
63

64
	constructor(private configuration: INativeWorkbenchConfiguration) {
B
Benjamin Pasero 已提交
65
		super();
B
Benjamin Pasero 已提交
66

B
Benjamin Pasero 已提交
67 68
		this.init();
	}
M
Martin Aeschlimann 已提交
69

B
Benjamin Pasero 已提交
70
	private init(): void {
71

B
Benjamin Pasero 已提交
72 73
		// Enable gracefulFs
		gracefulFs.gracefulify(fs);
74

B
Benjamin Pasero 已提交
75 76
		// Massage configuration file URIs
		this.reviveUris();
77

B
Benjamin Pasero 已提交
78
		// Setup perf
79
		importEntries(this.configuration.perfEntries);
A
Alex Dima 已提交
80

B
Benjamin Pasero 已提交
81
		// Browser config
82 83 84
		const zoomLevel = this.configuration.zoomLevel || 0;
		setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
		setZoomLevel(zoomLevel, true /* isTrusted */);
85
		setFullscreen(!!this.configuration.fullscreen);
M
Martin Aeschlimann 已提交
86
	}
87

B
Benjamin Pasero 已提交
88
	private reviveUris() {
89 90
		if (this.configuration.folderUri) {
			this.configuration.folderUri = URI.revive(this.configuration.folderUri);
B
Benjamin Pasero 已提交
91
		}
92

93 94
		if (this.configuration.workspace) {
			this.configuration.workspace = reviveWorkspaceIdentifier(this.configuration.workspace);
M
Martin Aeschlimann 已提交
95
		}
B
Benjamin Pasero 已提交
96

97
		const filesToWait = this.configuration.filesToWait;
B
Benjamin Pasero 已提交
98
		const filesToWaitPaths = filesToWait?.paths;
99
		[filesToWaitPaths, this.configuration.filesToOpenOrCreate, this.configuration.filesToDiff].forEach(paths => {
B
Benjamin Pasero 已提交
100 101 102
			if (Array.isArray(paths)) {
				paths.forEach(path => {
					if (path.fileUri) {
103
						path.fileUri = URI.revive(path.fileUri);
B
Benjamin Pasero 已提交
104 105 106 107
					}
				});
			}
		});
108

M
Martin Aeschlimann 已提交
109
		if (filesToWait) {
110
			filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
M
Martin Aeschlimann 已提交
111
		}
B
Benjamin Pasero 已提交
112
	}
B
Benjamin Pasero 已提交
113

114 115
	async open(): Promise<void> {
		const services = await this.initServices();
B
Benjamin Pasero 已提交
116

117 118
		await domContentLoaded();
		mark('willStartWorkbench');
B
Benjamin Pasero 已提交
119

120
		// Create Workbench
121
		const workbench = new Workbench(document.body, services.serviceCollection, services.logService);
B
Benjamin Pasero 已提交
122

B
Benjamin Pasero 已提交
123 124
		// Listeners
		this.registerListeners(workbench, services.storageService);
125

126
		// Startup
127
		const instantiationService = workbench.startup();
B
Benjamin Pasero 已提交
128

129
		// Window
130
		this._register(instantiationService.createInstance(NativeWindow));
B
Benjamin Pasero 已提交
131

132
		// Driver
133
		if (this.configuration.driver) {
B
Benjamin Pasero 已提交
134
			instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
135
		}
136

137
		// Logging
138
		services.logService.trace('workbench configuration', JSON.stringify(this.configuration));
B
Benjamin Pasero 已提交
139
	}
140

141
	private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
B
Benjamin Pasero 已提交
142 143 144 145 146 147 148 149 150

		// Layout
		this._register(addDisposableListener(window, EventType.RESIZE, e => this.onWindowResize(e, true, workbench)));

		// Workbench Lifecycle
		this._register(workbench.onShutdown(() => this.dispose()));
		this._register(workbench.onWillShutdown(event => event.join(storageService.close())));
	}

151
	private onWindowResize(e: Event, retry: boolean, workbench: Workbench): void {
152 153 154 155 156 157 158 159
		if (e.target === window) {
			if (window.document && window.document.body && window.document.body.clientWidth === 0) {
				// TODO@Ben this is an electron issue on macOS when simple fullscreen is enabled
				// where for some reason the window clientWidth is reported as 0 when switching
				// between simple fullscreen and normal screen. In that case we schedule the layout
				// call at the next animation frame once, in the hope that the dimensions are
				// proper then.
				if (retry) {
160
					scheduleAtNextAnimationFrame(() => this.onWindowResize(e, false, workbench));
161 162 163 164
				}
				return;
			}

165
			workbench.layout();
166 167 168
		}
	}

S
Sandeep Somavarapu 已提交
169
	private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: NativeStorageService }> {
B
Benjamin Pasero 已提交
170
		const serviceCollection = new ServiceCollection();
171

172 173 174 175 176 177 178 179 180 181 182 183 184

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// NOTE: Please do NOT register services here. Use `registerSingleton()`
		//       from `workbench.common.main.ts` if the service is shared between
		//       desktop and web or `workbench.sandbox.main.ts` if the service
		//       is desktop only.
		//
		//       DO NOT add services to `workbench.desktop.main.ts`, always add
		//       to `workbench.sandbox.main.ts` to support our Electron sandbox
		//
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

185

186
		// Main Process
187 188
		const mainProcessService = this._register(new MainProcessService(this.configuration.windowId));
		serviceCollection.set(IMainProcessService, mainProcessService);
189

B
Benjamin Pasero 已提交
190
		// Environment
191
		serviceCollection.set(IWorkbenchEnvironmentService, this.environmentService);
192
		serviceCollection.set(INativeWorkbenchEnvironmentService, this.environmentService);
B
Benjamin Pasero 已提交
193

194
		// Product
195
		serviceCollection.set(IProductService, this.productService);
196

B
Benjamin Pasero 已提交
197
		// Log
B
Benjamin Pasero 已提交
198
		const logService = this._register(new NativeLogService(this.configuration.windowId, mainProcessService, this.environmentService));
B
Benjamin Pasero 已提交
199 200
		serviceCollection.set(ILogService, logService);

201 202 203
		// Remote
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
B
Benjamin Pasero 已提交
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// NOTE: Please do NOT register services here. Use `registerSingleton()`
		//       from `workbench.common.main.ts` if the service is shared between
		//       desktop and web or `workbench.sandbox.main.ts` if the service
		//       is desktop only.
		//
		//       DO NOT add services to `workbench.desktop.main.ts`, always add
		//       to `workbench.sandbox.main.ts` to support our Electron sandbox
		//
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


I
isidor 已提交
219 220 221 222
		// Sign
		const signService = new SignService();
		serviceCollection.set(ISignService, signService);

223
		// Remote Agent
224
		const remoteAgentService = this._register(new RemoteAgentService(this.environmentService, this.productService, remoteAuthorityResolverService, signService, logService));
225 226
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

227 228 229
		// Native Host
		const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
		serviceCollection.set(INativeHostService, nativeHostService);
230

B
Benjamin Pasero 已提交
231
		// Files
B
Benjamin Pasero 已提交
232
		const fileService = this._register(new FileService(logService));
B
Benjamin Pasero 已提交
233 234
		serviceCollection.set(IFileService, fileService);

235
		const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService, nativeHostService));
236
		fileService.registerProvider(Schemas.file, diskFileSystemProvider);
B
Benjamin Pasero 已提交
237

238
		// User Data Provider
239
		fileService.registerProvider(Schemas.userData, new FileUserDataProvider(Schemas.file, diskFileSystemProvider, Schemas.userData, logService));
240

B
Benjamin Pasero 已提交
241
		// Uri Identity
242 243
		const uriIdentityService = new UriIdentityService(fileService);
		serviceCollection.set(IUriIdentityService, uriIdentityService);
244 245 246 247 248 249 250 251 252 253 254 255 256 257

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// NOTE: Please do NOT register services here. Use `registerSingleton()`
		//       from `workbench.common.main.ts` if the service is shared between
		//       desktop and web or `workbench.sandbox.main.ts` if the service
		//       is desktop only.
		//
		//       DO NOT add services to `workbench.desktop.main.ts`, always add
		//       to `workbench.sandbox.main.ts` to support our Electron sandbox
		//
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


258 259
		const connection = remoteAgentService.getConnection();
		if (connection) {
260
			const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService));
B
Benjamin Pasero 已提交
261
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
262 263
		}

S
Sandeep Somavarapu 已提交
264
		const payload = await this.resolveWorkspaceInitializationPayload();
265 266

		const services = await Promise.all([
267
			this.createWorkspaceService(payload, fileService, remoteAgentService, uriIdentityService, logService).then(service => {
B
Benjamin Pasero 已提交
268

269 270
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
271

272 273
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
274

275 276
				return service;
			}),
B
Benjamin Pasero 已提交
277

278
			this.createStorageService(payload, logService, mainProcessService).then(service => {
279 280 281 282

				// Storage
				serviceCollection.set(IStorageService, service);

283 284 285 286 287 288 289 290
				return service;
			}),

			this.createKeyboardLayoutService(logService, mainProcessService).then(service => {

				// KeyboardLayout
				serviceCollection.set(IKeyboardLayoutService, service);

291 292
				return service;
			})
293 294
		]);

295 296 297 298 299 300 301 302 303 304 305 306 307 308

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// NOTE: Please do NOT register services here. Use `registerSingleton()`
		//       from `workbench.common.main.ts` if the service is shared between
		//       desktop and web or `workbench.sandbox.main.ts` if the service
		//       is desktop only.
		//
		//       DO NOT add services to `workbench.desktop.main.ts`, always add
		//       to `workbench.sandbox.main.ts` to support our Electron sandbox
		//
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


309
		return { serviceCollection, logService, storageService: services[1] };
310
	}
311

S
Sandeep Somavarapu 已提交
312
	private async resolveWorkspaceInitializationPayload(): Promise<IWorkspaceInitializationPayload> {
B
Benjamin Pasero 已提交
313 314

		// Multi-root workspace
315 316
		if (this.configuration.workspace) {
			return this.configuration.workspace;
317 318
		}

B
Benjamin Pasero 已提交
319
		// Single-folder workspace
320
		let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined;
321
		if (this.configuration.folderUri) {
S
Sandeep Somavarapu 已提交
322
			workspaceInitializationPayload = await this.resolveSingleFolderWorkspaceInitializationPayload(this.configuration.folderUri);
B
Benjamin Pasero 已提交
323
		}
E
Erich Gamma 已提交
324

325 326 327
		// Fallback to empty workspace if we have no payload yet.
		if (!workspaceInitializationPayload) {
			let id: string;
S
Sandeep Somavarapu 已提交
328 329
			if (this.environmentService.backupWorkspaceHome) {
				id = basename(this.environmentService.backupWorkspaceHome); // we know the backupPath must be a unique path so we leverage its name as workspace ID
330
			} else if (this.environmentService.isExtensionDevelopment) {
331 332 333
				id = 'ext-dev'; // extension development window never stores backups and is a singleton
			} else {
				throw new Error('Unexpected window configuration without backupPath');
B
Benjamin Pasero 已提交
334
			}
335

336 337 338 339
			workspaceInitializationPayload = { id };
		}

		return workspaceInitializationPayload;
B
Benjamin Pasero 已提交
340
	}
341

S
Sandeep Somavarapu 已提交
342
	private async resolveSingleFolderWorkspaceInitializationPayload(folderUri: ISingleFolderWorkspaceIdentifier): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
343
		try {
344 345 346
			const folder = folderUri.scheme === Schemas.file
				? URI.file(sanitizeFilePath(folderUri.fsPath, process.env['VSCODE_CWD'] || process.cwd())) // For local: ensure path is absolute
				: folderUri;
S
Sandeep Somavarapu 已提交
347
			const id = await this.createHash(folderUri);
348
			return { id, folder };
349 350 351
		} catch (error) {
			onUnexpectedError(error);
		}
352

353
		return;
B
Benjamin Pasero 已提交
354
	}
355

S
Sandeep Somavarapu 已提交
356
	private async createHash(resource: URI): Promise<string> {
357

S
Sandeep Somavarapu 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
		// Return early the folder is not local
		if (resource.scheme !== Schemas.file) {
			return createHash('md5').update(resource.toString()).digest('hex');
		}

		const fileStat = await stat(resource.fsPath);
		let ctime: number | undefined;
		if (isLinux) {
			ctime = fileStat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead!
		} else if (isMacintosh) {
			ctime = fileStat.birthtime.getTime(); // macOS: birthtime is fine to use as is
		} else if (isWindows) {
			if (typeof fileStat.birthtimeMs === 'number') {
				ctime = Math.floor(fileStat.birthtimeMs); // Windows: fix precision issue in node.js 8.x to get 7.x results (see https://github.com/nodejs/node/issues/19897)
			} else {
				ctime = fileStat.birthtime.getTime();
			}
		}

		// we use the ctime as extra salt to the ID so that we catch the case of a folder getting
		// deleted and recreated. in that case we do not want to carry over previous state
		return createHash('md5').update(resource.fsPath).update(ctime ? String(ctime) : '').digest('hex');
	}

382 383
	private async createWorkspaceService(payload: IWorkspaceInitializationPayload, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
		const workspaceService = new WorkspaceService({ remoteAuthority: this.environmentService.remoteAuthority, configurationCache: new ConfigurationCache(this.environmentService) }, this.environmentService, fileService, remoteAgentService, uriIdentityService, logService);
S
Sandeep Somavarapu 已提交
384

385 386 387 388 389
		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
B
Benjamin Pasero 已提交
390 391
			onUnexpectedError(error);
			logService.error(error);
392

B
Benjamin Pasero 已提交
393
			return workspaceService;
394
		}
B
Benjamin Pasero 已提交
395
	}
396

397
	private async createStorageService(payload: IWorkspaceInitializationPayload, logService: ILogService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
398
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
399
		const storageService = new NativeStorageService(globalStorageDatabase, logService, this.environmentService);
400

401 402 403 404 405
		try {
			await storageService.initialize(payload);

			return storageService;
		} catch (error) {
B
Benjamin Pasero 已提交
406 407
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
408

B
Benjamin Pasero 已提交
409
			return storageService;
410
		}
B
Benjamin Pasero 已提交
411
	}
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

	private async createKeyboardLayoutService(logService: ILogService, mainProcessService: IMainProcessService): Promise<KeyboardLayoutService> {
		const keyboardLayoutService = new KeyboardLayoutService(mainProcessService);

		try {
			await keyboardLayoutService.initialize();

			return keyboardLayoutService;
		} catch (error) {
			onUnexpectedError(error);
			logService.error(error);

			return keyboardLayoutService;
		}
	}
427 428
}

429
export function main(configuration: INativeWorkbenchConfiguration): Promise<void> {
430
	const workbench = new DesktopMain(configuration);
431

432
	return workbench.open();
433
}