actions.ts 47.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 URI from 'vs/base/common/uri';
9
import * as collections from 'vs/base/common/collections';
J
Johannes Rieken 已提交
10 11
import { TPromise } from 'vs/base/common/winjs.base';
import { Action } from 'vs/base/common/actions';
12
import { IWindowService, IWindowsService, MenuBarVisibility } from 'vs/platform/windows/common/windows';
J
Johannes Rieken 已提交
13
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
E
Erich Gamma 已提交
14
import nls = require('vs/nls');
15 16
import product from 'vs/platform/node/product';
import pkg from 'vs/platform/node/package';
B
Benjamin Pasero 已提交
17
import errors = require('vs/base/common/errors');
J
Johannes Rieken 已提交
18 19 20 21
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationEditingService, ConfigurationTarget } from 'vs/workbench/services/configuration/common/configurationEditing';
22
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
J
Johannes Rieken 已提交
23 24
import { IExtensionManagementService, LocalExtensionType, ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
B
Benjamin Pasero 已提交
25
import paths = require('vs/base/common/paths');
26
import { isMacintosh, isLinux } from 'vs/base/common/platform';
J
Johannes Rieken 已提交
27
import { IQuickOpenService, IFilePickOpenEntry, ISeparator } from 'vs/platform/quickOpen/common/quickOpen';
J
Johannes Rieken 已提交
28
import { KeyMod } from 'vs/base/common/keyCodes';
29
import * as browser from 'vs/base/browser/browser';
J
Johannes Rieken 已提交
30
import { IIntegrityService } from 'vs/platform/integrity/common/integrity';
B
Benjamin Pasero 已提交
31
import { IEntryRunContext } from 'vs/base/parts/quickopen/common/quickOpen';
B
Benjamin Pasero 已提交
32
import { ITimerService, IStartupMetrics } from 'vs/workbench/services/timer/common/timerService';
S
sj.hwang 已提交
33 34 35 36
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts, Position as SidebarPosition } from 'vs/workbench/services/part/common/partService';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
B
Benjamin Pasero 已提交
37
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
B
Benjamin Pasero 已提交
38
import * as os from 'os';
39
import { webFrame } from 'electron';
B
Benjamin Pasero 已提交
40 41 42
import { getPathLabel } from 'vs/base/common/labels';
import { IViewlet } from 'vs/workbench/common/viewlet';
import { IPanel } from 'vs/workbench/common/panel';
43
import { IWorkspaceIdentifier, getWorkspaceLabel } from "vs/platform/workspaces/common/workspaces";
E
Erich Gamma 已提交
44

45 46
// --- actions

E
Erich Gamma 已提交
47 48 49 50 51 52 53 54
export class CloseEditorAction extends Action {

	public static ID = 'workbench.action.closeActiveEditor';
	public static LABEL = nls.localize('closeActiveEditor', "Close Editor");

	constructor(
		id: string,
		label: string,
55
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
E
Erich Gamma 已提交
56 57 58 59
	) {
		super(id, label);
	}

B
Benjamin Pasero 已提交
60
	public run(): TPromise<void> {
B
Benjamin Pasero 已提交
61
		const activeEditor = this.editorService.getActiveEditor();
E
Erich Gamma 已提交
62
		if (activeEditor) {
63
			return this.editorService.closeEditor(activeEditor.position, activeEditor.input);
E
Erich Gamma 已提交
64 65
		}

B
Benjamin Pasero 已提交
66
		return TPromise.as(null);
E
Erich Gamma 已提交
67 68 69 70 71 72 73 74
	}
}

export class CloseWindowAction extends Action {

	public static ID = 'workbench.action.closeWindow';
	public static LABEL = nls.localize('closeWindow', "Close Window");

75
	constructor(id: string, label: string, @IWindowService private windowService: IWindowService) {
E
Erich Gamma 已提交
76 77 78
		super(id, label);
	}

79
	public run(): TPromise<boolean> {
80
		this.windowService.closeWindow();
E
Erich Gamma 已提交
81

A
Alex Dima 已提交
82
		return TPromise.as(true);
E
Erich Gamma 已提交
83 84 85
	}
}

86
export class CloseWorkspaceAction extends Action {
E
Erich Gamma 已提交
87

J
Joao Moreno 已提交
88
	static ID = 'workbench.action.closeFolder';
89
	static LABEL = nls.localize('closeWorkspace', "Close Workspace");
E
Erich Gamma 已提交
90 91 92 93 94

	constructor(
		id: string,
		label: string,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
B
Benjamin Pasero 已提交
95
		@IMessageService private messageService: IMessageService,
J
Joao Moreno 已提交
96
		@IWindowService private windowService: IWindowService
E
Erich Gamma 已提交
97 98 99 100
	) {
		super(id, label);
	}

J
Joao Moreno 已提交
101
	run(): TPromise<void> {
B
Benjamin Pasero 已提交
102
		if (!this.contextService.hasWorkspace()) {
103 104
			this.messageService.show(Severity.Info, nls.localize('noWorkspaceOpened', "There is currently no workspace opened in this instance to close."));

J
Joao Moreno 已提交
105
			return TPromise.as(null);
E
Erich Gamma 已提交
106 107
		}

108
		return this.windowService.closeWorkspace();
E
Erich Gamma 已提交
109 110 111 112 113
	}
}

export class NewWindowAction extends Action {

J
Joao Moreno 已提交
114 115
	static ID = 'workbench.action.newWindow';
	static LABEL = nls.localize('newWindow', "New Window");
E
Erich Gamma 已提交
116

B
Benjamin Pasero 已提交
117 118 119
	constructor(
		id: string,
		label: string,
J
Joao Moreno 已提交
120
		@IWindowsService private windowsService: IWindowsService
B
Benjamin Pasero 已提交
121
	) {
E
Erich Gamma 已提交
122 123 124
		super(id, label);
	}

J
Joao Moreno 已提交
125 126
	run(): TPromise<void> {
		return this.windowsService.openNewWindow();
E
Erich Gamma 已提交
127 128 129 130 131
	}
}

export class ToggleFullScreenAction extends Action {

J
Joao Moreno 已提交
132 133
	static ID = 'workbench.action.toggleFullScreen';
	static LABEL = nls.localize('toggleFullScreen', "Toggle Full Screen");
E
Erich Gamma 已提交
134

J
Joao Moreno 已提交
135
	constructor(id: string, label: string, @IWindowService private windowService: IWindowService) {
E
Erich Gamma 已提交
136 137 138
		super(id, label);
	}

J
Joao Moreno 已提交
139 140
	run(): TPromise<void> {
		return this.windowService.toggleFullScreen();
E
Erich Gamma 已提交
141 142 143
	}
}

144 145
export class ToggleMenuBarAction extends Action {

J
Joao Moreno 已提交
146 147
	static ID = 'workbench.action.toggleMenuBar';
	static LABEL = nls.localize('toggleMenuBar', "Toggle Menu Bar");
148

149
	private static menuBarVisibilityKey = 'window.menuBarVisibility';
150 151 152 153 154 155 156 157

	constructor(
		id: string,
		label: string,
		@IMessageService private messageService: IMessageService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IConfigurationEditingService private configurationEditingService: IConfigurationEditingService
	) {
158 159 160
		super(id, label);
	}

B
Benjamin Pasero 已提交
161
	public run(): TPromise<void> {
162 163 164
		let currentVisibilityValue = this.configurationService.lookup<MenuBarVisibility>(ToggleMenuBarAction.menuBarVisibilityKey).value;
		if (typeof currentVisibilityValue !== 'string') {
			currentVisibilityValue = 'default';
165 166 167
		}

		let newVisibilityValue: string;
168
		if (currentVisibilityValue === 'visible' || currentVisibilityValue === 'default') {
169 170
			newVisibilityValue = 'toggle';
		} else {
171
			newVisibilityValue = 'default';
172 173
		}

S
Sandeep Somavarapu 已提交
174
		this.configurationEditingService.writeConfiguration(ConfigurationTarget.USER, { key: ToggleMenuBarAction.menuBarVisibilityKey, value: newVisibilityValue });
175 176

		return TPromise.as(null);
177 178 179
	}
}

