userDataSyncViews.ts 25.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*---------------------------------------------------------------------------------------------
 *  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';
10
import { TreeViewPane } from 'vs/workbench/browser/parts/views/treeView';
11
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
S
Sandeep Somavarapu 已提交
12
import { ALL_SYNC_RESOURCES, SyncResource, IUserDataSyncService, ISyncResourceHandle as IResourceHandle, SyncStatus, IUserDataSyncResourceEnablementService, IUserDataAutoSyncService } from 'vs/platform/userDataSync/common/userDataSync';
13
import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions';
14
import { ContextKeyExpr, ContextKeyEqualsExpr } 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
import { fromNow } from 'vs/base/common/date';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { Event } from 'vs/base/common/event';
S
Sandeep Somavarapu 已提交
21
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
S
#93960  
Sandeep Somavarapu 已提交
22 23 24 25 26 27 28 29 30 31 32
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 已提交
33
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';
34
import { IUserDataSyncMachinesService, IUserDataSyncMachine } from 'vs/platform/userDataSync/common/userDataSyncMachines';
S
Sandeep Somavarapu 已提交
35
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
S
Sandeep Somavarapu 已提交
36
import { INotificationService } from 'vs/platform/notification/common/notification';
37
import { TreeView } from 'vs/workbench/contrib/views/browser/treeView';
S
Sandeep Somavarapu 已提交
38
import { flatten } from 'vs/base/common/arrays';
39

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

S
#93960  
Sandeep Somavarapu 已提交
42 43
	constructor(
		containerId: string,
44 45
		@IDialogService private readonly dialogService: IDialogService,
		@IUserDataSyncWorkbenchService private readonly userDataSyncWorkbenchService: IUserDataSyncWorkbenchService,
S
#93960  
Sandeep Somavarapu 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
		@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)),
		];
	}

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	getSecondaryActions(): IAction[] {
		return [
			new Action('workbench.actions.syncData.reset', localize('workbench.actions.syncData.reset', "Reset Synced Data"), undefined, true, () => this.reset()),
		];
	}

	private async reset(): Promise<void> {
		const result = await this.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) {
			await this.userDataSyncWorkbenchService.turnoff(true);
		}
	}

S
#93960  
Sandeep Somavarapu 已提交
86 87 88
}

export class UserDataSyncDataViews extends Disposable {
89 90

	constructor(
S
#93960  
Sandeep Somavarapu 已提交
91
		container: ViewContainer,
92
		@IInstantiationService private readonly instantiationService: IInstantiationService,
93
		@IUserDataAutoSyncService private readonly userDataAutoSyncService: IUserDataAutoSyncService,
94
		@IUserDataSyncResourceEnablementService private readonly userDataSyncResourceEnablementService: IUserDataSyncResourceEnablementService,
95 96
	) {
		super();
S
#93960  
Sandeep Somavarapu 已提交
97
		this.registerViews(container);
98 99 100
	}

