main.ts 14.7 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 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';
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';
J
Joao Moreno 已提交
52

53
class CodeRendererMain extends Disposable {
E
Erich Gamma 已提交
54

55 56
	private workbench: Workbench;

B
Benjamin Pasero 已提交
57 58
	constructor(private readonly configuration: IWindowConfiguration) {
		super();
59

B
Benjamin Pasero 已提交
60 61
		this.init();
	}
M
Martin Aeschlimann 已提交
62

B
Benjamin Pasero 已提交
63
	private init(): void {
64

B
Benjamin Pasero 已提交
65 66
		// Enable gracefulFs
		gracefulFs.gracefulify(fs);
67

B
Benjamin Pasero 已提交
68 69
		// Massage configuration file URIs
		this.reviveUris();
70

B
Benjamin Pasero 已提交
71
		// Setup perf
72
		importEntries(this.configuration.perfEntries);
A
Alex Dima 已提交
73

B
Benjamin Pasero 已提交
74
		// Browser config
75 76 77
		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 已提交
78

B
Benjamin Pasero 已提交
79 80
		// Keyboard support
		KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
M
Martin Aeschlimann 已提交
81
	}
82

B
Benjamin Pasero 已提交
83 84 85 86 87 88
	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 已提交
89
		}
B
Benjamin Pasero 已提交
90

M
Martin Aeschlimann 已提交
91 92
		const filesToWait = this.configuration.filesToWait;
		const filesToWaitPaths = filesToWait && filesToWait.paths;
B
Benjamin Pasero 已提交
93 94 95 96 97 98 99 100 101
		[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 已提交
102 103 104
		if (filesToWait) {
			filesToWait.waitMarkerFileUri = uri.revive(filesToWait.waitMarkerFileUri);
		}
B
Benjamin Pasero 已提交
105
	}
B
Benjamin Pasero 已提交
106

