main.ts 11.9 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 nls from 'vs/nls';
7
import * as perf from 'vs/base/common/performance';
J
Johannes Rieken 已提交
8
import { WorkbenchShell } from 'vs/workbench/electron-browser/shell';
9
import * as browser from 'vs/base/browser/browser';
J
Johannes Rieken 已提交
10
import { domContentLoaded } from 'vs/base/browser/dom';
11 12 13
import * as errors from 'vs/base/common/errors';
import * as comparer from 'vs/base/common/comparers';
import * as platform from 'vs/base/common/platform';
14
import { URI as uri } from 'vs/base/common/uri';
15
import { IWorkspaceContextService, Workspace, WorkbenchState } from 'vs/platform/workspace/common/workspace';
16
import { WorkspaceService } from 'vs/workbench/services/configuration/node/configurationService';
17 18
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
19
import { stat } from 'vs/base/node/pfs';
J
Johannes Rieken 已提交
20
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
21
import * as gracefulFs from 'graceful-fs';
22
import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
B
Benjamin Pasero 已提交
23
import { IWindowConfiguration, IWindowsService } from 'vs/platform/windows/common/windows';
J
Joao Moreno 已提交
24
import { WindowsChannelClient } from 'vs/platform/windows/node/windowsIpc';
B
Benjamin Pasero 已提交
25 26
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
27
import { StorageService, inMemoryLocalStorageInstance, IStorage } from 'vs/platform/storage/common/storageService';
28
import { Client as ElectronIPCClient } from 'vs/base/parts/ipc/electron-browser/ipc.electron-browser';
29
import { webFrame } from 'electron';
J
Joao Moreno 已提交
30
import { UpdateChannelClient } from 'vs/platform/update/node/updateIpc';
31
import { IUpdateService } from 'vs/platform/update/common/update';
J
Joao Moreno 已提交
32
import { URLHandlerChannel, URLServiceChannelClient } from 'vs/platform/url/node/urlIpc';
33
import { IURLService } from 'vs/platform/url/common/url';
J
Joao Moreno 已提交
34
import { WorkspacesChannelClient } from 'vs/platform/workspaces/node/workspacesIpc';
35
import { IWorkspacesService, ISingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
36
import { createSpdLogService } from 'vs/platform/log/node/spdlogService';
37
import * as fs from 'fs';
S
Sandeep Somavarapu 已提交
38
import { ConsoleLogService, MultiplexLogService, ILogService } from 'vs/platform/log/common/log';
39
import { NextStorage2Service, NextDelegatingStorage2Service } from 'vs/platform/storage2/electron-browser/nextStorage2Service';
J
Joao Moreno 已提交
40
import { IssueChannelClient } from 'vs/platform/issue/node/issueIpc';
41
import { IIssueService } from 'vs/platform/issue/common/issue';
J
Joao Moreno 已提交
42
import { LogLevelSetterChannelClient, FollowerLogService } from 'vs/platform/log/node/logIpc';
J
Joao Moreno 已提交
43
import { RelayURLService } from 'vs/platform/url/common/urlService';
J
Joao Moreno 已提交
44
import { MenubarChannelClient } from 'vs/platform/menubar/node/menubarIpc';
45
import { IMenubarService } from 'vs/platform/menubar/common/menubar';
46
import { Schemas } from 'vs/base/common/network';
47
import { sanitizeFilePath } from 'vs/base/node/extfs';
J
Joao Moreno 已提交
48

B
Benjamin Pasero 已提交
49
gracefulFs.gracefulify(fs); // enable gracefulFs
E
Erich Gamma 已提交
50

51
export function startup(configuration: IWindowConfiguration): Promise<void> {
52

53
	// Massage configuration file URIs
M
Martin Aeschlimann 已提交
54 55
	revive(configuration);

56
	// Setup perf
57 58
	perf.importEntries(configuration.perfEntries);

59 60 61
	// Browser config
	browser.setZoomFactor(webFrame.getZoomFactor()); // Ensure others can listen to zoom level changes
	browser.setZoomLevel(webFrame.getZoomLevel(), true /* isTrusted */); // Can be trusted because we are not setting it ourselves (https://github.com/Microsoft/vscode/issues/26151)
62
	browser.setFullscreen(!!configuration.fullscreen);
63
	browser.setAccessibilitySupport(configuration.accessibilitySupport ? platform.AccessibilitySupport.Enabled : platform.AccessibilitySupport.Disabled);
64

65
	// Keyboard support
66
	KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
A
Alex Dima 已提交
67

68
	// Setup Intl for comparers
69 70
	comparer.setFileNameComparer(new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }));

71
	// Open workbench
B
Benjamin Pasero 已提交
72
	return openWorkbench(configuration);
E
Erich Gamma 已提交
73 74
}

