desktop.main.ts 16.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';
8
import { createHash } from 'crypto';
9
import { webFrame } from 'electron';
10
import { importEntries, mark } from 'vs/base/common/performance';
11
import { Workbench } from 'vs/workbench/browser/workbench';
12
import { NativeWindow } from 'vs/workbench/electron-browser/window';
13
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
14
import { domContentLoaded, addDisposableListener, EventType, scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';
15
import { onUnexpectedError } from 'vs/base/common/errors';
B
Benjamin Pasero 已提交
16
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
17
import { URI } from 'vs/base/common/uri';
18
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
19
import { NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService';
20
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
21
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
22
import { stat } from 'vs/base/node/pfs';
P
Peng Lyu 已提交
23
import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/nativeKeymapService';
24
import { INativeWindowConfiguration } from 'vs/platform/windows/node/window';
25
import { ISingleFolderWorkspaceIdentifier, IWorkspaceInitializationPayload, ISingleFolderWorkspaceInitializationPayload, reviveWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
26
import { ConsoleLogService, MultiplexLogService, ILogService, ConsoleLogInMainService } from 'vs/platform/log/common/log';
27
import { NativeStorageService } from 'vs/platform/storage/node/storageService';
28
import { LoggerChannelClient, FollowerLogService } from 'vs/platform/log/common/logIpc';
29
import { Schemas } from 'vs/base/common/network';
B
Benjamin Pasero 已提交
30
import { sanitizeFilePath } from 'vs/base/common/extpath';
B
wip  
Benjamin Pasero 已提交
31
import { GlobalStorageDatabaseChannelClient } from 'vs/platform/storage/node/storageIpc';
B
Benjamin Pasero 已提交
32 33 34
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
B
Benjamin Pasero 已提交
35
import { Disposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
36
import { registerWindowDriver } from 'vs/platform/driver/electron-browser/driver';
37
import { IMainProcessService, MainProcessService } from 'vs/platform/ipc/electron-browser/mainProcessService';
38 39 40 41
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-browser/remoteAuthorityResolverService';
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';
42
import { FileService } from 'vs/platform/files/common/fileService';
43
import { IFileService } from 'vs/platform/files/common/files';
44
import { DiskFileSystemProvider } from 'vs/platform/files/electron-browser/diskFileSystemProvider';
45
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
S
Sandeep Somavarapu 已提交
46
import { ConfigurationCache } from 'vs/workbench/services/configuration/node/configurationCache';
47
import { SpdLogService } from 'vs/platform/log/node/spdlogService';
I
isidor 已提交
48 49
import { SignService } from 'vs/platform/sign/node/signService';
import { ISignService } from 'vs/platform/sign/common/sign';
S
Sandeep Somavarapu 已提交
50
import { FileUserDataProvider } from 'vs/workbench/services/userData/common/fileUserDataProvider';
51
import { basename } from 'vs/base/common/resources';
52
import { IProductService } from 'vs/platform/product/common/productService';
53
import product from 'vs/platform/product/common/product';
J
Joao Moreno 已提交
54

B
Benjamin Pasero 已提交
55
class DesktopMain extends Disposable {
E
Erich Gamma 已提交
56

57
	private readonly environmentService: NativeWorkbenchEnvironmentService;
58

59
	constructor(private configuration: INativeWindowConfiguration) {
B
Benjamin Pasero 已提交
60
		super();
B
Benjamin Pasero 已提交
61

62
		this.environmentService = new NativeWorkbenchEnvironmentService(configuration, configuration.execPath);
63

B
Benjamin Pasero 已提交
64 65
		this.init();
	}
M
Martin Aeschlimann 已提交
66

B
Benjamin Pasero 已提交
67
	private init(): void {
68

B
Benjamin Pasero 已提交
69 70
		// Enable gracefulFs
		gracefulFs.gracefulify(fs);
71

B
Benjamin Pasero 已提交
72 73
		// Massage configuration file URIs
		this.reviveUris();
74

B
Benjamin Pasero 已提交
75
		// Setup perf
76
		importEntries(this.environmentService.configuration.perfEntries);
A
Alex Dima 已提交
77

B
Benjamin Pasero 已提交
78
		// Browser config
79 80
		setZoomFactor(webFrame.getZoomFactor()); // Ensure others can listen to zoom level changes
		setZoomLevel(webFrame.getZoomLevel(), true /* isTrusted */); // Can be trusted because we are not setting it ourselves (https://github.com/Microsoft/vscode/issues/26151)
81
		setFullscreen(!!this.environmentService.configuration.fullscreen);
E
Erich Gamma 已提交
82

B
Benjamin Pasero 已提交
83 84
		// Keyboard support
		KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
M
Martin Aeschlimann 已提交
85
	}
86

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

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

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

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

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

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

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

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

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

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

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

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

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

		// 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())));
	}

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

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

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

171 172
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		// NOTE: DO NOT ADD ANY OTHER SERVICE INTO THE COLLECTION HERE.
173
		// CONTRIBUTE IT VIA WORKBENCH.DESKTOP.MAIN.TS AND registerSingleton().
174 175
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

176
		// Main Process
177
		const mainProcessService = this._register(new MainProcessService(this.configuration.windowId));
178
		serviceCollection.set(IMainProcessService, mainProcessService);
179

B
Benjamin Pasero 已提交
180
		// Environment
181
		serviceCollection.set(IWorkbenchEnvironmentService, this.environmentService);
B
Benjamin Pasero 已提交
182

183 184 185
		// Product
		serviceCollection.set(IProductService, { _serviceBrand: undefined, ...product });

B
Benjamin Pasero 已提交
186
		// Log
187
		const logService = this._register(this.createLogService(mainProcessService, this.environmentService));
B
Benjamin Pasero 已提交
188 189
		serviceCollection.set(ILogService, logService);

190 191 192
		// Remote
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
B
Benjamin Pasero 已提交
193

I
isidor 已提交
194 195 196 197
		// Sign
		const signService = new SignService();
		serviceCollection.set(ISignService, signService);

198
		const remoteAgentService = this._register(new RemoteAgentService(this.environmentService.configuration, this.environmentService, remoteAuthorityResolverService, signService, logService));
199 200
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

B
Benjamin Pasero 已提交
201
		// Files
B
Benjamin Pasero 已提交
202
		const fileService = this._register(new FileService(logService));
B
Benjamin Pasero 已提交
203 204
		serviceCollection.set(IFileService, fileService);

205 206
		const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService));
		fileService.registerProvider(Schemas.file, diskFileSystemProvider);
B
Benjamin Pasero 已提交
207

208
		// User Data Provider
209
		fileService.registerProvider(Schemas.userData, new FileUserDataProvider(this.environmentService.appSettingsHome, this.environmentService.backupHome, diskFileSystemProvider, this.environmentService));
210

211 212
		const connection = remoteAgentService.getConnection();
		if (connection) {
213
			const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService));
B
Benjamin Pasero 已提交
214
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
215 216
		}

