progressService.ts 17.5 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6 7 8
import 'vs/css!./media/progressService';

import { localize } from 'vs/nls';
9
import { IDisposable, dispose, DisposableStore, Disposable, toDisposable } from 'vs/base/common/lifecycle';
10
import { IProgressService, IProgressOptions, IProgressStep, ProgressLocation, IProgress, Progress, IProgressCompositeOptions, IProgressNotificationOptions, IProgressRunner, IProgressIndicator, IProgressWindowOptions } from 'vs/platform/progress/common/progress';
B
Benjamin Pasero 已提交
11
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
12
import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/common/statusbar';
13 14
import { timeout } from 'vs/base/common/async';
import { ProgressBadge, IActivityService } from 'vs/workbench/services/activity/common/activity';
15
import { INotificationService, Severity, INotificationHandle } from 'vs/platform/notification/common/notification';
16
import { Action } from 'vs/base/common/actions';
17
import { Event, Emitter } from 'vs/base/common/event';
18 19 20 21 22 23 24 25
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { ILayoutService } from 'vs/platform/layout/browser/layoutService';
import { Dialog } from 'vs/base/browser/ui/dialog/dialog';
import { attachDialogStyler } from 'vs/platform/theme/common/styler';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { EventHelper } from 'vs/base/browser/dom';
B
Benjamin Pasero 已提交
26
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
27
import { parseLinkedText } from 'vs/base/common/linkedText';
28

