main.js 7.0 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6 7
'use strict';

J
Johannes Rieken 已提交
8
if (process.argv.indexOf('--prof-startup') >= 0) {
9
	var profiler = require('v8-profiler');
10 11 12
	var prefix = require('crypto').randomBytes(2).toString('hex');
	process.env.VSCODE_PROFILES_PREFIX = prefix;
	profiler.startProfiling('main', true);
13 14
}

B
Benjamin Pasero 已提交
15 16 17
// Workaround for https://github.com/electron/electron/issues/9225. Chrome has an issue where
// in certain locales (e.g. PL), image metrics are wrongly computed. We explicitly set the
// LC_NUMERIC to prevent this from happening (selects the numeric formatting category of the
18
// C locale, http://en.cppreference.com/w/cpp/locale/LC_categories). TODO@Ben temporary.
B
Benjamin Pasero 已提交
19 20 21 22 23 24
if (process.env.LC_ALL) {
	process.env.LC_ALL = 'C';
}
if (process.env.LC_NUMERIC) {
	process.env.LC_NUMERIC = 'C';
}
B
Benjamin Pasero 已提交
25

J
Joao Moreno 已提交
26
// Perf measurements
27
global.perfStartTime = Date.now();
J
Joao Moreno 已提交
28 29

var app = require('electron').app;
J
Joao Moreno 已提交
30
var fs = require('fs');
J
Joao Moreno 已提交
31
var path = require('path');
32
var minimist = require('minimist');
J
Joao Moreno 已提交
33
var paths = require('./paths');
J
Joao Moreno 已提交
34

J
Joao Moreno 已提交
35 36 37 38
var args = minimist(process.argv, {
	string: ['user-data-dir', 'locale']
});

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
function stripComments(content) {
	var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
	var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
		// Only one of m1, m2, m3, m4 matches
		if (m3) {
			// A block comment. Replace with nothing
			return '';
		}
		else if (m4) {
			// A line comment. If it ends in \r?\n then keep it.
			var length_1 = m4.length;
			if (length_1 > 2 && m4[length_1 - 1] === '\n') {
				return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
			}
			else {
				return '';
			}
		}
		else {
			// We match a string
			return match;
		}
	});
	return result;
J
lint  
Joao Moreno 已提交
63
}
64

J
Joao Moreno 已提交
65
function getNLSConfiguration() {
J
Joao Moreno 已提交
66
	var locale = args['locale'];
J
Joao Moreno 已提交
67

68 69
	if (!locale) {
		var userData = app.getPath('userData');
J
Joao Moreno 已提交
70
		var localeConfig = path.join(userData, 'User', 'locale.json');
71 72 73
		if (fs.existsSync(localeConfig)) {
			try {
				var content = stripComments(fs.readFileSync(localeConfig, 'utf8'));
J
Joao Moreno 已提交
74
				var value = JSON.parse(content).locale;
75 76 77 78
				if (value && typeof value === 'string') {
					locale = value;
				}
			} catch (e) {
J
lint  
Joao Moreno 已提交
79
				// noop
80 81 82 83
			}
		}
	}

84 85
	var appLocale = app.getLocale();
	locale = locale || appLocale;
86 87 88 89 90
	// Language tags are case insensitve however an amd loader is case sensitive
	// To make this work on case preserving & insensitive FS we do the following:
	// the language bundles have lower case language tags and we always lower case
	// the locale we receive from the user or OS.
	locale = locale ? locale.toLowerCase() : locale;
J
Joao Moreno 已提交
91
	if (locale === 'pseudo') {
92
		return { locale: locale, availableLanguages: {}, pseudo: true };
J
Joao Moreno 已提交
93
	}
94
	var initialLocale = locale;
J
Joao Moreno 已提交
95
	if (process.env['VSCODE_DEV']) {
96
		return { locale: locale, availableLanguages: {} };
J
Joao Moreno 已提交
97
	}
98

J
Joao Moreno 已提交
99 100
	// We have a built version so we have extracted nls file. Try to find
	// the right file to use.
101 102 103 104 105 106 107 108 109 110 111 112

	// Check if we have an English locale. If so fall to default since that is our
	// English translation (we don't ship *.nls.en.json files)
	if (locale && (locale == 'en' || locale.startsWith('en-'))) {
		return { locale: locale, availableLanguages: {} };
	}

	function resolveLocale(locale) {
		while (locale) {
			var candidate = path.join(__dirname, 'vs', 'code', 'electron-main', 'main.nls.') + locale + '.js';
			if (fs.existsSync(candidate)) {
				return { locale: initialLocale, availableLanguages: { '*': locale } };
J
Joao Moreno 已提交
113
			} else {
114 115 116 117 118 119
				var index = locale.lastIndexOf('-');
				if (index > 0) {
					locale = locale.substring(0, index);
				} else {
					locale = null;
				}
J
Joao Moreno 已提交
120 121
			}
		}
122
		return null;
J
Joao Moreno 已提交
123 124
	}

125 126 127 128 129
	var resolvedLocale = resolveLocale(locale);
	if (!resolvedLocale && appLocale && appLocale !== locale) {
		resolvedLocale = resolveLocale(appLocale);
	}
	return resolvedLocale ? resolvedLocale : { locale: initialLocale, availableLanguages: {} };
J
Joao Moreno 已提交
130 131
}

