userDataSyncViews.ts 24.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { Registry } from 'vs/platform/registry/common/platform';
import { IViewsRegistry, Extensions, ITreeViewDescriptor, ITreeViewDataProvider, ITreeItem, TreeItemCollapsibleState, IViewsService, TreeViewItemHandleArg, ViewContainer, IViewDescriptorService } from 'vs/workbench/common/views';
import { localize } from 'vs/nls';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { TreeViewPane, TreeView } from 'vs/workbench/browser/parts/views/treeView';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
12
import { ALL_SYNC_RESOURCES, SyncResource, IUserDataSyncService, ISyncResourceHandle, SyncStatus, IUserDataSyncEnablementService } from 'vs/platform/userDataSync/common/userDataSync';
13
import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions';
S
#93960  
Sandeep Somavarapu 已提交
14
import { ContextKeyExpr, ContextKeyEqualsExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
15 16
import { URI } from 'vs/base/common/uri';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
S
#93960  
Sandeep Somavarapu 已提交
17
import { FolderThemeIcon, IThemeService } from 'vs/platform/theme/common/themeService';
18 19 20 21
import { fromNow } from 'vs/base/common/date';
import { pad } from 'vs/base/common/strings';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { Event } from 'vs/base/common/event';
S
Sandeep Somavarapu 已提交
22
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
S
#93960  
Sandeep Somavarapu 已提交
23 24 25 26 27 28 29 30 31 32 33
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { Codicon } from 'vs/base/common/codicons';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IAction, Action } from 'vs/base/common/actions';
S
Sandeep Somavarapu 已提交
34
import { IUserDataSyncWorkbenchService, CONTEXT_SYNC_STATE, getSyncAreaLabel, CONTEXT_ACCOUNT_STATE, AccountStatus, CONTEXT_ENABLE_VIEWS, SHOW_SYNC_LOG_COMMAND_ID, CONFIGURE_SYNC_COMMAND_ID, ENABLE_SYNC_VIEWS_COMMAND_ID, SHOW_SYNCED_DATA_COMMAND_ID } from 'vs/workbench/services/userDataSync/common/userDataSync';
35
import { IUserDataSyncMachinesService, IUserDataSyncMachine } from 'vs/platform/userDataSync/common/userDataSyncMachines';
S
Sandeep Somavarapu 已提交
36
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
S
Sandeep Somavarapu 已提交
37
import { INotificationService } from 'vs/platform/notification/common/notification';
S
Sandeep Somavarapu 已提交
38
import { generateUuid } from 'vs/base/common/uuid';
39

S
#93960  
Sandeep Somavarapu 已提交
40
export class UserDataSyncViewPaneContainer extends ViewPaneContainer {
41

S
#93960  
Sandeep Somavarapu 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
	constructor(
		containerId: string,
		@ICommandService private readonly commandService: ICommandService,
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@ITelemetryService telemetryService: ITelemetryService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IThemeService themeService: IThemeService,
		@IConfigurationService configurationService: IConfigurationService,
		@IStorageService storageService: IStorageService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IContextMenuService contextMenuService: IContextMenuService,
		@IExtensionService extensionService: IExtensionService,
		@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
	) {
		super(containerId, { mergeViewWithContainerWhenSingleView: false }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);
	}

	getActions(): IAction[] {
		return [
			new Action(SHOW_SYNC_LOG_COMMAND_ID, localize('showLog', "Show Log"), Codicon.output.classNames, true, async () => this.commandService.executeCommand(SHOW_SYNC_LOG_COMMAND_ID)),
			new Action(CONFIGURE_SYNC_COMMAND_ID, localize('configure', "Configure..."), Codicon.settingsGear.classNames, true, async () => this.commandService.executeCommand(CONFIGURE_SYNC_COMMAND_ID)),
		];
	}

}

export class UserDataSyncDataViews extends Disposable {
69 70