217
		const payload = await this.resolveWorkspaceInitializationPayload();
218 219

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

222 223
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
224

225 226
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
227

228 229
				return service;
			}),
B
Benjamin Pasero 已提交
230

231
			this.createStorageService(payload, logService, mainProcessService).then(service => {
232 233 234 235 236 237

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

				return service;
			})
238 239 240
		]);

		return { serviceCollection, logService, storageService: services[1] };
241
	}
242

243
	private async resolveWorkspaceInitializationPayload(): Promise<IWorkspaceInitializationPayload> {
B
Benjamin Pasero 已提交
244 245

		// Multi-root workspace
246 247
		if (this.environmentService.configuration.workspace) {
			return this.environmentService.configuration.workspace;
248 249
		}

B
Benjamin Pasero 已提交
250
		// Single-folder workspace
251
		let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined;
252 253
		if (this.environmentService.configuration.folderUri) {
			workspaceInitializationPayload = await this.resolveSingleFolderWorkspaceInitializationPayload(this.environmentService.configuration.folderUri);
B
Benjamin Pasero 已提交
254
		}
E
Erich Gamma 已提交
255

256 257 258
		// Fallback to empty workspace if we have no payload yet.
		if (!workspaceInitializationPayload) {
			let id: string;
259 260 261
			if (this.environmentService.configuration.backupWorkspaceResource) {
				id = basename(this.environmentService.configuration.backupWorkspaceResource); // we know the backupPath must be a unique path so we leverage its name as workspace ID
			} else if (this.environmentService.isExtensionDevelopment) {
262 263 264
				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 已提交
265
			}
266

267 268 269 270
			workspaceInitializationPayload = { id };
		}

		return workspaceInitializationPayload;
B
Benjamin Pasero 已提交
271
	}
