outlineModel.ts 12.9 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 } from 'vs/base/common/arrays';
7 8 9
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { first, forEach, size } from 'vs/base/common/collections';
import { onUnexpectedExternalError } from 'vs/base/common/errors';
J
Johannes Rieken 已提交
10
import { fuzzyScore, FuzzyScore } from 'vs/base/common/filters';
11
import { LRUCache } from 'vs/base/common/map';
12
import { commonPrefixLength } from 'vs/base/common/strings';
13 14 15 16
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';
17
import { IMarker, MarkerSeverity } from 'vs/platform/markers/common/markers';
J
Johannes Rieken 已提交
18

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

J
Johannes Rieken 已提交
21 22
	abstract id: string;
	abstract children: { [id: string]: TreeElement };
23
	abstract parent: TreeElement | undefined;
J
Johannes Rieken 已提交
24

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

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

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

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

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

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

	static size(element: TreeElement): number {
		let res = 1;
		for (const key in element.children) {
			res += TreeElement.size(element.children[key]);
		}
		return res;
	}
81 82 83 84 85 86 87

	static empty(element: TreeElement): boolean {
		for (const _key in element.children) {
			return false;
		}
		return true;
	}
88 89
}

J
Johannes Rieken 已提交
90
export class OutlineElement extends TreeElement {
J
Johannes Rieken 已提交
91

J
Johannes Rieken 已提交
92
	children: { [id: string]: OutlineElement; } = Object.create(null);
93 94
	score: FuzzyScore | undefined = FuzzyScore.Default;
	marker: { count: number, topSev: MarkerSeverity } | undefined;
J
Johannes Rieken 已提交
95

J
Johannes Rieken 已提交
96 97
	constructor(
		readonly id: string,
98
		public parent: TreeElement | undefined,
99
		readonly symbol: DocumentSymbol
J
Johannes Rieken 已提交
100
	) {
J
Johannes Rieken 已提交
101
		super();
J
Johannes Rieken 已提交
102
	}
103

104
	adopt(parent: TreeElement): OutlineElement {
105 106 107 108
		let res = new OutlineElement(this.id, parent, this.symbol);
		forEach(this.children, entry => res.children[entry.key] = entry.value.adopt(res));
		return res;
	}
J
Johannes Rieken 已提交
109 110
}

J
Johannes Rieken 已提交
111
export class OutlineGroup extends TreeElement {
J
Johannes Rieken 已提交
112

J
Johannes Rieken 已提交
113
	children: { [id: string]: OutlineElement; } = Object.create(null);
J
Johannes Rieken 已提交
114

J
Johannes Rieken 已提交
115
	constructor(
J
Johannes Rieken 已提交
116
		readonly id: string,
117
		public parent: TreeElement | undefined,
J
Johannes Rieken 已提交
118 119
		readonly provider: DocumentSymbolProvider,
		readonly providerIndex: number,
J
Johannes Rieken 已提交
120
	) {
J
Johannes Rieken 已提交
121
		super();
J
Johannes Rieken 已提交
122
	}
J
Johannes Rieken 已提交
123

124
	adopt(parent: TreeElement): OutlineGroup {
125 126 127 128 129
		let res = new OutlineGroup(this.id, parent, this.provider, this.providerIndex);
		forEach(this.children, entry => res.children[entry.key] = entry.value.adopt(res));
		return res;
	}

130
	updateMatches(pattern: string, topMatch: OutlineElement | undefined): OutlineElement | undefined {
J
Johannes Rieken 已提交
131 132 133
		for (const key in this.children) {
			topMatch = this._updateMatches(pattern, this.children[key], topMatch);
		}
134 135 136
		return topMatch;
	}

137
	private _updateMatches(pattern: string, item: OutlineElement, topMatch: OutlineElement | undefined): OutlineElement | undefined {
J
Johannes Rieken 已提交
138 139 140

		item.score = pattern
			? fuzzyScore(pattern, pattern.toLowerCase(), 0, item.symbol.name, item.symbol.name.toLowerCase(), 0, true)
141
			: FuzzyScore.Default;
J
Johannes Rieken 已提交
142

143
		if (item.score && (!topMatch || !topMatch.score || item.score[0] > topMatch.score[0])) {
144 145
			topMatch = item;
		}
J
Johannes Rieken 已提交
146 147 148 149
		for (const key in item.children) {
			let child = item.children[key];
			topMatch = this._updateMatches(pattern, child, topMatch);
			if (!item.score && child.score) {
150
				// don't filter parents with unfiltered children
151
				item.score = FuzzyScore.Default;
152
			}
J
Johannes Rieken 已提交
153
		}
154
		return topMatch;
J
Johannes Rieken 已提交
155
	}
J
Johannes Rieken 已提交
156

157
	getItemEnclosingPosition(position: IPosition): OutlineElement | undefined {
J
Johannes Rieken 已提交
158
		return position ? this._getItemEnclosingPosition(position, this.children) : undefined;
J
Johannes Rieken 已提交
159 160
	}

161
	private _getItemEnclosingPosition(position: IPosition, children: { [id: string]: OutlineElement }): OutlineElement | undefined {
J
Johannes Rieken 已提交
162 163
		for (let key in children) {
			let item = children[key];
J
Johannes Rieken 已提交
164
			if (!item.symbol.range || !Range.containsPosition(item.symbol.range, position)) {
J
Johannes Rieken 已提交
165
				continue;
J
Johannes Rieken 已提交
166
			}
J
Johannes Rieken 已提交
167
			return this._getItemEnclosingPosition(position, item.children) || item;
J
Johannes Rieken 已提交
168 169 170
		}
		return undefined;
	}
171 172 173 174 175 176 177