	constructor(
S
#93960  
Sandeep Somavarapu 已提交
71
		container: ViewContainer,
72
		@IInstantiationService private readonly instantiationService: IInstantiationService,
S
#93960  
Sandeep Somavarapu 已提交
73
		@IUserDataSyncEnablementService private readonly userDataSyncEnablementService: IUserDataSyncEnablementService,
74
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
75 76
	) {
		super();
S
#93960  
Sandeep Somavarapu 已提交
77
		this.registerViews(container);
78 79 80
	}

	private registerViews(container: ViewContainer): void {
S
Sandeep Somavarapu 已提交
81
		const remoteView = this.registerDataView(container, true, true);
S
#93960  
Sandeep Somavarapu 已提交
82 83
		this.registerRemoteViewActions(remoteView);

S
Sandeep Somavarapu 已提交
84 85
		this.registerDataView(container, false, false);
		this.registerMachinesView(container);
86 87
	}

S
Sandeep Somavarapu 已提交
88
	private registerDataView(container: ViewContainer, remote: boolean, showByDefault: boolean): TreeView {
89
		const id = `workbench.views.sync.${remote ? 'remote' : 'local'}DataView`;
90 91
		const showByDefaultContext = new RawContextKey<boolean>(id, showByDefault);
		const viewEnablementContext = showByDefaultContext.bindTo(this.contextKeyService);
92 93 94 95 96 97 98
		const name = remote ? localize('remote title', "Synced Data") : localize('local title', "Local Backup");
		const treeView = this.instantiationService.createInstance(TreeView, id, name);
		treeView.showCollapseAllAction = true;
		treeView.showRefreshAction = true;
		const disposable = treeView.onDidChangeVisibility(visible => {
			if (visible && !treeView.dataProvider) {
				disposable.dispose();
S
Sandeep Somavarapu 已提交
99 100
				treeView.dataProvider = remote ? this.instantiationService.createInstance(RemoteUserDataSyncHistoryViewDataProvider)
					: this.instantiationService.createInstance(LocalUserDataSyncHistoryViewDataProvider);
101 102
			}
		});
S
#93960  
Sandeep Somavarapu 已提交
103
		this._register(Event.any(this.userDataSyncEnablementService.onDidChangeResourceEnablement, this.userDataSyncEnablementService.onDidChangeEnablement)(() => treeView.refresh()));
104 105 106 107 108
		const viewsRegistry = Registry.as<IViewsRegistry>(Extensions.ViewsRegistry);
		viewsRegistry.registerViews([<ITreeViewDescriptor>{
			id,
			name,
			ctorDescriptor: new SyncDescriptor(TreeViewPane),
109
			when: ContextKeyExpr.and(CONTEXT_SYNC_STATE.notEqualsTo(SyncStatus.Uninitialized), CONTEXT_ACCOUNT_STATE.isEqualTo(AccountStatus.Available), CONTEXT_ENABLE_VIEWS, showByDefaultContext),
110 111 112 113 114 115 116 117 118 119
			canToggleVisibility: true,
			canMoveView: true,
			treeView,
			collapsed: false,
			order: 100,
		}], container);

		registerAction2(class extends Action2 {
			constructor() {
				super({
S
Sandeep Somavarapu 已提交
120
					id: remote ? SHOW_SYNCED_DATA_COMMAND_ID : 'workbench.userDataSync.actions.showLocalBackupData',
121
					title: remote ?
S
#93960  
Sandeep Somavarapu 已提交
122
						{ value: localize('workbench.action.showSyncRemoteBackup', "Show Synced Data"), original: `Show Synced Data` }
123 124 125 126 127 128 129 130 131 132 133
						: { value: localize('workbench.action.showSyncLocalBackup', "Show Local Backup"), original: `Show Local Backup` },
					category: { value: localize('sync preferences', "Preferences Sync"), original: `Preferences Sync` },
					menu: {
						id: MenuId.CommandPalette,
						when: ContextKeyExpr.and(CONTEXT_SYNC_STATE.notEqualsTo(SyncStatus.Uninitialized), CONTEXT_ACCOUNT_STATE.isEqualTo(AccountStatus.Available)),
					},
				});
			}
			async run(accessor: ServicesAccessor): Promise<void> {
				const viewDescriptorService = accessor.get(IViewDescriptorService);
				const viewsService = accessor.get(IViewsService);
S
#93960  
Sandeep Somavarapu 已提交
134 135 136
				const commandService = accessor.get(ICommandService);

				await commandService.executeCommand(ENABLE_SYNC_VIEWS_COMMAND_ID);
137
				viewEnablementContext.set(true);
S
#93960  
Sandeep Somavarapu 已提交
138 139

				const viewContainer = viewDescriptorService.getViewContainerByViewId(id);
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
				if (viewContainer) {
					const model = viewDescriptorService.getViewContainerModel(viewContainer);
					if (model.activeViewDescriptors.some(viewDescriptor => viewDescriptor.id === id)) {
						viewsService.openView(id, true);
					} else {
						const disposable = model.onDidChangeActiveViewDescriptors(e => {
							if (e.added.some(viewDescriptor => viewDescriptor.id === id)) {
								disposable.dispose();
								viewsService.openView(id, true);
							}
						});
					}
				}
			}
		});

S
Sandeep Somavarapu 已提交
156
		this.registerDataViewActions(id);
S
#93960  
Sandeep Somavarapu 已提交
157
		return treeView;
158 159
	}

S
Sandeep Somavarapu 已提交
160 161 162 163
	private registerMachinesView(container: ViewContainer): void {
		const id = `workbench.views.sync.machines`;
		const name = localize('synced machines', "Synced Machines");
		const treeView = this.instantiationService.createInstance(TreeView, id, name);
S
Sandeep Somavarapu 已提交
164
		const dataProvider = this.instantiationService.createInstance(UserDataSyncMachinesViewDataProvider, treeView);
S
Sandeep Somavarapu 已提交
165 166 167 168
		treeView.showRefreshAction = true;
		const disposable = treeView.onDidChangeVisibility(visible => {
			if (visible && !treeView.dataProvider) {
				disposable.dispose();
S
Sandeep Somavarapu 已提交
169
				treeView.dataProvider = dataProvider;
S
Sandeep Somavarapu 已提交
170 171
			}
		});
172
		this._register(Event.any(this.userDataSyncEnablementService.onDidChangeResourceEnablement, this.userDataSyncEnablementService.onDidChangeEnablement)(() => treeView.refresh()));
S
Sandeep Somavarapu 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
		const viewsRegistry = Registry.as<IViewsRegistry>(Extensions.ViewsRegistry);
		viewsRegistry.registerViews([<ITreeViewDescriptor>{
			id,
			name,
			ctorDescriptor: new SyncDescriptor(TreeViewPane),
			when: ContextKeyExpr.and(CONTEXT_SYNC_STATE.notEqualsTo(SyncStatus.Uninitialized), CONTEXT_ACCOUNT_STATE.isEqualTo(AccountStatus.Available), CONTEXT_ENABLE_VIEWS),
			canToggleVisibility: true,
			canMoveView: true,
			treeView,
			collapsed: false,
			order: 200,
		}], container);

		registerAction2(class extends Action2 {
			constructor() {
				super({
S
Sandeep Somavarapu 已提交
189 190
					id: `workbench.actions.sync.editMachineName`,
					title: localize('workbench.actions.sync.editMachineName', "Edit Name"),
S
Sandeep Somavarapu 已提交
191 192 193
					icon: Codicon.edit,
					menu: {
						id: MenuId.ViewItemContext,
S
Sandeep Somavarapu 已提交
194
						when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', id)),
S
Sandeep Somavarapu 已提交
195 196 197 198 199
						group: 'inline',
					},
				});
			}
			async run(accessor: ServicesAccessor, handle: TreeViewItemHandleArg): Promise<void> {
S
Sandeep Somavarapu 已提交
200 201 202 203
				const changed = await dataProvider.rename(handle.$treeItemHandle);
				if (changed) {
					await treeView.refresh();
				}
S
Sandeep Somavarapu 已提交
204 205
			}
		});
S
Sandeep Somavarapu 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

		registerAction2(class extends Action2 {
			constructor() {
				super({
					id: `workbench.actions.sync.turnOffSyncOnMachine`,
					title: localize('workbench.actions.sync.turnOffSyncOnMachine', "Turn off Preferences Sync"),
					menu: {
						id: MenuId.ViewItemContext,
						when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', id), ContextKeyEqualsExpr.create('viewItem', 'sync-machine')),
					},
				});
			}
			async run(accessor: ServicesAccessor, handle: TreeViewItemHandleArg): Promise<void> {
				if (await dataProvider.disable(handle.$treeItemHandle)) {
					await treeView.refresh();
				}
			}
		});

S
Sandeep Somavarapu 已提交
225 226 227
	}

