main.ts 15.5 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 { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
20
import { stat } from 'vs/base/node/pfs';
J
Johannes Rieken 已提交
21
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
22
import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
23
import { IWindowConfiguration, IWindowService } from 'vs/platform/windows/common/windows';
24
import { WindowService } from 'vs/platform/windows/electron-browser/windowService';
B
Benjamin Pasero 已提交
25
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
26
import { webFrame } from 'electron';
27
import { ISingleFolderWorkspaceIdentifier, IWorkspaceInitializationPayload, ISingleFolderWorkspaceInitializationPayload, reviveWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
28
import { createSpdLogService } from 'vs/platform/log/node/spdlogService';
S
Sandeep Somavarapu 已提交
29
import { ConsoleLogService, MultiplexLogService, ILogService } from 'vs/platform/log/common/log';
30
import { StorageService } from 'vs/platform/storage/node/storageService';
J
Joao Moreno 已提交
31
import { LogLevelSetterChannelClient, FollowerLogService } from 'vs/platform/log/node/logIpc';
32
import { Schemas } from 'vs/base/common/network';
B
Benjamin Pasero 已提交
33
import { sanitizeFilePath } from 'vs/base/common/extpath';
34
import { basename } from 'vs/base/common/path';
B
wip  
Benjamin Pasero 已提交
35
import { GlobalStorageDatabaseChannelClient } from 'vs/platform/storage/node/storageIpc';
B
Benjamin Pasero 已提交
36 37 38
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 已提交
39
import { Disposable } from 'vs/base/common/lifecycle';
40
import { registerWindowDriver } from 'vs/platform/driver/electron-browser/driver';
41
import { IMainProcessService, MainProcessService } from 'vs/platform/ipc/electron-browser/mainProcessService';
42 43 44 45
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';
46 47
import { FileService2 } from 'vs/workbench/services/files2/common/fileService2';
import { IFileService } from 'vs/platform/files/common/files';
48
import { DiskFileSystemProvider } from 'vs/workbench/services/files2/electron-browser/diskFileSystemProvider';
49
import { IChannel } from 'vs/base/parts/ipc/common/ipc';
A
Alex Dima 已提交
50
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME, RemoteExtensionsFileSystemProvider } from 'vs/platform/remote/common/remoteAgentFileSystemChannel';
B
Benjamin Pasero 已提交
51
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
52
import { DefaultConfigurationExportHelper } from 'vs/workbench/services/configuration/node/configurationExportHelper';
S
Sandeep Somavarapu 已提交
53 54 55
import { HashService } from 'vs/workbench/services/hash/node/hashService';
import { IHashService } from 'vs/workbench/services/hash/common/hashService';
import { ConfigurationCache } from 'vs/workbench/services/configuration/node/configurationCache';
56
import { ConfigurationFileService } from 'vs/workbench/services/configuration/node/configurationFileService';
J
Joao Moreno 已提交
57

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

60 61
	private workbench: Workbench;

B
Benjamin Pasero 已提交
62 63
	constructor(private readonly configuration: IWindowConfiguration) {
		super();
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.configuration.perfEntries);
A
Alex Dima 已提交
78

B
Benjamin Pasero 已提交
79
		// Browser config
80 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)
		setFullscreen(!!this.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 89
	private reviveUris() {
		if (this.configuration.folderUri) {
90
			this.configuration.folderUri = URI.revive(this.configuration.folderUri);
B
Benjamin Pasero 已提交
91
		}
92

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

M
Martin Aeschlimann 已提交
97 98
		const filesToWait = this.configuration.filesToWait;
		const filesToWaitPaths = filesToWait && filesToWait.paths;
B
Benjamin Pasero 已提交
99 100 101 102
		[filesToWaitPaths, this.configuration.filesToOpen, this.configuration.filesToCreate, this.configuration.filesToDiff].forEach(paths => {
			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

B
Benjamin Pasero 已提交
114
	open(): Promise<void> {
115
		return this.initServices().then(services => {
B
Benjamin Pasero 已提交
116

B
Benjamin Pasero 已提交
117
			return domContentLoaded().then(() => {
118
				mark('willStartWorkbench');
B
Benjamin Pasero 已提交
119

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

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

B
Benjamin Pasero 已提交
126
				// Workbench Lifecycle
127
				this._register(this.workbench.onShutdown(() => this.dispose()));
128
				this._register(this.workbench.onWillShutdown(event => event.join(services.storageService.close())));
B
Benjamin Pasero 已提交
129 130

				// Startup
131
				const instantiationService = this.workbench.startup();
B
Benjamin Pasero 已提交
132 133

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

136
				// Driver
B
Benjamin Pasero 已提交
137
				if (this.configuration.driver) {
138
					instantiationService.invokeFunction(accessor => registerWindowDriver(accessor).then(disposable => this._register(disposable)));
139
				}
140 141

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

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

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

			this.workbench.layout();
		}
	}

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

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

177 178 179
		// Window
		serviceCollection.set(IWindowService, new SyncDescriptor(WindowService, [this.configuration]));

B
Benjamin Pasero 已提交
180 181 182 183 184
		// Environment
		const environmentService = new EnvironmentService(this.configuration, this.configuration.execPath);
		serviceCollection.set(IEnvironmentService, environmentService);

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

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

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

B
Benjamin Pasero 已提交
195
		// Files
196
		const fileService = this._register(new FileService2(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 203 204
		const connection = remoteAgentService.getConnection();
		if (connection) {
			const channel = connection.getChannel<IChannel>(REMOTE_FILE_SYSTEM_CHANNEL_NAME);
205 206
			const remoteFileSystemProvider = this._register(new RemoteExtensionsFileSystemProvider(channel, remoteAgentService.getEnvironment()));
			fileService.registerProvider(REMOTE_HOST_SCHEME, remoteFileSystemProvider);
207 208
		}

S
Sandeep Somavarapu 已提交
209 210 211 212
		// Hash Service
		const hashService = new HashService();
		serviceCollection.set(IHashService, hashService);

213
		return this.resolveWorkspaceInitializationPayload(environmentService).then(payload => Promise.all([
S
Sandeep Somavarapu 已提交
214
			this.createWorkspaceService(payload, environmentService, hashService, remoteAgentService, logService).then(service => {
B
Benjamin Pasero 已提交
215

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

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

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

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

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

				return service;
			})
		]).then(services => ({ serviceCollection, logService, storageService: services[1] })));
233
	}
234

B
Benjamin Pasero 已提交
235 236 237 238
	private resolveWorkspaceInitializationPayload(environmentService: EnvironmentService): Promise<IWorkspaceInitializationPayload> {

		// Multi-root workspace
		if (this.configuration.workspace) {
239
			return Promise.resolve(this.configuration.workspace);
240 241
		}

B
Benjamin Pasero 已提交
242 243 244 245 246
		// Single-folder workspace
		let workspaceInitializationPayload: Promise<IWorkspaceInitializationPayload | undefined> = Promise.resolve(undefined);
		if (this.configuration.folderUri) {
			workspaceInitializationPayload = this.resolveSingleFolderWorkspaceInitializationPayload(this.configuration.folderUri);
		}
E
Erich Gamma 已提交
247

B
Benjamin Pasero 已提交
248 249 250 251 252 253 254 255 256 257 258 259
		return workspaceInitializationPayload.then(payload => {

			// Fallback to empty workspace if we have no payload yet.
			if (!payload) {
				let id: string;
				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
				} else if (environmentService.isExtensionDevelopment) {
					id = 'ext-dev'; // extension development window never stores backups and is a singleton
				} else {
					return Promise.reject(new Error('Unexpected window configuration without backupPath'));
				}
E
Erich Gamma 已提交
260

261
				payload = { id };
B
Benjamin Pasero 已提交
262
			}
263

B
Benjamin Pasero 已提交
264 265 266
			return payload;
		});
	}
267

B
Benjamin Pasero 已提交
268
	private resolveSingleFolderWorkspaceInitializationPayload(folderUri: ISingleFolderWorkspaceIdentifier): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
269

B
Benjamin Pasero 已提交
270 271 272 273
		// Return early the folder is not local
		if (folderUri.scheme !== Schemas.file) {
			return Promise.resolve({ id: createHash('md5').update(folderUri.toString()).digest('hex'), folder: folderUri });
		}
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 295 296
		// For local: ensure path is absolute and exists
		const sanitizedFolderPath = sanitizeFilePath(folderUri.fsPath, process.env['VSCODE_CWD'] || process.cwd());
		return stat(sanitizedFolderPath).then(stat => {
297
			const sanitizedFolderUri = URI.file(sanitizedFolderPath);
B
Benjamin Pasero 已提交
298 299 300
			return {
				id: computeLocalDiskFolderId(sanitizedFolderUri, stat),
				folder: sanitizedFolderUri
301
			};
B
Benjamin Pasero 已提交
302 303
		}, error => onUnexpectedError(error));
	}
304

S
Sandeep Somavarapu 已提交
305
	private createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: IEnvironmentService, hashService: IHashService, remoteAgentService: IRemoteAgentService, logService: ILogService): Promise<WorkspaceService> {
306
		const workspaceService = new WorkspaceService({ userSettingsResource: URI.file(environmentService.appSettingsPath), remoteAuthority: this.configuration.remoteAuthority, configurationCache: new ConfigurationCache(environmentService) }, new ConfigurationFileService(), hashService, remoteAgentService);
S
Sandeep Somavarapu 已提交
307

B
Benjamin Pasero 已提交
308 309 310
		return workspaceService.initialize(payload).then(() => workspaceService, error => {
			onUnexpectedError(error);
			logService.error(error);
311

B
Benjamin Pasero 已提交
312 313 314
			return workspaceService;
		});
	}
315

316 317
	private createStorageService(payload: IWorkspaceInitializationPayload, environmentService: IEnvironmentService, logService: ILogService, mainProcessService: IMainProcessService): Promise<StorageService> {
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
B
Benjamin Pasero 已提交
318
		const storageService = new StorageService(globalStorageDatabase, logService, environmentService);
319

B
Benjamin Pasero 已提交
320 321 322
		return storageService.initialize(payload).then(() => storageService, error => {
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
323

B
Benjamin Pasero 已提交
324 325 326
			return storageService;
		});
	}
327

328
	private createLogService(mainProcessService: IMainProcessService, environmentService: IEnvironmentService): ILogService {
B
Benjamin Pasero 已提交
329 330 331
		const spdlogService = createSpdLogService(`renderer${this.configuration.windowId}`, this.configuration.logLevel, environmentService.logsPath);
		const consoleLogService = new ConsoleLogService(this.configuration.logLevel);
		const logService = new MultiplexLogService([consoleLogService, spdlogService]);
332
		const logLevelClient = new LogLevelSetterChannelClient(mainProcessService.getChannel('loglevel'));
333

B
Benjamin Pasero 已提交
334 335 336
		return new FollowerLogService(logLevelClient, logService);
	}
}
337

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

341
	return renderer.open();
342
}