272

273
	private async resolveSingleFolderWorkspaceInitializationPayload(folderUri: ISingleFolderWorkspaceIdentifier): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
274

B
Benjamin Pasero 已提交
275 276
		// Return early the folder is not local
		if (folderUri.scheme !== Schemas.file) {
277
			return { id: createHash('md5').update(folderUri.toString()).digest('hex'), folder: folderUri };
B
Benjamin Pasero 已提交
278
		}
279

280
		function computeLocalDiskFolderId(folder: URI, stat: fs.Stats): string {
B
Benjamin Pasero 已提交
281
			let ctime: number | undefined;
282
			if (isLinux) {
B
Benjamin Pasero 已提交
283
				ctime = stat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead!
284
			} else if (isMacintosh) {
B
Benjamin Pasero 已提交
285
				ctime = stat.birthtime.getTime(); // macOS: birthtime is fine to use as is
286
			} else if (isWindows) {
B
Benjamin Pasero 已提交
287 288 289 290 291 292
				if (typeof stat.birthtimeMs === 'number') {
					ctime = Math.floor(stat.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 = stat.birthtime.getTime();
				}
			}
293

B
Benjamin Pasero 已提交
294 295 296 297
			// 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(folder.fsPath).update(ctime ? String(ctime) : '').digest('hex');
		}
298

B
Benjamin Pasero 已提交
299
		// For local: ensure path is absolute and exists
300 301 302 303
		try {
			const sanitizedFolderPath = sanitizeFilePath(folderUri.fsPath, process.env['VSCODE_CWD'] || process.cwd());
			const fileStat = await stat(sanitizedFolderPath);

304
			const sanitizedFolderUri = URI.file(sanitizedFolderPath);
B
Benjamin Pasero 已提交
305
			return {
306
				id: computeLocalDiskFolderId(sanitizedFolderUri, fileStat),
B
Benjamin Pasero 已提交
307
				folder: sanitizedFolderUri
308
			};
309 310 311 312 313
		} catch (error) {
			onUnexpectedError(error);
		}

		return;
B
Benjamin Pasero 已提交
314
	}
315

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

319 320 321 322 323
		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
B
Benjamin Pasero 已提交
324 325
			onUnexpectedError(error);
			logService.error(error);
326

B
Benjamin Pasero 已提交
327
			return workspaceService;
328
		}
B
Benjamin Pasero 已提交
329
	}
330

331
	private async createStorageService(payload: IWorkspaceInitializationPayload, logService: ILogService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
332
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
333
		const storageService = new NativeStorageService(globalStorageDatabase, logService, this.environmentService);
334

335 336 337 338 339
		try {
			await storageService.initialize(payload);

			return storageService;
		} catch (error) {
B
Benjamin Pasero 已提交
340 341
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
342

B
Benjamin Pasero 已提交
343
			return storageService;
344
		}
B
Benjamin Pasero 已提交
345
	}
346

347
	private createLogService(mainProcessService: IMainProcessService, environmentService: IWorkbenchEnvironmentService): ILogService {
348 349 350 351 352 353 354 355 356 357 358 359 360 361
		const loggerClient = new LoggerChannelClient(mainProcessService.getChannel('logger'));

		// Extension development test CLI: forward everything to main side
		const loggers: ILogService[] = [];
		if (environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI) {
			loggers.push(
				new ConsoleLogInMainService(loggerClient, this.environmentService.configuration.logLevel)
			);
		}

		// Normal logger: spdylog and console
		else {
			loggers.push(
				new ConsoleLogService(this.environmentService.configuration.logLevel),
362
				new SpdLogService(`renderer${this.configuration.windowId}`, environmentService.logsPath, this.environmentService.configuration.logLevel)
363 364
			);
		}
365

366
		return new FollowerLogService(loggerClient, new MultiplexLogService(loggers));
B
Benjamin Pasero 已提交
367 368
	}
}
369

370
export function main(configuration: INativeWindowConfiguration): Promise<void> {
B
Benjamin Pasero 已提交
371
	const renderer = new DesktopMain(configuration);
372

373
	return renderer.open();
374
}