	updateMarker(marker: IMarker[]): void {
		for (const key in this.children) {
			this._updateMarker(marker, this.children[key]);
		}
	}

178 179 180 181
	private _updateMarker(markers: IMarker[], item: OutlineElement): void {
		item.marker = undefined;

		// find the proper start index to check for item/marker overlap.
182
		let idx = binarySearch<IRange>(markers, item.symbol.range, Range.compareRangesUsingStarts);
183 184 185
		let start: number;
		if (idx < 0) {
			start = ~idx;
186
			if (start > 0 && Range.areIntersecting(markers[start - 1], item.symbol.range)) {
187 188 189 190 191 192 193
				start -= 1;
			}
		} else {
			start = idx;
		}

		let myMarkers: IMarker[] = [];
R
Rudi Chen 已提交
194
		let myTopSev: MarkerSeverity | undefined;
195

196
		for (; start < markers.length && Range.areIntersecting(item.symbol.range, markers[start]); start++) {
197 198
			// remove markers intersecting with this outline element
			// and store them in a 'private' array.
199
			let marker = markers[start];
200
			myMarkers.push(marker);
201
			(markers as Array<IMarker | undefined>)[start] = undefined;
202 203
			if (!myTopSev || marker.severity > myTopSev) {
				myTopSev = marker.severity;
204 205 206
			}
		}

207 208 209 210
		// 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'
211 212 213
		for (const key in item.children) {
			this._updateMarker(myMarkers, item.children[key]);
		}
214

215
		if (myTopSev) {
216 217 218 219 220
			item.marker = {
				count: myMarkers.length,
				topSev: myTopSev
			};
		}
221

222
		coalesceInPlace(markers);
223
	}
J
Johannes Rieken 已提交
224
}
J
Johannes Rieken 已提交
225

