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 { 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';
S
Sandeep Somavarapu 已提交
26
import { ConsoleLogService, MultiplexLogService, ILogService } from 'vs/platform/log/common/log';
27
import { StorageService } from 'vs/platform/storage/node/storageService';
28
import { LogLevelSetterChannelClient, 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';
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';
47
import { DefaultConfigurationExportHelper } from 'vs/workbench/services/configuration/node/configurationExportHelper';
S
Sandeep Somavarapu 已提交
48
import { ConfigurationCache } from 'vs/workbench/services/configuration/node/configurationCache';
49
import { SpdLogService } from 'vs/platform/log/node/spdlogService';
I
isidor 已提交
50 51
import { SignService } from 'vs/platform/sign/node/signService';
import { ISignService } from 'vs/platform/sign/common/sign';
S
Sandeep Somavarapu 已提交
52
import { FileUserDataProvider } from 'vs/workbench/services/userData/common/fileUserDataProvider';
53
import { basename } from 'vs/base/common/resources';
54
import { IProductService } from 'vs/platform/product/common/productService';
55
import product from 'vs/platform/product/node/product';
J
Joao Moreno 已提交
56

57
class CodeRendererMain extends Disposable {
E
Erich Gamma 已提交
58

59
	private readonly environmentService: WorkbenchEnvironmentService;
60

61
	constructor(configuration: IWindowConfiguration) {
B
Benjamin Pasero 已提交
62
		super();
63
		this.environmentService = new WorkbenchEnvironmentService(configuration, configuration.execPath);
64

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

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

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

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

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

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

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

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

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

97
		const filesToWait = this.environmentService.configuration.filesToWait;
M
Martin Aeschlimann 已提交
98
		const filesToWaitPaths = filesToWait && filesToWait.paths;
99
		[filesToWaitPaths, this.environmentService.configuration.filesToOpenOrCreate, this.environmentService.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 116 117
	async open(): Promise<void> {
		const services = await this.initServices();
		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

122
		// Layout
123
		this._register(addDisposableListener(window, EventType.RESIZE, e => this.onWindowResize(e, true, workbench)));
B
Benjamin Pasero 已提交
124

125
		// Workbench Lifecycle
126 127
		this._register(workbench.onShutdown(() => this.dispose()));
		this._register(workbench.onWillShutdown(event => event.join(services.storageService.close())));
128

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

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

135
		// Driver
136
		if (this.environmentService.configuration.driver) {
137 138
			instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor)));
		}
139

140
		// Config Exporter
141
		if (this.environmentService.configuration['export-default-configuration']) {
142 143
			instantiationService.createInstance(DefaultConfigurationExportHelper);
		}
144

145
		// Logging
146
		services.logService.trace('workbench configuration', JSON.stringify(this.environmentService.configuration));
B
Benjamin Pasero 已提交
147
	}
148

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

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

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

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

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

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

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

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

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

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

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

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

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

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

210 211 212
		const connection = remoteAgentService.getConnection();
		if (connection) {
			const channel = connection.getChannel<IChannel>(REMOTE_FILE_SYSTEM_CHANNEL_NAME);
213
			const remoteFileSystemProvider = this._register(new RemoteExtensionsFileSystemProvider(channel, remoteAgentService.getEnvironment()));
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<StorageService> {
332
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
333
		const storageService = new StorageService(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
		const spdlogService = new SpdLogService(`renderer${this.environmentService.configuration.windowId}`, environmentService.logsPath, this.environmentService.configuration.logLevel);
		const consoleLogService = new ConsoleLogService(this.environmentService.configuration.logLevel);
B
Benjamin Pasero 已提交
350
		const logService = new MultiplexLogService([consoleLogService, spdlogService]);
351
		const logLevelClient = new LogLevelSetterChannelClient(mainProcessService.getChannel('loglevel'));
352

B
Benjamin Pasero 已提交
353 354 355
		return new FollowerLogService(logLevelClient, logService);
	}
}
356

B
Benjamin Pasero 已提交
357
export function main(configuration: IWindowConfiguration): Promise<void> {
358
	const renderer = new CodeRendererMain(configuration);
359

360
	return renderer.open();
361
}