codelensController.ts 16.4 KB
Newer Older
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.
 *--------------------------------------------------------------------------------------------*/

G
Gustavo Sampaio 已提交
6
import { CancelablePromise, RunOnceScheduler, createCancelablePromise, disposableTimeout } from 'vs/base/common/async';
7
import { onUnexpectedError, onUnexpectedExternalError } from 'vs/base/common/errors';
G
Gustavo Sampaio 已提交
8
import { toDisposable, DisposableStore, dispose } from 'vs/base/common/lifecycle';
9
import { StableEditorScrollState } from 'vs/editor/browser/core/editorState';
G
Gustavo Sampaio 已提交
10 11
import { ICodeEditor, MouseTargetType, IViewZoneChangeAccessor, IActiveCodeEditor } from 'vs/editor/browser/editorBrowser';
import { registerEditorContribution, EditorCommand, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
A
Alexandru Dima 已提交
12
import { IEditorContribution } from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
13
import { IModelDecorationsChangeAccessor } from 'vs/editor/common/model';
G
Gustavo Sampaio 已提交
14 15 16
import { CodeLensProviderRegistry, CodeLens } from 'vs/editor/common/modes';
import { CodeLensModel, getCodeLensData, CodeLensItem } from 'vs/editor/contrib/codelens/codelens';
import { CodeLensWidget, CodeLensHelper } from 'vs/editor/contrib/codelens/codelensWidget';
17
import { ICommandService } from 'vs/platform/commands/common/commands';
18
import { INotificationService } from 'vs/platform/notification/common/notification';
G
Gustavo Sampaio 已提交
19 20 21 22
import { ICodeLensCache } from 'vs/editor/contrib/codelens/codeLensCache';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import * as dom from 'vs/base/browser/dom';
import { hash } from 'vs/base/common/hash';
23
import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
24

A
Alexandru Dima 已提交
25
export class CodeLensContribution implements IEditorContribution {
26

27
	public static readonly ID: string = 'css.editor.codeLens';
28 29 30

	private _isEnabled: boolean;

31 32
	private readonly _globalToDispose = new DisposableStore();
	private readonly _localToDispose = new DisposableStore();
33 34
	private readonly _styleElement: HTMLStyleElement;
	private readonly _styleClassName: string;
J
Johannes Rieken 已提交
35 36
	private _lenses: CodeLensWidget[] = [];
	private _currentFindCodeLensSymbolsPromise: CancelablePromise<CodeLensModel> | undefined;
37 38
	private _oldCodeLensModels = new DisposableStore();
	private _currentCodeLensModel: CodeLensModel | undefined;
J
Johannes Rieken 已提交
39 40
	private _modelChangeCounter: number = 0;
	private _currentResolveCodeLensSymbolsPromise: CancelablePromise<any> | undefined;
J
Johannes Rieken 已提交
41
	private _detectVisibleLenses: RunOnceScheduler | undefined;
42 43

	constructor(
A
Alexandru Dima 已提交
44
		private readonly _editor: ICodeEditor,
45
		@ICommandService private readonly _commandService: ICommandService,
J
Johannes Rieken 已提交
46 47
		@INotificationService private readonly _notificationService: INotificationService,
		@ICodeLensCache private readonly _codeLensCache: ICodeLensCache
48
	) {
A
Alex Dima 已提交
49
		this._isEnabled = this._editor.getOption(EditorOption.codeLens);
50

51 52
		this._globalToDispose.add(this._editor.onDidChangeModel(() => this._onModelChange()));
		this._globalToDispose.add(this._editor.onDidChangeModelLanguage(() => this._onModelChange()));
J
Johannes Rieken 已提交
53 54
		this._globalToDispose.add(this._editor.onDidChangeConfiguration(() => {
			const prevIsEnabled = this._isEnabled;
A
Alex Dima 已提交
55
			this._isEnabled = this._editor.getOption(EditorOption.codeLens);
56
			if (prevIsEnabled !== this._isEnabled) {
57
				this._onModelChange();
58 59
			}
		}));
60
		this._globalToDispose.add(CodeLensProviderRegistry.onDidChange(this._onModelChange, this));
61 62 63 64 65
		this._globalToDispose.add(this._editor.onDidChangeConfiguration(e => {
			if (e.hasChanged(EditorOption.fontInfo)) {
				this._updateLensStyle();
			}
		}));
66
		this._onModelChange();
67 68

		this._styleClassName = hash(this._editor.getId()).toString(16);
69 70 71
		this._styleElement = dom.createStyleSheet(
			dom.isInShadowDOM(this._editor.getContainerDomNode())
				? this._editor.getContainerDomNode()
A
Alex Dima 已提交
72
				: undefined
73
		);
74
		this._updateLensStyle();
75 76
	}

77 78
	dispose(): void {
		this._localDispose();
79
		this._globalToDispose.dispose();
80 81
		this._oldCodeLensModels.dispose();
		dispose(this._currentCodeLensModel);
82 83
	}

84 85 86 87 88
	private _updateLensStyle(): void {
		const options = this._editor.getOptions();
		const fontInfo = options.get(EditorOption.fontInfo);
		const lineHeight = options.get(EditorOption.lineHeight);

89 90 91 92 93 94 95

		const height = Math.round(lineHeight * 1.1);
		const fontSize = Math.round(fontInfo.fontSize * 0.9);
		const newStyle = `
		.monaco-editor .codelens-decoration.${this._styleClassName} { height: ${height}px; line-height: ${lineHeight}px; font-size: ${fontSize}px; padding-right: ${Math.round(fontInfo.fontSize * 0.45)}px;}
		.monaco-editor .codelens-decoration.${this._styleClassName} > a > .codicon { line-height: ${lineHeight}px; font-size: ${fontSize}px; }
		`;
96 97 98
		this._styleElement.innerHTML = newStyle;
	}

99
	private _localDispose(): void {
100 101
		if (this._currentFindCodeLensSymbolsPromise) {
			this._currentFindCodeLensSymbolsPromise.cancel();
J
Johannes Rieken 已提交
102
			this._currentFindCodeLensSymbolsPromise = undefined;
103 104
			this._modelChangeCounter++;
		}
105 106
		if (this._currentResolveCodeLensSymbolsPromise) {
			this._currentResolveCodeLensSymbolsPromise.cancel();
J
Johannes Rieken 已提交
107
			this._currentResolveCodeLensSymbolsPromise = undefined;
108
		}
109
		this._localToDispose.clear();
110 111
		this._oldCodeLensModels.clear();
		dispose(this._currentCodeLensModel);
112 113
	}

114
	private _onModelChange(): void {
115

116
		this._localDispose();
117 118 119 120 121 122 123 124 125 126

		const model = this._editor.getModel();
		if (!model) {
			return;
		}

		if (!this._isEnabled) {
			return;
		}

127 128 129 130 131
		const cachedLenses = this._codeLensCache.get(model);
		if (cachedLenses) {
			this._renderCodeLensSymbols(cachedLenses);
		}

132
		if (!CodeLensProviderRegistry.has(model)) {
133 134 135
			// no provider -> return but check with
			// cached lenses. they expire after 30 seconds
			if (cachedLenses) {
136
				this._localToDispose.add(disposableTimeout(() => {
137 138 139 140 141 142 143
					const cachedLensesNow = this._codeLensCache.get(model);
					if (cachedLenses === cachedLensesNow) {
						this._codeLensCache.delete(model);
						this._onModelChange();
					}
				}, 30 * 1000));
			}
144 145 146 147 148 149
			return;
		}

		for (const provider of CodeLensProviderRegistry.all(model)) {
			if (typeof provider.onDidChange === 'function') {
				let registration = provider.onDidChange(() => scheduler.schedule());
150
				this._localToDispose.add(registration);
151 152 153
			}
		}

J
Johannes Rieken 已提交
154
		const detectVisibleLenses = this._detectVisibleLenses = new RunOnceScheduler(() => this._onViewportChanged(), 250);
155 156

		const scheduler = new RunOnceScheduler(() => {
J
Johannes Rieken 已提交
157
			const counterValue = ++this._modelChangeCounter;
158 159 160 161
			if (this._currentFindCodeLensSymbolsPromise) {
				this._currentFindCodeLensSymbolsPromise.cancel();
			}

162
			this._currentFindCodeLensSymbolsPromise = createCancelablePromise(token => getCodeLensData(model, token));
163

J
Johannes Rieken 已提交
164
			this._currentFindCodeLensSymbolsPromise.then(result => {
165
				if (counterValue === this._modelChangeCounter) { // only the last one wins
166 167 168 169
					if (this._currentCodeLensModel) {
						this._oldCodeLensModels.add(this._currentCodeLensModel);
					}
					this._currentCodeLensModel = result;
170 171

					// cache model to reduce flicker
J
Johannes Rieken 已提交
172
					this._codeLensCache.put(model, result);
173 174

					// render lenses
175
					this._renderCodeLensSymbols(result);
J
Johannes Rieken 已提交
176
					detectVisibleLenses.schedule();
177
				}
178
			}, onUnexpectedError);
179
		}, 250);
180
		this._localToDispose.add(scheduler);
J
Johannes Rieken 已提交
181
		this._localToDispose.add(detectVisibleLenses);
J
Johannes Rieken 已提交
182 183 184
		this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
			this._editor.changeDecorations(decorationsAccessor => {
				this._editor.changeViewZones(viewZonesAccessor => {
185
					let toDispose: CodeLensWidget[] = [];
J
Johannes Rieken 已提交
186 187
					let lastLensLineNumber: number = -1;

188
					this._lenses.forEach((lens) => {
J
Johannes Rieken 已提交
189 190 191
						if (!lens.isValid() || lastLensLineNumber === lens.getLineNumber()) {
							// invalid -> lens collapsed, attach range doesn't exist anymore
							// line_number -> lenses should never be on the same line
192
							toDispose.push(lens);
J
Johannes Rieken 已提交
193 194

						} else {
J
Johannes Rieken 已提交
195
							lens.update(viewZonesAccessor);
J
Johannes Rieken 已提交
196
							lastLensLineNumber = lens.getLineNumber();
197 198 199 200 201
						}
					});

					let helper = new CodeLensHelper();
					toDispose.forEach((l) => {
J
Johannes Rieken 已提交
202
						l.dispose(helper, viewZonesAccessor);
203 204
						this._lenses.splice(this._lenses.indexOf(l), 1);
					});
J
Johannes Rieken 已提交
205
					helper.commit(decorationsAccessor);
206 207 208 209
				});
			});

			// Compute new `visible` code lenses
J
Johannes Rieken 已提交
210
			detectVisibleLenses.schedule();
211 212 213
			// Ask for all references again
			scheduler.schedule();
		}));