	private registerDataViewActions(viewId: string) {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
		registerAction2(class extends Action2 {
			constructor() {
				super({
					id: `workbench.actions.sync.resolveResource`,
					title: localize('workbench.actions.sync.resolveResourceRef', "Show raw JSON sync data"),
					menu: {
						id: MenuId.ViewItemContext,
						when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', viewId), ContextKeyExpr.regex('viewItem', /sync-resource-.*/i))
					},
				});
			}
			async run(accessor: ServicesAccessor, handle: TreeViewItemHandleArg): Promise<void> {
				const { resource } = <{ resource: string }>JSON.parse(handle.$treeItemHandle);
				const editorService = accessor.get(IEditorService);
				await editorService.openEditor({ resource: URI.parse(resource) });
			}
		});

		registerAction2(class extends Action2 {
			constructor() {
				super({
					id: `workbench.actions.sync.replaceCurrent`,
250
					title: localize('workbench.actions.sync.replaceCurrent', "Restore"),
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
					icon: { id: 'codicon/cloud-download' },
					menu: {
						id: MenuId.ViewItemContext,
						when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', viewId), ContextKeyExpr.regex('viewItem', /sync-resource-.*/i)),
						group: 'inline',
					},
				});
			}
			async run(accessor: ServicesAccessor, handle: TreeViewItemHandleArg): Promise<void> {
				const dialogService = accessor.get(IDialogService);
				const userDataSyncService = accessor.get(IUserDataSyncService);
				const { resource, syncResource } = <{ resource: string, syncResource: SyncResource }>JSON.parse(handle.$treeItemHandle);
				const result = await dialogService.confirm({
					message: localize('confirm replace', "Would you like to replace your current {0} with selected?", getSyncAreaLabel(syncResource)),
					type: 'info',
					title: localize('preferences sync', "Preferences Sync")
				});
				if (result.confirmed) {
					return userDataSyncService.replace(URI.parse(resource));
				}
			}
		});

		registerAction2(class extends Action2 {
			constructor() {
				super({
					id: `workbench.actions.sync.commpareWithLocal`,
					title: localize('workbench.actions.sync.commpareWithLocal', "Open Changes"),
				});
			}
			async run(accessor: ServicesAccessor, handle: TreeViewItemHandleArg): Promise<void> {
				const editorService = accessor.get(IEditorService);
				const { resource, comparableResource } = <{ resource: string, comparableResource?: string }>JSON.parse(handle.$treeItemHandle);
				if (comparableResource) {
					await editorService.openEditor({
						leftResource: URI.parse(resource),
						rightResource: URI.parse(comparableResource),
						options: {
							preserveFocus: true,
							revealIfVisible: true,
						},
					});
				} else {
					await editorService.openEditor({ resource: URI.parse(resource) });
				}
			}
		});
	}

S
#93960  
Sandeep Somavarapu 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
	private registerRemoteViewActions(view: TreeView) {
		this.registerResetAction(view);
	}