M
Martin Aeschlimann 已提交
75 76 77 78
function revive(workbench: IWindowConfiguration) {
	if (workbench.folderUri) {
		workbench.folderUri = uri.revive(workbench.folderUri);
	}
79

M
Martin Aeschlimann 已提交
80 81 82 83 84 85 86 87
	const filesToWaitPaths = workbench.filesToWait && workbench.filesToWait.paths;
	[filesToWaitPaths, workbench.filesToOpen, workbench.filesToCreate, workbench.filesToDiff].forEach(paths => {
		if (Array.isArray(paths)) {
			paths.forEach(path => {
				if (path.fileUri) {
					path.fileUri = uri.revive(path.fileUri);
				}
			});
M
Martin Aeschlimann 已提交
88
		}
M
Martin Aeschlimann 已提交
89
	});
M
Martin Aeschlimann 已提交
90 91
}

92
function openWorkbench(configuration: IWindowConfiguration): Promise<void> {
J
Joao Moreno 已提交
93
	const mainProcessClient = new ElectronIPCClient(`window:${configuration.windowId}`);
94
	const mainServices = createMainProcessServices(mainProcessClient, configuration);
95

96
	const environmentService = new EnvironmentService(configuration, configuration.execPath);
97

S
Sandeep Somavarapu 已提交
98
	const logService = createLogService(mainProcessClient, configuration, environmentService);
J
Joao Moreno 已提交
99
	logService.trace('openWorkbench configuration', JSON.stringify(configuration));
100

101 102
	return Promise.all([
		createAndInitializeWorkspaceService(configuration, environmentService),
B
Benjamin Pasero 已提交
103
		createNextStorage2Service(environmentService, logService)
104 105
	]).then(services => {
		const workspaceService = services[0];
106
		const storageService = createStorageService(workspaceService, environmentService);
107
		const nextStorage2Service = new NextDelegatingStorage2Service(services[1], storageService, logService, environmentService);
108 109

		return domContentLoaded().then(() => {
110
			perf.mark('willStartWorkbench');
111 112

			// Create Shell
113 114 115 116
			const shell = new WorkbenchShell(document.body, {
				contextService: workspaceService,
				configurationService: workspaceService,
				environmentService,
J
Joao Moreno 已提交
117
				logService,
118
				storageService,
B
Benjamin Pasero 已提交
119
				nextStorage2Service
J
Joao Moreno 已提交
120
			}, mainServices, mainProcessClient, configuration);
121 122 123

			// Gracefully Shutdown Storage
			shell.onShutdown(event => {
124
				event.join(nextStorage2Service.close(event.reason));
125 126 127
			});

			// Open Shell
128 129 130 131 132 133
			shell.open();

			// Inform user about loading issues from the loader
			(<any>self).require.config({
				onError: (err: any) => {
					if (err.errorCode === 'load') {
134
						shell.onUnexpectedError(new Error(nls.localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err))));
135
					}
136
				}
137 138 139 140 141
			});
		});
	});
}

142
function createAndInitializeWorkspaceService(configuration: IWindowConfiguration, environmentService: EnvironmentService): Promise<WorkspaceService> {
M
Martin Aeschlimann 已提交
143
	return validateFolderUri(configuration.folderUri, configuration.verbose).then(validatedFolderUri => {
S
Sandeep Somavarapu 已提交
144
		const workspaceService = new WorkspaceService(environmentService);
145

146
		return workspaceService.initialize(configuration.workspace || validatedFolderUri || configuration).then(() => workspaceService, error => workspaceService);
147
	});
148 149
}

150
function validateFolderUri(folderUri: ISingleFolderWorkspaceIdentifier, verbose: boolean): Promise<uri> {
151

152 153
	// Return early if we do not have a single folder uri or if it is a non file uri
	if (!folderUri || folderUri.scheme !== Schemas.file) {
154
		return Promise.resolve(folderUri);
E
Erich Gamma 已提交
155 156
	}

157
	// Ensure absolute existing folder path
158 159
	const sanitizedFolderPath = sanitizeFilePath(folderUri.fsPath, process.env['VSCODE_CWD'] || process.cwd());
	return stat(sanitizedFolderPath).then(stat => uri.file(sanitizedFolderPath), error => {
160
		if (verbose) {
161 162 163 164 165
			errors.onUnexpectedError(error);
		}

		// Treat any error case as empty workbench case (no folder path)
		return null;
166
	});
E
Erich Gamma 已提交
167 168
}

B
Benjamin Pasero 已提交
169 170
function createNextStorage2Service(environmentService: IEnvironmentService, logService: ILogService): Promise<NextStorage2Service> {
	perf.mark('willCreateNextStorage2Service');
171

B
Benjamin Pasero 已提交
172
	const nextStorage2Service = new NextStorage2Service(':memory:', logService, environmentService);
173

B
Benjamin Pasero 已提交
174 175
	return nextStorage2Service.init().then(() => {
		perf.mark('didCreateNextStorage2Service');
176

B
Benjamin Pasero 已提交
177
		return nextStorage2Service;
178
	});
179 180
}

