main.ts 11.7 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

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

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

55
export function startup(configuration: IWindowConfiguration): TPromise<void> {
56

57 58
	// Ensure others can listen to zoom level changes
	browser.setZoomFactor(webFrame.getZoomFactor());
59

60 61
	// See https://github.com/Microsoft/vscode/issues/26151
	// Can be trusted because we are not setting it ourselves.
62
	browser.setZoomLevel(webFrame.getZoomLevel(), true /* isTrusted */);
63

64 65
	browser.setFullscreen(!!configuration.fullscreen);

66
	KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
A
Alex Dima 已提交
67

68
	browser.setAccessibilitySupport(configuration.accessibilitySupport ? platform.AccessibilitySupport.Enabled : platform.AccessibilitySupport.Disabled);
69

70 71 72
	// Setup Intl
	comparer.setFileNameComparer(new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }));

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

B
Benjamin Pasero 已提交
77
function openWorkbench(configuration: IWindowConfiguration): TPromise<void> {
J
Joao Moreno 已提交
78
	const mainProcessClient = new ElectronIPCClient(`window:${configuration.windowId}`);
79
	const mainServices = createMainProcessServices(mainProcessClient, configuration);
80

81
	const environmentService = new EnvironmentService(configuration, configuration.execPath);
S
Sandeep Somavarapu 已提交
82
	const logService = createLogService(mainProcessClient, configuration, environmentService);
J
Joao Moreno 已提交
83
	logService.trace('openWorkbench configuration', JSON.stringify(configuration));
84 85 86

	// Since the configuration service is one of the core services that is used in so many places, we initialize it
	// right before startup of the workbench shell to have its data ready for consumers
S
Sandeep Somavarapu 已提交
87
	return createAndInitializeWorkspaceService(configuration, environmentService).then(workspaceService => {
88
		const timerService = new TimerService(configuration, workspaceService.getWorkbenchState() === WorkbenchState.EMPTY);
89
		const storageService = createStorageService(workspaceService, environmentService);
90 91 92 93

		return domContentLoaded().then(() => {

			// Open Shell
94
			perf.mark('willStartWorkbench');
95 96 97 98
			const shell = new WorkbenchShell(document.body, {
				contextService: workspaceService,
				configurationService: workspaceService,
				environmentService,
J
Joao Moreno 已提交
99
				logService,
100 101
				timerService,
				storageService
J
Joao Moreno 已提交
102
			}, mainServices, mainProcessClient, configuration);
103 104 105 106 107 108 109
			shell.open();

			// Inform user about loading issues from the loader
			(<any>self).require.config({
				onError: (err: any) => {
					if (err.errorCode === 'load') {
						shell.onUnexpectedError(loaderError(err));
110
					}
111
				}
112 113 114 115 116
			});
		});
	});
}

S
Sandeep Somavarapu 已提交
117
function createAndInitializeWorkspaceService(configuration: IWindowConfiguration, environmentService: EnvironmentService): TPromise<WorkspaceService> {
118
	const folderUri = configuration.folderUri ? uri.revive(configuration.folderUri) : null;
119 120
	return validateFolderUri(folderUri, configuration.verbose).then(validatedFolderUri => {

S
Sandeep Somavarapu 已提交
121
		const workspaceService = new WorkspaceService(environmentService);
122

123
		return workspaceService.initialize(configuration.workspace || validatedFolderUri || configuration).then(() => workspaceService, error => workspaceService);
124
	});
125 126
}

127
function validateFolderUri(folderUri: ISingleFolderWorkspaceIdentifier, verbose: boolean): TPromise<uri> {
128

129 130 131
	// 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) {
		return TPromise.as(folderUri);
E
Erich Gamma 已提交
132 133
	}

134
	// Otherwise: use realpath to resolve symbolic links to the truth
