main.ts 10.9 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 11
import { TPromise } from 'vs/base/common/winjs.base';
import { WorkbenchShell } from 'vs/workbench/electron-browser/shell';
import { IOptions } from 'vs/workbench/common/options';
12
import * as browser from 'vs/base/browser/browser';
J
Johannes Rieken 已提交
13
import { domContentLoaded } from 'vs/base/browser/dom';
E
Erich Gamma 已提交
14
import errors = require('vs/base/common/errors');
15
import comparer = require('vs/base/common/comparers');
E
Erich Gamma 已提交
16 17 18 19
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');
J
Johannes Rieken 已提交
20
import { IResourceInput } from 'vs/platform/editor/common/editor';
21
import { Workspace } from 'vs/platform/workspace/common/workspace';
22
import { WorkspaceConfigurationService } from 'vs/workbench/services/configuration/node/configuration';
23
import { realpath, stat, readFile } from 'vs/base/node/pfs';
J
Johannes Rieken 已提交
24
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
E
Erich Gamma 已提交
25 26
import path = require('path');
import gracefulFs = require('graceful-fs');
B
Benjamin Pasero 已提交
27 28
import { IInitData } from 'vs/workbench/services/timer/common/timerService';
import { TimerService } from 'vs/workbench/services/timer/node/timerService';
A
Alex Dima 已提交
29
import { KeyboardMapperFactory } from "vs/workbench/services/keybinding/electron-browser/keybindingService";
B
Benjamin Pasero 已提交
30 31 32 33
import { IWindowConfiguration, IPath } from 'vs/platform/windows/common/windows';
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';
B
Benjamin Pasero 已提交
34

35 36
import { webFrame } from 'electron';

B
Benjamin Pasero 已提交
37
import fs = require('fs');
B
Benjamin Pasero 已提交
38
import { createHash } from 'crypto';
B
Benjamin Pasero 已提交
39
gracefulFs.gracefulify(fs); // enable gracefulFs
E
Erich Gamma 已提交
40

41
export function startup(configuration: IWindowConfiguration): TPromise<void> {
42

43 44
	// Ensure others can listen to zoom level changes
	browser.setZoomFactor(webFrame.getZoomFactor());
45

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

50 51
	browser.setFullscreen(!!configuration.fullscreen);

A
Alex Dima 已提交
52 53
	KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged(configuration.isISOKeyboard);

54
	browser.setAccessibilitySupport(configuration.accessibilitySupport ? platform.AccessibilitySupport.Enabled : platform.AccessibilitySupport.Disabled);
55

56 57 58
	// Setup Intl
	comparer.setFileNameComparer(new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }));

E
Erich Gamma 已提交
59
	// Shell Options
B
polish  
Benjamin Pasero 已提交
60 61 62
	const filesToOpen = configuration.filesToOpen && configuration.filesToOpen.length ? toInputs(configuration.filesToOpen) : null;
	const filesToCreate = configuration.filesToCreate && configuration.filesToCreate.length ? toInputs(configuration.filesToCreate) : null;
	const filesToDiff = configuration.filesToDiff && configuration.filesToDiff.length ? toInputs(configuration.filesToDiff) : null;
B
Benjamin Pasero 已提交
63
	const shellOptions: IOptions = {
64 65
		filesToOpen,
		filesToCreate,
B
Benjamin Pasero 已提交
66
		filesToDiff
E
Erich Gamma 已提交
67 68
	};

69 70
	// Open workbench
	return openWorkbench(configuration, shellOptions);
E
Erich Gamma 已提交
71 72
}

73
function toInputs(paths: IPath[], isUntitledFile?: boolean): IResourceInput[] {
E
Erich Gamma 已提交
74
	return paths.map(p => {
75 76 77 78 79 80 81
		const input = <IResourceInput>{};

		if (isUntitledFile) {
			input.resource = uri.from({ scheme: 'untitled', path: p.filePath });
		} else {
			input.resource = uri.file(p.filePath);
		}
E
Erich Gamma 已提交
82

83 84 85 86
		input.options = {
			pinned: true // opening on startup is always pinned and not preview
		};

E
Erich Gamma 已提交
87
		if (p.lineNumber) {
88 89 90
			input.options.selection = {
				startLineNumber: p.lineNumber,
				startColumn: p.columnNumber
E
Erich Gamma 已提交
91 92 93 94 95 96 97
			};
		}

		return input;
	});
}

98
function openWorkbench(configuration: IWindowConfiguration, options: IOptions): TPromise<void> {
99
	return resolveWorkspaceData(configuration).then(workspaceData => {
100
		const environmentService = new EnvironmentService(configuration, configuration.execPath);
101 102 103
		const workspaceConfigurationService = new WorkspaceConfigurationService(environmentService, createMultiRootWorkspace(workspaceData));
		const timerService = new TimerService((<any>window).MonacoEnvironment.timers as IInitData, !!workspaceData);
		const storageService = createStorageService(workspaceData, configuration, environmentService);
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

		// 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
		return workspaceConfigurationService.initialize().then(() => {
			timerService.beforeDOMContentLoaded = Date.now();

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

				// Open Shell
				timerService.beforeWorkbenchOpen = Date.now();
				const shell = new WorkbenchShell(document.body, {
					contextService: workspaceConfigurationService,
					configurationService: workspaceConfigurationService,
					environmentService,
					timerService,
					storageService
				}, configuration, options);
				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));
129
						}
130
					}
131 132 133 134 135 136
				});
			});
		});
	});
}