	private registerResetAction(view: TreeView) {
		registerAction2(class extends Action2 {
			constructor() {
				super({
					id: `workbench.actions.syncData.reset`,
					title: localize('workbench.actions.syncData.reset', "Reset Synced Data"),
					menu: {
						id: MenuId.ViewTitle,
						when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', view.id)),
					},
				});
			}
			async run(accessor: ServicesAccessor): Promise<void> {
317
				const dialogService = accessor.get(IDialogService);
318
				const userDataSyncWorkbenchService = accessor.get(IUserDataSyncWorkbenchService);
319 320 321 322 323 324 325
				const result = await dialogService.confirm({
					message: localize('reset', "This will clear your synced data from the cloud and stop sync on all your devices."),
					title: localize('reset title', "Reset Synced Data"),
					type: 'info',
					primaryButton: localize('reset button', "Reset"),
				});
				if (result.confirmed) {
326
					await userDataSyncWorkbenchService.turnoff(true);
327 328
					await view.refresh();
				}
S
#93960  
Sandeep Somavarapu 已提交
329 330 331
			}
		});
	}
332 333 334 335 336 337 338
}

interface SyncResourceTreeItem extends ITreeItem {
	resource: SyncResource;
	resourceHandle: ISyncResourceHandle;
}

339
abstract class UserDataSyncHistoryViewDataProvider implements ITreeViewDataProvider {
340

S
#93960  
Sandeep Somavarapu 已提交
341
	constructor(
S
Sandeep Somavarapu 已提交
342 343 344
		@IUserDataSyncService protected readonly userDataSyncService: IUserDataSyncService,
		@IUserDataSyncEnablementService private readonly userDataSyncEnablementService: IUserDataSyncEnablementService,
		@INotificationService private readonly notificationService: INotificationService,
S
#93960  
Sandeep Somavarapu 已提交
345
	) { }
346 347

