desktop.main.ts 16.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 { ConsoleLogService, MultiplexLogService, ILogService, ConsoleLogInMainService, DelegatedLogService } 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';
32
import { Disposable, DisposableStore } 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';
53 54
import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { BufferLogService } from 'vs/platform/log/common/bufferLog';
J
Joao Moreno 已提交
55

B
Benjamin Pasero 已提交
56
class DesktopMain extends Disposable {
E
Erich Gamma 已提交
57

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

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

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

B
Benjamin Pasero 已提交
66
	private init(): void {
67

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

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

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

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

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

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

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

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

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

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

115 116
		await domContentLoaded();
		mark('willStartWorkbench');
B
Benjamin Pasero 已提交
117

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

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

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

127 128 129 130 131 132
		// Lifecycle Listeners
		instantiationService.invokeFunction(accessor => {
			const lifecycleService = accessor.get(ILifecycleService);
			lifecycleService.when(LifecyclePhase.Restored).then(() => services.logService.init());
		});

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

136
		// Driver
137
		if (this.environmentService.configuration.driver) {
B
Benjamin Pasero 已提交
138
			instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
139
		}
140

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

145
	private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
B
Benjamin Pasero 已提交
146 147 148 149 150 151 152 153 154

		// 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())));
	}

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

169
			workbench.layout();
170 171 172
		}
	}

173
	private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: DesktopLogService, storageService: NativeStorageService }> {
B
Benjamin Pasero 已提交
174
		const serviceCollection = new ServiceCollection();
175

176 177
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		// NOTE: DO NOT ADD ANY OTHER SERVICE INTO THE COLLECTION HERE.
178
		// CONTRIBUTE IT VIA WORKBENCH.DESKTOP.MAIN.TS AND registerSingleton().
179 180
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

181
		// Main Process
182
		const mainProcessService = this._register(new MainProcessService(this.configuration.windowId));
183
		serviceCollection.set(IMainProcessService, mainProcessService);
184

B
Benjamin Pasero 已提交
185
		// Environment
186
		serviceCollection.set(IWorkbenchEnvironmentService, this.environmentService);
B
Benjamin Pasero 已提交
187

188 189 190
		// Product
		serviceCollection.set(IProductService, { _serviceBrand: undefined, ...product });

B
Benjamin Pasero 已提交
191
		// Log
192
		const logService = this._register(new DesktopLogService(this.configuration.windowId, mainProcessService, this.environmentService));
B
Benjamin Pasero 已提交
193 194
		serviceCollection.set(ILogService, logService);

195 196 197
		// Remote
		const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
		serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
B
Benjamin Pasero 已提交
198

I
isidor 已提交
199 200 201 202
		// Sign
		const signService = new SignService();
		serviceCollection.set(ISignService, signService);

203
		const remoteAgentService = this._register(new RemoteAgentService(this.environmentService, remoteAuthorityResolverService, signService, logService));
204 205
		serviceCollection.set(IRemoteAgentService, remoteAgentService);

B
Benjamin Pasero 已提交
206
		// Files
B
Benjamin Pasero 已提交
207
		const fileService = this._register(new FileService(logService));
B
Benjamin Pasero 已提交
208 209
		serviceCollection.set(IFileService, fileService);

210 211
		const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService));
		fileService.registerProvider(Schemas.file, diskFileSystemProvider);
B
Benjamin Pasero 已提交
212

213
		// User Data Provider
214
		fileService.registerProvider(Schemas.userData, new FileUserDataProvider(this.environmentService.appSettingsHome, this.environmentService.backupHome, diskFileSystemProvider, this.environmentService));
215

216 217
		const connection = remoteAgentService.getConnection();
		if (connection) {
218
			const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService));
B
Benjamin Pasero 已提交
219
			fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
220 221
		}

222 223 224 225
		const resourceIdentityService = this._register(new NativeResourceIdentityService());
		serviceCollection.set(IResourceIdentityService, resourceIdentityService);

		const payload = await this.resolveWorkspaceInitializationPayload(resourceIdentityService);
226 227

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

