desktop.main.ts 16.6 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 { importEntries, mark } from 'vs/base/common/performance';
10
import { Workbench } from 'vs/workbench/browser/workbench';
B
Benjamin Pasero 已提交
11
import { ElectronWindow } from 'vs/workbench/electron-browser/window';
12
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
13
import { domContentLoaded, addDisposableListener, EventType, scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';
14
import { onUnexpectedError } from 'vs/base/common/errors';
B
Benjamin Pasero 已提交
15
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
16
import { URI } from 'vs/base/common/uri';
17
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
18 19
import { WorkbenchEnvironmentService } from 'vs/workbench/services/environment/node/environmentService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
20
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
21
import { stat } from 'vs/base/node/pfs';
P
Peng Lyu 已提交
22
import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/nativeKeymapService';
23
import { IWindowConfiguration } from 'vs/platform/windows/common/windows';
24
import { webFrame } from 'electron';
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 { IChannel } from 'vs/base/parts/ipc/common/ipc';
A
Alex Dima 已提交
46
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME, RemoteExtensionsFileSystemProvider } from 'vs/platform/remote/common/remoteAgentFileSystemChannel';
S
Sandeep Somavarapu 已提交
47
import { ConfigurationCache } from 'vs/workbench/services/configuration/node/configurationCache';
48
import { SpdLogService } from 'vs/platform/log/node/spdlogService';
I
isidor 已提交
49 50
import { SignService } from 'vs/platform/sign/node/signService';
import { ISignService } from 'vs/platform/sign/common/sign';
S
Sandeep Somavarapu 已提交
51
import { FileUserDataProvider } from 'vs/workbench/services/userData/common/fileUserDataProvider';
52
import { basename } from 'vs/base/common/resources';
53
import { IProductService } from 'vs/platform/product/common/productService';
54
import product from 'vs/platform/product/common/product';
55
import { ElectronEnvironmentService, IElectronEnvironmentService } from 'vs/workbench/services/electron/electron-browser/electronEnvironmentService';
J
Joao Moreno 已提交
56

B
Benjamin Pasero 已提交
57
class DesktopMain extends Disposable {
E
Erich Gamma 已提交
58

59
	private readonly environmentService: WorkbenchEnvironmentService;
60

61
	constructor(private configuration: IWindowConfiguration) {
B
Benjamin Pasero 已提交
62
		super();
B
Benjamin Pasero 已提交
63

64
		this.environmentService = new WorkbenchEnvironmentService(configuration, configuration.execPath, configuration.windowId);
65

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

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

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

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

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

B
Benjamin Pasero 已提交
80
		// Browser config
81 82
		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)
83
		setFullscreen(!!this.environmentService.configuration.fullscreen);
E
Erich Gamma 已提交
84

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

B
Benjamin Pasero 已提交
182
		// Environment
183
		serviceCollection.set(IWorkbenchEnvironmentService, this.environmentService);
184 185 186 187
		serviceCollection.set(IElectronEnvironmentService, new ElectronEnvironmentService(
			this.configuration.windowId,
			this.environmentService.sharedIPCHandle
		));
B
Benjamin Pasero 已提交
188

189 190 191
		// Product
		serviceCollection.set(IProductService, { _serviceBrand: undefined, ...product });

B
Benjamin Pasero 已提交
192
		// Log
193
		const logService = this._register(this.createLogService(mainProcessService, this.environmentService));
B
Benjamin Pasero 已提交
194 195
		serviceCollection.set(ILogService, logService);

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

I
isidor 已提交
200 201 202 203
		// Sign
		const signService = new SignService();
		serviceCollection.set(ISignService, signService);

204
		const remoteAgentService = this._register(new RemoteAgentService(this.environmentService.configuration, this.environmentService, remoteAuthorityResolverService, signService, logService));
205 206
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

B
Benjamin Pasero 已提交
207
		// Files
B
Benjamin Pasero 已提交
208
		const fileService = this._register(new FileService(logService));
B
Benjamin Pasero 已提交
209 210
		serviceCollection.set(IFileService, fileService);

211 212
		const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService));
		fileService.registerProvider(Schemas.file, diskFileSystemProvider);
B
Benjamin Pasero 已提交
213

214
		// User Data Provider
215
		fileService.registerProvider(Schemas.userData, new FileUserDataProvider(this.environmentService.appSettingsHome, this.environmentService.backupHome, diskFileSystemProvider, this.environmentService));
216

217 218 219
		const connection = remoteAgentService.getConnection();
		if (connection) {
			const channel = connection.getChannel<IChannel>(REMOTE_FILE_SYSTEM_CHANNEL_NAME);
220
			const remoteFileSystemProvider = this._register(new RemoteExtensionsFileSystemProvider(channel, remoteAgentService.getEnvironment()));
B
Benjamin Pasero 已提交
221
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
222 223
		}

