desktop.main.ts 15.2 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 { webFrame } from 'electron';
9
import { importEntries, mark } from 'vs/base/common/performance';
10
import { Workbench } from 'vs/workbench/browser/workbench';
11
import { NativeWindow } 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 { URI } from 'vs/base/common/uri';
16
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
17
import { NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService';
18
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
19
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
P
Peng Lyu 已提交
20
import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/nativeKeymapService';
21
import { INativeWindowConfiguration } from 'vs/platform/windows/node/window';
22
import { ISingleFolderWorkspaceIdentifier, IWorkspaceInitializationPayload, ISingleFolderWorkspaceInitializationPayload, reviveWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
23
import { ConsoleLogService, MultiplexLogService, ILogService, ConsoleLogInMainService } from 'vs/platform/log/common/log';
24
import { NativeStorageService } from 'vs/platform/storage/node/storageService';
25
import { LoggerChannelClient, FollowerLogService } from 'vs/platform/log/common/logIpc';
26
import { Schemas } from 'vs/base/common/network';
B
Benjamin Pasero 已提交
27
import { sanitizeFilePath } from 'vs/base/common/extpath';
B
wip  
Benjamin Pasero 已提交
28
import { GlobalStorageDatabaseChannelClient } from 'vs/platform/storage/node/storageIpc';
B
Benjamin Pasero 已提交
29 30 31
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 已提交
32
import { Disposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
33
import { registerWindowDriver } from 'vs/platform/driver/electron-browser/driver';
34
import { IMainProcessService, MainProcessService } from 'vs/platform/ipc/electron-browser/mainProcessService';
35 36 37 38
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';
39
import { FileService } from 'vs/platform/files/common/fileService';
40
import { IFileService } from 'vs/platform/files/common/files';
41
import { DiskFileSystemProvider } from 'vs/platform/files/electron-browser/diskFileSystemProvider';
42
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
S
Sandeep Somavarapu 已提交
43
import { ConfigurationCache } from 'vs/workbench/services/configuration/node/configurationCache';
44
import { SpdLogService } from 'vs/platform/log/node/spdlogService';
I
isidor 已提交
45 46
import { SignService } from 'vs/platform/sign/node/signService';
import { ISignService } from 'vs/platform/sign/common/sign';
S
Sandeep Somavarapu 已提交
47
import { FileUserDataProvider } from 'vs/workbench/services/userData/common/fileUserDataProvider';
48
import { basename } from 'vs/base/common/resources';
49
import { IProductService } from 'vs/platform/product/common/productService';
50
import product from 'vs/platform/product/common/product';
51 52
import { NativeResourceIdentityService } from 'vs/platform/resource/node/resourceIdentityServiceImpl';
import { IResourceIdentityService } from 'vs/platform/resource/common/resourceIdentityService';
J
Joao Moreno 已提交
53

B
Benjamin Pasero 已提交
54
class DesktopMain extends Disposable {
E
Erich Gamma 已提交
55

B
Benjamin Pasero 已提交
56
	private readonly environmentService = new NativeWorkbenchEnvironmentService(this.configuration, this.configuration.execPath);
57

58
	constructor(private configuration: INativeWindowConfiguration) {
B
Benjamin Pasero 已提交
59
		super();
B
Benjamin Pasero 已提交
60

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

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

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

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

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

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

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

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

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

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

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

110 111
	async open(): Promise<void> {
		const services = await this.initServices();
B
Benjamin Pasero 已提交
112

113 114
		await domContentLoaded();
		mark('willStartWorkbench');
B
Benjamin Pasero 已提交
115

116
		// Create Workbench
117
		const workbench = new Workbench(document.body, services.serviceCollection, services.logService);
B
Benjamin Pasero 已提交
118

B
Benjamin Pasero 已提交
119 120
		// Listeners
		this.registerListeners(workbench, services.storageService);
121

122
		// Startup
123
		const instantiationService = workbench.startup();
B
Benjamin Pasero 已提交
124

125
		// Window
126
		this._register(instantiationService.createInstance(NativeWindow));
B
Benjamin Pasero 已提交
127

128
		// Driver
129
		if (this.environmentService.configuration.driver) {
B
Benjamin Pasero 已提交
130
			instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
131
		}
132

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

137
	private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
B
Benjamin Pasero 已提交
138 139 140 141 142 143 144 145 146

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

		// Workbench Lifecycle
		this._register(workbench.onShutdown(() => this.dispose()));
		this._register(workbench.onWillShutdown(event => event.join(storageService.close())));
	}

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: NativeStorageService }> {
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.configuration.windowId));
175
		serviceCollection.set(IMainProcessService, mainProcessService);
176

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

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

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

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

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

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

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

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

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

208 209
		const connection = remoteAgentService.getConnection();
		if (connection) {
210
			const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService));
B
Benjamin Pasero 已提交
211
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
212 213
		}

214 215 216 217
		const resourceIdentityService = this._register(new NativeResourceIdentityService());
		serviceCollection.set(IResourceIdentityService, resourceIdentityService);

		const payload = await this.resolveWorkspaceInitializationPayload(resourceIdentityService);
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(resourceIdentityService: IResourceIdentityService): 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
		if (this.environmentService.configuration.folderUri) {
253
			workspaceInitializationPayload = await this.resolveSingleFolderWorkspaceInitializationPayload(this.environmentService.configuration.folderUri, resourceIdentityService);
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, resourceIdentityService: IResourceIdentityService): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
274
		try {
275 276 277 278 279
			const folder = folderUri.scheme === Schemas.file
				? URI.file(sanitizeFilePath(folderUri.fsPath, process.env['VSCODE_CWD'] || process.cwd())) // For local: ensure path is absolute
				: folderUri;
			const id = await resourceIdentityService.resolveResourceIdentity(folderUri);
			return { id, folder };
280 281 282 283
		} catch (error) {
			onUnexpectedError(error);
		}
		return;
B
Benjamin Pasero 已提交
284
	}