	async getChildren(element?: ITreeItem): Promise<ITreeItem[]> {
S
Sandeep Somavarapu 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		try {
			if (!element) {
				return await this.getRoots();
			}
			const syncResource = ALL_SYNC_RESOURCES.filter(key => key === element.handle)[0] as SyncResource;
			if (syncResource) {
				return await this.getChildrenForSyncResource(syncResource);
			}
			if ((<SyncResourceTreeItem>element).resourceHandle) {
				return await this.getChildrenForSyncResourceTreeItem(<SyncResourceTreeItem>element);
			}
			return [];
		} catch (error) {
			this.notificationService.error(error);
			throw error;
363 364
		}
	}
365 366 367 368 369 370 371 372 373 374 375 376 377 378

	protected async getRoots(): Promise<ITreeItem[]> {
		return ALL_SYNC_RESOURCES.map(resourceKey => ({
			handle: resourceKey,
			collapsibleState: TreeItemCollapsibleState.Collapsed,
			label: { label: getSyncAreaLabel(resourceKey) },
			description: !this.userDataSyncEnablementService.isEnabled() || this.userDataSyncEnablementService.isResourceEnabled(resourceKey) ? undefined : localize('not syncing', "Not syncing"),
			themeIcon: FolderThemeIcon,
			contextValue: resourceKey
		}));
	}

	protected async getChildrenForSyncResource(syncResource: SyncResource): Promise<ITreeItem[]> {
		const refHandles = await this.getSyncResourceHandles(syncResource);
S
Sandeep Somavarapu 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
		if (refHandles.length) {
			return refHandles.map(({ uri, created }) => {
				const handle = JSON.stringify({ resource: uri.toString(), syncResource });
				return <SyncResourceTreeItem>{
					handle,
					collapsibleState: TreeItemCollapsibleState.Collapsed,
					label: { label: label(new Date(created)) },
					description: fromNow(created, true),
					resourceUri: uri,
					resource: syncResource,
					resourceHandle: { uri, created },
					contextValue: `sync-resource-${syncResource}`
				};
			});
		} else {
			return [{
				handle: generateUuid(),
				collapsibleState: TreeItemCollapsibleState.None,
				label: { label: localize('no data', "No Data") },
			}];
		}
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
	}

