main.ts 10.0 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 nls = require('vs/nls');
J
Johannes Rieken 已提交
9 10
import { TPromise } from 'vs/base/common/winjs.base';
import { WorkbenchShell } from 'vs/workbench/electron-browser/shell';
11
import * as browser from 'vs/base/browser/browser';
J
Johannes Rieken 已提交
12
import { domContentLoaded } from 'vs/base/browser/dom';
E
Erich Gamma 已提交
13
import errors = require('vs/base/common/errors');
14
import comparer = require('vs/base/common/comparers');
E
Erich Gamma 已提交
15 16 17 18
import platform = require('vs/base/common/platform');
import paths = require('vs/base/common/paths');
import uri from 'vs/base/common/uri';
import strings = require('vs/base/common/strings');
19
import { IWorkspaceContextService, Workspace, WorkbenchState } from 'vs/platform/workspace/common/workspace';
20
import { WorkspaceService } from 'vs/workbench/services/configuration/node/configurationService';
21 22
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
23
import { realpath } from 'vs/base/node/pfs';
J
Johannes Rieken 已提交
24
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
E
Erich Gamma 已提交
25
import gracefulFs = require('graceful-fs');
B
Benjamin Pasero 已提交
26 27
import { IInitData } from 'vs/workbench/services/timer/common/timerService';
import { TimerService } from 'vs/workbench/services/timer/node/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 33
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { StorageService, inMemoryLocalStorageInstance } 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 38 39 40 41
import { UpdateChannelClient } from 'vs/platform/update/common/updateIpc';
import { IUpdateService } from 'vs/platform/update/common/update';
import { URLChannelClient } from 'vs/platform/url/common/urlIpc';
import { IURLService } from 'vs/platform/url/common/url';
import { WorkspacesChannelClient } from 'vs/platform/workspaces/common/workspacesIpc';
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
42
import { createLogService } from 'vs/platform/log/node/spdlogService';
43

B
Benjamin Pasero 已提交
44
import fs = require('fs');
J
Joao Moreno 已提交
45
import { ConsoleLogService, MultiplexLogService } from 'vs/platform/log/common/log';
B
Benjamin Pasero 已提交
46
gracefulFs.gracefulify(fs); // enable gracefulFs
E
Erich Gamma 已提交
47

48
export function startup(configuration: IWindowConfiguration): TPromise<void> {
49

50 51
	// Ensure others can listen to zoom level changes
	browser.setZoomFactor(webFrame.getZoomFactor());
52

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

57 58
	browser.setFullscreen(!!configuration.fullscreen);

59
	KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
A
Alex Dima 已提交
60

61
	browser.setAccessibilitySupport(configuration.accessibilitySupport ? platform.AccessibilitySupport.Enabled : platform.AccessibilitySupport.Disabled);
62

63 64 65
	// Setup Intl
	comparer.setFileNameComparer(new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }));

66
	// Open workbench
B
Benjamin Pasero 已提交
67
	return openWorkbench(configuration);
E
Erich Gamma 已提交
68 69
}

B
Benjamin Pasero 已提交
70
function openWorkbench(configuration: IWindowConfiguration): TPromise<void> {
71 72
	const mainProcessClient = new ElectronIPCClient(String(`window${configuration.windowId}`));
	const mainServices = createMainProcessServices(mainProcessClient, configuration);
73

74
	const environmentService = new EnvironmentService(configuration, configuration.execPath);
75
	const spdlogService = createLogService(`renderer${configuration.windowId}`, environmentService);
J
Joao Moreno 已提交
76 77
	const consoleLogService = new ConsoleLogService(environmentService);
	const logService = new MultiplexLogService([consoleLogService, spdlogService]);
J
Joao Moreno 已提交
78

J
Joao Moreno 已提交
79
	logService.trace('openWorkbench configuration', JSON.stringify(configuration));
80 81 82

	// 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 已提交
83
	return createAndInitializeWorkspaceService(configuration, environmentService).then(workspaceService => {
84

85
		const timerService = new TimerService((<any>window).MonacoEnvironment.timers as IInitData, workspaceService.getWorkbenchState() === WorkbenchState.EMPTY);
86
		const storageService = createStorageService(workspaceService, environmentService);
87 88 89 90 91 92 93 94 95

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

			// Open Shell
			timerService.beforeWorkbenchOpen = Date.now();
			const shell = new WorkbenchShell(document.body, {
				contextService: workspaceService,
				configurationService: workspaceService,
				environmentService,
J
Joao Moreno 已提交
96
				logService,
97 98
				timerService,
				storageService
B
Benjamin Pasero 已提交
99
			}, mainServices, configuration);
100 101 102 103 104 105 106
			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));
107
					}
108
				}
109 110 111 112 113
			});
		});
	});
}

S
Sandeep Somavarapu 已提交
114
function createAndInitializeWorkspaceService(configuration: IWindowConfiguration, environmentService: EnvironmentService): TPromise<WorkspaceService> {
115
	return validateSingleFolderPath(configuration).then(() => {
S
Sandeep Somavarapu 已提交
116
		const workspaceService = new WorkspaceService(environmentService);
117

118
		return workspaceService.initialize(configuration.workspace || configuration.folderPath || configuration).then(() => workspaceService, error => workspaceService);
119
	});
120 121
}

122 123 124
function validateSingleFolderPath(configuration: IWindowConfiguration): TPromise<void> {

	// Return early if we do not have a single folder path
125
	if (!configuration.folderPath) {
126
		return TPromise.as(void 0);
E
Erich Gamma 已提交
127 128
	}

129
	// Otherwise: use realpath to resolve symbolic links to the truth
130
	return realpath(configuration.folderPath).then(realFolderPath => {
131

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

140
		return realFolderPath;
141
	}, error => {
142 143 144 145 146 147 148 149
		if (configuration.verbose) {
			errors.onUnexpectedError(error);
		}

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

	}).then(realFolderPathOrNull => {
150

151 152
		// Update config with real path if we have one
		configuration.folderPath = realFolderPathOrNull;
153
	});
E
Erich Gamma 已提交
154 155
}

156
function createStorageService(workspaceService: IWorkspaceContextService, environmentService: IEnvironmentService): IStorageService {
157 158 159
	let workspaceId: string;
	let secondaryWorkspaceId: number;

160
	switch (workspaceService.getWorkbenchState()) {
161 162

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

186 187
	const disableStorage = !!environmentService.extensionTestsPath; // never keep any state when running extension tests!
	const storage = disableStorage ? inMemoryLocalStorageInstance : window.localStorage;
188

189
	return new StorageService(storage, storage, workspaceId, secondaryWorkspaceId);
190 191
}

192
function createMainProcessServices(mainProcessClient: ElectronIPCClient, configuration: IWindowConfiguration): ServiceCollection {
193 194 195 196 197 198 199 200 201
	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));

	const urlChannel = mainProcessClient.getChannel('url');
202
	serviceCollection.set(IURLService, new SyncDescriptor(URLChannelClient, urlChannel, configuration.windowId));
203 204

	const workspacesChannel = mainProcessClient.getChannel('workspaces');
205
	serviceCollection.set(IWorkspacesService, new WorkspacesChannelClient(workspacesChannel));
206 207 208 209

	return serviceCollection;
}

210 211 212 213 214 215
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)));
216
}