E
Erich Gamma 已提交
180 181
export class ToggleDevToolsAction extends Action {

J
Joao Moreno 已提交
182 183
	static ID = 'workbench.action.toggleDevTools';
	static LABEL = nls.localize('toggleDevTools', "Toggle Developer Tools");
E
Erich Gamma 已提交
184

J
Joao Moreno 已提交
185
	constructor(id: string, label: string, @IWindowService private windowsService: IWindowService) {
E
Erich Gamma 已提交
186 187 188
		super(id, label);
	}

B
Benjamin Pasero 已提交
189
	public run(): TPromise<void> {
J
Joao Moreno 已提交
190
		return this.windowsService.toggleDevTools();
E
Erich Gamma 已提交
191 192 193
	}
}

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
export abstract class BaseZoomAction extends Action {
	private static SETTING_KEY = 'window.zoomLevel';

	constructor(
		id: string,
		label: string,
		@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService,
		@IConfigurationEditingService private configurationEditingService: IConfigurationEditingService
	) {
		super(id, label);
	}

	protected setConfiguredZoomLevel(level: number): void {
		let target = ConfigurationTarget.USER;
		if (typeof this.configurationService.lookup(BaseZoomAction.SETTING_KEY).workspace === 'number') {
			target = ConfigurationTarget.WORKSPACE;
		}

212 213
		level = Math.round(level); // when reaching smallest zoom, prevent fractional zoom levels

B
Benjamin Pasero 已提交
214
		const applyZoom = () => {
215
			webFrame.setZoomLevel(level);
B
Benjamin Pasero 已提交
216
			browser.setZoomFactor(webFrame.getZoomFactor());
217 218 219 220
			// See https://github.com/Microsoft/vscode/issues/26151
			// Cannot be trusted because the webFrame might take some time
			// until it really applies the new zoom level
			browser.setZoomLevel(webFrame.getZoomLevel(), /*isTrusted*/false);
221 222
		};

S
Sandeep Somavarapu 已提交
223
		this.configurationEditingService.writeConfiguration(target, { key: BaseZoomAction.SETTING_KEY, value: level }, { donotNotifyError: true }).done(() => applyZoom(), error => applyZoom());
224 225 226 227
	}
}

export class ZoomInAction extends BaseZoomAction {
E
Erich Gamma 已提交
228 229

	public static ID = 'workbench.action.zoomIn';
B
Benjamin Pasero 已提交
230
	public static LABEL = nls.localize('zoomIn', "Zoom In");
E
Erich Gamma 已提交
231

232 233 234 235 236 237
	constructor(
		id: string,
		label: string,
		@IWorkspaceConfigurationService configurationService: IWorkspaceConfigurationService,
		@IConfigurationEditingService configurationEditingService: IConfigurationEditingService
	) {
B
Benjamin Pasero 已提交
238
		super(id, label, configurationService, configurationEditingService);
E
Erich Gamma 已提交
239 240
	}

241
	public run(): TPromise<boolean> {
242
		this.setConfiguredZoomLevel(webFrame.getZoomLevel() + 1);
E
Erich Gamma 已提交
243

A
Alex Dima 已提交
244
		return TPromise.as(true);
E
Erich Gamma 已提交
245 246 247
	}
}

248
export class ZoomOutAction extends BaseZoomAction {
E
Erich Gamma 已提交
249 250

	public static ID = 'workbench.action.zoomOut';
B
Benjamin Pasero 已提交
251
	public static LABEL = nls.localize('zoomOut', "Zoom Out");
E
Erich Gamma 已提交
252

253 254
	constructor(
		id: string,
255 256 257
		label: string,
		@IWorkspaceConfigurationService configurationService: IWorkspaceConfigurationService,
		@IConfigurationEditingService configurationEditingService: IConfigurationEditingService
258
	) {
B
Benjamin Pasero 已提交
259
		super(id, label, configurationService, configurationEditingService);
E
Erich Gamma 已提交
260 261
	}

262
	public run(): TPromise<boolean> {
263
		this.setConfiguredZoomLevel(webFrame.getZoomLevel() - 1);
264

265
		return TPromise.as(true);
E
Erich Gamma 已提交
266 267 268
	}
}

269
export class ZoomResetAction extends BaseZoomAction {
E
Erich Gamma 已提交
270 271 272 273

	public static ID = 'workbench.action.zoomReset';
	public static LABEL = nls.localize('zoomReset', "Reset Zoom");

274 275 276
	constructor(
		id: string,
		label: string,
277 278
		@IWorkspaceConfigurationService configurationService: IWorkspaceConfigurationService,
		@IConfigurationEditingService configurationEditingService: IConfigurationEditingService
279
	) {
B
Benjamin Pasero 已提交
280
		super(id, label, configurationService, configurationEditingService);
E
Erich Gamma 已提交
281 282
	}

283
	public run(): TPromise<boolean> {
284
		this.setConfiguredZoomLevel(0);
285

286
		return TPromise.as(true);
E
Erich Gamma 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	}
}

/* Copied from loader.ts */
enum LoaderEventType {
	LoaderAvailable = 1,

	BeginLoadingScript = 10,
	EndLoadingScriptOK = 11,
	EndLoadingScriptError = 12,

	BeginInvokeFactory = 21,
	EndInvokeFactory = 22,

	NodeBeginEvaluatingScript = 31,
	NodeEndEvaluatingScript = 32,

	NodeBeginNativeRequire = 33,
	NodeEndNativeRequire = 34
}
307

E
Erich Gamma 已提交
308 309 310 311 312
interface ILoaderEvent {
	type: LoaderEventType;
	timestamp: number;
	detail: string;
}
313

E
Erich Gamma 已提交
314 315 316 317 318
export class ShowStartupPerformance extends Action {

	public static ID = 'workbench.action.appPerf';
	public static LABEL = nls.localize('appPerf', "Startup Performance");

319 320 321
	constructor(
		id: string,
		label: string,
J
Joao Moreno 已提交
322
		@IWindowService private windowService: IWindowService,
B
Benjamin Pasero 已提交
323
		@ITimerService private timerService: ITimerService,
324
		@IEnvironmentService private environmentService: IEnvironmentService
325
	) {
E
Erich Gamma 已提交
326
		super(id, label);
327 328 329 330 331 332 333 334 335
	}