224
		const payload = await this.resolveWorkspaceInitializationPayload();
225 226

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

229 230
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
231

232 233
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
234

235 236
				return service;
			}),
B
Benjamin Pasero 已提交
237

238
			this.createStorageService(payload, logService, mainProcessService).then(service => {
239 240 241 242 243 244

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

				return service;
			})
245 246 247
		]);

		return { serviceCollection, logService, storageService: services[1] };
248
	}
249

250
	private async resolveWorkspaceInitializationPayload(): Promise<IWorkspaceInitializationPayload> {
B
Benjamin Pasero 已提交
251 252

		// Multi-root workspace
253 254
		if (this.environmentService.configuration.workspace) {
			return this.environmentService.configuration.workspace;
255 256
		}

B
Benjamin Pasero 已提交
257
		// Single-folder workspace
258
		let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined;
259 260
		if (this.environmentService.configuration.folderUri) {
			workspaceInitializationPayload = await this.resolveSingleFolderWorkspaceInitializationPayload(this.environmentService.configuration.folderUri);
B
Benjamin Pasero 已提交
261
		}
E
Erich Gamma 已提交
262

263 264 265
		// Fallback to empty workspace if we have no payload yet.
		if (!workspaceInitializationPayload) {
			let id: string;
266 267 268
			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) {
269 270 271
				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 已提交
272
			}
273

274 275 276 277
			workspaceInitializationPayload = { id };
		}

		return workspaceInitializationPayload;
B
Benjamin Pasero 已提交
278
	}
279

280
	private async resolveSingleFolderWorkspaceInitializationPayload(folderUri: ISingleFolderWorkspaceIdentifier): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
281

B
Benjamin Pasero 已提交
282 283
		// Return early the folder is not local
		if (folderUri.scheme !== Schemas.file) {
284
			return { id: createHash('md5').update(folderUri.toString()).digest('hex'), folder: folderUri };
B
Benjamin Pasero 已提交
285
		}
286

287
		function computeLocalDiskFolderId(folder: URI, stat: fs.Stats): string {
B
Benjamin Pasero 已提交
288
			let ctime: number | undefined;
289
			if (isLinux) {
B
Benjamin Pasero 已提交
290
				ctime = stat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead!
291
			} else if (isMacintosh) {
B
Benjamin Pasero 已提交
292
				ctime = stat.birthtime.getTime(); // macOS: birthtime is fine to use as is
293
			} else if (isWindows) {
B
Benjamin Pasero 已提交
294 295 296 297 298 299
				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();
				}
			}
300

B
Benjamin Pasero 已提交
301 302 303 304
			// 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');
		}
305

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

311
			const sanitizedFolderUri = URI.file(sanitizedFolderPath);
B
Benjamin Pasero 已提交
312
			return {
313
				id: computeLocalDiskFolderId(sanitizedFolderUri, fileStat),
B
Benjamin Pasero 已提交
314
				folder: sanitizedFolderUri
315
			};
316 317 318 319 320
		} catch (error) {
			onUnexpectedError(error);
		}

		return;
B
Benjamin Pasero 已提交
321
	}
322

323 324
	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 已提交
325

326 327 328 329 330
		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
B
Benjamin Pasero 已提交
331 332
			onUnexpectedError(error);
			logService.error(error);
333

B
Benjamin Pasero 已提交
334
			return workspaceService;
335
		}
B
Benjamin Pasero 已提交
336
	}
337

338
	private async createStorageService(payload: IWorkspaceInitializationPayload, logService: ILogService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
339
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
340
		const storageService = new NativeStorageService(globalStorageDatabase, logService, this.environmentService);
341

342 343 344 345 346
		try {
			await storageService.initialize(payload);

			return storageService;
		} catch (error) {
B
Benjamin Pasero 已提交
347 348
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
349

B
Benjamin Pasero 已提交
350
			return storageService;
351
		}
B
Benjamin Pasero 已提交
352
	}
353

354
	private createLogService(mainProcessService: IMainProcessService, environmentService: IWorkbenchEnvironmentService): ILogService {
355 356 357 358 359 360 361 362 363 364 365 366 367 368
		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),
369
				new SpdLogService(`renderer${this.configuration.windowId}`, environmentService.logsPath, this.environmentService.configuration.logLevel)
370 371
			);
		}
372

373
		return new FollowerLogService(loggerClient, new MultiplexLogService(loggers));
B
Benjamin Pasero 已提交
374 375
	}
}
376

B
Benjamin Pasero 已提交
377
export function main(configuration: IWindowConfiguration): Promise<void> {
B
Benjamin Pasero 已提交
378
	const renderer = new DesktopMain(configuration);
379

380
	return renderer.open();
381
}