	private registerViews(container: ViewContainer): void {
101
		this.registerSyncedDataView(container);
S
Sandeep Somavarapu 已提交
102
		this.registerMachinesView(container);
103 104 105

		this.registerActivityView(container, true);
		this.registerActivityView(container, false);
106 107
	}

108 109 110
	private registerSyncedDataView(container: ViewContainer): void {
		const id = `workbench.views.syncedDataView`;
		const name = localize('remote title', "Synced Data");
111 112 113 114 115
		const treeView = this.instantiationService.createInstance(TreeView, id, name);
		treeView.showRefreshAction = true;
		const disposable = treeView.onDidChangeVisibility(visible => {
			if (visible && !treeView.dataProvider) {
				disposable.dispose();
116
				treeView.dataProvider = this.instantiationService.createInstance(SyncedDataViewDataProvider);
117 118
			}
		});
119
		this._register(Event.any(this.userDataSyncResourceEnablementService.onDidChangeResourceEnablement, this.userDataAutoSyncService.onDidChangeEnablement)(() => treeView.refresh()));
120 121 122 123 124
		const viewsRegistry = Registry.as<IViewsRegistry>(Extensions.ViewsRegistry);
		viewsRegistry.registerViews([<ITreeViewDescriptor>{
			id,
			name,
			ctorDescriptor: new SyncDescriptor(TreeViewPane),
125
			when: ContextKeyExpr.and(CONTEXT_SYNC_STATE.notEqualsTo(SyncStatus.Uninitialized), CONTEXT_ACCOUNT_STATE.isEqualTo(AccountStatus.Available), CONTEXT_ENABLE_VIEWS),
126
			canToggleVisibility: true,
127
			canMoveView: false,
128 129 130 131 132 133 134 135
			treeView,
			collapsed: false,
			order: 100,
		}], container);

		registerAction2(class extends Action2 {
			constructor() {
				super({
136 137
					id: SHOW_SYNCED_DATA_COMMAND_ID,
					title: { value: localize('workbench.action.showSyncRemoteBackup', "Show Synced Data"), original: `Show Synced Data` },
138 139 140 141 142 143 144 145 146 147
					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 已提交
148 149 150 151 152
				const commandService = accessor.get(ICommandService);

				await commandService.executeCommand(ENABLE_SYNC_VIEWS_COMMAND_ID);

				const viewContainer = viewDescriptorService.getViewContainerByViewId(id);
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
				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 已提交
169
		this.registerDataViewActions(id);
170 171
	}

S
Sandeep Somavarapu 已提交
172 173 174 175
	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 已提交
176
		const dataProvider = this.instantiationService.createInstance(UserDataSyncMachinesViewDataProvider, treeView);
S
Sandeep Somavarapu 已提交
177 178 179 180
		treeView.showRefreshAction = true;
		const disposable = treeView.onDidChangeVisibility(visible => {
			if (visible && !treeView.dataProvider) {
				disposable.dispose();
S
Sandeep Somavarapu 已提交
181
				treeView.dataProvider = dataProvider;
S
Sandeep Somavarapu 已提交
182 183
			}
		});
184
		this._register(Event.any(this.userDataSyncResourceEnablementService.onDidChangeResourceEnablement, this.userDataAutoSyncService.onDidChangeEnablement)(() => treeView.refresh()));
S
Sandeep Somavarapu 已提交
185 186 187 188 189 190 191
		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,
192
			canMoveView: false,
S
Sandeep Somavarapu 已提交
193 194 195 196 197 198 199 200
			treeView,
			collapsed: false,
			order: 200,
		}], container);

		registerAction2(class extends Action2 {
			constructor() {
				super({
S
Sandeep Somavarapu 已提交
201 202
					id: `workbench.actions.sync.editMachineName`,
					title: localize('workbench.actions.sync.editMachineName', "Edit Name"),
S
Sandeep Somavarapu 已提交
203 204 205
					icon: Codicon.edit,
					menu: {
						id: MenuId.ViewItemContext,
S
Sandeep Somavarapu 已提交
206
						when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', id)),
S
Sandeep Somavarapu 已提交
207 208 209 210 211
						group: 'inline',
					},
				});
			}
			async run(accessor: ServicesAccessor, handle: TreeViewItemHandleArg): Promise<void> {
S
Sandeep Somavarapu 已提交
212 213 214 215
				const changed = await dataProvider.rename(handle.$treeItemHandle);
				if (changed) {
					await treeView.refresh();
				}
S
Sandeep Somavarapu 已提交
216 217
			}
		});
S
Sandeep Somavarapu 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

		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 已提交
237 238
	}

239 240 241 242 243 244 245 246 247
	private registerActivityView(container: ViewContainer, remote: boolean): void {
		const id = `workbench.views.sync.${remote ? 'remote' : 'local'}Activity`;
		const name = remote ? localize('remote sync activity title', "Sync Activity (Remote)") : localize('local sync activity title', "Sync Activity (Local)");
		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 已提交
248 249
				treeView.dataProvider = remote ? this.instantiationService.createInstance(RemoteUserDataSyncActivityViewDataProvider)
					: this.instantiationService.createInstance(LocalUserDataSyncActivityViewDataProvider);
250 251 252 253 254 255 256 257 258 259 260 261 262 263
			}
		});
		this._register(Event.any(this.userDataSyncResourceEnablementService.onDidChangeResourceEnablement, this.userDataAutoSyncService.onDidChangeEnablement)(() => treeView.refresh()));
		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: false,
			treeView,
			collapsed: false,
			order: 300,
264
			hideByDefault: !remote,
265 266 267 268 269
		}], container);

		this.registerDataViewActions(id);
	}