	public run(): TPromise<boolean> {

		// Show dev tools
		this.windowService.openDevTools();

		// Print to console
		setTimeout(() => {
336
			(<any>console).group('Startup Performance Measurement');
B
Benjamin Pasero 已提交
337 338 339 340 341
			const metrics: IStartupMetrics = this.timerService.startupMetrics;
			console.log(`OS: ${metrics.platform} (${metrics.release})`);
			console.log(`CPUs: ${metrics.cpus.model} (${metrics.cpus.count} x ${metrics.cpus.speed})`);
			console.log(`Memory (System): ${(metrics.totalmem / (1024 * 1024 * 1024)).toFixed(2)}GB (${(metrics.freemem / (1024 * 1024 * 1024)).toFixed(2)}GB free)`);
			console.log(`Memory (Process): ${(metrics.meminfo.workingSetSize / 1024).toFixed(2)}MB working set (${(metrics.meminfo.peakWorkingSetSize / 1024).toFixed(2)}MB peak, ${(metrics.meminfo.privateBytes / 1024).toFixed(2)}MB private, ${(metrics.meminfo.sharedBytes / 1024).toFixed(2)}MB shared)`);
342
			console.log(`VM (likelyhood): ${metrics.isVMLikelyhood}%`);
B
Benjamin Pasero 已提交
343 344 345
			console.log(`Initial Startup: ${metrics.initialStartup}`);
			console.log(`Screen Reader Active: ${metrics.hasAccessibilitySupport}`);
			console.log(`Empty Workspace: ${metrics.emptyWorkbench}`);
346 347 348 349 350 351 352 353 354

			let nodeModuleLoadTime: number;
			let nodeModuleLoadDetails: any[];
			if (this.environmentService.performance) {
				const nodeModuleTimes = this.analyzeNodeModulesLoadTimes();
				nodeModuleLoadTime = nodeModuleTimes.duration;
				nodeModuleLoadDetails = nodeModuleTimes.table;
			}

B
Benjamin Pasero 已提交
355
			(<any>console).table(this.getStartupMetricsTable(nodeModuleLoadTime));
356

357 358 359 360 361 362 363
			if (this.environmentService.performance) {
				const data = this.analyzeLoaderStats();
				for (let type in data) {
					(<any>console).groupCollapsed(`Loader: ${type}`);
					(<any>console).table(data[type]);
					(<any>console).groupEnd();
				}
364
			}
365

366 367
			(<any>console).groupEnd();
		}, 1000);
368

369
		return TPromise.as(true);
E
Erich Gamma 已提交
370 371
	}

B
Benjamin Pasero 已提交
372
	private getStartupMetricsTable(nodeModuleLoadTime?: number): any[] {
373
		const table: any[] = [];
B
Benjamin Pasero 已提交
374
		const metrics: IStartupMetrics = this.timerService.startupMetrics;
375

B
Benjamin Pasero 已提交
376
		if (metrics.initialStartup) {
377 378
			table.push({ Topic: '[main] start => app.isReady', 'Took (ms)': metrics.timers.ellapsedAppReady });
			table.push({ Topic: '[main] app.isReady => window.loadUrl()', 'Took (ms)': metrics.timers.ellapsedWindowLoad });
E
Erich Gamma 已提交
379
		}
380

B
Benjamin Pasero 已提交
381 382
		table.push({ Topic: '[renderer] window.loadUrl() => begin to require(workbench.main.js)', 'Took (ms)': metrics.timers.ellapsedWindowLoadToRequire });
		table.push({ Topic: '[renderer] require(workbench.main.js)', 'Took (ms)': metrics.timers.ellapsedRequire });
383 384 385 386 387

		if (nodeModuleLoadTime) {
			table.push({ Topic: '[renderer] -> of which require() node_modules', 'Took (ms)': nodeModuleLoadTime });
		}

B
Benjamin Pasero 已提交
388 389 390 391
		table.push({ Topic: '[renderer] create extension host => extensions onReady()', 'Took (ms)': metrics.timers.ellapsedExtensions });
		table.push({ Topic: '[renderer] restore viewlet', 'Took (ms)': metrics.timers.ellapsedViewletRestore });
		table.push({ Topic: '[renderer] restore editor view state', 'Took (ms)': metrics.timers.ellapsedEditorRestore });
		table.push({ Topic: '[renderer] overall workbench load', 'Took (ms)': metrics.timers.ellapsedWorkbench });
392
		table.push({ Topic: '------------------------------------------------------' });
B
Benjamin Pasero 已提交
393 394
		table.push({ Topic: '[main, renderer] start => extensions ready', 'Took (ms)': metrics.timers.ellapsedExtensionsReady });
		table.push({ Topic: '[main, renderer] start => workbench ready', 'Took (ms)': metrics.ellapsed });
E
Erich Gamma 已提交
395

396
		return table;
E
Erich Gamma 已提交
397 398
	}

399
	private analyzeNodeModulesLoadTimes(): { table: any[], duration: number } {
400 401 402 403 404 405 406 407 408
		const stats = <ILoaderEvent[]>(<any>require).getStats();
		const result = [];

		let total = 0;

		for (let i = 0, len = stats.length; i < len; i++) {
			if (stats[i].type === LoaderEventType.NodeEndNativeRequire) {
				if (stats[i - 1].type === LoaderEventType.NodeBeginNativeRequire && stats[i - 1].detail === stats[i].detail) {
					const entry: any = {};
409
					const dur = (stats[i].timestamp - stats[i - 1].timestamp);
410
					entry['Event'] = 'nodeRequire ' + stats[i].detail;
411 412 413 414
					entry['Took (ms)'] = dur.toFixed(2);
					total += dur;
					entry['Start (ms)'] = '**' + stats[i - 1].timestamp.toFixed(2);
					entry['End (ms)'] = '**' + stats[i - 1].timestamp.toFixed(2);
415 416 417 418 419 420
					result.push(entry);
				}
			}
		}

		if (total > 0) {
421 422
			result.push({ Event: '------------------------------------------------------' });

423
			const entry: any = {};
424 425
			entry['Event'] = '[renderer] total require() node_modules';
			entry['Took (ms)'] = total.toFixed(2);
426 427 428 429 430
			entry['Start (ms)'] = '**';
			entry['End (ms)'] = '**';
			result.push(entry);
		}

431
		return { table: result, duration: Math.round(total) };
E
Erich Gamma 已提交
432
	}
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540

	private analyzeLoaderStats(): { [type: string]: any[] } {
		const stats = <ILoaderEvent[]>(<any>require).getStats().slice(0).sort((a, b) => {
			if (a.detail < b.detail) {
				return -1;
			} else if (a.detail > b.detail) {
				return 1;
			} else if (a.type < b.type) {
				return -1;
			} else if (a.type > b.type) {
				return 1;
			} else {
				return 0;
			}
		});

		class Tick {

			public readonly duration: number;
			public readonly detail: string;

			constructor(public readonly start: ILoaderEvent, public readonly end: ILoaderEvent) {
				console.assert(start.detail === end.detail);

				this.duration = this.end.timestamp - this.start.timestamp;
				this.detail = start.detail;
			}

			toTableObject() {
				return {
					['Path']: this.start.detail,
					['Took (ms)']: this.duration.toFixed(2),
					// ['Start (ms)']: this.start.timestamp,
					// ['End (ms)']: this.end.timestamp
				};
			}

			static compareUsingStartTimestamp(a: Tick, b: Tick): number {
				if (a.start.timestamp < b.start.timestamp) {
					return -1;
				} else if (a.start.timestamp > b.start.timestamp) {
					return 1;
				} else {
					return 0;
				}
			}
		}

		const ticks: { [type: number]: Tick[] } = {
			[LoaderEventType.BeginLoadingScript]: [],
			[LoaderEventType.BeginInvokeFactory]: [],
			[LoaderEventType.NodeBeginEvaluatingScript]: [],
			[LoaderEventType.NodeBeginNativeRequire]: [],
		};

		for (let i = 1; i < stats.length - 1; i++) {
			const stat = stats[i];
			const nextStat = stats[i + 1];

			if (nextStat.type - stat.type > 2) {
				//bad?!
				break;
			}

			i += 1;
			ticks[stat.type].push(new Tick(stat, nextStat));
		}

		ticks[LoaderEventType.BeginInvokeFactory].sort(Tick.compareUsingStartTimestamp);
		ticks[LoaderEventType.BeginInvokeFactory].sort(Tick.compareUsingStartTimestamp);
		ticks[LoaderEventType.NodeBeginEvaluatingScript].sort(Tick.compareUsingStartTimestamp);
		ticks[LoaderEventType.NodeBeginNativeRequire].sort(Tick.compareUsingStartTimestamp);

		const ret = {
			'Load Script': ticks[LoaderEventType.BeginLoadingScript].map(t => t.toTableObject()),
			'(Node) Load Script': ticks[LoaderEventType.NodeBeginNativeRequire].map(t => t.toTableObject()),
			'Eval Script': ticks[LoaderEventType.BeginInvokeFactory].map(t => t.toTableObject()),
			'(Node) Eval Script': ticks[LoaderEventType.NodeBeginEvaluatingScript].map(t => t.toTableObject()),
		};

		function total(ticks: Tick[]): number {
			let sum = 0;
			for (const tick of ticks) {
				sum += tick.duration;
			}
			return sum;
		}

		// totals
		ret['Load Script'].push({
			['Path']: 'TOTAL TIME',
			['Took (ms)']: total(ticks[LoaderEventType.BeginLoadingScript]).toFixed(2)
		});
		ret['Eval Script'].push({
			['Path']: 'TOTAL TIME',
			['Took (ms)']: total(ticks[LoaderEventType.BeginInvokeFactory]).toFixed(2)
		});
		ret['(Node) Load Script'].push({
			['Path']: 'TOTAL TIME',
			['Took (ms)']: total(ticks[LoaderEventType.NodeBeginNativeRequire]).toFixed(2)
		});
		ret['(Node) Eval Script'].push({
			['Path']: 'TOTAL TIME',
			['Took (ms)']: total(ticks[LoaderEventType.NodeBeginEvaluatingScript]).toFixed(2)
		});

		return ret;
	}
E
Erich Gamma 已提交
541 542 543 544
}