214
		this._localToDispose.add(this._editor.onDidScrollChange(e => {
215
			if (e.scrollTopChanged && this._lenses.length > 0) {
J
Johannes Rieken 已提交
216
				detectVisibleLenses.schedule();
217 218
			}
		}));
J
Johannes Rieken 已提交
219
		this._localToDispose.add(this._editor.onDidLayoutChange(() => {
J
Johannes Rieken 已提交
220
			detectVisibleLenses.schedule();
221
		}));
222
		this._localToDispose.add(toDisposable(() => {
223 224
			if (this._editor.getModel()) {
				const scrollState = StableEditorScrollState.capture(this._editor);
J
Johannes Rieken 已提交
225 226 227
				this._editor.changeDecorations(decorationsAccessor => {
					this._editor.changeViewZones(viewZonesAccessor => {
						this._disposeAllLenses(decorationsAccessor, viewZonesAccessor);
228
					});
229 230 231 232
				});
				scrollState.restore(this._editor);
			} else {
				// No accessors available
R
Rob Lourens 已提交
233
				this._disposeAllLenses(undefined, undefined);
234
			}
235
		}));
236
		this._localToDispose.add(this._editor.onMouseUp(e => {
A
Alexandru Dima 已提交
237
			if (e.target.type !== MouseTargetType.CONTENT_WIDGET) {
J
Johannes Rieken 已提交
238 239 240 241 242 243 244
				return;
			}
			let target = e.target.element;
			if (target?.tagName === 'SPAN') {
				target = target.parentElement;
			}
			if (target?.tagName === 'A') {
245
				for (const lens of this._lenses) {
J
Johannes Rieken 已提交
246
					let command = lens.getCommand(target as HTMLLinkElement);
247
					if (command) {
M
Matt Bierner 已提交
248
						this._commandService.executeCommand(command.id, ...(command.arguments || [])).catch(err => this._notificationService.error(err));
249 250 251 252 253
						break;
					}
				}
			}
		}));
