main.ts 12.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';
15
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
16
import { URI as uri } from 'vs/base/common/uri';
17
import { WorkspaceService, DefaultConfigurationExportHelper } from 'vs/workbench/services/configuration/node/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, IMultiFolderWorkspaceInitializationPayload, IEmptyWorkspaceInitializationPayload, 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';
33
import { sanitizeFilePath } from 'vs/base/node/extfs';
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';
J
Joao Moreno 已提交
42

43
class CodeRendererMain extends Disposable {
E
Erich Gamma 已提交
44

45 46
	private workbench: Workbench;

B
Benjamin Pasero 已提交
47 48
	constructor(private readonly configuration: IWindowConfiguration) {
		super();
49

B
Benjamin Pasero 已提交
50 51
		this.init();
	}
M
Martin Aeschlimann 已提交
52

B
Benjamin Pasero 已提交
53
	private init(): void {
54

B
Benjamin Pasero 已提交
55 56
		// Enable gracefulFs
		gracefulFs.gracefulify(fs);
57

B
Benjamin Pasero 已提交
58 59
		// Massage configuration file URIs
		this.reviveUris();
60

B
Benjamin Pasero 已提交
61
		// Setup perf
62
		importEntries(this.configuration.perfEntries);
A
Alex Dima 已提交
63

B
Benjamin Pasero 已提交
64
		// Browser config
65 66 67
		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 已提交
68

B
Benjamin Pasero 已提交
69 70
		// Keyboard support
		KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
M
Martin Aeschlimann 已提交
71
	}
72

B
Benjamin Pasero 已提交
73 74 75 76 77 78
	private reviveUris() {
		if (this.configuration.folderUri) {
			this.configuration.folderUri = uri.revive(this.configuration.folderUri);
		}
		if (this.configuration.workspace) {
			this.configuration.workspace = reviveWorkspaceIdentifier(this.configuration.workspace);
M
Martin Aeschlimann 已提交
79
		}
B
Benjamin Pasero 已提交
80

M
Martin Aeschlimann 已提交
81 82
		const filesToWait = this.configuration.filesToWait;
		const filesToWaitPaths = filesToWait && filesToWait.paths;
B
Benjamin Pasero 已提交
83 84 85 86 87 88 89 90 91
		[filesToWaitPaths, this.configuration.filesToOpen, this.configuration.filesToCreate, this.configuration.filesToDiff].forEach(paths => {
			if (Array.isArray(paths)) {
				paths.forEach(path => {
					if (path.fileUri) {
						path.fileUri = uri.revive(path.fileUri);
					}
				});
			}
		});
M
Martin Aeschlimann 已提交
92 93 94
		if (filesToWait) {
			filesToWait.waitMarkerFileUri = uri.revive(filesToWait.waitMarkerFileUri);
		}
B
Benjamin Pasero 已提交
95
	}
B
Benjamin Pasero 已提交
96

B
Benjamin Pasero 已提交
97
	open(): Promise<void> {
98
		return this.initServices().then(services => {
B
Benjamin Pasero 已提交
99

B
Benjamin Pasero 已提交
100
			return domContentLoaded().then(() => {
101
				mark('willStartWorkbench');
B
Benjamin Pasero 已提交
102

B
Benjamin Pasero 已提交
103
				// Create Workbench
104
				this.workbench = new Workbench(document.body, services.serviceCollection, services.logService);
B
Benjamin Pasero 已提交
105

106 107 108
				// Layout
				this._register(addDisposableListener(window, EventType.RESIZE, e => this.onWindowResize(e, true)));

B
Benjamin Pasero 已提交
109
				// Workbench Lifecycle
110
				this._register(this.workbench.onShutdown(() => this.dispose()));
111
				this._register(this.workbench.onWillShutdown(event => event.join(services.storageService.close())));
B
Benjamin Pasero 已提交
112 113

				// Startup
114
				const instantiationService = this.workbench.startup();
B
Benjamin Pasero 已提交
115 116

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

119
				// Driver
B
Benjamin Pasero 已提交
120
				if (this.configuration.driver) {
121
					instantiationService.invokeFunction(accessor => registerWindowDriver(accessor).then(disposable => this._register(disposable)));
122
				}
123 124

				// Config Exporter
125
				if (this.configuration['export-default-configuration']) {
126 127
					instantiationService.createInstance(DefaultConfigurationExportHelper);
				}
128 129

				// Logging
130
				services.logService.trace('workbench configuration', JSON.stringify(this.configuration));
131 132
			});
		});
B
Benjamin Pasero 已提交
133
	}
134

135
	private onWindowResize(e: Event, retry: boolean): void {
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
		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();
		}
	}

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