export class ReloadWindowAction extends Action {

545 546
	static ID = 'workbench.action.reloadWindow';
	static LABEL = nls.localize('reloadWindow', "Reload Window");
E
Erich Gamma 已提交
547

548 549 550
	constructor(
		id: string,
		label: string,
B
Benjamin Pasero 已提交
551
		@IWindowService private windowService: IWindowService
552
	) {
E
Erich Gamma 已提交
553 554 555
		super(id, label);
	}

556 557
	run(): TPromise<boolean> {
		return this.windowService.reloadWindow().then(() => true);
E
Erich Gamma 已提交
558 559 560
	}
}

B
Benjamin Pasero 已提交
561
export abstract class BaseSwitchWindow extends Action {
E
Erich Gamma 已提交
562

B
Benjamin Pasero 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
	constructor(
		id: string,
		label: string,
		private windowsService: IWindowsService,
		private windowService: IWindowService,
		private quickOpenService: IQuickOpenService,
		private keybindingService: IKeybindingService
	) {
		super(id, label);
	}

	protected abstract isQuickNavigate(): boolean;

	public run(): TPromise<void> {
		const currentWindowId = this.windowService.getCurrentWindowId();

579
		return this.windowsService.getWindows().then(windows => {
B
Benjamin Pasero 已提交
580
			const placeHolder = nls.localize('switchWindowPlaceHolder', "Select a window to switch to");
581 582 583
			const picks = windows.map(win => ({
				resource: win.filename ? URI.file(win.filename) : win.folderPath ? URI.file(win.folderPath) : win.workspace ? URI.file(win.workspace.configPath) : void 0,
				isFolder: !win.workspace && !win.filename && !!win.folderPath,
B
Benjamin Pasero 已提交
584 585 586 587 588 589 590 591 592 593 594 595
				label: win.title,
				description: (currentWindowId === win.id) ? nls.localize('current', "Current Window") : void 0,
				run: () => {
					setTimeout(() => {
						// Bug: somehow when not running this code in a timeout, it is not possible to use this picker
						// with quick navigate keys (not able to trigger quick navigate once running it once).
						this.windowsService.showWindow(win.id).done(null, errors.onUnexpectedError);
					});
				}
			} as IFilePickOpenEntry));

			this.quickOpenService.pick(picks, {
596
				contextKey: 'inWindowsPicker',
B
Benjamin Pasero 已提交
597 598 599 600 601 602 603 604 605 606 607 608
				autoFocus: { autoFocusFirstEntry: true },
				placeHolder,
				quickNavigateConfiguration: this.isQuickNavigate() ? { keybindings: this.keybindingService.lookupKeybindings(this.id) } : void 0
			});
		});
	}
}

export class SwitchWindow extends BaseSwitchWindow {

	static ID = 'workbench.action.switchWindow';
	static LABEL = nls.localize('switchWindow', "Switch Window...");
E
Erich Gamma 已提交
609 610 611 612

	constructor(
		id: string,
		label: string,
B
Benjamin Pasero 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
		@IWindowsService windowsService: IWindowsService,
		@IWindowService windowService: IWindowService,
		@IQuickOpenService quickOpenService: IQuickOpenService,
		@IKeybindingService keybindingService: IKeybindingService
	) {
		super(id, label, windowsService, windowService, quickOpenService, keybindingService);
	}

	protected isQuickNavigate(): boolean {
		return false;
	}
}

export class QuickSwitchWindow extends BaseSwitchWindow {

	static ID = 'workbench.action.quickSwitchWindow';
	static LABEL = nls.localize('quickSwitchWindow', "Quick Switch Window...");

	constructor(
		id: string,
		label: string,
		@IWindowsService windowsService: IWindowsService,
		@IWindowService windowService: IWindowService,
		@IQuickOpenService quickOpenService: IQuickOpenService,
		@IKeybindingService keybindingService: IKeybindingService
	) {
		super(id, label, windowsService, windowService, quickOpenService, keybindingService);
	}

	protected isQuickNavigate(): boolean {
		return true;
	}
}

647 648
export const inRecentFilesPickerContextKey = 'inRecentFilesPicker';

B
Benjamin Pasero 已提交
649 650 651 652 653 654 655 656 657 658 659
export abstract class BaseOpenRecentAction extends Action {

	constructor(
		id: string,
		label: string,
		private windowsService: IWindowsService,
		private windowService: IWindowService,
		private quickOpenService: IQuickOpenService,
		private contextService: IWorkspaceContextService,
		private environmentService: IEnvironmentService,
		private keybindingService: IKeybindingService
E
Erich Gamma 已提交
660 661 662 663
	) {
		super(id, label);
	}

B
Benjamin Pasero 已提交
664 665
	protected abstract isQuickNavigate(): boolean;

J
Joao Moreno 已提交
666
	public run(): TPromise<void> {
B
Benjamin Pasero 已提交
667
		return this.windowService.getRecentlyOpened()
668
			.then(({ workspaces, files, folders }) => this.openRecent(workspaces, files, folders));
B
Benjamin Pasero 已提交
669 670
	}

671 672 673 674 675 676
	private openRecent(recentWorkspaces: IWorkspaceIdentifier[], recentFiles: string[], recentFolders: string[]): void {

		function toPick(arg1: IWorkspaceIdentifier | string, separator: ISeparator, isFolder: boolean, environmentService: IEnvironmentService): IFilePickOpenEntry {
			const path = (typeof arg1 === 'string') ? arg1 : arg1.configPath;
			const label = (typeof arg1 === 'string') ? paths.basename(path) : getWorkspaceLabel(environmentService, arg1);
			const description = (typeof arg1 === 'string') ? getPathLabel(paths.dirname(path), null, environmentService) : void 0;
B
Benjamin Pasero 已提交
677

B
Benjamin Pasero 已提交
678
			return {
B
Benjamin Pasero 已提交
679 680
				resource: URI.file(path),
				isFolder,
681 682
				label,
				description,
B
Benjamin Pasero 已提交
683
				separator,
B
Benjamin Pasero 已提交
684 685 686 687 688 689 690
				run: context => {
					setTimeout(() => {
						// Bug: somehow when not running this code in a timeout, it is not possible to use this picker
						// with quick navigate keys (not able to trigger quick navigate once running it once).
						runPick(path, context);
					});
				}
B
Benjamin Pasero 已提交
691 692 693
			};
		}

694
		const runPick = (arg1: IWorkspaceIdentifier | string, context: IEntryRunContext) => {
695
			const forceNewWindow = context.keymods.indexOf(KeyMod.CtrlCmd) >= 0;
696
			this.windowsService.openWindow([typeof arg1 === 'string' ? arg1 : arg1.configPath], { forceNewWindow });
697
		};
B
Benjamin Pasero 已提交
698

699
		const workspacePicks: IFilePickOpenEntry[] = recentWorkspaces.map((p, index) => toPick(p, index === 0 ? { label: nls.localize('workspaces', "workspaces") } : void 0, false, this.environmentService));
700 701
		const folderPicks: IFilePickOpenEntry[] = recentFolders.map((p, index) => toPick(p, index === 0 ? { label: nls.localize('folders', "folders") } : void 0, true, this.environmentService));
		const filePicks: IFilePickOpenEntry[] = recentFiles.map((p, index) => toPick(p, index === 0 ? { label: nls.localize('files', "files"), border: true } : void 0, false, this.environmentService));
B
Benjamin Pasero 已提交
702

B
Benjamin Pasero 已提交
703
		const hasWorkspace = this.contextService.hasWorkspace();
B
Benjamin Pasero 已提交
704

705 706 707 708 709 710 711 712 713 714
		let autoFocusFirstEntry = !hasWorkspace;
		let autoFocusSecondEntry = !autoFocusFirstEntry;
		if (workspacePicks.length > 0 && folderPicks.length > 0) {
			// if we show both workspace picks and folder picks, we can no longer make any smart
			// auto focus choice because the list is no longer in pure MRU order. In this case
			// we simply do not focus any entry.
			autoFocusFirstEntry = false;
			autoFocusSecondEntry = false;
		}

715
		this.quickOpenService.pick([...workspacePicks, ...folderPicks, ...filePicks], {
716
			contextKey: inRecentFilesPickerContextKey,
717
			autoFocus: { autoFocusFirstEntry, autoFocusSecondEntry },
B
Benjamin Pasero 已提交
718
			placeHolder: isMacintosh ? nls.localize('openRecentPlaceHolderMac', "Select to open (hold Cmd-key to open in new window)") : nls.localize('openRecentPlaceHolder', "Select to open (hold Ctrl-key to open in new window)"),
B
Benjamin Pasero 已提交
719 720
			matchOnDescription: true,
			quickNavigateConfiguration: this.isQuickNavigate() ? { keybindings: this.keybindingService.lookupKeybindings(this.id) } : void 0
B
Benjamin Pasero 已提交
721
		}).done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
722 723 724
	}
}