J
Johannes Rieken 已提交
226 227
export class OutlineModel extends TreeElement {

228
	private static readonly _requests = new LRUCache<string, { promiseCnt: number, source: CancellationTokenSource, promise: Promise<any>, model: OutlineModel | undefined }>(9, .75);
J
Johannes Rieken 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
	private static readonly _keys = new class {

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

		for(textModel: ITextModel): string {
			return `${textModel.id}/${textModel.getVersionId()}/${this._hash(DocumentSymbolProviderRegistry.all(textModel))}`;
		}

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

252

253
	static create(textModel: ITextModel, token: CancellationToken): Promise<OutlineModel> {
254

J
Johannes Rieken 已提交
255
		let key = this._keys.for(textModel);
256 257
		let data = OutlineModel._requests.get(key);

258
		if (!data) {
259
			let source = new CancellationTokenSource();
260 261
			data = {
				promiseCnt: 0,
262 263
				source,
				promise: OutlineModel._create(textModel, source.token),
264 265
				model: undefined,
			};
266 267 268
			OutlineModel._requests.set(key, data);
		}

269
		if (data!.model) {
270
			// resolved -> return data
271
			return Promise.resolve(data.model);
272 273
		}

274
		// increase usage counter
275
		data!.promiseCnt += 1;
276

277 278
		token.onCancellationRequested(() => {
			// last -> cancel provider request, remove cached promise
279 280
			if (--data!.promiseCnt === 0) {
				data!.source.cancel();
281 282 283 284 285
				OutlineModel._requests.delete(key);
			}
		});

		return new Promise((resolve, reject) => {
286 287
			data!.promise.then(model => {
				data!.model = model;
288
				resolve(model);
289 290
			}, err => {
				OutlineModel._requests.delete(key);
291 292
				reject(err);
			});
293 294 295
		});
	}

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

J
Johannes Rieken 已提交
298 299
		let result = new OutlineModel(textModel);
		let promises = DocumentSymbolProviderRegistry.ordered(textModel).map((provider, index) => {
300

J
Johannes Rieken 已提交
301 302
			let id = TreeElement.findId(`provider_${index}`, result);
			let group = new OutlineGroup(id, result, provider, index);
303

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

321
		return Promise.all(promises).then(() => result._compact());
322 323
	}

324
	private static _makeOutlineElement(info: DocumentSymbol, container: OutlineGroup | OutlineElement): void {
325
		let id = TreeElement.findId(info, container);
J
Johannes Rieken 已提交
326 327 328 329 330
		let res = new OutlineElement(id, container, info);
		if (info.children) {
			for (const childInfo of info.children) {
				OutlineModel._makeOutlineElement(childInfo, res);
			}
331
		}
J
Johannes Rieken 已提交
332
		container.children[res.id] = res;
333 334
	}

335
	static get(element: TreeElement | undefined): OutlineModel | undefined {
336 337 338 339 340 341 342 343 344
		while (element) {
			if (element instanceof OutlineModel) {
				return element;
			}
			element = element.parent;
		}
		return undefined;
	}

J
Johannes Rieken 已提交
345 346 347
	readonly id = 'root';
	readonly parent = undefined;

348
	protected _groups: { [id: string]: OutlineGroup; } = Object.create(null);
J
Johannes Rieken 已提交
349 350
	children: { [id: string]: OutlineGroup | OutlineElement; } = Object.create(null);

351
	protected constructor(readonly textModel: ITextModel) {
J
Johannes Rieken 已提交
352 353 354
		super();
	}

355 356 357 358 359
	adopt(): OutlineModel {
		let res = new OutlineModel(this.textModel);
		forEach(this._groups, entry => res._groups[entry.key] = entry.value.adopt(res));
		return res._compact();
	}
J
Johannes Rieken 已提交
360

361
	private _compact(): this {
R
Rudi Chen 已提交
362
		let count = 0;
363 364 365 366
		for (const key in this._groups) {
			let group = this._groups[key];
			if (first(group.children) === undefined) { // empty
				delete this._groups[key];
R
Rudi Chen 已提交
367 368
			} else {
				count += 1;
369 370
			}
		}
R
Rudi Chen 已提交
371 372 373 374
		if (count !== 1) {
			//
			this.children = this._groups;
		} else {
375
			// adopt all elements of the first group
R
Rudi Chen 已提交
376
			let group = first(this._groups);
R
Rudi Chen 已提交
377 378
			for (let key in group!.children) {
				let child = group!.children[key];
379 380 381 382 383
				child.parent = this;
				this.children[child.id] = child;
			}
		}
		return this;
J
Johannes Rieken 已提交
384 385
	}

386
	merge(other: OutlineModel): boolean {
J
Johannes Rieken 已提交
387 388 389 390 391 392 393 394 395 396 397
		if (this.textModel.uri.toString() !== other.textModel.uri.toString()) {
			return false;
		}
		if (size(this._groups) !== size(other._groups)) {
			return false;
		}
		this._groups = other._groups;
		this.children = other.children;
		return true;
	}

398
	private _matches: [string, OutlineElement | undefined];
399

400
	updateMatches(pattern: string): OutlineElement | undefined {
401 402 403
		if (this._matches && this._matches[0] === pattern) {
			return this._matches[1];
		}
404
		let topMatch: OutlineElement | undefined;
405 406
		for (const key in this._groups) {
			topMatch = this._groups[key].updateMatches(pattern, topMatch);
J
Johannes Rieken 已提交
407
		}
408
		this._matches = [pattern, topMatch];
J
Johannes Rieken 已提交
409
		return topMatch;
410 411
	}

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 key in this._groups) {
427 428 429 430
			const group = this._groups[key];
			result = group.getItemEnclosingPosition(position);
			if (result && (!preferredGroup || preferredGroup === group)) {
				break;
J
Johannes Rieken 已提交
431 432
			}
		}
433
		return result;
434 435
	}

436
	getItemById(id: string): TreeElement | undefined {
J
Johannes Rieken 已提交
437
		return TreeElement.getElementById(id, this);
438
	}
439 440 441 442 443 444 445

	updateMarker(marker: IMarker[]): void {
		// sort markers by start range so that we can use
		// outline element starts for quicker look up
		marker.sort(Range.compareRangesUsingStarts);

		for (const key in this._groups) {
446
			this._groups[key].updateMarker(marker.slice(0));
447 448
		}
	}
449
}