135
	return realpath(folderUri.fsPath).then(realFolderPath => {
136

137
		// For some weird reason, node adds a trailing slash to UNC paths
E
Erich Gamma 已提交
138 139 140
		// we never ever want trailing slashes as our workspace path unless
		// someone opens root ("/").
		// See also https://github.com/nodejs/io.js/issues/1765
141 142
		if (paths.isUNC(realFolderPath) && strings.endsWith(realFolderPath, paths.nativeSep)) {
			realFolderPath = strings.rtrim(realFolderPath, paths.nativeSep);
143
		}
E
Erich Gamma 已提交
144

145
		return uri.file(realFolderPath);
146
	}, error => {
147
		if (verbose) {
148 149 150 151 152 153
			errors.onUnexpectedError(error);
		}

		// Treat any error case as empty workbench case (no folder path)
		return null;

154
	}).then(realFolderUriOrNull => {
155

156
		// Update config with real path if we have one
157
		return realFolderUriOrNull;
158
	});
E
Erich Gamma 已提交
159 160
}

161
function createStorageService(workspaceService: IWorkspaceContextService, environmentService: IEnvironmentService): IStorageService {
162 163 164
	let workspaceId: string;
	let secondaryWorkspaceId: number;

165
	switch (workspaceService.getWorkbenchState()) {
166 167

		// in multi root workspace mode we use the provided ID as key for workspace storage
168
		case WorkbenchState.WORKSPACE:
169
			workspaceId = uri.from({ path: workspaceService.getWorkspace().id, scheme: 'root' }).toString();
170 171 172 173
			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
174
		case WorkbenchState.FOLDER:
175
			const workspace: Workspace = <Workspace>workspaceService.getWorkspace();
176
			workspaceId = workspace.folders[0].uri.toString();
177 178 179 180 181 182 183 184 185
			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.
186
		case WorkbenchState.EMPTY:
187
			workspaceId = workspaceService.getWorkspace().id;
188
			break;
189 190
	}

191
	const disableStorage = !!environmentService.extensionTestsPath; // never keep any state when running extension tests!
192 193 194 195 196 197 198

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

200
	return new StorageService(storage, storage, workspaceId, secondaryWorkspaceId);
201 202
}

S
Sandeep Somavarapu 已提交
203
function createLogService(mainProcessClient: ElectronIPCClient, configuration: IWindowConfiguration, environmentService: IEnvironmentService): ILogService {
S
Sandeep Somavarapu 已提交
204 205
	const spdlogService = createSpdLogService(`renderer${configuration.windowId}`, configuration.logLevel, environmentService.logsPath);
	const consoleLogService = new ConsoleLogService(configuration.logLevel);
S
Sandeep Somavarapu 已提交
206
	const logService = new MultiplexLogService([consoleLogService, spdlogService]);
207
	const logLevelClient = new LogLevelSetterChannelClient(mainProcessClient.getChannel('loglevel'));
S
Sandeep Somavarapu 已提交
208 209 210
	return new FollowerLogService(logLevelClient, logService);
}

211
function createMainProcessServices(mainProcessClient: ElectronIPCClient, configuration: IWindowConfiguration): ServiceCollection {
212 213 214 215 216 217 218 219
	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 已提交
220 221 222 223
	const urlChannel = mainProcessClient.getChannel('url');
	const mainUrlService = new URLServiceChannelClient(urlChannel);
	const urlService = new RelayURLService(mainUrlService);
	serviceCollection.set(IURLService, urlService);
J
Joao Moreno 已提交
224

J
Joao Moreno 已提交
225
	const urlHandlerChannel = new URLHandlerChannel(urlService);
J
Joao Moreno 已提交
226
	mainProcessClient.registerChannel('urlHandler', urlHandlerChannel);
227

228 229 230
	const issueChannel = mainProcessClient.getChannel('issue');
	serviceCollection.set(IIssueService, new SyncDescriptor(IssueChannelClient, issueChannel));

231 232 233
	const menubarChannel = mainProcessClient.getChannel('menubar');
	serviceCollection.set(IMenubarService, new SyncDescriptor(MenubarChannelClient, menubarChannel));

234
	const workspacesChannel = mainProcessClient.getChannel('workspaces');
235
	serviceCollection.set(IWorkspacesService, new WorkspacesChannelClient(workspacesChannel));
236 237 238 239

	return serviceCollection;
}

240 241 242 243 244 245
function loaderError(err: Error): Error {
	if (platform.isWeb) {
		return new Error(nls.localize('loaderError', "Failed to load a required file. Either you are no longer connected to the internet or the server you are connected to is offline. Please refresh the browser to try again."));
	}

	return new Error(nls.localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err)));
246
}