B
Benjamin Pasero 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
export class OpenRecentAction extends BaseOpenRecentAction {

	public static ID = 'workbench.action.openRecent';
	public static LABEL = nls.localize('openRecent', "Open Recent...");

	constructor(
		id: string,
		label: string,
		@IWindowsService windowsService: IWindowsService,
		@IWindowService windowService: IWindowService,
		@IQuickOpenService quickOpenService: IQuickOpenService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IEnvironmentService environmentService: IEnvironmentService,
		@IKeybindingService keybindingService: IKeybindingService
	) {
		super(id, label, windowsService, windowService, quickOpenService, contextService, environmentService, keybindingService);
	}

	protected isQuickNavigate(): boolean {
		return false;
	}
}

export class QuickOpenRecentAction extends BaseOpenRecentAction {

	public static ID = 'workbench.action.quickOpenRecent';
	public static LABEL = nls.localize('quickOpenRecent', "Quick Open Recent...");

	constructor(
		id: string,
		label: string,
		@IWindowsService windowsService: IWindowsService,
		@IWindowService windowService: IWindowService,
		@IQuickOpenService quickOpenService: IQuickOpenService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IEnvironmentService environmentService: IEnvironmentService,
		@IKeybindingService keybindingService: IKeybindingService
	) {
		super(id, label, windowsService, windowService, quickOpenService, contextService, environmentService, keybindingService);
	}

	protected isQuickNavigate(): boolean {
		return true;
	}
}

E
Erich Gamma 已提交
771 772 773 774 775 776 777 778 779 780 781 782 783 784
export class CloseMessagesAction extends Action {

	public static ID = 'workbench.action.closeMessages';
	public static LABEL = nls.localize('closeMessages', "Close Notification Messages");

	constructor(
		id: string,
		label: string,
		@IMessageService private messageService: IMessageService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
	) {
		super(id, label);
	}

785
	public run(): TPromise<boolean> {
E
Erich Gamma 已提交
786 787 788 789 790 791 792 793 794 795

		// Close any Message if visible
		this.messageService.hideAll();

		// Restore focus if we got an editor
		const editor = this.editorService.getActiveEditor();
		if (editor) {
			editor.focus();
		}

796
		return TPromise.as(true);
E
Erich Gamma 已提交
797
	}
798 799
}

B
Benjamin Pasero 已提交
800 801 802 803 804 805 806 807 808
export class ReportIssueAction extends Action {

	public static ID = 'workbench.action.reportIssues';
	public static LABEL = nls.localize('reportIssues', "Report Issues");

	constructor(
		id: string,
		label: string,
		@IIntegrityService private integrityService: IIntegrityService,
B
Benjamin Pasero 已提交
809
		@IExtensionManagementService private extensionManagementService: IExtensionManagementService
B
Benjamin Pasero 已提交
810 811 812 813
	) {
		super(id, label);
	}

814 815 816 817 818 819 820 821 822 823 824
	private _optimisticIsPure(): TPromise<boolean> {
		let isPure = true;
		let integrityPromise = this.integrityService.isPure().then(res => {
			isPure = res.isPure;
		});

		return TPromise.any([TPromise.timeout(100), integrityPromise]).then(() => {
			return isPure;
		});
	}

B
Benjamin Pasero 已提交
825
	public run(): TPromise<boolean> {
826
		return this._optimisticIsPure().then(isPure => {
B
Benjamin Pasero 已提交
827
			return this.extensionManagementService.getInstalled(LocalExtensionType.User).then(extensions => {
828
				const issueUrl = this.generateNewIssueUrl(product.reportIssueUrl, pkg.name, pkg.version, product.commit, product.date, isPure, extensions);
B
Benjamin Pasero 已提交
829

B
Benjamin Pasero 已提交
830
				window.open(issueUrl);
B
Benjamin Pasero 已提交
831

B
Benjamin Pasero 已提交
832 833
				return TPromise.as(true);
			});
B
Benjamin Pasero 已提交
834 835 836
		});
	}

J
Johannes Rieken 已提交
837
	private generateNewIssueUrl(baseUrl: string, name: string, version: string, commit: string, date: string, isPure: boolean, extensions: ILocalExtension[]): string {
C
Christof Marti 已提交
838
		// Avoid backticks, these can trigger XSS detectors. (https://github.com/Microsoft/vscode/issues/13098)
B
Benjamin Pasero 已提交
839 840 841 842 843
		const osVersion = `${os.type()} ${os.arch()} ${os.release()}`;
		const queryStringPrefix = baseUrl.indexOf('?') === -1 ? '?' : '&';
		const body = encodeURIComponent(
			`- VSCode Version: ${name} ${version}${isPure ? '' : ' **[Unsupported]**'} (${product.commit || 'Commit unknown'}, ${product.date || 'Date unknown'})
- OS Version: ${osVersion}
B
Benjamin Pasero 已提交
844
- Extensions: ${this.generateExtensionTable(extensions)}
845
---
B
Benjamin Pasero 已提交
846 847 848 849

Steps to Reproduce:

1.
850 851 852 853
2.` + (extensions.length ? `

<!-- Launch with \`code --disable-extensions\` to check. -->
Reproduces without extensions: Yes/No` : '')
B
Benjamin Pasero 已提交
854 855 856 857
		);

		return `${baseUrl}${queryStringPrefix}body=${body}`;
	}
858 859

	private generateExtensionTable(extensions: ILocalExtension[]): string {
860 861 862 863 864 865
		const { nonThemes, themes } = collections.groupBy(extensions, ext => {
			const manifestKeys = ext.manifest.contributes ? Object.keys(ext.manifest.contributes) : [];
			const onlyTheme = !ext.manifest.activationEvents && manifestKeys.length === 1 && manifestKeys[0] === 'themes';
			return onlyTheme ? 'themes' : 'nonThemes';
		});

866 867
		const themeExclusionStr = (themes && themes.length) ? `\n(${themes.length} theme extensions excluded)` : '';
		extensions = nonThemes || [];
868

B
Benjamin Pasero 已提交
869
		if (!extensions.length) {
870
			return 'none' + themeExclusionStr;
B
Benjamin Pasero 已提交
871 872
		}

873
		let tableHeader = `Extension|Author (truncated)|Version
874
---|---|---`;
875
		const table = extensions.map(e => {
876
			return `${e.manifest.name}|${e.manifest.publisher.substr(0, 3)}|${e.manifest.version}`;
877 878
		}).join('\n');

879
		const extensionTable = `
B
Benjamin Pasero 已提交
880

881 882
${tableHeader}
${table}
883
${themeExclusionStr}
B
Benjamin Pasero 已提交
884 885

`;
886

887 888 889
		// 2000 chars is browsers de-facto limit for URLs, 400 chars are allowed for other string parts of the issue URL
		// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
		if (encodeURIComponent(extensionTable).length > 1600) {
890
			return 'the listing length exceeds browsers\' URL characters limit';
891 892 893
		}

		return extensionTable;
894
	}
B
Benjamin Pasero 已提交
895 896
}

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
export class ReportPerformanceIssueAction extends Action {