B
Benjamin Pasero 已提交
107
	open(): Promise<void> {
108
		return this.initServices().then(services => {
B
Benjamin Pasero 已提交
109

B
Benjamin Pasero 已提交
110
			return domContentLoaded().then(() => {
111
				mark('willStartWorkbench');
B
Benjamin Pasero 已提交
112

B
Benjamin Pasero 已提交
113
				// Create Workbench
114
				this.workbench = new Workbench(document.body, services.serviceCollection, services.logService);
B
Benjamin Pasero 已提交
115

116 117 118
				// Layout
				this._register(addDisposableListener(window, EventType.RESIZE, e => this.onWindowResize(e, true)));

B
Benjamin Pasero 已提交
119
				// Workbench Lifecycle
120
				this._register(this.workbench.onShutdown(() => this.dispose()));
121
				this._register(this.workbench.onWillShutdown(event => event.join(services.storageService.close())));
B
Benjamin Pasero 已提交
122 123

				// Startup
124
				const instantiationService = this.workbench.startup();
B
Benjamin Pasero 已提交
125 126

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

129
				// Driver
B
Benjamin Pasero 已提交
130
				if (this.configuration.driver) {
131
					instantiationService.invokeFunction(accessor => registerWindowDriver(accessor).then(disposable => this._register(disposable)));
132
				}
133 134

				// Config Exporter
135
				if (this.configuration['export-default-configuration']) {
136 137
					instantiationService.createInstance(DefaultConfigurationExportHelper);
				}
138 139

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

145
	private onWindowResize(e: Event, retry: boolean): void {
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
		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();
		}
	}

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

166 167 168
		// Main Process
		const mainProcessService = this._register(new MainProcessService(this.configuration.windowId));
		serviceCollection.set(IMainProcessService, mainProcessService);
169

170 171 172
		// Window
		serviceCollection.set(IWindowService, new SyncDescriptor(WindowService, [this.configuration]));

B
Benjamin Pasero 已提交
173 174 175 176 177
		// Environment
		const environmentService = new EnvironmentService(this.configuration, this.configuration.execPath);
		serviceCollection.set(IEnvironmentService, environmentService);

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

181 182 183
		// Remote
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
B
Benjamin Pasero 已提交
184

185 186 187
		const remoteAgentService = new RemoteAgentService(this.configuration, environmentService, remoteAuthorityResolverService);
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

B
Benjamin Pasero 已提交
188 189 190 191 192 193
		// Files
		const fileService = new FileService2(logService);
		serviceCollection.set(IFileService, fileService);

		fileService.registerProvider(Schemas.file, new DiskFileSystemProvider(logService));

194 195 196
		const connection = remoteAgentService.getConnection();
		if (connection) {
			const channel = connection.getChannel<IChannel>(REMOTE_FILE_SYSTEM_CHANNEL_NAME);
B
Benjamin Pasero 已提交
197
			fileService.registerProvider(REMOTE_HOST_SCHEME, new RemoteExtensionsFileSystemProvider(channel, remoteAgentService.getEnvironment()));
198 199
		}

200
		return this.resolveWorkspaceInitializationPayload(environmentService).then(payload => Promise.all([
201
			this.createWorkspaceService(payload, environmentService, remoteAgentService, logService).then(service => {
B
Benjamin Pasero 已提交
202

203 204
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
205

206 207
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
208

209 210
				return service;
			}),
B
Benjamin Pasero 已提交
211

212 213 214 215 216 217 218 219
			this.createStorageService(payload, environmentService, logService, mainProcessService).then(service => {

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

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

B
Benjamin Pasero 已提交
222 223 224 225 226
	private resolveWorkspaceInitializationPayload(environmentService: EnvironmentService): Promise<IWorkspaceInitializationPayload> {

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

B
Benjamin Pasero 已提交
229 230 231 232 233
		// Single-folder workspace
		let workspaceInitializationPayload: Promise<IWorkspaceInitializationPayload | undefined> = Promise.resolve(undefined);
		if (this.configuration.folderUri) {
			workspaceInitializationPayload = this.resolveSingleFolderWorkspaceInitializationPayload(this.configuration.folderUri);
		}
E
Erich Gamma 已提交
234

B
Benjamin Pasero 已提交
235 236 237 238 239 240 241 242 243 244 245 246
		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 已提交
247

B
Benjamin Pasero 已提交
248 249
				payload = { id } as IEmptyWorkspaceInitializationPayload;
			}
250

B
Benjamin Pasero 已提交
251 252 253
			return payload;
		});
	}
254

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

B
Benjamin Pasero 已提交
257 258 259 260
		// 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 });
		}
261

B
Benjamin Pasero 已提交
262 263
		function computeLocalDiskFolderId(folder: uri, stat: fs.Stats): string {
			let ctime: number | undefined;
264
			if (isLinux) {
B
Benjamin Pasero 已提交
265
				ctime = stat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead!
266
			} else if (isMacintosh) {
B
Benjamin Pasero 已提交
267
				ctime = stat.birthtime.getTime(); // macOS: birthtime is fine to use as is
268
			} else if (isWindows) {
B
Benjamin Pasero 已提交
269 270 271 272 273 274
				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();
				}
			}
275

B
Benjamin Pasero 已提交
276 277 278 279
			// 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');
		}
280

B
Benjamin Pasero 已提交
281 282 283 284 285 286 287 288 289 290
		// 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));
	}
291

292 293
	private createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: IEnvironmentService, remoteAgentService: IRemoteAgentService, logService: ILogService): Promise<WorkspaceService> {
		const workspaceService = new WorkspaceService(this.configuration, environmentService, remoteAgentService);
S
Sandeep Somavarapu 已提交
294

B
Benjamin Pasero 已提交
295 296 297
		return workspaceService.initialize(payload).then(() => workspaceService, error => {
			onUnexpectedError(error);
			logService.error(error);
298

B
Benjamin Pasero 已提交
299 300 301
			return workspaceService;
		});
	}
302

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

B
Benjamin Pasero 已提交
307 308 309
		return storageService.initialize(payload).then(() => storageService, error => {
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
310

B
Benjamin Pasero 已提交
311 312 313
			return storageService;
		});
	}
314

315
	private createLogService(mainProcessService: IMainProcessService, environmentService: IEnvironmentService): ILogService {
B
Benjamin Pasero 已提交
316 317 318
		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]);
319
		const logLevelClient = new LogLevelSetterChannelClient(mainProcessService.getChannel('loglevel'));
320

B
Benjamin Pasero 已提交
321 322 323
		return new FollowerLogService(logLevelClient, logService);
	}
}
324

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

328
	return renderer.open();
329
}