137 138
function createMultiRootWorkspace(workspaceData: ISingleFolderWorkspaceData | IMultiRootWorkspaceData): Workspace {
	if (!workspaceData) {
B
Benjamin Pasero 已提交
139 140 141
		return null;
	}

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	let id: string;
	let name: string;
	let folders: uri[];

	const singleFolderWorkspaceData = workspaceData as ISingleFolderWorkspaceData;
	if (singleFolderWorkspaceData.folderPath) {
		folders = [uri.file(singleFolderWorkspaceData.folderPath)];
		id = createHash('md5').update(folders[0].fsPath).update(singleFolderWorkspaceData.ctime ? String(singleFolderWorkspaceData.ctime) : '').digest('hex');
		name = path.basename(folders[0].fsPath);
	} else {
		const multiRootWorkspaceData = workspaceData as IMultiRootWorkspaceData;
		id = multiRootWorkspaceData.id;
		folders = multiRootWorkspaceData.folders.map(f => uri.parse(f));
		name = multiRootWorkspaceData.name;
	}

	return new Workspace(id, name, folders);
}

interface ISingleFolderWorkspaceData {
	folderPath: string;
	ctime: number;
}

interface IMultiRootWorkspaceData {
	id: string;
	name: string;
	folders: string[];
170 171
}

172 173 174
function resolveWorkspaceData(configuration: IWindowConfiguration): TPromise<ISingleFolderWorkspaceData | IMultiRootWorkspaceData> {
	if (configuration.workspaceConfigPath) {
		return resolveMultiRootWorkspaceData(configuration);
E
Erich Gamma 已提交
175 176
	}

177 178 179 180 181 182 183 184
	if (configuration.folderPath) {
		return resolveSingleFolderWorkspaceData(configuration);
	}

	return TPromise.as(null);
}

function resolveSingleFolderWorkspaceData(configuration: IWindowConfiguration): TPromise<ISingleFolderWorkspaceData> {
185
	return realpath(configuration.folderPath).then(realFolderPath => {
186

E
Erich Gamma 已提交
187 188 189 190
		// 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
191 192
		if (paths.isUNC(realFolderPath) && strings.endsWith(realFolderPath, paths.nativeSep)) {
			realFolderPath = strings.rtrim(realFolderPath, paths.nativeSep);
193
		}
E
Erich Gamma 已提交
194

195
		// update config
196
		configuration.folderPath = realFolderPath;
197

198
		// resolve ctime of workspace
199 200 201 202 203 204
		return stat(realFolderPath).then(folderStat => {
			return {
				folderPath: realFolderPath,
				ctime: platform.isLinux ? folderStat.ino : folderStat.birthtime.getTime() // On Linux, birthtime is ctime, so we cannot use it! We use the ino instead!
			} as ISingleFolderWorkspaceData;
		});
205
	}, error => {
206 207
		errors.onUnexpectedError(error);

208
		return null; // treat invalid paths as empty window
209
	});
E
Erich Gamma 已提交
210 211
}

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
function resolveMultiRootWorkspaceData(configuration: IWindowConfiguration): TPromise<IMultiRootWorkspaceData> {
	return readFile(configuration.workspaceConfigPath).then(buffer => {
		const contents = buffer.toString('utf8');

		const res = JSON.parse(contents) as IMultiRootWorkspaceData;
		if (!res.name) {
			res.name = path.basename(configuration.workspaceConfigPath);
		}

		return res;
	}, error => {
		errors.onUnexpectedError(error);

		return null; // treat invalid paths as empty window
	});
}

function createStorageService(workspaceData: ISingleFolderWorkspaceData | IMultiRootWorkspaceData, configuration: IWindowConfiguration, environmentService: IEnvironmentService): IStorageService {
	let workspaceId: string;
	let secondaryWorkspaceId: number;

	const singleFolderWorkspaceData = workspaceData as ISingleFolderWorkspaceData;
	const multiRootWorkspaceData = workspaceData as IMultiRootWorkspaceData;

	// in multi root workspace mode we use the provided ID as key for workspace storage
	if (multiRootWorkspaceData && multiRootWorkspaceData.id) {
		workspaceId = uri.from({ path: multiRootWorkspaceData.id, scheme: 'workspace' }).toString();
	}

	// 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
	else if (singleFolderWorkspaceData && singleFolderWorkspaceData.folderPath) {
		workspaceId = uri.file(singleFolderWorkspaceData.folderPath).toString();
		secondaryWorkspaceId = singleFolderWorkspaceData.ctime;
	}

	// 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.
	else if (configuration.backupPath) {
		workspaceId = uri.from({ path: path.basename(configuration.backupPath), scheme: 'empty' }).toString();
256 257
	}

258 259
	const disableStorage = !!environmentService.extensionTestsPath; // never keep any state when running extension tests!
	const storage = disableStorage ? inMemoryLocalStorageInstance : window.localStorage;
260

261
	return new StorageService(storage, storage, workspaceId, secondaryWorkspaceId);
262 263 264 265 266 267 268 269
}

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)));
270
}