	public static ID = 'workbench.action.reportPerformanceIssue';
	public static LABEL = nls.localize('reportPerformanceIssue', "Report Performance Issue");

	constructor(
		id: string,
		label: string,
		@IIntegrityService private integrityService: IIntegrityService,
		@IEnvironmentService private environmentService: IEnvironmentService,
		@ITimerService private timerService: ITimerService
	) {
		super(id, label);
	}

912
	public run(appendix?: string): TPromise<boolean> {
913
		return this.integrityService.isPure().then(res => {
914
			const issueUrl = this.generatePerformanceIssueUrl(product.reportIssueUrl, pkg.name, pkg.version, product.commit, product.date, res.isPure, appendix);
915 916 917 918 919 920 921

			window.open(issueUrl);

			return TPromise.as(true);
		});
	}

922 923 924 925 926 927 928 929 930
	private generatePerformanceIssueUrl(baseUrl: string, name: string, version: string, commit: string, date: string, isPure: boolean, appendix?: string): string {

		if (!appendix) {
			appendix = `Additional Steps to Reproduce (if any):

1.
2.`;
		}

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
		let nodeModuleLoadTime: number;
		if (this.environmentService.performance) {
			nodeModuleLoadTime = this.computeNodeModulesLoadTime();
		}

		const metrics: IStartupMetrics = this.timerService.startupMetrics;

		const osVersion = `${os.type()} ${os.arch()} ${os.release()}`;
		const queryStringPrefix = baseUrl.indexOf('?') === -1 ? '?' : '&';
		const body = encodeURIComponent(
			`- VSCode Version: <code>${name} ${version}${isPure ? '' : ' **[Unsupported]**'} (${product.commit || 'Commit unknown'}, ${product.date || 'Date unknown'})</code>
- OS Version: <code>${osVersion}</code>
- CPUs: <code>${metrics.cpus.model} (${metrics.cpus.count} x ${metrics.cpus.speed})</code>
- Memory (System): <code>${(metrics.totalmem / (1024 * 1024 * 1024)).toFixed(2)}GB (${(metrics.freemem / (1024 * 1024 * 1024)).toFixed(2)}GB free)</code>
- Memory (Process): <code>${(metrics.meminfo.workingSetSize / 1024).toFixed(2)}MB working set (${(metrics.meminfo.peakWorkingSetSize / 1024).toFixed(2)}MB peak, ${(metrics.meminfo.privateBytes / 1024).toFixed(2)}MB private, ${(metrics.meminfo.sharedBytes / 1024).toFixed(2)}MB shared)</code>
- Load (avg): <code>${metrics.loadavg.map(l => Math.round(l)).join(', ')}</code>
947
- VM: <code>${metrics.isVMLikelyhood}%</code>
948
- Initial Startup: <code>${metrics.initialStartup ? 'yes' : 'no'}</code>
949
- Screen Reader: <code>${metrics.hasAccessibilitySupport ? 'yes' : 'no'}</code>
950 951 952 953 954 955 956
- Empty Workspace: <code>${metrics.emptyWorkbench ? 'yes' : 'no'}</code>
- Timings:

${this.generatePerformanceTable(nodeModuleLoadTime)}

---

957
${appendix}`
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
		);

		return `${baseUrl}${queryStringPrefix}body=${body}`;
	}

	private computeNodeModulesLoadTime(): number {
		const stats = <ILoaderEvent[]>(<any>require).getStats();
		let total = 0;

		for (let i = 0, len = stats.length; i < len; i++) {
			if (stats[i].type === LoaderEventType.NodeEndNativeRequire) {
				if (stats[i - 1].type === LoaderEventType.NodeBeginNativeRequire && stats[i - 1].detail === stats[i].detail) {
					const dur = (stats[i].timestamp - stats[i - 1].timestamp);
					total += dur;
				}
			}
		}

		return Math.round(total);
	}

	private generatePerformanceTable(nodeModuleLoadTime?: number): string {
		let tableHeader = `|Component|Task|Time (ms)|
|---|---|---|`;

		const table = this.getStartupMetricsTable(nodeModuleLoadTime).map(e => {
984
			return `|${e.component}|${e.task}|${e.time}|`;
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
		}).join('\n');

		return `${tableHeader}\n${table}`;
	}

	private getStartupMetricsTable(nodeModuleLoadTime?: number): { component: string, task: string; time: number; }[] {
		const table: any[] = [];
		const metrics: IStartupMetrics = this.timerService.startupMetrics;

		if (metrics.initialStartup) {
			table.push({ component: 'main', task: 'start => app.isReady', time: metrics.timers.ellapsedAppReady });
			table.push({ component: 'main', task: 'app.isReady => window.loadUrl()', time: metrics.timers.ellapsedWindowLoad });
		}

		table.push({ component: 'renderer', task: 'window.loadUrl() => begin to require(workbench.main.js)', time: metrics.timers.ellapsedWindowLoadToRequire });
		table.push({ component: 'renderer', task: 'require(workbench.main.js)', time: metrics.timers.ellapsedRequire });

		if (nodeModuleLoadTime) {
			table.push({ component: 'renderer', task: '-> of which require() node_modules', time: nodeModuleLoadTime });
		}

		table.push({ component: 'renderer', task: 'create extension host => extensions onReady()', time: metrics.timers.ellapsedExtensions });
		table.push({ component: 'renderer', task: 'restore viewlet', time: metrics.timers.ellapsedViewletRestore });
		table.push({ component: 'renderer', task: 'restore editor view state', time: metrics.timers.ellapsedEditorRestore });
		table.push({ component: 'renderer', task: 'overall workbench load', time: metrics.timers.ellapsedWorkbench });
		table.push({ component: 'main + renderer', task: 'start => extensions ready', time: metrics.timers.ellapsedExtensionsReady });
		table.push({ component: 'main + renderer', task: 'start => workbench ready', time: metrics.ellapsed });

		return table;
	}
}

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
export class KeybindingsReferenceAction extends Action {

	public static ID = 'workbench.action.keybindingsReference';
	public static LABEL = nls.localize('keybindingsReference', "Keyboard Shortcuts Reference");

	private static URL = isLinux ? product.keyboardShortcutsUrlLinux : isMacintosh ? product.keyboardShortcutsUrlMac : product.keyboardShortcutsUrlWin;
	public static AVAILABLE = !!KeybindingsReferenceAction.URL;

	constructor(
		id: string,
		label: string
	) {
		super(id, label);
	}

	public run(): TPromise<void> {
		window.open(KeybindingsReferenceAction.URL);
		return null;
	}
}

C
Christof Marti 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
export class OpenDocumentationUrlAction extends Action {

	public static ID = 'workbench.action.openDocumentationUrl';
	public static LABEL = nls.localize('openDocumentationUrl', "Documentation");

	private static URL = product.documentationUrl;
	public static AVAILABLE = !!OpenDocumentationUrlAction.URL;

	constructor(
		id: string,
		label: string
	) {
		super(id, label);
	}

	public run(): TPromise<void> {
		window.open(OpenDocumentationUrlAction.URL);
		return null;
	}
}

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
export class OpenIntroductoryVideosUrlAction extends Action {

	public static ID = 'workbench.action.openIntroductoryVideosUrl';
	public static LABEL = nls.localize('openIntroductoryVideosUrl', "Introductory Videos");

	private static URL = product.introductoryVideosUrl;
	public static AVAILABLE = !!OpenIntroductoryVideosUrlAction.URL;

	constructor(
		id: string,
		label: string
	) {
		super(id, label);
	}

	public run(): TPromise<void> {
		window.open(OpenIntroductoryVideosUrlAction.URL);
		return null;
	}
1078
}
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
export class OpenTipsAndTricksUrlAction extends Action {

