main.ts 9.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 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 35 36 37 38 39 40 41
import { Client as ElectronIPCClient } from 'vs/base/parts/ipc/electron-browser/ipc.electron-browser';
import { webFrame, remote } from 'electron';
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

B
Benjamin Pasero 已提交
43
import fs = require('fs');
B
Benjamin Pasero 已提交
44
gracefulFs.gracefulify(fs); // enable gracefulFs
E
Erich Gamma 已提交
45

46 47
const currentWindowId = remote.getCurrentWindow().id;

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${currentWindowId}`));
	const mainServices = createMainProcessServices(mainProcessClient);
73

74 75 76 77
	const environmentService = new EnvironmentService(configuration, configuration.execPath);

	// 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
78
	return createAndInitializeWorkspaceService(configuration, environmentService, <IWorkspacesService>mainServices.get(IWorkspacesService)).then(workspaceService => {
79
		const timerService = new TimerService((<any>window).MonacoEnvironment.timers as IInitData, workspaceService.getWorkbenchState() === WorkbenchState.EMPTY);
80
		const storageService = createStorageService(workspaceService, environmentService);
81 82 83 84 85 86 87 88 89 90 91 92 93 94

		timerService.beforeDOMContentLoaded = Date.now();

		return domContentLoaded().then(() => {
			timerService.afterDOMContentLoaded = Date.now();

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

110
function createAndInitializeWorkspaceService(configuration: IWindowConfiguration, environmentService: EnvironmentService, workspacesService: IWorkspacesService): TPromise<WorkspaceService> {
111
	return validateSingleFolderPath(configuration).then(() => {
112 113
		const workspaceService = new WorkspaceService(environmentService, workspacesService);

114
		return workspaceService.initialize(configuration.workspace || configuration.folderPath || configuration).then(() => workspaceService, error => workspaceService);
115
	});
116 117
}

118 119 120
function validateSingleFolderPath(configuration: IWindowConfiguration): TPromise<void> {

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

125
	// Otherwise: use realpath to resolve symbolic links to the truth
126
	return realpath(configuration.folderPath).then(realFolderPath => {
127

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

136
		return realFolderPath;
137
	}, error => {
138 139 140 141 142 143 144 145
		if (configuration.verbose) {
			errors.onUnexpectedError(error);
		}

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

	}).then(realFolderPathOrNull => {
146

147 148
		// Update config with real path if we have one
		configuration.folderPath = realFolderPathOrNull;
149
	});
E
Erich Gamma 已提交
150 151
}

152
function createStorageService(workspaceService: IWorkspaceContextService, environmentService: IEnvironmentService): IStorageService {
153 154 155
	let workspaceId: string;
	let secondaryWorkspaceId: number;

156
	switch (workspaceService.getWorkbenchState()) {
157 158

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

182 183
	const disableStorage = !!environmentService.extensionTestsPath; // never keep any state when running extension tests!
	const storage = disableStorage ? inMemoryLocalStorageInstance : window.localStorage;
184

185
	return new StorageService(storage, storage, workspaceId, secondaryWorkspaceId);
186 187
}

188
function createMainProcessServices(mainProcessClient: ElectronIPCClient): ServiceCollection {
189 190 191 192 193 194 195 196 197
	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');
198
	serviceCollection.set(IURLService, new SyncDescriptor(URLChannelClient, urlChannel, currentWindowId));
199 200

	const workspacesChannel = mainProcessClient.getChannel('workspaces');
201
	serviceCollection.set(IWorkspacesService, new WorkspacesChannelClient(workspacesChannel));
202 203 204 205

	return serviceCollection;
}

206 207 208 209 210 211
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)));
212
}