230 231
				// Workspace
				serviceCollection.set(IWorkspaceContextService, service);
B
Benjamin Pasero 已提交
232

233 234
				// Configuration
				serviceCollection.set(IConfigurationService, service);
B
Benjamin Pasero 已提交
235

236 237
				return service;
			}),
B
Benjamin Pasero 已提交
238

239
			this.createStorageService(payload, logService, mainProcessService).then(service => {
240 241 242 243 244 245

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

				return service;
			})
246 247 248
		]);

		return { serviceCollection, logService, storageService: services[1] };
249
	}
250

251
	private async resolveWorkspaceInitializationPayload(resourceIdentityService: IResourceIdentityService): Promise<IWorkspaceInitializationPayload> {
B
Benjamin Pasero 已提交
252 253

		// Multi-root workspace
254 255
		if (this.environmentService.configuration.workspace) {
			return this.environmentService.configuration.workspace;
256 257
		}

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

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

275 276 277 278
			workspaceInitializationPayload = { id };
		}

		return workspaceInitializationPayload;
B
Benjamin Pasero 已提交
279
	}
280

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

294 295
	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 已提交
296

297 298 299 300 301
		try {
			await workspaceService.initialize(payload);

			return workspaceService;
		} catch (error) {
B
Benjamin Pasero 已提交
302 303
			onUnexpectedError(error);
			logService.error(error);
304

B
Benjamin Pasero 已提交
305
			return workspaceService;
306
		}
B
Benjamin Pasero 已提交
307
	}
308

309
	private async createStorageService(payload: IWorkspaceInitializationPayload, logService: ILogService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
310
		const globalStorageDatabase = new GlobalStorageDatabaseChannelClient(mainProcessService.getChannel('storage'));
311
		const storageService = new NativeStorageService(globalStorageDatabase, logService, this.environmentService);
312

313 314 315 316 317
		try {
			await storageService.initialize(payload);

			return storageService;
		} catch (error) {
B
Benjamin Pasero 已提交
318 319
			onUnexpectedError(error);
			logService.error(error);
J
Joao Moreno 已提交
320

B
Benjamin Pasero 已提交
321
			return storageService;
322
		}
B
Benjamin Pasero 已提交
323
	}
324

325 326 327 328 329 330 331 332 333 334 335
}

class DesktopLogService extends DelegatedLogService {

	private readonly bufferSpdLogService: BufferLogService | undefined;
	private readonly windowId: number;
	private readonly environmentService: NativeWorkbenchEnvironmentService;

	constructor(windowId: number, mainProcessService: IMainProcessService, environmentService: NativeWorkbenchEnvironmentService) {

		const disposables = new DisposableStore();
336
		const loggerClient = new LoggerChannelClient(mainProcessService.getChannel('logger'));
337
		let bufferSpdLogService: BufferLogService | undefined;
338 339 340 341 342

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

		// Normal logger: spdylog and console
		else {
349
			bufferSpdLogService = disposables.add(new BufferLogService(environmentService.configuration.logLevel));
350
			loggers.push(
351 352
				disposables.add(new ConsoleLogService(environmentService.configuration.logLevel)),
				bufferSpdLogService,
353 354
			);
		}
355

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
		const multiplexLogger = disposables.add(new MultiplexLogService(loggers));
		const followerLogger = disposables.add(new FollowerLogService(loggerClient, multiplexLogger));
		super(followerLogger);

		this.bufferSpdLogService = bufferSpdLogService;
		this.windowId = windowId;
		this.environmentService = environmentService;

		this._register(disposables);
	}

	init(): void {
		if (this.bufferSpdLogService) {
			this.bufferSpdLogService.logger = this._register(new SpdLogService(`renderer${this.windowId}`, this.environmentService.logsPath, this.getLevel()));
			this.trace('Created Spdlogger');
		}
B
Benjamin Pasero 已提交
372 373
	}
}
374

375
export function main(configuration: INativeWindowConfiguration): Promise<void> {
376
	const workbench = new DesktopMain(configuration);
377

378
	return workbench.open();
379
}