outlineModel.ts 13.6 KB
Newer Older
J
Johannes Rieken 已提交
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
import { binarySearch, coalesceInPlace, equals } from 'vs/base/common/arrays';
7 8 9
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { onUnexpectedExternalError } from 'vs/base/common/errors';
import { LRUCache } from 'vs/base/common/map';
10
import { commonPrefixLength } from 'vs/base/common/strings';
11 12 13 14
import { IPosition } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { DocumentSymbol, DocumentSymbolProvider, DocumentSymbolProviderRegistry } from 'vs/editor/common/modes';
J
Johannes Rieken 已提交
15
import { MarkerSeverity } from 'vs/platform/markers/common/markers';
16
import { Iterable } from 'vs/base/common/iterator';
17
import { URI } from 'vs/base/common/uri';
18
import { LanguageFeatureRequestDelays } from 'vs/editor/common/modes/languageFeatureRegistry';
J
Johannes Rieken 已提交
19

J
Johannes Rieken 已提交
20
export abstract class TreeElement {
21

J
Johannes Rieken 已提交
22
	abstract id: string;
23
	abstract children: Map<string, TreeElement>;
24
	abstract parent: TreeElement | undefined;
J
Johannes Rieken 已提交
25

26 27
	abstract adopt(newParent: TreeElement): TreeElement;

28
	remove(): void {
29
		if (this.parent) {
30
			this.parent.children.delete(this.id);
31
		}
32 33
	}

34
	static findId(candidate: DocumentSymbol | string, container: TreeElement): string {
J
Johannes Rieken 已提交
35 36
		// complex id-computation which contains the origin/extension,
		// the parent path, and some dedupe logic when names collide
37 38 39 40 41
		let candidateId: string;
		if (typeof candidate === 'string') {
			candidateId = `${container.id}/${candidate}`;
		} else {
			candidateId = `${container.id}/${candidate.name}`;
42
			if (container.children.get(candidateId) !== undefined) {
43
				candidateId = `${container.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
44 45 46 47
			}
		}

		let id = candidateId;
48
		for (let i = 0; container.children.get(id) !== undefined; i++) {
49
			id = `${candidateId}_${i}`;
J
Johannes Rieken 已提交
50
		}
51

J
Johannes Rieken 已提交
52
		return id;
53
	}
54

55
	static getElementById(id: string, element: TreeElement): TreeElement | undefined {
56 57 58 59 60
		if (!id) {
			return undefined;
		}
		let len = commonPrefixLength(id, element.id);
		if (len === id.length) {
J
Johannes Rieken 已提交
61 62
			return element;
		}
63 64 65
		if (len < element.id.length) {
			return undefined;
		}
66 67
		for (const [, child] of element.children) {
			let candidate = TreeElement.getElementById(id, child);
J
Johannes Rieken 已提交
68 69 70
			if (candidate) {
				return candidate;
			}
J
Johannes Rieken 已提交
71
		}
J
Johannes Rieken 已提交
72
		return undefined;
J
Johannes Rieken 已提交
73
	}
74 75 76

	static size(element: TreeElement): number {
		let res = 1;
77 78
		for (const [, child] of element.children) {
			res += TreeElement.size(child);
79 80 81
		}
		return res;
	}
82 83

	static empty(element: TreeElement): boolean {
84
		return element.children.size === 0;
85
	}
86 87
}

J
Johannes Rieken 已提交
88 89 90 91 92 93 94 95
export interface IOutlineMarker {
	startLineNumber: number;
	startColumn: number;
	endLineNumber: number;
	endColumn: number;
	severity: MarkerSeverity;
}

J
Johannes Rieken 已提交
96
export class OutlineElement extends TreeElement {
J
Johannes Rieken 已提交
97

98
	children = new Map<string, OutlineElement>();
99
	marker: { count: number, topSev: MarkerSeverity } | undefined;
J
Johannes Rieken 已提交
100

J
Johannes Rieken 已提交
101 102
	constructor(
		readonly id: string,
103
		public parent: TreeElement | undefined,
104
		readonly symbol: DocumentSymbol
J
Johannes Rieken 已提交
105
	) {
J
Johannes Rieken 已提交
106
		super();
J
Johannes Rieken 已提交
107
	}
108

109
	adopt(parent: TreeElement): OutlineElement {
110
		let res = new OutlineElement(this.id, parent, this.symbol);
111 112 113
		for (const [key, value] of this.children) {
			res.children.set(key, value.adopt(res));
		}
114 115
		return res;
	}
J
Johannes Rieken 已提交
116 117
}

J
Johannes Rieken 已提交
118
export class OutlineGroup extends TreeElement {
J
Johannes Rieken 已提交
119

120
	children = new Map<string, OutlineElement>();
J
Johannes Rieken 已提交
121

J
Johannes Rieken 已提交
122
	constructor(
J
Johannes Rieken 已提交
123
		readonly id: string,
124
		public parent: TreeElement | undefined,
125 126
		readonly label: string,
		readonly order: number,
J
Johannes Rieken 已提交
127
	) {
J
Johannes Rieken 已提交
128
		super();
J
Johannes Rieken 已提交
129
	}
J
Johannes Rieken 已提交
130

131
	adopt(parent: TreeElement): OutlineGroup {
132
		let res = new OutlineGroup(this.id, parent, this.label, this.order);
133 134 135
		for (const [key, value] of this.children) {
			res.children.set(key, value.adopt(res));
		}
136 137 138
		return res;
	}

139
	getItemEnclosingPosition(position: IPosition): OutlineElement | undefined {
J
Johannes Rieken 已提交
140
		return position ? this._getItemEnclosingPosition(position, this.children) : undefined;
J
Johannes Rieken 已提交
141 142
	}

143 144
	private _getItemEnclosingPosition(position: IPosition, children: Map<string, OutlineElement>): OutlineElement | undefined {
		for (const [, item] of children) {
J
Johannes Rieken 已提交
145
			if (!item.symbol.range || !Range.containsPosition(item.symbol.range, position)) {
J
Johannes Rieken 已提交
146
				continue;
J
Johannes Rieken 已提交
147
			}
J
Johannes Rieken 已提交
148
			return this._getItemEnclosingPosition(position, item.children) || item;
J
Johannes Rieken 已提交
149 150 151
		}
		return undefined;
	}
152

J
Johannes Rieken 已提交
153
	updateMarker(marker: IOutlineMarker[]): void {
154 155
		for (const [, child] of this.children) {
			this._updateMarker(marker, child);
156 157 158
		}
	}

J
Johannes Rieken 已提交
159
	private _updateMarker(markers: IOutlineMarker[], item: OutlineElement): void {
160 161 162
		item.marker = undefined;

		// find the proper start index to check for item/marker overlap.
163
		let idx = binarySearch<IRange>(markers, item.symbol.range, Range.compareRangesUsingStarts);
164 165 166
		let start: number;
		if (idx < 0) {
			start = ~idx;
167
			if (start > 0 && Range.areIntersecting(markers[start - 1], item.symbol.range)) {
168 169 170 171 172 173
				start -= 1;
			}
		} else {
			start = idx;
		}

J
Johannes Rieken 已提交
174
		let myMarkers: IOutlineMarker[] = [];
R
Rudi Chen 已提交
175
		let myTopSev: MarkerSeverity | undefined;
176

177
		for (; start < markers.length && Range.areIntersecting(item.symbol.range, markers[start]); start++) {
178 179
			// remove markers intersecting with this outline element
			// and store them in a 'private' array.
180
			let marker = markers[start];
181
			myMarkers.push(marker);
J
Johannes Rieken 已提交
182
			(markers as Array<IOutlineMarker | undefined>)[start] = undefined;
183 184
			if (!myTopSev || marker.severity > myTopSev) {
				myTopSev = marker.severity;
185 186 187
			}
		}

188 189 190 191
		// Recurse into children and let them match markers that have matched
		// this outline element. This might remove markers from this element and
		// therefore we remember that we have had markers. That allows us to render
		// the dot, saying 'this element has children with markers'
192 193
		for (const [, child] of item.children) {
			this._updateMarker(myMarkers, child);
194
		}
195

196
		if (myTopSev) {
197 198 199 200 201
			item.marker = {
				count: myMarkers.length,
				topSev: myTopSev
			};
		}
202

203
		coalesceInPlace(markers);
204
	}
J
Johannes Rieken 已提交
205
}
J
Johannes Rieken 已提交
206

207 208


J
Johannes Rieken 已提交
209 210
export class OutlineModel extends TreeElement {

211
	private static readonly _requestDurations = new LanguageFeatureRequestDelays(DocumentSymbolProviderRegistry, 350);
212
	private static readonly _requests = new LRUCache<string, { promiseCnt: number, source: CancellationTokenSource, promise: Promise<any>, model: OutlineModel | undefined }>(9, 0.75);
J
Johannes Rieken 已提交
213 214 215 216 217
	private static readonly _keys = new class {

		private _counter = 1;
		private _data = new WeakMap<DocumentSymbolProvider, number>();

218 219
		for(textModel: ITextModel, version: boolean): string {
			return `${textModel.id}/${version ? textModel.getVersionId() : ''}/${this._hash(DocumentSymbolProviderRegistry.all(textModel))}`;
J
Johannes Rieken 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
		}

		private _hash(providers: DocumentSymbolProvider[]): string {
			let result = '';
			for (const provider of providers) {
				let n = this._data.get(provider);
				if (typeof n === 'undefined') {
					n = this._counter++;
					this._data.set(provider, n);
				}
				result += n;
			}
			return result;
		}
	};

236

237
	static create(textModel: ITextModel, token: CancellationToken): Promise<OutlineModel> {
238

239
		let key = this._keys.for(textModel, true);
240 241
		let data = OutlineModel._requests.get(key);

242
		if (!data) {
243
			let source = new CancellationTokenSource();
244 245
			data = {
				promiseCnt: 0,
246 247
				source,
				promise: OutlineModel._create(textModel, source.token),
248 249
				model: undefined,
			};
250
			OutlineModel._requests.set(key, data);
251 252 253 254

			// keep moving average of request durations
			const now = Date.now();
			data.promise.then(() => {
255
				this._requestDurations.update(textModel, Date.now() - now);
256
			});
257 258
		}

259
		if (data!.model) {
260
			// resolved -> return data
261
			return Promise.resolve(data.model!);
262 263
		}

264
		// increase usage counter
265
		data!.promiseCnt += 1;
266

267 268
		token.onCancellationRequested(() => {
			// last -> cancel provider request, remove cached promise
269 270
			if (--data!.promiseCnt === 0) {
				data!.source.cancel();
271 272 273 274 275
				OutlineModel._requests.delete(key);
			}
		});

		return new Promise((resolve, reject) => {
276 277
			data!.promise.then(model => {
				data!.model = model;
278
				resolve(model);
279 280
			}, err => {
				OutlineModel._requests.delete(key);
281 282
				reject(err);
			});
283 284 285
		});
	}

286
	static getRequestDelay(textModel: ITextModel | null): number {
287
		return textModel ? this._requestDurations.get(textModel) : this._requestDurations.min;
288 289 290
	}

	private static _create(textModel: ITextModel, token: CancellationToken): Promise<OutlineModel> {
J
Johannes Rieken 已提交
291

292
		const cts = new CancellationTokenSource(token);
293
		const result = new OutlineModel(textModel.uri);
294 295
		const provider = DocumentSymbolProviderRegistry.ordered(textModel);
		const promises = provider.map((provider, index) => {
296

J
Johannes Rieken 已提交
297
			let id = TreeElement.findId(`provider_${index}`, result);
298
			let group = new OutlineGroup(id, result, provider.displayName ?? 'Unknown Outline Provider', index);
299

300
			return Promise.resolve(provider.provideDocumentSymbols(textModel, cts.token)).then(result => {
301 302
				for (const info of result || []) {
					OutlineModel._makeOutlineElement(info, group);
J
Johannes Rieken 已提交
303 304 305
				}
				return group;
			}, err => {
J
Johannes Rieken 已提交
306
				onUnexpectedExternalError(err);
J
Johannes Rieken 已提交
307 308
				return group;
			}).then(group => {
309
				if (!TreeElement.empty(group)) {
310
					result._groups.set(id, group);
311 312 313
				} else {
					group.remove();
				}
J
Johannes Rieken 已提交
314 315 316
			});
		});

317 318 319
		const listener = DocumentSymbolProviderRegistry.onDidChange(() => {
			const newProvider = DocumentSymbolProviderRegistry.ordered(textModel);
			if (!equals(newProvider, provider)) {
320
				cts.cancel();
321 322 323 324
			}
		});

		return Promise.all(promises).then(() => {
325
			if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
326 327 328 329 330 331 332
				return OutlineModel._create(textModel, token);
			} else {
				return result._compact();
			}
		}).finally(() => {
			listener.dispose();
		});
333 334
	}

335
	private static _makeOutlineElement(info: DocumentSymbol, container: OutlineGroup | OutlineElement): void {
336
		let id = TreeElement.findId(info, container);
J
Johannes Rieken 已提交
337 338 339 340 341
		let res = new OutlineElement(id, container, info);
		if (info.children) {
			for (const childInfo of info.children) {
				OutlineModel._makeOutlineElement(childInfo, res);
			}
342
		}
343
		container.children.set(res.id, res);
344 345
	}

346
	static get(element: TreeElement | undefined): OutlineModel | undefined {
347 348 349 350 351 352 353 354 355
		while (element) {
			if (element instanceof OutlineModel) {
				return element;
			}
			element = element.parent;
		}
		return undefined;
	}

J
Johannes Rieken 已提交
356 357 358
	readonly id = 'root';
	readonly parent = undefined;

359 360
	protected _groups = new Map<string, OutlineGroup>();
	children = new Map<string, OutlineGroup | OutlineElement>();
J
Johannes Rieken 已提交
361

362
	protected constructor(readonly uri: URI) {
J
Johannes Rieken 已提交
363
		super();
P
Peng Lyu 已提交
364 365 366

		this.id = 'root';
		this.parent = undefined;
J
Johannes Rieken 已提交
367 368
	}

369
	adopt(): OutlineModel {
370
		let res = new OutlineModel(this.uri);
371 372 373
		for (const [key, value] of this._groups) {
			res._groups.set(key, value.adopt(res));
		}
374 375
		return res._compact();
	}
J
Johannes Rieken 已提交
376

377
	private _compact(): this {
R
Rudi Chen 已提交
378
		let count = 0;
379 380 381
		for (const [key, group] of this._groups) {
			if (group.children.size === 0) { // empty
				this._groups.delete(key);
R
Rudi Chen 已提交
382 383
			} else {
				count += 1;
384 385
			}
		}
R
Rudi Chen 已提交
386 387 388 389
		if (count !== 1) {
			//
			this.children = this._groups;
		} else {
390
			// adopt all elements of the first group
391 392
			let group = Iterable.first(this._groups.values())!;
			for (let [, child] of group.children) {
393
				child.parent = this;
394
				this.children.set(child.id, child);
395 396 397
			}
		}
		return this;
J
Johannes Rieken 已提交
398 399
	}

400
	merge(other: OutlineModel): boolean {
401
		if (this.uri.toString() !== other.uri.toString()) {
J
Johannes Rieken 已提交
402 403
			return false;
		}
404
		if (this._groups.size !== other._groups.size) {
J
Johannes Rieken 已提交
405 406 407 408 409 410 411
			return false;
		}
		this._groups = other._groups;
		this.children = other.children;
		return true;
	}

412
	getItemEnclosingPosition(position: IPosition, context?: OutlineElement): OutlineElement | undefined {
413

414
		let preferredGroup: OutlineGroup | undefined;
415 416 417 418 419 420 421 422 423 424
		if (context) {
			let candidate = context.parent;
			while (candidate && !preferredGroup) {
				if (candidate instanceof OutlineGroup) {
					preferredGroup = candidate;
				}
				candidate = candidate.parent;
			}
		}

425
		let result: OutlineElement | undefined = undefined;
426
		for (const [, group] of this._groups) {
427 428 429
			result = group.getItemEnclosingPosition(position);
			if (result && (!preferredGroup || preferredGroup === group)) {
				break;
J
Johannes Rieken 已提交
430 431
			}
		}
432
		return result;
433 434
	}

435
	getItemById(id: string): TreeElement | undefined {
J
Johannes Rieken 已提交
436
		return TreeElement.getElementById(id, this);
437
	}
438

J
Johannes Rieken 已提交
439
	updateMarker(marker: IOutlineMarker[]): void {
440 441 442 443
		// sort markers by start range so that we can use
		// outline element starts for quicker look up
		marker.sort(Range.compareRangesUsingStarts);

444 445
		for (const [, group] of this._groups) {
			group.updateMarker(marker.slice(0));
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 472 473 474 475 476 477 478 479 480 481

	asListOfDocumentSymbols(): DocumentSymbol[] {
		const roots: DocumentSymbol[] = [];
		for (const child of this.children.values()) {
			if (child instanceof OutlineElement) {
				roots.push(child.symbol);
			} else {
				roots.push(...Iterable.map(child.children.values(), child => child.symbol));
			}
		}
		const bucket: DocumentSymbol[] = [];
		OutlineModel._flattenDocumentSymbols(bucket, roots, '');
		return bucket;
	}

	private static _flattenDocumentSymbols(bucket: DocumentSymbol[], entries: DocumentSymbol[], overrideContainerLabel: string): void {
		for (const entry of entries) {
			bucket.push({
				kind: entry.kind,
				tags: entry.tags,
				name: entry.name,
				detail: entry.detail,
				containerName: entry.containerName || overrideContainerLabel,
				range: entry.range,
				selectionRange: entry.selectionRange,
				children: undefined, // we flatten it...
			});

			// Recurse over children
			if (entry.children) {
				OutlineModel._flattenDocumentSymbols(bucket, entry.children, entry.name);
			}
		}
	}
482
}