254 255 256
		scheduler.schedule();
	}

A
Alexandru Dima 已提交
257
	private _disposeAllLenses(decChangeAccessor: IModelDecorationsChangeAccessor | undefined, viewZoneChangeAccessor: IViewZoneChangeAccessor | undefined): void {
258 259 260 261
		const helper = new CodeLensHelper();
		for (const lens of this._lenses) {
			lens.dispose(helper, viewZoneChangeAccessor);
		}
262 263 264 265 266 267
		if (decChangeAccessor) {
			helper.commit(decChangeAccessor);
		}
		this._lenses = [];
	}

268
	private _renderCodeLensSymbols(symbols: CodeLensModel): void {
M
Matt Bierner 已提交
269
		if (!this._editor.hasModel()) {
270 271 272 273
			return;
		}

		let maxLineNumber = this._editor.getModel().getLineCount();
274 275
		let groups: CodeLensItem[][] = [];
		let lastGroup: CodeLensItem[] | undefined;
276

277
		for (let symbol of symbols.lenses) {
278 279 280 281 282 283 284 285 286 287 288 289 290 291
			let line = symbol.symbol.range.startLineNumber;
			if (line < 1 || line > maxLineNumber) {
				// invalid code lens
				continue;
			} else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) {
				// on same line as previous
				lastGroup.push(symbol);
			} else {
				// on later line as previous
				lastGroup = [symbol];
				groups.push(lastGroup);
			}
		}