156 157 158
		// Main Process
		const mainProcessService = this._register(new MainProcessService(this.configuration.windowId));
		serviceCollection.set(IMainProcessService, mainProcessService);
159

160 161 162
		// Window
		serviceCollection.set(IWindowService, new SyncDescriptor(WindowService, [this.configuration]));

B
Benjamin Pasero 已提交
163 164 165 166 167
		// Environment
		const environmentService = new EnvironmentService(this.configuration, this.configuration.execPath);
		serviceCollection.set(IEnvironmentService, environmentService);

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

171 172
		return this.resolveWorkspaceInitializationPayload(environmentService).then(payload => Promise.all([
			this.createWorkspaceService(payload, environmentService, logService).then(service => {
B
Benjamin Pasero 已提交
173

174 175
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
176

177 178
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
179

180 181
				return service;
			}),
B
Benjamin Pasero 已提交
182

183 184 185 186 187 188 189 190
			this.createStorageService(payload, environmentService, logService, mainProcessService).then(service => {

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

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

B
Benjamin Pasero 已提交
193 194 195 196 197
	private resolveWorkspaceInitializationPayload(environmentService: EnvironmentService): Promise<IWorkspaceInitializationPayload> {

		// Multi-root workspace
		if (this.configuration.workspace) {
			return Promise.resolve(this.configuration.workspace as IMultiFolderWorkspaceInitializationPayload);
198 199
		}

B
Benjamin Pasero 已提交
200 201 202 203 204
		// Single-folder workspace
		let workspaceInitializationPayload: Promise<IWorkspaceInitializationPayload | undefined> = Promise.resolve(undefined);
		if (this.configuration.folderUri) {
			workspaceInitializationPayload = this.resolveSingleFolderWorkspaceInitializationPayload(this.configuration.folderUri);
		}
E
Erich Gamma 已提交
205

B
Benjamin Pasero 已提交
206 207 208 209 210 211 212 213 214 215 216 217
		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 已提交
218

B
Benjamin Pasero 已提交
219 220
				payload = { id } as IEmptyWorkspaceInitializationPayload;
			}
221

B
Benjamin Pasero 已提交
222 223 224
			return payload;
		});
	}
225

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

B
Benjamin Pasero 已提交
228 229 230 231
		// 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 });
		}
232

B
Benjamin Pasero 已提交
233 234
		function computeLocalDiskFolderId(folder: uri, stat: fs.Stats): string {
			let ctime: number | undefined;
235
			if (isLinux) {
B
Benjamin Pasero 已提交
236
				ctime = stat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead!
237
			} else if (isMacintosh) {
B
Benjamin Pasero 已提交
238
				ctime = stat.birthtime.getTime(); // macOS: birthtime is fine to use as is
239
			} else if (isWindows) {
B
Benjamin Pasero 已提交
240 241 242 243 244 245
				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();
				}
			}
246

B
Benjamin Pasero 已提交
247 248 249 250
			// 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');
		}
251

B
Benjamin Pasero 已提交
252 253 254 255 256 257 258 259 260 261
		// For local: ensure path is absolute and exists
		const sanitizedFolderPath = sanitizeFilePath(folderUri.fsPath, process.env['VSCODE_CWD'] || process.cwd());
		return stat(sanitizedFolderPath).then(stat => {
			const sanitizedFolderUri = uri.file(sanitizedFolderPath);
			return {
				id: computeLocalDiskFolderId(sanitizedFolderUri, stat),
				folder: sanitizedFolderUri
			} as ISingleFolderWorkspaceInitializationPayload;
		}, error => onUnexpectedError(error));
	}
262

B
Benjamin Pasero 已提交
263 264
	private createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: IEnvironmentService, logService: ILogService): Promise<WorkspaceService> {
		const workspaceService = new WorkspaceService(environmentService);
S
Sandeep Somavarapu 已提交
265

B
Benjamin Pasero 已提交
266 267 268
		return workspaceService.initialize(payload).then(() => workspaceService, error => {
			onUnexpectedError(error);
			logService.error(error);
269

B
Benjamin Pasero 已提交
270 271 272
			return workspaceService;
		});
	}
273

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

B
Benjamin Pasero 已提交
278 279 280
		return storageService.initialize(payload).then(() => storageService, error => {
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
281

B
Benjamin Pasero 已提交
282 283 284
			return storageService;
		});
	}
285

286
	private createLogService(mainProcessService: IMainProcessService, environmentService: IEnvironmentService): ILogService {
B
Benjamin Pasero 已提交
287 288 289
		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]);
290
		const logLevelClient = new LogLevelSetterChannelClient(mainProcessService.getChannel('loglevel'));
291

B
Benjamin Pasero 已提交
292 293 294
		return new FollowerLogService(logLevelClient, logService);
	}
}
295

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

299
	return renderer.open();
300
}