	protected async getChildrenForSyncResourceTreeItem(element: SyncResourceTreeItem): Promise<ITreeItem[]> {
		const associatedResources = await this.userDataSyncService.getAssociatedResources((<SyncResourceTreeItem>element).resource, (<SyncResourceTreeItem>element).resourceHandle);
		return associatedResources.map(({ resource, comparableResource }) => {
			const handle = JSON.stringify({ resource: resource.toString(), comparableResource: comparableResource?.toString() });
			return {
				handle,
				collapsibleState: TreeItemCollapsibleState.None,
				resourceUri: resource,
				command: { id: `workbench.actions.sync.commpareWithLocal`, title: '', arguments: [<TreeViewItemHandleArg>{ $treeViewId: '', $treeItemHandle: handle }] },
				contextValue: `sync-associatedResource-${(<SyncResourceTreeItem>element).resource}`
			};
		});
	}

	protected abstract getSyncResourceHandles(syncResource: SyncResource): Promise<ISyncResourceHandle[]>;
}

class LocalUserDataSyncHistoryViewDataProvider extends UserDataSyncHistoryViewDataProvider {

	protected getSyncResourceHandles(syncResource: SyncResource): Promise<ISyncResourceHandle[]> {
		return this.userDataSyncService.getLocalSyncResourceHandles(syncResource);
	}
}

class RemoteUserDataSyncHistoryViewDataProvider extends UserDataSyncHistoryViewDataProvider {

	private machinesPromise: Promise<IUserDataSyncMachine[]> | undefined;

	constructor(
S
Sandeep Somavarapu 已提交
431 432 433 434
		@IUserDataSyncService userDataSyncService: IUserDataSyncService,
		@IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
		@IUserDataSyncMachinesService private readonly userDataSyncMachinesService: IUserDataSyncMachinesService,
		@INotificationService notificationService: INotificationService,
435
	) {
S
Sandeep Somavarapu 已提交
436
		super(userDataSyncService, userDataSyncEnablementService, notificationService);
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
	}

	async getChildren(element?: ITreeItem): Promise<ITreeItem[]> {
		if (!element) {
			this.machinesPromise = undefined;
		}
		return super.getChildren(element);
	}

	private getMachines(): Promise<IUserDataSyncMachine[]> {
		if (this.machinesPromise === undefined) {
			this.machinesPromise = this.userDataSyncMachinesService.getMachines();
		}
		return this.machinesPromise;
	}

	protected getSyncResourceHandles(syncResource: SyncResource): Promise<ISyncResourceHandle[]> {
		return this.userDataSyncService.getRemoteSyncResourceHandles(syncResource);
	}

	protected async getChildrenForSyncResourceTreeItem(element: SyncResourceTreeItem): Promise<ITreeItem[]> {
		const children = await super.getChildrenForSyncResourceTreeItem(element);
		const machineId = await this.userDataSyncService.getMachineId(element.resource, element.resourceHandle);
		if (machineId) {
			const machines = await this.getMachines();
			const machine = machines.find(({ id }) => id === machineId);
			children.push({
				handle: machineId,
				label: { label: machine?.name || machineId },
				collapsibleState: TreeItemCollapsibleState.None,
				themeIcon: Codicon.vm,
			});
		}
		return children;
	}
472 473
}