A
Alex Dima 已提交
292
		const scrollState = StableEditorScrollState.capture(this._editor);
293

J
Johannes Rieken 已提交
294 295
		this._editor.changeDecorations(decorationsAccessor => {
			this._editor.changeViewZones(viewZoneAccessor => {
296

J
Johannes Rieken 已提交
297 298 299
				const helper = new CodeLensHelper();
				let codeLensIndex = 0;
				let groupsIndex = 0;
300 301 302 303 304 305 306

				while (groupsIndex < groups.length && codeLensIndex < this._lenses.length) {

					let symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
					let codeLensLineNumber = this._lenses[codeLensIndex].getLineNumber();

					if (codeLensLineNumber < symbolsLineNumber) {
J
Johannes Rieken 已提交
307
						this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
308 309 310 311 312 313
						this._lenses.splice(codeLensIndex, 1);
					} else if (codeLensLineNumber === symbolsLineNumber) {
						this._lenses[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex], helper);
						groupsIndex++;
						codeLensIndex++;
					} else {
A
Alexandru Dima 已提交
314
						this._lenses.splice(codeLensIndex, 0, new CodeLensWidget(groups[groupsIndex], <IActiveCodeEditor>this._editor, this._styleClassName, helper, viewZoneAccessor, () => this._detectVisibleLenses && this._detectVisibleLenses.schedule()));
315 316 317 318 319 320 321
						codeLensIndex++;
						groupsIndex++;
					}
				}

				// Delete extra code lenses
				while (codeLensIndex < this._lenses.length) {
J
Johannes Rieken 已提交
322
					this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
323 324 325 326 327
					this._lenses.splice(codeLensIndex, 1);
				}

				// Create extra symbols
				while (groupsIndex < groups.length) {
A
Alexandru Dima 已提交
328
					this._lenses.push(new CodeLensWidget(groups[groupsIndex], <IActiveCodeEditor>this._editor, this._styleClassName, helper, viewZoneAccessor, () => this._detectVisibleLenses && this._detectVisibleLenses.schedule()));
329 330 331
					groupsIndex++;
				}

J
Johannes Rieken 已提交
332
				helper.commit(decorationsAccessor);
333 334
			});
		});
335

A
Alex Dima 已提交
336
		scrollState.restore(this._editor);
337 338
	}

