desktop.main.ts 14.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 { 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 { ILogService } from 'vs/platform/log/common/log';
24
import { NativeStorageService } from 'vs/platform/storage/node/storageService';
25
import { Schemas } from 'vs/base/common/network';
B
Benjamin Pasero 已提交
26
import { sanitizeFilePath } from 'vs/base/common/extpath';
B
wip  
Benjamin Pasero 已提交
27
import { GlobalStorageDatabaseChannelClient } from 'vs/platform/storage/node/storageIpc';
B
Benjamin Pasero 已提交
28 29 30
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
31
import { Disposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
32
import { registerWindowDriver } from 'vs/platform/driver/electron-browser/driver';
33
import { IMainProcessService, MainProcessService } from 'vs/platform/ipc/electron-browser/mainProcessService';
34
import { IMainProcessService2, MainProcessService2 } from 'vs/platform/ipc/electron-sandbox/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';
I
isidor 已提交
44 45
import { SignService } from 'vs/platform/sign/node/signService';
import { ISignService } from 'vs/platform/sign/common/sign';
S
Sandeep Somavarapu 已提交
46
import { FileUserDataProvider } from 'vs/workbench/services/userData/common/fileUserDataProvider';
47
import { basename } from 'vs/base/common/resources';
48
import { IProductService } from 'vs/platform/product/common/productService';
49
import product from 'vs/platform/product/common/product';
50 51
import { NativeResourceIdentityService } from 'vs/platform/resource/node/resourceIdentityServiceImpl';
import { IResourceIdentityService } from 'vs/platform/resource/common/resourceIdentityService';
52
import { DesktopLogService } from 'vs/workbench/services/log/electron-browser/logService';
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
		}
	}

S
Sandeep Somavarapu 已提交
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 (legacy)
174
		const mainProcessService = this._register(new MainProcessService(this.configuration.windowId));
175
		serviceCollection.set(IMainProcessService, mainProcessService);
176

177 178 179 180
		// Main Process (sandbox)
		const mainProcessService2 = this._register(new MainProcessService2(this.configuration.windowId));
		serviceCollection.set(IMainProcessService2, mainProcessService2);

B
Benjamin Pasero 已提交
181
		// Environment
182
		serviceCollection.set(IWorkbenchEnvironmentService, this.environmentService);
B
Benjamin Pasero 已提交
183

184 185 186
		// Product
		serviceCollection.set(IProductService, { _serviceBrand: undefined, ...product });

B
Benjamin Pasero 已提交
187
		// Log
188
		const logService = this._register(new DesktopLogService(this.configuration.windowId, mainProcessService, this.environmentService));
B
Benjamin Pasero 已提交
189 190
		serviceCollection.set(ILogService, logService);

191 192 193
		// Remote
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
B
Benjamin Pasero 已提交
194

I
isidor 已提交
195 196 197 198
		// Sign
		const signService = new SignService();
		serviceCollection.set(ISignService, signService);

199
		const remoteAgentService = this._register(new RemoteAgentService(this.environmentService, remoteAuthorityResolverService, signService, logService));
200 201
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

B
Benjamin Pasero 已提交
202
		// Files
B
Benjamin Pasero 已提交
203
		const fileService = this._register(new FileService(logService));
B
Benjamin Pasero 已提交
204 205
		serviceCollection.set(IFileService, fileService);

206 207
		const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService));
		fileService.registerProvider(Schemas.file, diskFileSystemProvider);
B
Benjamin Pasero 已提交
208

209
		// User Data Provider
210
		fileService.registerProvider(Schemas.userData, new FileUserDataProvider(this.environmentService.appSettingsHome, this.environmentService.backupHome, diskFileSystemProvider, this.environmentService, logService));
211

212 213
		const connection = remoteAgentService.getConnection();
		if (connection) {
214
			const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService));
B
Benjamin Pasero 已提交
215
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
216 217
		}

218 219 220 221
		const resourceIdentityService = this._register(new NativeResourceIdentityService());
		serviceCollection.set(IResourceIdentityService, resourceIdentityService);

		const payload = await this.resolveWorkspaceInitializationPayload(resourceIdentityService);
222 223

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

226 227
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
228

229 230
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
231

232 233
				return service;
			}),
B
Benjamin Pasero 已提交
234

235
			this.createStorageService(payload, logService, mainProcessService).then(service => {
236 237 238 239 240 241

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

				return service;
			})
242 243 244
		]);

		return { serviceCollection, logService, storageService: services[1] };
245
	}
246

247
	private async resolveWorkspaceInitializationPayload(resourceIdentityService: IResourceIdentityService): Promise<IWorkspaceInitializationPayload> {
B
Benjamin Pasero 已提交
248 249

		// Multi-root workspace
250 251
		if (this.environmentService.configuration.workspace) {
			return this.environmentService.configuration.workspace;
252 253
		}

B
Benjamin Pasero 已提交
254
		// Single-folder workspace
255
		let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined;
256
		if (this.environmentService.configuration.folderUri) {
257
			workspaceInitializationPayload = await this.resolveSingleFolderWorkspaceInitializationPayload(this.environmentService.configuration.folderUri, resourceIdentityService);
B
Benjamin Pasero 已提交
258
		}
E
Erich Gamma 已提交
259

260 261 262
		// Fallback to empty workspace if we have no payload yet.
		if (!workspaceInitializationPayload) {
			let id: string;
263 264 265
			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) {
266 267 268
				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 已提交
269
			}
270

271 272 273 274
			workspaceInitializationPayload = { id };
		}

		return workspaceInitializationPayload;
B
Benjamin Pasero 已提交
275
	}
276

277
	private async resolveSingleFolderWorkspaceInitializationPayload(folderUri: ISingleFolderWorkspaceIdentifier, resourceIdentityService: IResourceIdentityService): Promise<ISingleFolderWorkspaceInitializationPayload | undefined> {
278
		try {
279 280 281 282 283
			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 };
284 285 286 287
		} catch (error) {
			onUnexpectedError(error);
		}
		return;
B
Benjamin Pasero 已提交
288
	}
289

290 291
	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 已提交
292

293 294 295 296 297
		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
B
Benjamin Pasero 已提交
298 299
			onUnexpectedError(error);
			logService.error(error);
300

B
Benjamin Pasero 已提交
301
			return workspaceService;
302
		}
B
Benjamin Pasero 已提交
303
	}
304

305
	private async createStorageService(payload: IWorkspaceInitializationPayload, logService: ILogService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
306
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
307
		const storageService = new NativeStorageService(globalStorageDatabase, logService, this.environmentService);
308

309 310 311 312 313
		try {
			await storageService.initialize(payload);

			return storageService;
		} catch (error) {
B
Benjamin Pasero 已提交
314 315
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
316

B
Benjamin Pasero 已提交
317
			return storageService;
318
		}
B
Benjamin Pasero 已提交
319
	}
320

321 322
}

323
export function main(configuration: INativeWindowConfiguration): Promise<void> {
324
	const workbench = new DesktopMain(configuration);
325

326
	return workbench.open();
327
}