	public static ID = 'workbench.action.openTipsAndTricksUrl';
	public static LABEL = nls.localize('openTipsAndTricksUrl', "Tips and Tricks");

	private static URL = product.tipsAndTricksUrl;
	public static AVAILABLE = !!OpenTipsAndTricksUrlAction.URL;

	constructor(
		id: string,
		label: string
	) {
		super(id, label);
	}

	public run(): TPromise<void> {
		window.open(OpenTipsAndTricksUrlAction.URL);
		return null;
	}
}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
export class ToggleSharedProcessAction extends Action {

	static ID = 'workbench.action.toggleSharedProcess';
	static LABEL = nls.localize('toggleSharedProcess', "Toggle Shared Process");

	constructor(id: string, label: string, @IWindowsService private windowsService: IWindowsService) {
		super(id, label);
	}

	run(): TPromise<void> {
		return this.windowsService.toggleSharedProcess();
	}
1113 1114
}

S
sj.hwang 已提交
1115 1116 1117 1118
enum Direction {
	Next,
	Previous,
}
1119

S
sj.hwang 已提交
1120
export abstract class BaseNavigationAction extends Action {
1121

1122
	constructor(
S
sj.hwang 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
		id: string,
		label: string,
		@IEditorGroupService protected groupService: IEditorGroupService,
		@IPanelService protected panelService: IPanelService,
		@IPartService protected partService: IPartService,
		@IViewletService protected viewletService: IViewletService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
		const isEditorFocus = this.partService.hasFocus(Parts.EDITOR_PART);
		const isPanelFocus = this.partService.hasFocus(Parts.PANEL_PART);
		const isSidebarFocus = this.partService.hasFocus(Parts.SIDEBAR_PART);

		const isEditorGroupVertical = this.groupService.getGroupOrientation() === 'vertical';
		const isSidebarPositionLeft = this.partService.getSideBarPosition() === SidebarPosition.LEFT;

		if (isEditorFocus) {
			return this.navigateOnEditorFocus(isEditorGroupVertical, isSidebarPositionLeft);
1143 1144
		}

S
sj.hwang 已提交
1145 1146
		if (isPanelFocus) {
			return this.navigateOnPanelFocus(isEditorGroupVertical, isSidebarPositionLeft);
1147 1148
		}

S
sj.hwang 已提交
1149 1150
		if (isSidebarFocus) {
			return this.navigateOnSidebarFocus(isEditorGroupVertical, isSidebarPositionLeft);
1151 1152
		}

S
sj.hwang 已提交
1153
		return TPromise.as(false);
1154 1155
	}

B
Benjamin Pasero 已提交
1156
	protected navigateOnEditorFocus(isEditorGroupVertical: boolean, isSidebarPositionLeft: boolean): TPromise<boolean | IViewlet | IPanel> {
S
sj.hwang 已提交
1157
		return TPromise.as(true);
1158 1159
	}

B
Benjamin Pasero 已提交
1160
	protected navigateOnPanelFocus(isEditorGroupVertical: boolean, isSidebarPositionLeft: boolean): TPromise<boolean | IPanel> {
S
sj.hwang 已提交
1161
		return TPromise.as(true);
1162 1163
	}

B
Benjamin Pasero 已提交
1164
	protected navigateOnSidebarFocus(isEditorGroupVertical: boolean, isSidebarPositionLeft: boolean): TPromise<boolean | IViewlet> {
S
sj.hwang 已提交
1165
		return TPromise.as(true);
1166 1167
	}

B
Benjamin Pasero 已提交
1168
	protected navigateToPanel(): TPromise<IPanel | boolean> {
S
sj.hwang 已提交
1169 1170
		if (!this.partService.isVisible(Parts.PANEL_PART)) {
			return TPromise.as(false);
1171 1172
		}

S
sj.hwang 已提交
1173
		const activePanelId = this.panelService.getActivePanel().getId();
B
Benjamin Pasero 已提交
1174

S
sj.hwang 已提交
1175
		return this.panelService.openPanel(activePanelId, true);
1176 1177
	}

B
Benjamin Pasero 已提交
1178
	protected navigateToSidebar(): TPromise<IViewlet | boolean> {
S
sj.hwang 已提交
1179 1180
		if (!this.partService.isVisible(Parts.SIDEBAR_PART)) {
			return TPromise.as(false);
1181 1182
		}

S
sj.hwang 已提交
1183
		const activeViewletId = this.viewletService.getActiveViewlet().getId();
B
Benjamin Pasero 已提交
1184

S
sj.hwang 已提交
1185
		return this.viewletService.openViewlet(activeViewletId, true);
1186 1187
	}

B
Benjamin Pasero 已提交
1188
	protected navigateAcrossEditorGroup(direction): TPromise<boolean> {
1189 1190
		const model = this.groupService.getStacksModel();
		const currentPosition = model.positionOfGroup(model.activeGroup);
S
sj.hwang 已提交
1191
		const nextPosition = direction === Direction.Next ? currentPosition + 1 : currentPosition - 1;
1192 1193 1194 1195 1196 1197

		if (nextPosition < 0 || nextPosition > model.groups.length - 1) {
			return TPromise.as(false);
		}

		this.groupService.focusGroup(nextPosition);
B
Benjamin Pasero 已提交
1198

1199 1200 1201
		return TPromise.as(true);
	}

B
Benjamin Pasero 已提交
1202
	protected navigateToLastActiveGroup(): TPromise<boolean> {
S
sj.hwang 已提交
1203
		const model = this.groupService.getStacksModel();
1204 1205
		const lastActiveGroup = model.activeGroup;
		this.groupService.focusGroup(lastActiveGroup);
B
Benjamin Pasero 已提交
1206

1207
		return TPromise.as(true);
1208 1209
	}

B
Benjamin Pasero 已提交
1210
	protected navigateToFirstEditorGroup(): TPromise<boolean> {
1211
		this.groupService.focusGroup(0);
B
Benjamin Pasero 已提交
1212

1213
		return TPromise.as(true);
1214 1215
	}

B
Benjamin Pasero 已提交
1216
	protected navigateToLastEditorGroup(): TPromise<boolean> {
S
sj.hwang 已提交
1217
		const model = this.groupService.getStacksModel();
1218 1219
		const lastEditorGroupPosition = model.groups.length - 1;
		this.groupService.focusGroup(lastEditorGroupPosition);
B
Benjamin Pasero 已提交
1220

1221
		return TPromise.as(true);
1222 1223
	}
}
S
sj.hwang 已提交
1224 1225 1226 1227

export class NavigateLeftAction extends BaseNavigationAction {

	public static ID = 'workbench.action.navigateLeft';
B
Benjamin Pasero 已提交
1228
	public static LABEL = nls.localize('navigateLeft', "Navigate to the View on the Left");
S
sj.hwang 已提交
1229 1230 1231 1232 1233 1234 1235 1236 1237

	constructor(
		id: string,
		label: string,
		@IEditorGroupService groupService: IEditorGroupService,
		@IPanelService panelService: IPanelService,
		@IPartService partService: IPartService,
		@IViewletService viewletService: IViewletService
	) {
1238
		super(id, label, groupService, panelService, partService, viewletService);
S
sj.hwang 已提交
1239 1240
	}

B
Benjamin Pasero 已提交
1241
	protected navigateOnEditorFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean | IViewlet> {
1242
		if (!isEditorGroupVertical) {
S
sj.hwang 已提交
1243 1244 1245 1246
			if (isSidebarPositionLeft) {
				return this.navigateToSidebar();
			}
			return TPromise.as(false);
S
sj.hwang 已提交
1247
		}
S
sj.hwang 已提交
1248
		return this.navigateAcrossEditorGroup(Direction.Previous)
1249 1250 1251 1252 1253 1254
			.then(didNavigate => {
				if (!didNavigate && isSidebarPositionLeft) {
					return this.navigateToSidebar();
				}
				return TPromise.as(true);
			});
S
sj.hwang 已提交
1255 1256
	}

B
Benjamin Pasero 已提交
1257
	protected navigateOnPanelFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean | IViewlet> {
S
sj.hwang 已提交
1258 1259 1260
		if (isSidebarPositionLeft) {
			return this.navigateToSidebar();
		}
B
Benjamin Pasero 已提交
1261

S
sj.hwang 已提交
1262 1263 1264 1265 1266 1267 1268
		return TPromise.as(false);
	}