S
Sandeep Somavarapu 已提交
270
	private registerDataViewActions(viewId: string) {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
		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`,
293
					title: localize('workbench.actions.sync.replaceCurrent', "Restore"),
294
					icon: { id: 'codicon/discard' },
295 296 297 298 299 300 301 302 303 304 305 306
					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({
307
					message: localize({ key: 'confirm replace', comment: ['A confirmation message to replace current user data (settings, extensions, keybindings, snippets) with selected version'] }, "Would you like to replace your current {0} with selected?", getSyncAreaLabel(syncResource)),
308 309 310 311 312 313 314 315 316 317 318 319
					type: 'info',
					title: localize('preferences sync', "Preferences Sync")
				});
				if (result.confirmed) {
					return userDataSyncService.replace(URI.parse(resource));
				}
			}
		});

		registerAction2(class extends Action2 {
			constructor() {
				super({
320 321
					id: `workbench.actions.sync.compareWithLocal`,
					title: localize({ key: 'workbench.actions.sync.compareWithLocal', comment: ['This is an action title to show the changes between local and remote version of resources'] }, "Open Changes"),
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
				});
			}
			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) });
				}
			}
		});
	}

343
}
S
#93960  
Sandeep Somavarapu 已提交
344

S
Sandeep Somavarapu 已提交
345 346
interface ISyncResourceHandle extends IResourceHandle {
	syncResource: SyncResource
347 348
}

S
Sandeep Somavarapu 已提交
349 350
interface SyncResourceHandleTreeItem extends ITreeItem {
	syncResourceHandle: ISyncResourceHandle;
351 352
}

S
Sandeep Somavarapu 已提交
353 354 355
abstract class UserDataSyncActivityViewDataProvider implements ITreeViewDataProvider {

	private syncResourceHandlesPromise: Promise<ISyncResourceHandle[]> | undefined;
356

S
#93960  
Sandeep Somavarapu 已提交
357
	constructor(
S
Sandeep Somavarapu 已提交
358
		@IUserDataSyncService protected readonly userDataSyncService: IUserDataSyncService,
359
		@IUserDataAutoSyncService protected readonly userDataAutoSyncService: IUserDataAutoSyncService,
S
Sandeep Somavarapu 已提交
360
		@INotificationService private readonly notificationService: INotificationService,
S
#93960  
Sandeep Somavarapu 已提交
361
	) { }
362 363

	async getChildren(element?: ITreeItem): Promise<ITreeItem[]> {
S
Sandeep Somavarapu 已提交
364 365 366 367
		try {
			if (!element) {
				return await this.getRoots();
			}
S
Sandeep Somavarapu 已提交
368 369
			if ((<SyncResourceHandleTreeItem>element).syncResourceHandle) {
				return await this.getChildrenForSyncResourceTreeItem(<SyncResourceHandleTreeItem>element);
S
Sandeep Somavarapu 已提交
370 371 372 373 374
			}
			return [];
		} catch (error) {
			this.notificationService.error(error);
			throw error;
375 376
		}
	}
377

S
Sandeep Somavarapu 已提交
378 379
	private async getRoots(): Promise<SyncResourceHandleTreeItem[]> {
		this.syncResourceHandlesPromise = undefined;
380

S
Sandeep Somavarapu 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394
		const syncResourceHandles = await this.getSyncResourceHandles();

		return syncResourceHandles.map(syncResourceHandle => {
			const handle = JSON.stringify({ resource: syncResourceHandle.uri.toString(), syncResource: syncResourceHandle.syncResource });
			return {
				handle,
				collapsibleState: TreeItemCollapsibleState.Collapsed,
				label: { label: getSyncAreaLabel(syncResourceHandle.syncResource) },
				description: fromNow(syncResourceHandle.created, true),
				themeIcon: FolderThemeIcon,
				syncResourceHandle,
				contextValue: `sync-resource-${syncResourceHandle.syncResource}`
			};
		});
395 396
	}

S
Sandeep Somavarapu 已提交
397 398
	protected async getChildrenForSyncResourceTreeItem(element: SyncResourceHandleTreeItem): Promise<ITreeItem[]> {
		const associatedResources = await this.userDataSyncService.getAssociatedResources((<SyncResourceHandleTreeItem>element).syncResourceHandle.syncResource, (<SyncResourceHandleTreeItem>element).syncResourceHandle);
399 400 401 402 403 404
		return associatedResources.map(({ resource, comparableResource }) => {
			const handle = JSON.stringify({ resource: resource.toString(), comparableResource: comparableResource?.toString() });
			return {
				handle,
				collapsibleState: TreeItemCollapsibleState.None,
				resourceUri: resource,
405
				command: { id: `workbench.actions.sync.compareWithLocal`, title: '', arguments: [<TreeViewItemHandleArg>{ $treeViewId: '', $treeItemHandle: handle }] },
S
Sandeep Somavarapu 已提交
406
				contextValue: `sync-associatedResource-${(<SyncResourceHandleTreeItem>element).syncResourceHandle.syncResource}`
407 408 409 410
			};
		});
	}

S
Sandeep Somavarapu 已提交
411 412 413 414 415 416 417 418 419 420 421
	private getSyncResourceHandles(): Promise<ISyncResourceHandle[]> {
		if (this.syncResourceHandlesPromise === undefined) {
			this.syncResourceHandlesPromise = Promise.all(ALL_SYNC_RESOURCES.map(async syncResource => {
				const resourceHandles = await this.getResourceHandles(syncResource);
				return resourceHandles.map(resourceHandle => ({ ...resourceHandle, syncResource }));
			})).then(result => flatten(result).sort((a, b) => b.created - a.created));
		}
		return this.syncResourceHandlesPromise;
	}

	protected abstract getResourceHandles(syncResource: SyncResource): Promise<IResourceHandle[]>;
422 423
}

S
Sandeep Somavarapu 已提交
424
class LocalUserDataSyncActivityViewDataProvider extends UserDataSyncActivityViewDataProvider {
425

S
Sandeep Somavarapu 已提交
426
	protected getResourceHandles(syncResource: SyncResource): Promise<IResourceHandle[]> {
427 428 429 430
		return this.userDataSyncService.getLocalSyncResourceHandles(syncResource);
	}
}

S
Sandeep Somavarapu 已提交
431
class RemoteUserDataSyncActivityViewDataProvider extends UserDataSyncActivityViewDataProvider {
432 433 434 435

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

	constructor(
S
Sandeep Somavarapu 已提交
436
		@IUserDataSyncService userDataSyncService: IUserDataSyncService,
437
		@IUserDataAutoSyncService userDataAutoSyncService: IUserDataAutoSyncService,
S
Sandeep Somavarapu 已提交
438 439
		@IUserDataSyncMachinesService private readonly userDataSyncMachinesService: IUserDataSyncMachinesService,
		@INotificationService notificationService: INotificationService,
440
	) {
S
Sandeep Somavarapu 已提交
441
		super(userDataSyncService, userDataAutoSyncService, notificationService);
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
	}

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

S
Sandeep Somavarapu 已提交
458
	protected getResourceHandles(syncResource: SyncResource): Promise<IResourceHandle[]> {
459 460 461
		return this.userDataSyncService.getRemoteSyncResourceHandles(syncResource);
	}

S
Sandeep Somavarapu 已提交
462
	protected async getChildrenForSyncResourceTreeItem(element: SyncResourceHandleTreeItem): Promise<ITreeItem[]> {
463
		const children = await super.getChildrenForSyncResourceTreeItem(element);
S
Sandeep Somavarapu 已提交
464
		const machineId = await this.userDataSyncService.getMachineId(element.syncResourceHandle.syncResource, element.syncResourceHandle);
465 466 467
		if (machineId) {
			const machines = await this.getMachines();
			const machine = machines.find(({ id }) => id === machineId);
468
			children[0].description = machine?.isCurrent ? localize({ key: 'current', comment: ['Represents current machine'] }, "Current") : machine?.name;
469 470 471
		}
		return children;
	}
472 473
}

S
Sandeep Somavarapu 已提交
474 475 476 477 478 479 480 481
class SyncedDataViewDataProvider extends RemoteUserDataSyncActivityViewDataProvider {

	protected async getResourceHandles(syncResource: SyncResource): Promise<IResourceHandle[]> {
		const resourceHandles = await this.userDataSyncService.getRemoteSyncResourceHandles(syncResource);
		return resourceHandles.length ? [resourceHandles[0]] : [];
	}
}

S
Sandeep Somavarapu 已提交
482 483
class UserDataSyncMachinesViewDataProvider implements ITreeViewDataProvider {

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

S
Sandeep Somavarapu 已提交
486 487
	constructor(
		private readonly treeView: TreeView,
S
Sandeep Somavarapu 已提交
488 489
		@IUserDataSyncMachinesService private readonly userDataSyncMachinesService: IUserDataSyncMachinesService,
		@IQuickInputService private readonly quickInputService: IQuickInputService,
S
Sandeep Somavarapu 已提交
490
		@INotificationService private readonly notificationService: INotificationService,
S
Sandeep Somavarapu 已提交
491 492 493 494
		@IDialogService private readonly dialogService: IDialogService,
		@IUserDataSyncWorkbenchService private readonly userDataSyncWorkbenchService: IUserDataSyncWorkbenchService,
	) {
	}
S
Sandeep Somavarapu 已提交
495

S
Sandeep Somavarapu 已提交
496 497 498 499
	async getChildren(element?: ITreeItem): Promise<ITreeItem[]> {
		if (!element) {
			this.machinesPromise = undefined;
		}
S
Sandeep Somavarapu 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512
		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 已提交
513
			this.notificationService.error(error);
S
Sandeep Somavarapu 已提交
514 515
			return [];
		}
S
Sandeep Somavarapu 已提交
516
	}
S
Sandeep Somavarapu 已提交
517 518 519 520 521 522 523 524

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

S
Sandeep Somavarapu 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
	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 {
545
			await this.userDataSyncMachinesService.setEnablement(machineId, false);
S
Sandeep Somavarapu 已提交
546 547 548 549 550
		}

		return true;
	}

S
Sandeep Somavarapu 已提交
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 581 582 583 584 585 586 587 588
	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 已提交
589
}