S
Sandeep Somavarapu 已提交
474 475
class UserDataSyncMachinesViewDataProvider implements ITreeViewDataProvider {

S
Sandeep Somavarapu 已提交
476 477
	private machinesPromise: Promise<IUserDataSyncMachine[]> | undefined;

S
Sandeep Somavarapu 已提交
478 479
	constructor(
		private readonly treeView: TreeView,
S
Sandeep Somavarapu 已提交
480 481
		@IUserDataSyncMachinesService private readonly userDataSyncMachinesService: IUserDataSyncMachinesService,
		@IQuickInputService private readonly quickInputService: IQuickInputService,
S
Sandeep Somavarapu 已提交
482
		@INotificationService private readonly notificationService: INotificationService,
S
Sandeep Somavarapu 已提交
483 484 485 486
		@IDialogService private readonly dialogService: IDialogService,
		@IUserDataSyncWorkbenchService private readonly userDataSyncWorkbenchService: IUserDataSyncWorkbenchService,
	) {
	}
S
Sandeep Somavarapu 已提交
487

S
Sandeep Somavarapu 已提交
488 489 490 491
	async getChildren(element?: ITreeItem): Promise<ITreeItem[]> {
		if (!element) {
			this.machinesPromise = undefined;
		}
S
Sandeep Somavarapu 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504
		try {
			let machines = await this.getMachines();
			machines = machines.filter(m => !m.disabled).sort((m1, m2) => m1.isCurrent ? -1 : 1);
			this.treeView.message = machines.length ? undefined : localize('no machines', "No Machines");
			return machines.map(({ id, name, isCurrent }) => ({
				handle: id,
				collapsibleState: TreeItemCollapsibleState.None,
				label: { label: name },
				description: isCurrent ? localize({ key: 'current', comment: ['Current machine'] }, "Current") : undefined,
				themeIcon: Codicon.vm,
				contextValue: 'sync-machine'
			}));
		} catch (error) {
S
Sandeep Somavarapu 已提交
505
			this.notificationService.error(error);
S
Sandeep Somavarapu 已提交
506 507
			return [];
		}
S
Sandeep Somavarapu 已提交
508
	}
S
Sandeep Somavarapu 已提交
509 510 511 512 513 514 515 516

	private getMachines(): Promise<IUserDataSyncMachine[]> {
		if (this.machinesPromise === undefined) {
			this.machinesPromise = this.userDataSyncMachinesService.getMachines();
		}
		return this.machinesPromise;
	}

S
Sandeep Somavarapu 已提交
517 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
	async disable(machineId: string): Promise<boolean> {
		const machines = await this.getMachines();
		const machine = machines.find(({ id }) => id === machineId);
		if (!machine) {
			throw new Error(localize('not found', "machine not found with id: {0}", machineId));
		}

		const result = await this.dialogService.confirm({
			type: 'info',
			message: localize('turn off sync on machine', "Are you sure you want to turn off sync on {0}?", machine.name),
			primaryButton: localize('turn off', "Turn off"),
		});

		if (!result.confirmed) {
			return false;
		}

		if (machine.isCurrent) {
			await this.userDataSyncWorkbenchService.turnoff(false);
		} else {
			await this.userDataSyncMachinesService.disableMachine(machineId);
		}

		return true;
	}

S
Sandeep Somavarapu 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
	async rename(machineId: string): Promise<boolean> {
		const disposableStore = new DisposableStore();
		const inputBox = disposableStore.add(this.quickInputService.createInputBox());
		inputBox.placeholder = localize('placeholder', "Enter the name of the machine");
		inputBox.busy = true;
		inputBox.show();
		const machines = await this.getMachines();
		const machine = machines.find(({ id }) => id === machineId);
		if (!machine) {
			inputBox.hide();
			disposableStore.dispose();
			throw new Error(localize('not found', "machine not found with id: {0}", machineId));
		}
		inputBox.busy = false;
		inputBox.value = machine.name;
		const validateMachineName = (machineName: string): string | null => {
			machineName = machineName.trim();
			return machineName && !machines.some(m => m.id !== machineId && m.name === machineName) ? machineName : null;
		};
		disposableStore.add(inputBox.onDidChangeValue(() =>
			inputBox.validationMessage = validateMachineName(inputBox.value) ? '' : localize('valid message', "Machine name should be unique and not empty")));
		return new Promise<boolean>((c, e) => {
			disposableStore.add(inputBox.onDidAccept(async () => {
				const machineName = validateMachineName(inputBox.value);
				disposableStore.dispose();
				if (machineName && machineName !== machine.name) {
					try {
						await this.userDataSyncMachinesService.renameMachine(machineId, machineName);
						c(true);
					} catch (error) {
						e(error);
					}
				} else {
					c(false);
				}
			}));
		});
	}
S
Sandeep Somavarapu 已提交
581 582
}

583 584 585 586 587 588
function label(date: Date): string {
	return date.toLocaleDateString() +
		' ' + pad(date.getHours(), 2) +
		':' + pad(date.getMinutes(), 2) +
		':' + pad(date.getSeconds(), 2);
}