	protected navigateOnSidebarFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean> {
		if (isSidebarPositionLeft) {
			return TPromise.as(false);
		}
B
Benjamin Pasero 已提交
1269

S
sj.hwang 已提交
1270
		if (isEditorGroupVertical) {
1271
			return this.navigateToLastEditorGroup();
S
sj.hwang 已提交
1272
		}
B
Benjamin Pasero 已提交
1273

1274
		return this.navigateToLastActiveGroup();
S
sj.hwang 已提交
1275 1276
	}
}
1277 1278 1279 1280

export class NavigateRightAction extends BaseNavigationAction {

	public static ID = 'workbench.action.navigateRight';
B
Benjamin Pasero 已提交
1281
	public static LABEL = nls.localize('navigateRight', "Navigate to the View on the Right");
1282 1283 1284 1285 1286 1287 1288 1289 1290

	constructor(
		id: string,
		label: string,
		@IEditorGroupService groupService: IEditorGroupService,
		@IPanelService panelService: IPanelService,
		@IPartService partService: IPartService,
		@IViewletService viewletService: IViewletService
	) {
1291
		super(id, label, groupService, panelService, partService, viewletService);
1292 1293
	}

B
Benjamin Pasero 已提交
1294
	protected navigateOnEditorFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean | IViewlet> {
1295
		if (!isEditorGroupVertical) {
S
sj.hwang 已提交
1296 1297 1298 1299
			if (!isSidebarPositionLeft) {
				return this.navigateToSidebar();
			}
			return TPromise.as(false);
1300
		}
B
Benjamin Pasero 已提交
1301

S
sj.hwang 已提交
1302
		return this.navigateAcrossEditorGroup(Direction.Next)
1303 1304 1305 1306 1307 1308
			.then(didNavigate => {
				if (!didNavigate && !isSidebarPositionLeft) {
					return this.navigateToSidebar();
				}
				return TPromise.as(true);
			});
1309 1310
	}

B
Benjamin Pasero 已提交
1311
	protected navigateOnPanelFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean | IViewlet> {
1312 1313 1314
		if (!isSidebarPositionLeft) {
			return this.navigateToSidebar();
		}
B
Benjamin Pasero 已提交
1315

1316 1317 1318 1319 1320 1321 1322
		return TPromise.as(false);
	}

	protected navigateOnSidebarFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean> {
		if (!isSidebarPositionLeft) {
			return TPromise.as(false);
		}
B
Benjamin Pasero 已提交
1323

1324
		if (isEditorGroupVertical) {
1325
			return this.navigateToFirstEditorGroup();
1326
		}
B
Benjamin Pasero 已提交
1327

1328
		return this.navigateToLastActiveGroup();
1329 1330
	}
}
S
sj.hwang 已提交
1331 1332 1333 1334

export class NavigateUpAction extends BaseNavigationAction {

	public static ID = 'workbench.action.navigateUp';
B
Benjamin Pasero 已提交
1335
	public static LABEL = nls.localize('navigateUp', "Navigate to the View Above");
S
sj.hwang 已提交
1336 1337 1338 1339 1340 1341 1342 1343 1344

	constructor(
		id: string,
		label: string,
		@IEditorGroupService groupService: IEditorGroupService,
		@IPanelService panelService: IPanelService,
		@IPartService partService: IPartService,
		@IViewletService viewletService: IViewletService
	) {
1345
		super(id, label, groupService, panelService, partService, viewletService);
S
sj.hwang 已提交
1346 1347 1348 1349 1350 1351
	}

	protected navigateOnEditorFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean> {
		if (isEditorGroupVertical) {
			return TPromise.as(false);
		}
S
sj.hwang 已提交
1352
		return this.navigateAcrossEditorGroup(Direction.Previous);
S
sj.hwang 已提交
1353 1354 1355 1356
	}

	protected navigateOnPanelFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean> {
		if (isEditorGroupVertical) {
1357
			return this.navigateToLastActiveGroup();
S
sj.hwang 已提交
1358
		}
1359
		return this.navigateToLastEditorGroup();
S
sj.hwang 已提交
1360 1361
	}
}
S
sj.hwang 已提交
1362 1363 1364 1365

export class NavigateDownAction extends BaseNavigationAction {

	public static ID = 'workbench.action.navigateDown';
B
Benjamin Pasero 已提交
1366
	public static LABEL = nls.localize('navigateDown', "Navigate to the View Below");
S
sj.hwang 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375

	constructor(
		id: string,
		label: string,
		@IEditorGroupService groupService: IEditorGroupService,
		@IPanelService panelService: IPanelService,
		@IPartService partService: IPartService,
		@IViewletService viewletService: IViewletService
	) {
1376
		super(id, label, groupService, panelService, partService, viewletService);
S
sj.hwang 已提交
1377 1378
	}

B
Benjamin Pasero 已提交
1379
	protected navigateOnEditorFocus(isEditorGroupVertical, isSidebarPositionLeft): TPromise<boolean | IPanel> {
S
sj.hwang 已提交
1380 1381 1382
		if (isEditorGroupVertical) {
			return this.navigateToPanel();
		}
B
Benjamin Pasero 已提交
1383

S
sj.hwang 已提交
1384
		return this.navigateAcrossEditorGroup(Direction.Next)
1385 1386 1387 1388 1389 1390
			.then(didNavigate => {
				if (didNavigate) {
					return TPromise.as(true);
				}
				return this.navigateToPanel();
			});
S
sj.hwang 已提交
1391 1392
	}
}
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412

// Resize focused view actions
export abstract class BaseResizeViewAction extends Action {

	// This is a media-size percentage
	protected static RESIZE_INCREMENT = 6.5;

	constructor(
		id: string,
		label: string,
		@IPartService protected partService: IPartService
	) {
		super(id, label);
	}

	protected resizePart(sizeChange: number): void {
		const isEditorFocus = this.partService.hasFocus(Parts.EDITOR_PART);
		const isSidebarFocus = this.partService.hasFocus(Parts.SIDEBAR_PART);
		const isPanelFocus = this.partService.hasFocus(Parts.PANEL_PART);

B
Benjamin Pasero 已提交
1413
		let part: Parts;
1414
		if (isSidebarFocus) {
B
Benjamin Pasero 已提交
1415 1416 1417 1418 1419
			part = Parts.SIDEBAR_PART;
		} else if (isPanelFocus) {
			part = Parts.PANEL_PART;
		} else if (isEditorFocus) {
			part = Parts.EDITOR_PART;
1420
		}
B
Benjamin Pasero 已提交
1421 1422 1423

		if (part) {
			this.partService.resizePart(part, sizeChange);
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
		}
	}
}

export class IncreaseViewSizeAction extends BaseResizeViewAction {

	public static ID = 'workbench.action.increaseViewSize';
	public static LABEL = nls.localize('increaseViewSize', "Increase Current View Size");

	constructor(
		id: string,
		label: string,
		@IPartService partService: IPartService
	) {
		super(id, label, partService);
	}

	public run(): TPromise<boolean> {
		this.resizePart(BaseResizeViewAction.RESIZE_INCREMENT);
		return TPromise.as(true);
	}
}

export class DecreaseViewSizeAction extends BaseResizeViewAction {

	public static ID = 'workbench.action.decreaseViewSize';
	public static LABEL = nls.localize('decreaseViewSize', "Decrease Current View Size");

	constructor(
		id: string,
		label: string,
		@IPartService partService: IPartService

	) {
		super(id, label, partService);
	}

	public run(): TPromise<boolean> {
		this.resizePart(-BaseResizeViewAction.RESIZE_INCREMENT);
		return TPromise.as(true);
	}
B
Benjamin Pasero 已提交
1465
}