main.ts 9.8 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';
C
Christof Marti 已提交
42 43
import { ICredentialsService } from 'vs/platform/credentials/common/credentials';
import { CredentialsChannelClient } from 'vs/platform/credentials/node/credentialsIpc';
44

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

48 49
const currentWindowId = remote.getCurrentWindow().id;

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

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

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

59 60
	browser.setFullscreen(!!configuration.fullscreen);

61
	KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
A
Alex Dima 已提交
62

63
	browser.setAccessibilitySupport(configuration.accessibilitySupport ? platform.AccessibilitySupport.Enabled : platform.AccessibilitySupport.Disabled);
64

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

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

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

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

		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 已提交
97
			}, mainServices, configuration);
98 99 100 101 102 103 104
			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));
105
					}
106
				}
107 108 109 110 111
			});
		});
	});
}

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

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

120 121 122
function validateWorkspacePath(configuration: IWindowConfiguration): TPromise<void> {
	if (!configuration.folderPath) {
		return TPromise.as(null);
E
Erich Gamma 已提交
123 124
	}

125
	return realpath(configuration.folderPath).then(realFolderPath => {
126

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

135
		// update config
136
		configuration.folderPath = realFolderPath;
137
	}, error => {
138 139
		errors.onUnexpectedError(error);

140
		return null; // treat invalid paths as empty workspace
141
	});
E
Erich Gamma 已提交
142 143
}

144
function createStorageService(workspaceService: IWorkspaceContextService, environmentService: IEnvironmentService): IStorageService {
145 146 147
	let workspaceId: string;
	let secondaryWorkspaceId: number;

148
	switch (workspaceService.getWorkbenchState()) {
149 150

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

174 175
	const disableStorage = !!environmentService.extensionTestsPath; // never keep any state when running extension tests!
	const storage = disableStorage ? inMemoryLocalStorageInstance : window.localStorage;
176

177
	return new StorageService(storage, storage, workspaceId, secondaryWorkspaceId);
178 179
}

180
function createMainProcessServices(mainProcessClient: ElectronIPCClient): ServiceCollection {
181 182 183 184 185 186 187 188 189
	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');
190
	serviceCollection.set(IURLService, new SyncDescriptor(URLChannelClient, urlChannel, currentWindowId));
191 192

	const workspacesChannel = mainProcessClient.getChannel('workspaces');
193
	serviceCollection.set(IWorkspacesService, new WorkspacesChannelClient(workspacesChannel));
194

C
Christof Marti 已提交
195 196 197
	const credentialsChannel = mainProcessClient.getChannel('credentials');
	serviceCollection.set(ICredentialsService, new CredentialsChannelClient(credentialsChannel));

198 199 200
	return serviceCollection;
}

201 202 203 204 205 206
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)));
207
}