339
	private _onViewportChanged(): void {
340 341
		if (this._currentResolveCodeLensSymbolsPromise) {
			this._currentResolveCodeLensSymbolsPromise.cancel();
J
Johannes Rieken 已提交
342
			this._currentResolveCodeLensSymbolsPromise = undefined;
343 344 345 346 347 348 349
		}

		const model = this._editor.getModel();
		if (!model) {
			return;
		}

350 351
		const toResolve: CodeLensItem[][] = [];
		const lenses: CodeLensWidget[] = [];
352 353 354 355 356 357 358 359 360 361 362 363
		this._lenses.forEach((lens) => {
			const request = lens.computeIfNecessary(model);
			if (request) {
				toResolve.push(request);
				lenses.push(lens);
			}
		});

		if (toResolve.length === 0) {
			return;
		}

364
		const resolvePromise = createCancelablePromise(token => {
365

366
			const promises = toResolve.map((request, i) => {
367

368
				const resolvedSymbols = new Array<CodeLens | undefined | null>(request.length);
369
				const promises = request.map((request, i) => {
370
					if (!request.symbol.command && typeof request.provider.resolveCodeLens === 'function') {
371 372
						return Promise.resolve(request.provider.resolveCodeLens(model, request.symbol, token)).then(symbol => {
							resolvedSymbols[i] = symbol;
373
						}, onUnexpectedExternalError);
374 375 376
					} else {
						resolvedSymbols[i] = request.symbol;
						return Promise.resolve(undefined);
377 378 379 380
					}
				});

				return Promise.all(promises).then(() => {
381
					if (!token.isCancellationRequested && !lenses[i].isDisposed()) {
382 383
						lenses[i].updateCommands(resolvedSymbols);
					}
384
				});
385
			});
386 387

			return Promise.all(promises);
388
		});
389
		this._currentResolveCodeLensSymbolsPromise = resolvePromise;
390

391
		this._currentResolveCodeLensSymbolsPromise.then(() => {
392 393 394
			if (this._currentCodeLensModel) { // update the cached state with new resolved items
				this._codeLensCache.put(model, this._currentCodeLensModel);
			}
395
			this._oldCodeLensModels.clear(); // dispose old models once we have updated the UI with the current model
396 397 398
			if (resolvePromise === this._currentResolveCodeLensSymbolsPromise) {
				this._currentResolveCodeLensSymbolsPromise = undefined;
			}
399 400
		}, err => {
			onUnexpectedError(err); // can also be cancellation!
401 402 403
			if (resolvePromise === this._currentResolveCodeLensSymbolsPromise) {
				this._currentResolveCodeLensSymbolsPromise = undefined;
			}
404 405
		});
	}
406 407 408 409

	public getLenses(): CodeLensWidget[] {
		return this._lenses;
	}
410
}
411

G
Gustavo Sampaio 已提交
412 413
export class ShowLensesInCurrentLineCommand extends EditorCommand {
	public runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void | Promise<void> {
414 415 416 417
		const quickInputService = accessor.get(IQuickInputService);
		const commandService = accessor.get(ICommandService);
		const notificationService = accessor.get(INotificationService);

G
Gustavo Sampaio 已提交
418 419
		const lineNumber = editor.getSelection()?.positionLineNumber;
		const codelensController = editor.getContribution(CodeLensContribution.ID) as CodeLensContribution;
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

		const activeLensesWidgets = codelensController.getLenses().filter(lens => lens.getLineNumber() === lineNumber);

		const commandArguments: Map<string, any[] | undefined> = new Map();

		const picker = quickInputService.createQuickPick();
		const items: (IQuickPickItem | IQuickPickSeparator)[] = [];

		activeLensesWidgets.forEach(widget => {
			widget.getItems().forEach(codelens => {
				const command = codelens.symbol.command;
				if (!command) {
					return;
				}
				items.push({ id: command.id, label: command.title });

				commandArguments.set(command.id, command.arguments);
			});
		});

		picker.items = items;
		picker.canSelectMany = false;
		picker.onDidAccept(_ => {
			const selectedItems = picker.selectedItems;
			if (selectedItems.length === 1) {
				const id = selectedItems[0].id!;

				if (!id) {
					picker.hide();
					return;
				}

				commandService.executeCommand(id, ...(commandArguments.get(id) || [])).catch(err => notificationService.error(err));
			}
			picker.hide();
		});
		picker.show();
	}

}

461
registerEditorContribution(CodeLensContribution.ID, CodeLensContribution);
462 463 464

const showLensesInCurrentLineCommand = new ShowLensesInCurrentLineCommand({ id: 'codelens.showLensesInCurrentLine', precondition: undefined });
showLensesInCurrentLineCommand.register();