main.ts 11.8 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';
25
import { IStorageLegacyService, StorageLegacyService, inMemoryLocalStorageInstance, IStorageLegacy } from 'vs/platform/storage/common/storageLegacyService';
B
Benjamin Pasero 已提交
26
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
27
import { Client as ElectronIPCClient } from 'vs/base/parts/ipc/electron-browser/ipc.electron-browser';
28
import { webFrame } from 'electron';
J
Joao Moreno 已提交
29
import { UpdateChannelClient } from 'vs/platform/update/node/updateIpc';
30
import { IUpdateService } from 'vs/platform/update/common/update';
J
Joao Moreno 已提交
31
import { URLHandlerChannel, URLServiceChannelClient } from 'vs/platform/url/node/urlIpc';
32
import { IURLService } from 'vs/platform/url/common/url';
J
Joao Moreno 已提交
33
import { WorkspacesChannelClient } from 'vs/platform/workspaces/node/workspacesIpc';
34
import { IWorkspacesService, ISingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
35
import { createSpdLogService } from 'vs/platform/log/node/spdlogService';
36
import * as fs from 'fs';
S
Sandeep Somavarapu 已提交
37
import { ConsoleLogService, MultiplexLogService, ILogService } from 'vs/platform/log/common/log';
B
Benjamin Pasero 已提交
38
import { StorageService, DelegatingStorageService } from 'vs/platform/storage/electron-browser/storageService';
J
Joao Moreno 已提交
39
import { IssueChannelClient } from 'vs/platform/issue/node/issueIpc';
40
import { IIssueService } from 'vs/platform/issue/common/issue';
J
Joao Moreno 已提交
41
import { LogLevelSetterChannelClient, FollowerLogService } from 'vs/platform/log/node/logIpc';
J
Joao Moreno 已提交
42
import { RelayURLService } from 'vs/platform/url/common/urlService';
J
Joao Moreno 已提交
43
import { MenubarChannelClient } from 'vs/platform/menubar/node/menubarIpc';
44
import { IMenubarService } from 'vs/platform/menubar/common/menubar';
45
import { Schemas } from 'vs/base/common/network';
46
import { sanitizeFilePath } from 'vs/base/node/extfs';
J
Joao Moreno 已提交
47

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

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

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

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

58 59 60
	// 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)
61
	browser.setFullscreen(!!configuration.fullscreen);
62
	browser.setAccessibilitySupport(configuration.accessibilitySupport ? platform.AccessibilitySupport.Enabled : platform.AccessibilitySupport.Disabled);
63

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

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

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

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

M
Martin Aeschlimann 已提交
79 80 81 82 83 84 85 86
	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 已提交
87
		}
M
Martin Aeschlimann 已提交
88
	});
M
Martin Aeschlimann 已提交
89 90
}

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

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

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

100 101
	return Promise.all([
		createAndInitializeWorkspaceService(configuration, environmentService),
102
		createStorageService(environmentService, logService)
103 104
	]).then(services => {
		const workspaceService = services[0];
105
		const storageLegacyService = createStorageLegacyService(workspaceService, environmentService);
106
		const storageService = new DelegatingStorageService(services[1], storageLegacyService, logService, environmentService);
107 108

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

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

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

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

			// Inform user about loading issues from the loader
			(<any>self).require.config({
				onError: (err: any) => {
					if (err.errorCode === 'load') {
133
						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))));
134
					}
135
				}
136 137 138 139 140
			});
		});
	});
}

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

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

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

151 152
	// 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) {
153
		return Promise.resolve(folderUri);
E
Erich Gamma 已提交
154 155
	}

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

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

168 169
function createStorageService(environmentService: IEnvironmentService, logService: ILogService): Promise<StorageService> {
	perf.mark('willCreateStorageService');
170

171
	const storageService = new StorageService(':memory:', logService, environmentService);
172

173 174
	return storageService.init().then(() => {
		perf.mark('didCreateStorageService');
175

176
		return storageService;
177
	});
178 179
}

180
function createStorageLegacyService(workspaceService: IWorkspaceContextService, environmentService: IEnvironmentService): IStorageLegacyService {
181 182 183
	let workspaceId: string;
	let secondaryWorkspaceId: number;

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

		// in multi root workspace mode we use the provided ID as key for workspace storage
187
		case WorkbenchState.WORKSPACE:
188
			workspaceId = uri.from({ path: workspaceService.getWorkspace().id, scheme: 'root' }).toString();
189 190 191 192
			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
193
		case WorkbenchState.FOLDER:
194
			const workspace: Workspace = <Workspace>workspaceService.getWorkspace();
195
			workspaceId = workspace.folders[0].uri.toString();
196 197 198 199 200 201 202 203 204
			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.
205
		case WorkbenchState.EMPTY:
206
			workspaceId = workspaceService.getWorkspace().id;
207
			break;
208 209
	}

210
	const disableStorage = !!environmentService.extensionTestsPath; // never keep any state when running extension tests!
211

212
	let storage: IStorageLegacy;
213 214 215 216 217
	if (disableStorage) {
		storage = inMemoryLocalStorageInstance;
	} else {
		storage = window.localStorage;
	}
218

219
	return new StorageLegacyService(storage, storage, workspaceId, secondaryWorkspaceId);
220 221
}

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

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

231
function createMainProcessServices(mainProcessClient: ElectronIPCClient, configuration: IWindowConfiguration): ServiceCollection {
232 233 234 235 236 237 238 239
	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 已提交
240 241 242 243
	const urlChannel = mainProcessClient.getChannel('url');
	const mainUrlService = new URLServiceChannelClient(urlChannel);
	const urlService = new RelayURLService(mainUrlService);
	serviceCollection.set(IURLService, urlService);
J
Joao Moreno 已提交
244

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

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

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

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

	return serviceCollection;
258
}