29
export class ProgressService extends Disposable implements IProgressService {
30

31
	_serviceBrand: undefined;
32

33
	constructor(
34 35 36 37 38 39 40 41 42 43
		@IActivityService private readonly activityService: IActivityService,
		@IViewletService private readonly viewletService: IViewletService,
		@IPanelService private readonly panelService: IPanelService,
		@INotificationService private readonly notificationService: INotificationService,
		@IStatusbarService private readonly statusbarService: IStatusbarService,
		@ILayoutService private readonly layoutService: ILayoutService,
		@IThemeService private readonly themeService: IThemeService,
		@IKeybindingService private readonly keybindingService: IKeybindingService
	) {
		super();
44 45
	}

46
	async withProgress<R = unknown>(options: IProgressOptions, task: (progress: IProgress<IProgressStep>) => Promise<R>, onDidCancel?: (choice?: number) => void): Promise<R> {
47 48
		const { location } = options;
		if (typeof location === 'string') {
49 50
			if (this.viewletService.getProgressIndicator(location)) {
				return this.withViewletProgress(location, task, { ...options, location });
51
			}
52

53 54
			if (this.panelService.getProgressIndicator(location)) {
				return this.withPanelProgress(location, task, { ...options, location });
B
Benjamin Pasero 已提交
55 56
			}

57
			throw new Error(`Bad progress location: ${location}`);
58
		}
59

60 61
		switch (location) {
			case ProgressLocation.Notification:
62
				return this.withNotificationProgress({ ...options, location }, task, onDidCancel);
63
			case ProgressLocation.Window:
64
				return this.withWindowProgress({ ...options, location }, task);
65
			case ProgressLocation.Explorer:
66
				return this.withViewletProgress('workbench.view.explorer', task, { ...options, location });
67
			case ProgressLocation.Scm:
68
				return this.withViewletProgress('workbench.view.scm', task, { ...options, location });
69
			case ProgressLocation.Extensions:
70
				return this.withViewletProgress('workbench.view.extensions', task, { ...options, location });
71
			case ProgressLocation.Dialog:
72
				return this.withDialogProgress(options, task, onDidCancel);
73
			default:
74
				throw new Error(`Bad progress location: ${location}`);
75
		}
76 77
	}

78 79 80
	private readonly windowProgressStack: [IProgressOptions, Progress<IProgressStep>][] = [];
	private windowProgressStatusEntry: IStatusbarEntryAccessor | undefined = undefined;

81 82
	private withWindowProgress<R = unknown>(options: IProgressWindowOptions, callback: (progress: IProgress<{ message?: string }>) => Promise<R>): Promise<R> {
		const task: [IProgressWindowOptions, Progress<IProgressStep>] = [options, new Progress<IProgressStep>(() => this.updateWindowProgress())];
83 84 85 86 87

		const promise = callback(task[1]);

		let delayHandle: any = setTimeout(() => {
			delayHandle = undefined;
88
			this.windowProgressStack.unshift(task);
89
			this.updateWindowProgress();
90 91 92 93 94 95

			// show progress for at least 150ms
			Promise.all([
				timeout(150),
				promise
			]).finally(() => {
96 97
				const idx = this.windowProgressStack.indexOf(task);
				this.windowProgressStack.splice(idx, 1);
98
				this.updateWindowProgress();
99 100 101 102 103 104
			});
		}, 150);

		// cancel delay if promise finishes below 150ms
		return promise.finally(() => clearTimeout(delayHandle));
	}
105

106
	private updateWindowProgress(idx: number = 0) {
107

108 109 110
		// We still have progress to show
		if (idx < this.windowProgressStack.length) {
			const [options, progress] = this.windowProgressStack[idx];
111

112 113
			let progressTitle = options.title;
			let progressMessage = progress.value && progress.value.message;
114
			let progressCommand = (<IProgressWindowOptions>options).command;
115 116
			let text: string;
			let title: string;
E
Erich Gamma 已提交
117

118 119 120 121
			if (progressTitle && progressMessage) {
				// <title>: <message>
				text = localize('progress.text2', "{0}: {1}", progressTitle, progressMessage);
				title = options.source ? localize('progress.title3', "[{0}] {1}: {2}", options.source, progressTitle, progressMessage) : text;
E
Erich Gamma 已提交
122

123 124 125 126
			} else if (progressTitle) {
				// <title>
				text = progressTitle;
				title = options.source ? localize('progress.title2', "[{0}]: {1}", options.source, progressTitle) : text;
E
Erich Gamma 已提交
127

128 129 130 131
			} else if (progressMessage) {
				// <message>
				text = progressMessage;
				title = options.source ? localize('progress.title2', "[{0}]: {1}", options.source, progressMessage) : text;
E
Erich Gamma 已提交
132

133 134
			} else {
				// no title, no message -> no progress. try with next on stack
135
				this.updateWindowProgress(idx + 1);
136
				return;
137 138
			}

139
			const statusEntryProperties: IStatusbarEntry = {
140
				text: `$(sync~spin) ${text}`,
141 142
				tooltip: title,
				command: progressCommand
143 144 145 146 147 148 149 150 151 152 153 154 155
			};

			if (this.windowProgressStatusEntry) {
				this.windowProgressStatusEntry.update(statusEntryProperties);
			} else {
				this.windowProgressStatusEntry = this.statusbarService.addEntry(statusEntryProperties, 'status.progress', localize('status.progress', "Progress Message"), StatusbarAlignment.LEFT);
			}
		}

		// Progress is done so we remove the status entry
		else {
			this.windowProgressStatusEntry?.dispose();
			this.windowProgressStatusEntry = undefined;
E
Erich Gamma 已提交
156
		}
157
	}
E
Erich Gamma 已提交
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	private withNotificationProgress<P extends Promise<R>, R = unknown>(options: IProgressNotificationOptions, callback: (progress: IProgress<IProgressStep>) => P, onDidCancel?: (choice?: number) => void): P {

		const progressStateModel = new class extends Disposable {

			private readonly _onDidReport = this._register(new Emitter<IProgressStep>());
			readonly onDidReport = this._onDidReport.event;

			private readonly _onDispose = this._register(new Emitter<void>());
			readonly onDispose = this._onDispose.event;

			private _step: IProgressStep | undefined = undefined;
			get step() { return this._step; }

			private _done = false;
			get done() { return this._done; }

			readonly promise: P;

			constructor() {
				super();

				this.promise = callback(this);

				this.promise.finally(() => {
					this.dispose();
				});
			}

			report(step: IProgressStep): void {
				this._step = step;

				this._onDidReport.fire(step);
			}

			cancel(choice?: number): void {
				onDidCancel?.(choice);

				this.dispose();
			}

			dispose(): void {
				this._done = true;
				this._onDispose.fire();

				super.dispose();
			}
		};

207 208 209 210 211 212 213 214 215
		const createWindowProgress = () => {

			// Create a promise that we can resolve as needed
			// when the outside calls dispose on us
			let promiseResolve: () => void;
			const promise = new Promise<R>(resolve => promiseResolve = resolve);

			this.withWindowProgress<R>({
				location: ProgressLocation.Window,
216
				title: options.title ? parseLinkedText(options.title).toString() : undefined, // convert markdown links => string
217 218 219
				command: 'notifications.showList'
			}, progress => {

220 221 222 223 224 225 226 227
				function reportProgress(step: IProgressStep) {
					if (step.message) {
						progress.report({
							message: parseLinkedText(step.message).toString()  // convert markdown links => string
						});
					}
				}

228 229
				// Apply any progress that was made already
				if (progressStateModel.step) {
230
					reportProgress(progressStateModel.step);
231 232 233
				}

				// Continue to report progress as it happens
234
				const onDidReportListener = progressStateModel.onDidReport(step => reportProgress(step));
235 236 237 238 239 240 241 242 243 244 245 246
				promise.finally(() => onDidReportListener.dispose());

				// When the progress model gets disposed, we are done as well
				Event.once(progressStateModel.onDispose)(() => promiseResolve());

				return promise;
			});

			// Dispose means completing our promise
			return toDisposable(() => promiseResolve());
		};

247
		const createNotification = (message: string, increment?: number): INotificationHandle => {
248
			const notificationDisposables = new DisposableStore();
E
Erich Gamma 已提交
249

250 251
			const primaryActions = options.primaryActions ? Array.from(options.primaryActions) : [];
			const secondaryActions = options.secondaryActions ? Array.from(options.secondaryActions) : [];
S
SteVen Batten 已提交
252 253 254 255 256 257 258 259

			if (options.buttons) {
				options.buttons.forEach((button, index) => {
					const buttonAction = new class extends Action {
						constructor() {
							super(`progress.button.${button}`, button, undefined, true);
						}

260
						async run(): Promise<void> {
261
							progressStateModel.cancel(index);
S
SteVen Batten 已提交
262 263
						}
					};
264
					notificationDisposables.add(buttonAction);
S
SteVen Batten 已提交
265 266 267 268 269

					primaryActions.push(buttonAction);
				});
			}

270 271 272 273 274
			if (options.cancellable) {
				const cancelAction = new class extends Action {
					constructor() {
						super('progress.cancel', localize('cancel', "Cancel"), undefined, true);
					}
275

276
					async run(): Promise<void> {
277
						progressStateModel.cancel();
278 279
					}
				};
280
				notificationDisposables.add(cancelAction);
E
Erich Gamma 已提交
281

282
				primaryActions.push(cancelAction);
E
Erich Gamma 已提交
283 284
			}

285
			const notification = this.notificationService.notify({
286 287 288
				severity: Severity.Info,
				message,
				source: options.source,
289 290
				actions: { primary: primaryActions, secondary: secondaryActions },
				progress: typeof increment === 'number' && increment >= 0 ? { total: 100, worked: increment } : { infinite: true }
291
			});
E
Erich Gamma 已提交
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
			// Switch to window based progress once the notification
			// changes visibility to hidden and is still ongoing.
			// Remove that window based progress once the notification
			// shows again.
			let windowProgressDisposable: IDisposable | undefined = undefined;
			notificationDisposables.add(notification.onDidChangeVisibility(visible => {

				// Clear any previous running window progress
				dispose(windowProgressDisposable);

				// Create new window progress if notification got hidden
				if (!visible && !progressStateModel.done) {
					windowProgressDisposable = createWindowProgress();
				}
			}));
E
Erich Gamma 已提交
308

309
			// Clear upon dispose
310
			Event.once(notification.onDidClose)(() => notificationDisposables.dispose());
E
Erich Gamma 已提交
311

312
			return notification;
313
		};
E
Erich Gamma 已提交
314

315 316 317 318 319 320 321 322
		const updateProgress = (notification: INotificationHandle, increment?: number): void => {
			if (typeof increment === 'number' && increment >= 0) {
				notification.progress.total(100); // always percentage based
				notification.progress.worked(increment);
			} else {
				notification.progress.infinite();
			}
		};
E
Erich Gamma 已提交
323

324 325
		let notificationHandle: INotificationHandle | undefined;
		let notificationTimeout: any | undefined;
326 327
		let titleAndMessage: string | undefined; // hoisted to make sure a delayed notification shows the most recent message

328
		const updateNotification = (step?: IProgressStep): void => {
329 330

			// full message (inital or update)
331 332
			if (step?.message && options.title) {
				titleAndMessage = `${options.title}: ${step.message}`; // always prefix with overall title if we have it (https://github.com/Microsoft/vscode/issues/50932)
333
			} else {
334
				titleAndMessage = options.title || step?.message;
335
			}
E
Erich Gamma 已提交
336

337 338
			if (!notificationHandle && titleAndMessage) {

339 340
				// create notification now or after a delay
				if (typeof options.delay === 'number' && options.delay > 0) {
341 342
					if (typeof notificationTimeout !== 'number') {
						notificationTimeout = setTimeout(() => notificationHandle = createNotification(titleAndMessage!, step?.increment), options.delay);
343 344
					}
				} else {
345
					notificationHandle = createNotification(titleAndMessage, step?.increment);
E
Erich Gamma 已提交
346
				}
347
			}
E
Erich Gamma 已提交
348

349
			if (notificationHandle) {
350
				if (titleAndMessage) {
351
					notificationHandle.updateMessage(titleAndMessage);
352
				}
353 354 355

				if (typeof step?.increment === 'number') {
					updateProgress(notificationHandle, step.increment);
E
Erich Gamma 已提交
356 357 358
				}
			}
		};
359

360
		// Show initially
361 362 363
		updateNotification(progressStateModel.step);
		const listener = progressStateModel.onDidReport(step => updateNotification(step));
		Event.once(progressStateModel.onDispose)(() => listener.dispose());
E
Erich Gamma 已提交
364

365
		// Show progress for at least 800ms and then hide once done or canceled
366 367 368
		Promise.all([timeout(800), progressStateModel.promise]).finally(() => {
			clearTimeout(notificationTimeout);
			notificationHandle?.close();
369
		});
E
Erich Gamma 已提交
370

371
		return progressStateModel.promise;
372
	}
E
Erich Gamma 已提交
373

374
	private withViewletProgress<P extends Promise<R>, R = unknown>(viewletId: string, task: (progress: IProgress<IProgressStep>) => P, options: IProgressCompositeOptions): P {
E
Erich Gamma 已提交
375

376
		// show in viewlet
377
		const promise = this.withCompositeProgress(this.viewletService.getProgressIndicator(viewletId), task, options);
E
Erich Gamma 已提交
378

379 380 381 382 383
		// show activity bar
		let activityProgress: IDisposable;
		let delayHandle: any = setTimeout(() => {
			delayHandle = undefined;

384
			const handle = this.activityService.showActivity(
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
				viewletId,
				new ProgressBadge(() => ''),
				'progress-badge',
				100
			);

			const startTimeVisible = Date.now();
			const minTimeVisible = 300;
			activityProgress = {
				dispose() {
					const d = Date.now() - startTimeVisible;
					if (d < minTimeVisible) {
						// should at least show for Nms
						setTimeout(() => handle.dispose(), minTimeVisible - d);
					} else {
						// shown long enough
						handle.dispose();
					}
403
				}
404 405
			};
		}, options.delay || 300);
E
Erich Gamma 已提交
406

407 408 409 410
		promise.finally(() => {
			clearTimeout(delayHandle);
			dispose(activityProgress);
		});
E
Erich Gamma 已提交
411

412
		return promise;
E
Erich Gamma 已提交
413
	}
414

415
	private withPanelProgress<P extends Promise<R>, R = unknown>(panelid: string, task: (progress: IProgress<IProgressStep>) => P, options: IProgressCompositeOptions): P {
B
Benjamin Pasero 已提交
416 417

		// show in panel
418 419 420
		return this.withCompositeProgress(this.panelService.getProgressIndicator(panelid), task, options);
	}

B
Benjamin Pasero 已提交
421
	private withCompositeProgress<P extends Promise<R>, R = unknown>(progressIndicator: IProgressIndicator | undefined, task: (progress: IProgress<IProgressStep>) => P, options: IProgressCompositeOptions): P {
422 423 424 425 426 427 428 429 430 431 432
		let progressRunner: IProgressRunner | undefined = undefined;

		const promise = task({
			report: progress => {
				if (!progressRunner) {
					return;
				}

				if (typeof progress.increment === 'number') {
					progressRunner.worked(progress.increment);
				}
B
Benjamin Pasero 已提交
433 434 435 436

				if (typeof progress.total === 'number') {
					progressRunner.total(progress.total);
				}
437 438 439
			}
		});

440
		if (progressIndicator) {
441
			if (typeof options.total === 'number') {
442
				progressRunner = progressIndicator.show(options.total, options.delay);
B
Benjamin Pasero 已提交
443
				promise.catch(() => undefined /* ignore */).finally(() => progressRunner ? progressRunner.done() : undefined);
444
			} else {
445
				progressIndicator.showWhile(promise, options.delay);
446
			}
B
Benjamin Pasero 已提交
447 448 449 450 451
		}

		return promise;
	}

S
SteVen Batten 已提交
452
	private withDialogProgress<P extends Promise<R>, R = unknown>(options: IProgressOptions, task: (progress: IProgress<IProgressStep>) => P, onDidCancel?: (choice?: number) => void): P {
453 454 455
		const disposables = new DisposableStore();
		const allowableCommands = [
			'workbench.action.quit',
S
SteVen Batten 已提交
456 457 458
			'workbench.action.reloadWindow',
			'copy',
			'cut'
459 460 461 462 463
		];

		let dialog: Dialog;

		const createDialog = (message: string) => {
S
SteVen Batten 已提交
464 465 466 467

			const buttons = options.buttons || [];
			buttons.push(options.cancellable ? localize('cancel', "Cancel") : localize('dismiss', "Dismiss"));

468
			dialog = new Dialog(
469
				this.layoutService.container,
470
				message,
S
SteVen Batten 已提交
471
				buttons,
472 473
				{
					type: 'pending',
S
SteVen Batten 已提交
474
					cancelId: buttons.length - 1,
475
					keyEventProcessor: (event: StandardKeyboardEvent) => {
476
						const resolved = this.keybindingService.softDispatch(event, this.layoutService.container);
B
Benjamin Pasero 已提交
477
						if (resolved?.commandId) {
478 479 480 481 482 483 484
							if (allowableCommands.indexOf(resolved.commandId) === -1) {
								EventHelper.stop(event, true);
							}
						}
					}
				}
			);
485

486
			disposables.add(dialog);
487
			disposables.add(attachDialogStyler(dialog, this.themeService));
488

S
SteVen Batten 已提交
489
			dialog.show().then((dialogResult) => {
490
				if (typeof onDidCancel === 'function') {
S
SteVen Batten 已提交
491
					onDidCancel(dialogResult.button);
492
				}
493

494 495
				dispose(dialog);
			});
496

497 498
			return dialog;
		};
499

500 501 502 503 504
		const updateDialog = (message?: string) => {
			if (message && !dialog) {
				dialog = createDialog(message);
			} else if (message) {
				dialog.updateMessage(message);
505 506 507
			}
		};

508 509 510 511 512
		const promise = task({
			report: progress => {
				updateDialog(progress.message);
			}
		});
513

514 515 516 517 518
		promise.finally(() => {
			dispose(disposables);
		});

		return promise;
519
	}
520
}
521 522

registerSingleton(IProgressService, ProgressService, true);