desktop.main.ts 15.8 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';
J
Joao Moreno 已提交
54

55
class CodeRendererMain extends Disposable {
E
Erich Gamma 已提交
56

57
	private readonly environmentService: WorkbenchEnvironmentService;
58

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

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

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

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

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

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

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

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

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

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

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

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

112 113 114 115
	async open(): Promise<void> {
		const services = await this.initServices();
		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

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

123
		// Workbench Lifecycle
124 125
		this._register(workbench.onShutdown(() => this.dispose()));
		this._register(workbench.onWillShutdown(event => event.join(services.storageService.close())));
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) {
135 136
			instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor)));
		}
137

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

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

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

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

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

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

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

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

		// Log
181
		const logService = this._register(this.createLogService(mainProcessService, this.environmentService));
B
Benjamin Pasero 已提交
182 183
		serviceCollection.set(ILogService, logService);

184 185 186
		// Remote
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
B
Benjamin Pasero 已提交
187

I
isidor 已提交
188 189 190 191
		// Sign
		const signService = new SignService();
		serviceCollection.set(ISignService, signService);

192
		const remoteAgentService = this._register(new RemoteAgentService(this.environmentService.configuration, this.environmentService, remoteAuthorityResolverService, signService));
193 194
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

B
Benjamin Pasero 已提交
195
		// Files
B
Benjamin Pasero 已提交
196
		const fileService = this._register(new FileService(logService));
B
Benjamin Pasero 已提交
197 198
		serviceCollection.set(IFileService, fileService);

199 200
		const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService));
		fileService.registerProvider(Schemas.file, diskFileSystemProvider);
B
Benjamin Pasero 已提交
201

202
		// User Data Provider
203
		fileService.registerProvider(Schemas.userData, new FileUserDataProvider(this.environmentService.appSettingsHome, this.environmentService.backupHome, diskFileSystemProvider, this.environmentService));
204

205 206 207
		const connection = remoteAgentService.getConnection();
		if (connection) {
			const channel = connection.getChannel<IChannel>(REMOTE_FILE_SYSTEM_CHANNEL_NAME);
208
			const remoteFileSystemProvider = this._register(new RemoteExtensionsFileSystemProvider(channel, remoteAgentService.getEnvironment()));
B
Benjamin Pasero 已提交
209
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
210 211
		}

212
		const payload = await this.resolveWorkspaceInitializationPayload();
213 214

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

217 218
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
219

220 221
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
222

223 224
				return service;
			}),
B
Benjamin Pasero 已提交
225

226
			this.createStorageService(payload, logService, mainProcessService).then(service => {
227 228 229 230 231 232

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

				return service;
			})
233 234 235
		]);

		return { serviceCollection, logService, storageService: services[1] };
236
	}
237

238
	private async resolveWorkspaceInitializationPayload(): Promise<IWorkspaceInitializationPayload> {
B
Benjamin Pasero 已提交
239 240

		// Multi-root workspace
241 242
		if (this.environmentService.configuration.workspace) {
			return this.environmentService.configuration.workspace;
243 244
		}

B
Benjamin Pasero 已提交
245
		// Single-folder workspace
246
		let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined;
247 248
		if (this.environmentService.configuration.folderUri) {
			workspaceInitializationPayload = await this.resolveSingleFolderWorkspaceInitializationPayload(this.environmentService.configuration.folderUri);
B
Benjamin Pasero 已提交
249
		}
E
Erich Gamma 已提交
250

251 252 253
		// Fallback to empty workspace if we have no payload yet.
		if (!workspaceInitializationPayload) {
			let id: string;
254 255 256
			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) {
257 258 259
				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 已提交
260
			}
261

262 263 264 265
			workspaceInitializationPayload = { id };
		}

		return workspaceInitializationPayload;
B
Benjamin Pasero 已提交
266
	}
267

268
	private async resolveSingleFolderWorkspaceInitializationPayload(folderUri: ISingleFolderWorkspaceIdentifier): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
269

B
Benjamin Pasero 已提交
270 271
		// Return early the folder is not local
		if (folderUri.scheme !== Schemas.file) {
272
			return { id: createHash('md5').update(folderUri.toString()).digest('hex'), folder: folderUri };
B
Benjamin Pasero 已提交
273
		}
274

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

B
Benjamin Pasero 已提交
289 290 291 292
			// 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');
		}
293

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

299
			const sanitizedFolderUri = URI.file(sanitizedFolderPath);
B
Benjamin Pasero 已提交
300
			return {
301
				id: computeLocalDiskFolderId(sanitizedFolderUri, fileStat),
B
Benjamin Pasero 已提交
302
				folder: sanitizedFolderUri
303
			};
304 305 306 307 308
		} catch (error) {
			onUnexpectedError(error);
		}

		return;
B
Benjamin Pasero 已提交
309
	}
310

311 312
	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 已提交
313

314 315 316 317 318
		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
B
Benjamin Pasero 已提交
319 320
			onUnexpectedError(error);
			logService.error(error);
321

B
Benjamin Pasero 已提交
322
			return workspaceService;
323
		}
B
Benjamin Pasero 已提交
324
	}
325

326
	private async createStorageService(payload: IWorkspaceInitializationPayload, logService: ILogService, mainProcessService: IMainProcessService): Promise<StorageService> {
327
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
328
		const storageService = new StorageService(globalStorageDatabase, logService, this.environmentService);
329

330 331 332 333 334
		try {
			await storageService.initialize(payload);

			return storageService;
		} catch (error) {
B
Benjamin Pasero 已提交
335 336
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
337

B
Benjamin Pasero 已提交
338
			return storageService;
339
		}
B
Benjamin Pasero 已提交
340
	}
341

342
	private createLogService(mainProcessService: IMainProcessService, environmentService: IWorkbenchEnvironmentService): ILogService {
343 344
		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 已提交
345
		const logService = new MultiplexLogService([consoleLogService, spdlogService]);
346
		const logLevelClient = new LogLevelSetterChannelClient(mainProcessService.getChannel('loglevel'));
347

B
Benjamin Pasero 已提交
348 349 350
		return new FollowerLogService(logLevelClient, logService);
	}
}
351

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

355
	return renderer.open();
356
}