desktop.main.ts 18.0 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 { 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
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
S
Sandeep Somavarapu 已提交
31
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
B
Benjamin Pasero 已提交
32
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/path';
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
		// Browser config
79 80 81
		const zoomLevel = this.configuration.zoomLevel || 0;
		setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
		setZoomLevel(zoomLevel, true /* isTrusted */);
82
		setFullscreen(!!this.configuration.fullscreen);
M
Martin Aeschlimann 已提交
83
	}
84

B
Benjamin Pasero 已提交
85
	private reviveUris() {
86 87
		if (this.configuration.folderUri) {
			this.configuration.folderUri = URI.revive(this.configuration.folderUri);
B
Benjamin Pasero 已提交
88
		}
89

90 91
		if (this.configuration.workspace) {
			this.configuration.workspace = reviveWorkspaceIdentifier(this.configuration.workspace);
M
Martin Aeschlimann 已提交
92
		}
B
Benjamin Pasero 已提交
93

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

M
Martin Aeschlimann 已提交
106
		if (filesToWait) {
107
			filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
M
Martin Aeschlimann 已提交
108
		}
B
Benjamin Pasero 已提交
109
	}
B
Benjamin Pasero 已提交
110

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

114 115
		await domContentLoaded();
		mark('willStartWorkbench');
B
Benjamin Pasero 已提交
116

117
		// Create Workbench
118
		const workbench = new Workbench(document.body, services.serviceCollection, services.logService);
B
Benjamin Pasero 已提交
119

B
Benjamin Pasero 已提交
120 121
		// Listeners
		this.registerListeners(workbench, services.storageService);
122

123
		// Startup
124
		const instantiationService = workbench.startup();
B
Benjamin Pasero 已提交
125

126
		// Window
127
		this._register(instantiationService.createInstance(NativeWindow));
B
Benjamin Pasero 已提交
128

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

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

138
	private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
B
Benjamin Pasero 已提交
139 140 141 142 143 144

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

		// Workbench Lifecycle
		this._register(workbench.onShutdown(() => this.dispose()));
145
		this._register(workbench.onWillShutdown(event => event.join(storageService.close(), 'join.closeStorage')));
B
Benjamin Pasero 已提交
146 147
	}

148
	private onWindowResize(e: Event, retry: boolean, workbench: Workbench): void {
149 150 151 152 153 154 155 156
		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) {
157
					scheduleAtNextAnimationFrame(() => this.onWindowResize(e, false, workbench));
158 159 160 161
				}
				return;
			}

162
			workbench.layout();
163 164 165
		}
	}

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

169 170 171 172 173 174 175 176 177 178 179 180 181

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// 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
		//
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

182

183
		// Main Process
184 185
		const mainProcessService = this._register(new MainProcessService(this.configuration.windowId));
		serviceCollection.set(IMainProcessService, mainProcessService);
186

B
Benjamin Pasero 已提交
187
		// Environment
188
		serviceCollection.set(IWorkbenchEnvironmentService, this.environmentService);
189
		serviceCollection.set(INativeWorkbenchEnvironmentService, this.environmentService);
B
Benjamin Pasero 已提交
190

191
		// Product
192
		serviceCollection.set(IProductService, this.productService);
193

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

198 199 200
		// Remote
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
B
Benjamin Pasero 已提交
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// 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 已提交
216 217 218 219
		// Sign
		const signService = new SignService();
		serviceCollection.set(ISignService, signService);

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

224 225 226
		// Native Host
		const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
		serviceCollection.set(INativeHostService, nativeHostService);
227

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

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

235
		// User Data Provider
236
		fileService.registerProvider(Schemas.userData, new FileUserDataProvider(Schemas.file, diskFileSystemProvider, Schemas.userData, logService));
237

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

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// 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
		//
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


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

S
Sandeep Somavarapu 已提交
261
		const payload = await this.resolveWorkspaceInitializationPayload();
262 263

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

266 267
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
268

269
				// Configuration
S
Sandeep Somavarapu 已提交
270
				serviceCollection.set(IWorkbenchConfigurationService, service);
B
Benjamin Pasero 已提交
271

272 273
				return service;
			}),
B
Benjamin Pasero 已提交
274

275
			this.createStorageService(payload, logService, mainProcessService).then(service => {
276 277 278 279

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

280 281 282 283 284 285 286 287
				return service;
			}),

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

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

288 289
				return service;
			})
290 291
		]);

292 293 294 295 296 297 298 299 300 301 302 303 304 305

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//
		// 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
		//
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


306
		return { serviceCollection, logService, storageService: services[1] };
307
	}
308

S
Sandeep Somavarapu 已提交
309
	private async resolveWorkspaceInitializationPayload(): Promise<IWorkspaceInitializationPayload> {
B
Benjamin Pasero 已提交
310 311

		// Multi-root workspace
312 313
		if (this.configuration.workspace) {
			return this.configuration.workspace;
314 315
		}

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

322 323 324
		// Fallback to empty workspace if we have no payload yet.
		if (!workspaceInitializationPayload) {
			let id: string;
325 326
			if (this.configuration.backupPath) {
				id = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID
327
			} else if (this.environmentService.isExtensionDevelopment) {
328 329 330
				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 已提交
331
			}
332

333 334 335 336
			workspaceInitializationPayload = { id };
		}

		return workspaceInitializationPayload;
B
Benjamin Pasero 已提交
337
	}
338

S
Sandeep Somavarapu 已提交
339
	private async resolveSingleFolderWorkspaceInitializationPayload(folderUri: ISingleFolderWorkspaceIdentifier): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
340
		try {
341 342 343
			const folder = folderUri.scheme === Schemas.file
				? URI.file(sanitizeFilePath(folderUri.fsPath, process.env['VSCODE_CWD'] || process.cwd())) // For local: ensure path is absolute
				: folderUri;
B
Benjamin Pasero 已提交
344 345 346 347 348

			return {
				id: await this.createHash(folderUri),
				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
}