remote.ts 28.5 KB
Newer Older
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.
 *--------------------------------------------------------------------------------------------*/

import 'vs/css!./remoteViewlet';
import * as nls from 'vs/nls';
8
import * as dom from 'vs/base/browser/dom';
9 10 11 12 13 14 15 16 17 18
import { URI } from 'vs/base/common/uri';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
S
SteVen Batten 已提交
19
import { FilterViewPaneContainer } from 'vs/workbench/browser/parts/views/viewsViewlet';
20
import { VIEWLET_ID } from 'vs/workbench/contrib/remote/common/remote.contribution';
A
Alex Ross 已提交
21
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
22
import { IViewDescriptor, IViewsRegistry, Extensions, ViewContainerLocation, IViewContainersRegistry } from 'vs/workbench/common/views';
23 24 25
import { Registry } from 'vs/platform/registry/common/platform';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { IOpenerService } from 'vs/platform/opener/common/opener';
26
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
27
import { ICommandService } from 'vs/platform/commands/common/commands';
S
Sandeep Somavarapu 已提交
28
import { ShowViewletAction } from 'vs/workbench/browser/viewlet';
29 30 31 32
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actions';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
A
Alex Dima 已提交
33 34 35 36 37 38 39 40 41
import { IProgress, IProgressStep, IProgressService, ProgressLocation } from 'vs/platform/progress/common/progress';
import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { ReconnectionWaitEvent, PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection';
import Severity from 'vs/base/common/severity';
import { ReloadWindowAction } from 'vs/workbench/browser/actions/windowActions';
import { IDisposable } from 'vs/base/common/lifecycle';
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
42 43 44
import { SwitchRemoteViewItem, SwitchRemoteAction } from 'vs/workbench/contrib/remote/browser/explorerViewItems';
import { Action, IActionViewItem, IAction } from 'vs/base/common/actions';
import { isStringArray } from 'vs/base/common/types';
45
import { IRemoteExplorerService } from 'vs/workbench/services/remote/common/remoteExplorerService';
46 47
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { startsWith } from 'vs/base/common/strings';
A
Alex Ross 已提交
48
import { TunnelPanelDescriptor, TunnelViewModel, forwardedPortsViewEnabled } from 'vs/workbench/contrib/remote/browser/tunnelView';
A
Alex Ross 已提交
49
import { IAddedViewDescriptorRef } from 'vs/workbench/browser/parts/views/views';
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { ITreeRenderer, ITreeNode, IAsyncDataSource } from 'vs/base/browser/ui/tree/tree';
import { WorkbenchAsyncDataTree, TreeResourceNavigator2 } from 'vs/platform/list/browser/listService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { Event } from 'vs/base/common/event';
import { ExtensionsRegistry, IExtensionPointUser } from 'vs/workbench/services/extensions/common/extensionsRegistry';

export interface HelpInformation {
	extensionDescription: IExtensionDescription;
	getStarted?: string;
	documentation?: string;
	feedback?: string;
	issues?: string;
	remoteName?: string[] | string;
}

const remoteHelpExtPoint = ExtensionsRegistry.registerExtensionPoint<HelpInformation>({
	extensionPoint: 'remoteHelp',
	jsonSchema: {
		description: nls.localize('RemoteHelpInformationExtPoint', 'Contributes help information for Remote'),
		type: 'object',
		properties: {
			'getStarted': {
				description: nls.localize('RemoteHelpInformationExtPoint.getStarted', "The url to your project's Getting Started page"),
				type: 'string'
			},
			'documentation': {
				description: nls.localize('RemoteHelpInformationExtPoint.documentation', "The url to your project's documentation page"),
				type: 'string'
			},
			'feedback': {
				description: nls.localize('RemoteHelpInformationExtPoint.feedback', "The url to your project's feedback reporter"),
				type: 'string'
			},
			'issues': {
				description: nls.localize('RemoteHelpInformationExtPoint.issues', "The url to your project's issues list"),
				type: 'string'
			}
		}
	}
});

interface IViewModel {
	helpInformation: HelpInformation[];
}

class HelpTreeVirtualDelegate implements IListVirtualDelegate<IHelpItem> {
	getHeight(element: IHelpItem): number {
		return 22;
	}

	getTemplateId(element: IHelpItem): string {
		return 'HelpItemTemplate';
	}
}

interface IHelpItemTemplateData {
	parent: HTMLElement;
	icon: HTMLElement;
}

class HelpTreeRenderer implements ITreeRenderer<HelpModel | IHelpItem, IHelpItem, IHelpItemTemplateData> {
	templateId: string = 'HelpItemTemplate';

	renderTemplate(container: HTMLElement): IHelpItemTemplateData {
		dom.addClass(container, 'remote-help-tree-node-item');
		const icon = dom.append(container, dom.$('.remote-help-tree-node-item-icon'));
		const data = <IHelpItemTemplateData>Object.create(null);
		data.parent = container;
		data.icon = icon;
		return data;
	}

	renderElement(element: ITreeNode<IHelpItem, IHelpItem>, index: number, templateData: IHelpItemTemplateData, height: number | undefined): void {
		const container = templateData.parent;
		dom.append(container, templateData.icon);
		dom.addClasses(templateData.icon, ...element.element.iconClasses);
		const labelContainer = dom.append(container, dom.$('.help-item-label'));
		labelContainer.innerText = element.element.label;
	}

	disposeTemplate(templateData: IHelpItemTemplateData): void {

	}
}

class HelpDataSource implements IAsyncDataSource<any, any> {
	hasChildren(element: any) {
		return element instanceof HelpModel;
	}

	getChildren(element: any) {
		if (element instanceof HelpModel && element.items) {
			return element.items;
		}

		return [];
	}
}

interface IHelpItem {
	key: string;
	iconClasses: string[];
	label: string;
	handleClick(): Promise<void>;
}
157 158

class HelpModel {
B
Benjamin Pasero 已提交
159
	items: IHelpItem[] | undefined;
160 161

	constructor(
162
		viewModel: IViewModel,
163 164
		openerService: IOpenerService,
		quickInputService: IQuickInputService,
165 166
		commandService: ICommandService,
		remoteExplorerService: IRemoteExplorerService,
167
		environmentService: IWorkbenchEnvironmentService
168 169
	) {
		let helpItems: IHelpItem[] = [];
170
		const getStarted = viewModel.helpInformation.filter(info => info.getStarted);
171 172 173

		if (getStarted.length) {
			helpItems.push(new HelpItem(
174 175
				'star',
				nls.localize('remote.help.getStarted', "Get Started"),
176 177
				getStarted.map((info: HelpInformation) => ({
					extensionDescription: info.extensionDescription,
178 179
					url: info.getStarted!,
					remoteAuthority: (typeof info.remoteName === 'string') ? [info.remoteName] : info.remoteName
180
				})),
181 182
				quickInputService,
				environmentService,
183 184
				openerService,
				remoteExplorerService
185 186 187
			));
		}

188
		const documentation = viewModel.helpInformation.filter(info => info.documentation);
189 190 191

		if (documentation.length) {
			helpItems.push(new HelpItem(
192 193
				'book',
				nls.localize('remote.help.documentation', "Read Documentation"),
194 195
				documentation.map((info: HelpInformation) => ({
					extensionDescription: info.extensionDescription,
196 197
					url: info.documentation!,
					remoteAuthority: (typeof info.remoteName === 'string') ? [info.remoteName] : info.remoteName
198
				})),
199 200
				quickInputService,
				environmentService,
201 202
				openerService,
				remoteExplorerService
203 204 205
			));
		}

206
		const feedback = viewModel.helpInformation.filter(info => info.feedback);
207 208 209

		if (feedback.length) {
			helpItems.push(new HelpItem(
210 211
				'twitter',
				nls.localize('remote.help.feedback', "Provide Feedback"),
212 213
				feedback.map((info: HelpInformation) => ({
					extensionDescription: info.extensionDescription,
214 215
					url: info.feedback!,
					remoteAuthority: (typeof info.remoteName === 'string') ? [info.remoteName] : info.remoteName
216
				})),
217 218
				quickInputService,
				environmentService,
219 220
				openerService,
				remoteExplorerService
221 222 223
			));
		}

224
		const issues = viewModel.helpInformation.filter(info => info.issues);
225 226 227

		if (issues.length) {
			helpItems.push(new HelpItem(
228 229
				'issues',
				nls.localize('remote.help.issues', "Review Issues"),
230 231
				issues.map((info: HelpInformation) => ({
					extensionDescription: info.extensionDescription,
232 233
					url: info.issues!,
					remoteAuthority: (typeof info.remoteName === 'string') ? [info.remoteName] : info.remoteName
234
				})),
235 236
				quickInputService,
				environmentService,
237 238
				openerService,
				remoteExplorerService
239 240 241 242 243
			));
		}

		if (helpItems.length) {
			helpItems.push(new IssueReporterItem(
244 245 246
				'comment',
				nls.localize('remote.help.report', "Report Issue"),
				viewModel.helpInformation.map(info => ({
247 248 249
					extensionDescription: info.extensionDescription,
					remoteAuthority: (typeof info.remoteName === 'string') ? [info.remoteName] : info.remoteName
				})),
250
				quickInputService,
251
				environmentService,
252 253
				commandService,
				remoteExplorerService
254 255 256 257 258 259 260 261 262
			));
		}

		if (helpItems.length) {
			this.items = helpItems;
		}
	}
}

263
abstract class HelpItemBase implements IHelpItem {
264
	public iconClasses: string[] = [];
265
	constructor(
266
		public key: string,
267
		public label: string,
268 269
		public values: { extensionDescription: IExtensionDescription, url?: string, remoteAuthority: string[] | undefined }[],
		private quickInputService: IQuickInputService,
270 271
		private environmentService: IWorkbenchEnvironmentService,
		private remoteExplorerService: IRemoteExplorerService
272
	) {
273 274 275
		this.iconClasses.push(`codicon-${key}`);
		this.iconClasses.push('remote-help-tree-node-item-icon');
		this.iconClasses.push('codicon');
276 277
	}

278
	async handleClick() {
279
		const remoteAuthority = this.environmentService.configuration.remoteAuthority;
280
		if (remoteAuthority && startsWith(remoteAuthority, this.remoteExplorerService.targetType)) {
281 282 283 284 285 286 287 288 289 290 291 292
			for (let value of this.values) {
				if (value.remoteAuthority) {
					for (let authority of value.remoteAuthority) {
						if (startsWith(remoteAuthority, authority)) {
							await this.takeAction(value.extensionDescription, value.url);
							return;
						}
					}
				}
			}
		}

293 294 295 296
		if (this.values.length > 1) {
			let actions = this.values.map(value => {
				return {
					label: value.extensionDescription.displayName || value.extensionDescription.identifier.value,
297 298
					description: value.url,
					extensionDescription: value.extensionDescription
299 300
				};
			});
301

302
			const action = await this.quickInputService.pick(actions, { placeHolder: nls.localize('pickRemoteExtension', "Select url to open") });
303

304
			if (action) {
305
				await this.takeAction(action.extensionDescription, action.description);
306 307
			}
		} else {
308
			await this.takeAction(this.values[0].extensionDescription, this.values[0].url);
309 310
		}
	}
311 312

	protected abstract takeAction(extensionDescription: IExtensionDescription, url?: string): Promise<void>;
313
}
314

315
class HelpItem extends HelpItemBase {
316
	constructor(
317
		key: string,
318 319 320 321
		label: string,
		values: { extensionDescription: IExtensionDescription; url: string, remoteAuthority: string[] | undefined }[],
		quickInputService: IQuickInputService,
		environmentService: IWorkbenchEnvironmentService,
322 323
		private openerService: IOpenerService,
		remoteExplorerService: IRemoteExplorerService
324
	) {
325
		super(key, label, values, quickInputService, environmentService, remoteExplorerService);
326 327
	}

328 329 330 331
	protected async takeAction(extensionDescription: IExtensionDescription, url: string): Promise<void> {
		await this.openerService.open(URI.parse(url));
	}
}
332

333 334
class IssueReporterItem extends HelpItemBase {
	constructor(
335
		key: string,
336 337 338 339 340
		label: string,
		values: { extensionDescription: IExtensionDescription; remoteAuthority: string[] | undefined }[],
		quickInputService: IQuickInputService,
		environmentService: IWorkbenchEnvironmentService,
		private commandService: ICommandService,
341
		remoteExplorerService: IRemoteExplorerService
342
	) {
343
		super(key, label, values, quickInputService, environmentService, remoteExplorerService);
344
	}
345

346 347
	protected async takeAction(extensionDescription: IExtensionDescription): Promise<void> {
		await this.commandService.executeCommand('workbench.action.openIssueReporter', [extensionDescription.identifier.value]);
348 349 350
	}
}

351 352 353 354
class HelpPanel extends ViewPane {
	static readonly ID = '~remote.helpPanel';
	static readonly TITLE = nls.localize('remote.help', "Help and feedback");
	private tree!: WorkbenchAsyncDataTree<any, any, any>;
355

356 357 358 359 360 361 362 363 364 365 366 367 368
	constructor(
		protected viewModel: IViewModel,
		options: IViewPaneOptions,
		@IKeybindingService protected keybindingService: IKeybindingService,
		@IContextMenuService protected contextMenuService: IContextMenuService,
		@IContextKeyService protected contextKeyService: IContextKeyService,
		@IConfigurationService protected configurationService: IConfigurationService,
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
		@IOpenerService protected openerService: IOpenerService,
		@IQuickInputService protected quickInputService: IQuickInputService,
		@ICommandService protected commandService: ICommandService,
		@IRemoteExplorerService protected readonly remoteExplorerService: IRemoteExplorerService,
		@IWorkbenchEnvironmentService protected readonly workbenchEnvironmentService: IWorkbenchEnvironmentService
369
	) {
370
		super(options, keybindingService, contextMenuService, configurationService, contextKeyService);
371
	}
372

373 374 375 376 377 378 379 380 381 382 383 384 385 386
	protected renderBody(container: HTMLElement): void {
		dom.addClass(container, 'remote-help');
		const treeContainer = document.createElement('div');
		dom.addClass(treeContainer, 'remote-help-content');
		container.appendChild(treeContainer);

		this.tree = this.instantiationService.createInstance(WorkbenchAsyncDataTree,
			'RemoteHelp',
			treeContainer,
			new HelpTreeVirtualDelegate(),
			[new HelpTreeRenderer()],
			new HelpDataSource(),
			{
				keyboardSupport: true,
387
			}
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
		);

		const model = new HelpModel(this.viewModel, this.openerService, this.quickInputService, this.commandService, this.remoteExplorerService, this.workbenchEnvironmentService);

		this.tree.setInput(model);

		const helpItemNavigator = this._register(new TreeResourceNavigator2(this.tree, { openOnFocus: false, openOnSelection: false }));

		this._register(Event.debounce(helpItemNavigator.onDidOpenResource, (last, event) => event, 75, true)(e => {
			e.element.handleClick();
		}));
	}

	protected layoutBody(height: number, width: number): void {
		this.tree.layout(height, width);
	}
}

class HelpPanelDescriptor implements IViewDescriptor {
	readonly id = HelpPanel.ID;
	readonly name = HelpPanel.TITLE;
	readonly ctorDescriptor: { ctor: any, arguments?: any[] };
	readonly canToggleVisibility = true;
	readonly hideByDefault = false;
	readonly workspace = true;

	constructor(viewModel: IViewModel) {
		this.ctorDescriptor = { ctor: HelpPanel, arguments: [viewModel] };
416 417 418
	}
}

419 420 421
export class RemoteViewPaneContainer extends FilterViewPaneContainer implements IViewModel {
	private helpPanelDescriptor = new HelpPanelDescriptor(this);
	helpInformation: HelpInformation[] = [];
422
	private actions: IAction[] | undefined;
A
Alex Ross 已提交
423
	private tunnelPanelDescriptor: TunnelPanelDescriptor | undefined;
424 425 426 427 428 429 430 431 432 433

	constructor(
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@ITelemetryService telemetryService: ITelemetryService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IStorageService storageService: IStorageService,
		@IConfigurationService configurationService: IConfigurationService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IThemeService themeService: IThemeService,
		@IContextMenuService contextMenuService: IContextMenuService,
434
		@IExtensionService extensionService: IExtensionService,
A
Alex Ross 已提交
435 436
		@IRemoteExplorerService private readonly remoteExplorerService: IRemoteExplorerService,
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
437
		@IContextKeyService private readonly contextKeyService: IContextKeyService
438
	) {
439
		super(VIEWLET_ID, remoteExplorerService.onDidChangeTargetType, configurationService, layoutService, telemetryService, storageService, instantiationService, themeService, contextMenuService, extensionService, contextService);
440 441 442 443 444 445 446 447 448 449 450
		this.addConstantViewDescriptors([this.helpPanelDescriptor]);
		remoteHelpExtPoint.setHandler((extensions) => {
			let helpInformation: HelpInformation[] = [];
			for (let extension of extensions) {
				this._handleRemoteInfoExtensionPoint(extension, helpInformation);
			}

			this.helpInformation = helpInformation;

			const viewsRegistry = Registry.as<IViewsRegistry>(Extensions.ViewsRegistry);
			if (this.helpInformation.length) {
S
Sandeep Somavarapu 已提交
451
				viewsRegistry.registerViews([this.helpPanelDescriptor], this.viewContainer);
452
			} else {
S
Sandeep Somavarapu 已提交
453
				viewsRegistry.deregisterViews([this.helpPanelDescriptor], this.viewContainer);
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
			}
		});
	}

	private _handleRemoteInfoExtensionPoint(extension: IExtensionPointUser<HelpInformation>, helpInformation: HelpInformation[]) {
		if (!extension.description.enableProposedApi) {
			return;
		}

		if (!extension.value.documentation && !extension.value.feedback && !extension.value.getStarted && !extension.value.issues) {
			return;
		}

		helpInformation.push({
			extensionDescription: extension.description,
			getStarted: extension.value.getStarted,
			documentation: extension.value.documentation,
			feedback: extension.value.feedback,
			issues: extension.value.issues,
			remoteName: extension.value.remoteName
		});
475 476 477 478 479 480 481 482
	}

	protected getFilterOn(viewDescriptor: IViewDescriptor): string | undefined {
		return isStringArray(viewDescriptor.remoteAuthority) ? viewDescriptor.remoteAuthority[0] : viewDescriptor.remoteAuthority;
	}

	public getActionViewItem(action: Action): IActionViewItem | undefined {
		if (action.id === SwitchRemoteAction.ID) {
483
			return this.instantiationService.createInstance(SwitchRemoteViewItem, action, SwitchRemoteViewItem.createOptionItems(Registry.as<IViewsRegistry>(Extensions.ViewsRegistry).getViews(this.viewContainer), this.contextKeyService));
484 485 486 487 488 489 490 491
		}

		return super.getActionViewItem(action);
	}

	public getActions(): IAction[] {
		if (!this.actions) {
			this.actions = [
492
				this.instantiationService.createInstance(SwitchRemoteAction, SwitchRemoteAction.ID, SwitchRemoteAction.LABEL)
493 494 495 496 497 498
			];
			this.actions.forEach(a => {
				this._register(a);
			});
		}
		return this.actions;
499 500 501 502 503 504
	}

	getTitle(): string {
		const title = nls.localize('remote.explorer', "Remote Explorer");
		return title;
	}
A
Alex Ross 已提交
505

S
SteVen Batten 已提交
506
	onDidAddViews(added: IAddedViewDescriptorRef[]): ViewPane[] {
A
Alex Ross 已提交
507
		// Call to super MUST be first, since registering the additional view will cause this to be called again.
S
SteVen Batten 已提交
508
		const panels: ViewPane[] = super.onDidAddViews(added);
509
		// This context key is set to false in the constructor, but is expected to be changed by resolver extensions to enable the forwarded ports view.
510
		const viewEnabled: boolean = !!forwardedPortsViewEnabled.getValue(this.contextKeyService);
511
		if (this.environmentService.configuration.remoteAuthority && !this.tunnelPanelDescriptor && viewEnabled) {
A
Alex Ross 已提交
512 513
			this.tunnelPanelDescriptor = new TunnelPanelDescriptor(new TunnelViewModel(this.remoteExplorerService), this.environmentService);
			const viewsRegistry = Registry.as<IViewsRegistry>(Extensions.ViewsRegistry);
514
			viewsRegistry.registerViews([this.tunnelPanelDescriptor!], this.viewContainer);
A
Alex Ross 已提交
515 516 517
		}
		return panels;
	}
518 519
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
Registry.as<IViewContainersRegistry>(Extensions.ViewContainersRegistry).registerViewContainer(
	{
		id: VIEWLET_ID,
		name: nls.localize('remote.explorer', "Remote Explorer"),
		ctorDescriptor: { ctor: RemoteViewPaneContainer },
		hideIfEmpty: true,
		viewOrderDelegate: {
			getOrder: (group?: string) => {
				if (!group) {
					return;
				}

				let matches = /^targets@(\d+)$/.exec(group);
				if (matches) {
					return -1000;
				}

				matches = /^details(@(\d+))?$/.exec(group);

				if (matches) {
					return -500;
				}

				return;
			}
		},
		icon: 'codicon-remote-explorer',
		order: 4
	}, ViewContainerLocation.Sidebar);
549 550 551 552

class OpenRemoteViewletAction extends ShowViewletAction {

	static readonly ID = VIEWLET_ID;
553
	static readonly LABEL = nls.localize('toggleRemoteViewlet', "Show Remote Explorer");
554 555 556 557 558 559 560 561

	constructor(id: string, label: string, @IViewletService viewletService: IViewletService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService) {
		super(id, label, VIEWLET_ID, viewletService, editorGroupService, layoutService);
	}
}

// Register Action to Open Viewlet
Registry.as<IWorkbenchActionRegistry>(WorkbenchActionExtensions.WorkbenchActions).registerWorkbenchAction(
562
	SyncActionDescriptor.create(OpenRemoteViewletAction, VIEWLET_ID, nls.localize('toggleRemoteViewlet', "Show Remote Explorer"), {
563 564 565 566 567
		primary: 0
	}),
	'View: Show Remote Explorer',
	nls.localize('view', "View")
);
A
Alex Dima 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609


class ProgressReporter {
	private _currentProgress: IProgress<IProgressStep> | null = null;
	private lastReport: string | null = null;

	constructor(currentProgress: IProgress<IProgressStep> | null) {
		this._currentProgress = currentProgress;
	}

	set currentProgress(progress: IProgress<IProgressStep>) {
		this._currentProgress = progress;
	}

	report(message?: string) {
		if (message) {
			this.lastReport = message;
		}

		if (this.lastReport && this._currentProgress) {
			this._currentProgress.report({ message: this.lastReport });
		}
	}
}

class RemoteAgentConnectionStatusListener implements IWorkbenchContribution {
	constructor(
		@IRemoteAgentService remoteAgentService: IRemoteAgentService,
		@IProgressService progressService: IProgressService,
		@IDialogService dialogService: IDialogService,
		@ICommandService commandService: ICommandService,
		@IContextKeyService contextKeyService: IContextKeyService
	) {
		const connection = remoteAgentService.getConnection();
		if (connection) {
			let currentProgressPromiseResolve: (() => void) | null = null;
			let progressReporter: ProgressReporter | null = null;
			let lastLocation: ProgressLocation | null = null;
			let currentTimer: ReconnectionTimer | null = null;
			let reconnectWaitEvent: ReconnectionWaitEvent | null = null;
			let disposableListener: IDisposable | null = null;

610
			function showProgress(location: ProgressLocation, buttons: { label: string, callback: () => void }[]) {
A
Alex Dima 已提交
611 612 613 614 615 616 617 618 619 620
				if (currentProgressPromiseResolve) {
					currentProgressPromiseResolve();
				}

				const promise = new Promise<void>((resolve) => currentProgressPromiseResolve = resolve);
				lastLocation = location;

				if (location === ProgressLocation.Dialog) {
					// Show dialog
					progressService!.withProgress(
621
						{ location: ProgressLocation.Dialog, buttons: buttons.map(button => button.label) },
A
Alex Dima 已提交
622 623 624
						(progress) => { if (progressReporter) { progressReporter.currentProgress = progress; } return promise; },
						(choice?) => {
							// Handle choice from dialog
625 626
							if (buttons[choice]) {
								buttons[choice].callback();
A
Alex Dima 已提交
627 628 629 630 631 632 633 634 635
							} else {
								showProgress(ProgressLocation.Notification, buttons);
							}

							progressReporter!.report();
						});
				} else {
					// Show notification
					progressService!.withProgress(
636
						{ location: ProgressLocation.Notification, buttons: buttons.map(button => button.label) },
A
Alex Dima 已提交
637 638
						(progress) => { if (progressReporter) { progressReporter.currentProgress = progress; } return promise; },
						(choice?) => {
639 640 641
							// Handle choice from dialog
							if (buttons[choice]) {
								buttons[choice].callback();
A
Alex Dima 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
							} else {
								hideProgress();
							}
						});
				}
			}

			function hideProgress() {
				if (currentProgressPromiseResolve) {
					currentProgressPromiseResolve();
				}

				currentProgressPromiseResolve = null;
			}

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
			const reconnectButton = {
				label: nls.localize('reconnectNow', "Reconnect Now"),
				callback: () => {
					if (reconnectWaitEvent) {
						reconnectWaitEvent.skipWait();
					}
				}
			};

			const reloadButton = {
				label: nls.localize('reloadWindow', "Reload Window"),
				callback: () => {
					commandService.executeCommand(ReloadWindowAction.ID);
				}
			};

A
Alex Dima 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686
			connection.onDidStateChange((e) => {
				if (currentTimer) {
					currentTimer.dispose();
					currentTimer = null;
				}

				if (disposableListener) {
					disposableListener.dispose();
					disposableListener = null;
				}
				switch (e.type) {
					case PersistentConnectionEventType.ConnectionLost:
						if (!currentProgressPromiseResolve) {
							progressReporter = new ProgressReporter(null);
687
							showProgress(ProgressLocation.Dialog, [reconnectButton, reloadButton]);
A
Alex Dima 已提交
688 689 690 691 692 693 694
						}

						progressReporter!.report(nls.localize('connectionLost', "Connection Lost"));
						break;
					case PersistentConnectionEventType.ReconnectionWait:
						hideProgress();
						reconnectWaitEvent = e;
695
						showProgress(lastLocation || ProgressLocation.Notification, [reconnectButton, reloadButton]);
A
Alex Dima 已提交
696 697 698 699
						currentTimer = new ReconnectionTimer(progressReporter!, Date.now() + 1000 * e.durationSeconds);
						break;
					case PersistentConnectionEventType.ReconnectionRunning:
						hideProgress();
700
						showProgress(lastLocation || ProgressLocation.Notification, [reloadButton]);
A
Alex Dima 已提交
701 702 703 704 705 706 707 708 709
						progressReporter!.report(nls.localize('reconnectionRunning', "Attempting to reconnect..."));

						// Register to listen for quick input is opened
						disposableListener = contextKeyService.onDidChangeContext((contextKeyChangeEvent) => {
							const reconnectInteraction = new Set<string>(['inQuickOpen']);
							if (contextKeyChangeEvent.affectsSome(reconnectInteraction)) {
								// Need to move from dialog if being shown and user needs to type in a prompt
								if (lastLocation === ProgressLocation.Dialog && progressReporter !== null) {
									hideProgress();
710
									showProgress(ProgressLocation.Notification, [reloadButton]);
A
Alex Dima 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 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
									progressReporter.report();
								}
							}
						});

						break;
					case PersistentConnectionEventType.ReconnectionPermanentFailure:
						hideProgress();
						progressReporter = null;

						dialogService.show(Severity.Error, nls.localize('reconnectionPermanentFailure', "Cannot reconnect. Please reload the window."), [nls.localize('reloadWindow', "Reload Window"), nls.localize('cancel', "Cancel")], { cancelId: 1 }).then(result => {
							// Reload the window
							if (result.choice === 0) {
								commandService.executeCommand(ReloadWindowAction.ID);
							}
						});
						break;
					case PersistentConnectionEventType.ConnectionGain:
						hideProgress();
						progressReporter = null;
						break;
				}
			});
		}
	}
}

class ReconnectionTimer implements IDisposable {
	private readonly _progressReporter: ProgressReporter;
	private readonly _completionTime: number;
	private readonly _token: any;

	constructor(progressReporter: ProgressReporter, completionTime: number) {
		this._progressReporter = progressReporter;
		this._completionTime = completionTime;
		this._token = setInterval(() => this._render(), 1000);
		this._render();
	}

	public dispose(): void {
		clearInterval(this._token);
	}

	private _render() {
		const remainingTimeMs = this._completionTime - Date.now();
		if (remainingTimeMs < 0) {
			return;
		}
		const remainingTime = Math.ceil(remainingTimeMs / 1000);
		if (remainingTime === 1) {
			this._progressReporter.report(nls.localize('reconnectionWaitOne', "Attempting to reconnect in {0} second...", remainingTime));
		} else {
			this._progressReporter.report(nls.localize('reconnectionWaitMany', "Attempting to reconnect in {0} seconds...", remainingTime));
		}
	}
}

const workbenchContributionsRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);
workbenchContributionsRegistry.registerWorkbenchContribution(RemoteAgentConnectionStatusListener, LifecyclePhase.Eventually);