132 133 134 135
function getNodeCachedDataDir() {

	// IEnvironmentService.isBuilt
	if (process.env['VSCODE_DEV']) {
136
		return Promise.resolve(undefined);
137 138
	}

139 140 141 142 143 144 145
	// find commit id
	var productJson = require(path.join(__dirname, '../product.json'));
	if (!productJson.commit) {
		return Promise.resolve(undefined);
	}

	var dir = path.join(app.getPath('userData'), 'CachedData', productJson.commit);
146

J
Johannes Rieken 已提交
147
	return mkdirp(dir).then(undefined, function (err) { /*ignore*/ });
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
}

function mkdirp(dir) {
	return mkdir(dir)
		.then(null, function (err) {
			if (err && err.code === 'ENOENT') {
				var parent = path.dirname(dir);
				if (parent !== dir) { // if not arrived at root
					return mkdirp(parent)
						.then(function () {
							return mkdir(dir);
						});
				}
			}
			throw err;
		});
}

function mkdir(dir) {
167 168 169 170 171 172 173 174
	return new Promise(function (resolve, reject) {
		fs.mkdir(dir, function (err) {
			if (err && err.code !== 'EEXIST') {
				reject(err);
			} else {
				resolve(dir);
			}
		});
175 176 177
	});
}

178
// Set userData path before app 'ready' event and call to process.chdir
179
var userData = path.resolve(args['user-data-dir'] || paths.getDefaultUserDataPath(process.platform));
180 181
app.setPath('userData', userData);

B
polish  
Benjamin Pasero 已提交
182
// Update cwd based on environment and platform
J
Joao Moreno 已提交
183
try {
B
polish  
Benjamin Pasero 已提交
184
	if (process.platform === 'win32') {
J
Joao Moreno 已提交
185
		process.env['VSCODE_CWD'] = process.cwd(); // remember as environment variable
B
polish  
Benjamin Pasero 已提交
186
		process.chdir(path.dirname(app.getPath('exe'))); // always set application folder as cwd
J
Joao Moreno 已提交
187 188
	} else if (process.env['VSCODE_CWD']) {
		process.chdir(process.env['VSCODE_CWD']);
J
Joao Moreno 已提交
189 190
	}
} catch (err) {
B
polish  
Benjamin Pasero 已提交
191
	console.error(err);
J
Joao Moreno 已提交
192 193 194 195 196
}

// Mac: when someone drops a file to the not-yet running VSCode, the open-file event fires even before
// the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
global.macOpenFiles = [];
B
polish  
Benjamin Pasero 已提交
197
app.on('open-file', function (event, path) {
J
Joao Moreno 已提交
198 199 200
	global.macOpenFiles.push(path);
});

201 202
var openUrls = [];
var onOpenUrl = function (event, url) {
J
Joao Moreno 已提交
203 204 205 206
	event.preventDefault();
	openUrls.push(url);
};

207 208 209
app.on('will-finish-launching', function () {
	app.on('open-url', onOpenUrl);
});
J
Joao Moreno 已提交
210

211
global.getOpenUrls = function () {
J
Joao Moreno 已提交
212 213 214 215
	app.removeListener('open-url', onOpenUrl);
	return openUrls;
};

216

217 218
// use '<UserData>/CachedData'-directory to store
// node/v8 cached data.
219
var nodeCachedDataDir = getNodeCachedDataDir().then(function (value) {
220
	if (value) {
221
		// store the data directory
222
		process.env['VSCODE_NODE_CACHED_DATA_DIR_' + process.pid] = value;
223 224 225 226

		// tell v8 to not be lazy when parsing JavaScript. Generally this makes startup slower
		// but because we generate cached data it makes subsequent startups much faster
		app.commandLine.appendSwitch('--js-flags', '--nolazy');
227
	}
228 229
});

230 231 232 233 234 235 236 237
var nlsConfig = getNLSConfiguration();
process.env['VSCODE_NLS_CONFIG'] = JSON.stringify(nlsConfig);

var bootstrap = require('./bootstrap-amd');
nodeCachedDataDir.then(function () {
	bootstrap.bootstrap('vs/code/electron-main/main');
}, function (err) {
	console.error(err);
238
});