285

286 287
	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 已提交
288

289 290 291 292 293
		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
B
Benjamin Pasero 已提交
294 295
			onUnexpectedError(error);
			logService.error(error);
296

B
Benjamin Pasero 已提交
297
			return workspaceService;
298
		}
B
Benjamin Pasero 已提交
299
	}
300

301
	private async createStorageService(payload: IWorkspaceInitializationPayload, logService: ILogService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
302
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
303
		const storageService = new NativeStorageService(globalStorageDatabase, logService, this.environmentService);
304

305 306 307 308 309
		try {
			await storageService.initialize(payload);

			return storageService;
		} catch (error) {
B
Benjamin Pasero 已提交
310 311
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
312

B
Benjamin Pasero 已提交
313
			return storageService;
314
		}
B
Benjamin Pasero 已提交
315
	}
316

317
	private createLogService(mainProcessService: IMainProcessService, environmentService: IWorkbenchEnvironmentService): ILogService {
318 319 320 321 322 323 324 325 326 327 328 329 330 331
		const loggerClient = new LoggerChannelClient(mainProcessService.getChannel('logger'));

		// Extension development test CLI: forward everything to main side
		const loggers: ILogService[] = [];
		if (environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI) {
			loggers.push(
				new ConsoleLogInMainService(loggerClient, this.environmentService.configuration.logLevel)
			);
		}

		// Normal logger: spdylog and console
		else {
			loggers.push(
				new ConsoleLogService(this.environmentService.configuration.logLevel),
332
				new SpdLogService(`renderer${this.configuration.windowId}`, environmentService.logsPath, this.environmentService.configuration.logLevel)
333 334
			);
		}
335

336
		return new FollowerLogService(loggerClient, new MultiplexLogService(loggers));
B
Benjamin Pasero 已提交
337 338
	}
}
339

340
export function main(configuration: INativeWindowConfiguration): Promise<void> {
B
Benjamin Pasero 已提交
341
	const renderer = new DesktopMain(configuration);
342

343
	return renderer.open();
344
}