181
function createStorageService(workspaceService: IWorkspaceContextService, environmentService: IEnvironmentService): IStorageService {
182 183 184
	let workspaceId: string;
	let secondaryWorkspaceId: number;

185
	switch (workspaceService.getWorkbenchState()) {
186 187

		// in multi root workspace mode we use the provided ID as key for workspace storage
188
		case WorkbenchState.WORKSPACE:
189
			workspaceId = uri.from({ path: workspaceService.getWorkspace().id, scheme: 'root' }).toString();
190 191 192 193
			break;

		// in single folder mode we use the path of the opened folder as key for workspace storage
		// the ctime is used as secondary workspace id to clean up stale UI state if necessary
194
		case WorkbenchState.FOLDER:
195
			const workspace: Workspace = <Workspace>workspaceService.getWorkspace();
196
			workspaceId = workspace.folders[0].uri.toString();
197 198 199 200 201 202 203 204 205
			secondaryWorkspaceId = workspace.ctime;
			break;

		// finaly, if we do not have a workspace open, we need to find another identifier for the window to store
		// workspace UI state. if we have a backup path in the configuration we can use that because this
		// will be a unique identifier per window that is stable between restarts as long as there are
		// dirty files in the workspace.
		// We use basename() to produce a short identifier, we do not need the full path. We use a custom
		// scheme so that we can later distinguish these identifiers from the workspace one.
206
		case WorkbenchState.EMPTY:
207
			workspaceId = workspaceService.getWorkspace().id;
208
			break;
209 210
	}

211
	const disableStorage = !!environmentService.extensionTestsPath; // never keep any state when running extension tests!
212 213 214 215 216 217 218

	let storage: IStorage;
	if (disableStorage) {
		storage = inMemoryLocalStorageInstance;
	} else {
		storage = window.localStorage;
	}
219

220
	return new StorageService(storage, storage, workspaceId, secondaryWorkspaceId);
221 222
}

S
Sandeep Somavarapu 已提交
223
function createLogService(mainProcessClient: ElectronIPCClient, configuration: IWindowConfiguration, environmentService: IEnvironmentService): ILogService {
S
Sandeep Somavarapu 已提交
224 225
	const spdlogService = createSpdLogService(`renderer${configuration.windowId}`, configuration.logLevel, environmentService.logsPath);
	const consoleLogService = new ConsoleLogService(configuration.logLevel);
S
Sandeep Somavarapu 已提交
226
	const logService = new MultiplexLogService([consoleLogService, spdlogService]);
227
	const logLevelClient = new LogLevelSetterChannelClient(mainProcessClient.getChannel('loglevel'));
228

S
Sandeep Somavarapu 已提交
229 230 231
	return new FollowerLogService(logLevelClient, logService);
}

232
function createMainProcessServices(mainProcessClient: ElectronIPCClient, configuration: IWindowConfiguration): ServiceCollection {
233 234 235 236 237 238 239 240
	const serviceCollection = new ServiceCollection();

	const windowsChannel = mainProcessClient.getChannel('windows');
	serviceCollection.set(IWindowsService, new WindowsChannelClient(windowsChannel));

	const updateChannel = mainProcessClient.getChannel('update');
	serviceCollection.set(IUpdateService, new SyncDescriptor(UpdateChannelClient, updateChannel));

J
Joao Moreno 已提交
241 242 243 244
	const urlChannel = mainProcessClient.getChannel('url');
	const mainUrlService = new URLServiceChannelClient(urlChannel);
	const urlService = new RelayURLService(mainUrlService);
	serviceCollection.set(IURLService, urlService);
J
Joao Moreno 已提交
245

J
Joao Moreno 已提交
246
	const urlHandlerChannel = new URLHandlerChannel(urlService);
J
Joao Moreno 已提交
247
	mainProcessClient.registerChannel('urlHandler', urlHandlerChannel);
248

249 250 251
	const issueChannel = mainProcessClient.getChannel('issue');
	serviceCollection.set(IIssueService, new SyncDescriptor(IssueChannelClient, issueChannel));

252 253 254
	const menubarChannel = mainProcessClient.getChannel('menubar');
	serviceCollection.set(IMenubarService, new SyncDescriptor(MenubarChannelClient, menubarChannel));

255
	const workspacesChannel = mainProcessClient.getChannel('workspaces');
256
	serviceCollection.set(IWorkspacesService, new WorkspacesChannelClient(workspacesChannel));
257 258

	return serviceCollection;
259
}