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

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

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

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

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

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
	// todo@joh sort by position!
	firstChild(): TreeElement | undefined {
		const [first] = Object.keys(this.children);
		return this.children[first];
	}

	lastChild(): TreeElement | undefined {
		const [last] = Object.keys(this.children).slice(-1);
		return this.children[last];
	}

	sibling(next: boolean): TreeElement | undefined {
		if (!this.parent) {
			return undefined;
		}
		const all = Object.keys(this.parent.children);
		const index = all.indexOf(this.id) + (next ? +1 : -1);
		return this.parent.children[all[index]];
	}

52
	static findId(candidate: DocumentSymbol | string, container: TreeElement): string {
J
Johannes Rieken 已提交
53 54
		// complex id-computation which contains the origin/extension,
		// the parent path, and some dedupe logic when names collide
55 56 57 58 59
		let candidateId: string;
		if (typeof candidate === 'string') {
			candidateId = `${container.id}/${candidate}`;
		} else {
			candidateId = `${container.id}/${candidate.name}`;
R
Rob Lourens 已提交
60
			if (container.children[candidateId] !== undefined) {
61
				candidateId = `${container.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
62 63 64 65
			}
		}

		let id = candidateId;
R
Rob Lourens 已提交
66
		for (let i = 0; container.children[id] !== undefined; i++) {
67
			id = `${candidateId}_${i}`;
J
Johannes Rieken 已提交
68
		}
69

J
Johannes Rieken 已提交
70
		return id;
71
	}
72

73
	static getElementById(id: string, element: TreeElement): TreeElement | undefined {
74 75 76 77 78
		if (!id) {
			return undefined;
		}
		let len = commonPrefixLength(id, element.id);
		if (len === id.length) {
J
Johannes Rieken 已提交
79 80
			return element;
		}
81 82 83
		if (len < element.id.length) {
			return undefined;
		}
J
Johannes Rieken 已提交
84 85 86 87 88
		for (const key in element.children) {
			let candidate = TreeElement.getElementById(id, element.children[key]);
			if (candidate) {
				return candidate;
			}
J
Johannes Rieken 已提交
89
		}
J
Johannes Rieken 已提交
90
		return undefined;
J
Johannes Rieken 已提交
91
	}
92 93 94 95 96 97 98 99

	static size(element: TreeElement): number {
		let res = 1;
		for (const key in element.children) {
			res += TreeElement.size(element.children[key]);
		}
		return res;
	}
100 101 102 103 104 105 106

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

J
Johannes Rieken 已提交
109 110 111 112 113 114 115 116
export interface IOutlineMarker {
	startLineNumber: number;
	startColumn: number;
	endLineNumber: number;
	endColumn: number;
	severity: MarkerSeverity;
}

J
Johannes Rieken 已提交
117
export class OutlineElement extends TreeElement {
J
Johannes Rieken 已提交
118

J
Johannes Rieken 已提交
119
	children: { [id: string]: OutlineElement; } = Object.create(null);
120
	marker: { count: number, topSev: MarkerSeverity } | undefined;
J
Johannes Rieken 已提交
121

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

130
	adopt(parent: TreeElement): OutlineElement {
131 132 133 134
		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 已提交
135 136
}

J
Johannes Rieken 已提交
137
export class OutlineGroup extends TreeElement {
J
Johannes Rieken 已提交
138

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

J
Johannes Rieken 已提交
141
	constructor(
J
Johannes Rieken 已提交
142
		readonly id: string,
143
		public parent: TreeElement | undefined,
J
Johannes Rieken 已提交
144 145
		readonly provider: DocumentSymbolProvider,
		readonly providerIndex: number,
J
Johannes Rieken 已提交
146
	) {
J
Johannes Rieken 已提交
147
		super();
J
Johannes Rieken 已提交
148
	}
J
Johannes Rieken 已提交
149

150
	adopt(parent: TreeElement): OutlineGroup {
151 152 153 154 155
		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;
	}

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

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

J
Johannes Rieken 已提交
171
	updateMarker(marker: IOutlineMarker[]): void {
172 173 174 175 176
		for (const key in this.children) {
			this._updateMarker(marker, this.children[key]);
		}
	}

J
Johannes Rieken 已提交
177
	private _updateMarker(markers: IOutlineMarker[], item: OutlineElement): void {
178 179 180
		item.marker = undefined;

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

J
Johannes Rieken 已提交
192
		let myMarkers: IOutlineMarker[] = [];
R
Rudi Chen 已提交
193
		let myTopSev: MarkerSeverity | undefined;
194

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

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

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

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

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
class MovingAverage {

	private _n = 1;
	private _val = 0;

	update(value: number): this {
		this._val = this._val + (value - this._val) / this._n;
		this._n += 1;
		return this;
	}

	get value(): number {
		return this._val;
	}
}

J
Johannes Rieken 已提交
241 242
export class OutlineModel extends TreeElement {

243
	private static readonly _requestDurations = new LRUCache<string, MovingAverage>(50, 0.7);
244
	private static readonly _requests = new LRUCache<string, { promiseCnt: number, source: CancellationTokenSource, promise: Promise<any>, model: OutlineModel | undefined }>(9, 0.75);
J
Johannes Rieken 已提交
245 246 247 248 249
	private static readonly _keys = new class {

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

250 251
		for(textModel: ITextModel, version: boolean): string {
			return `${textModel.id}/${version ? textModel.getVersionId() : ''}/${this._hash(DocumentSymbolProviderRegistry.all(textModel))}`;
J
Johannes Rieken 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
		}

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

268

269
	static create(textModel: ITextModel, token: CancellationToken): Promise<OutlineModel> {
270

271
		let key = this._keys.for(textModel, true);
272 273
		let data = OutlineModel._requests.get(key);

274
		if (!data) {
275
			let source = new CancellationTokenSource();
276 277
			data = {
				promiseCnt: 0,
278 279
				source,
				promise: OutlineModel._create(textModel, source.token),
280 281
				model: undefined,
			};
282
			OutlineModel._requests.set(key, data);
283 284 285 286 287 288 289 290 291 292 293 294

			// keep moving average of request durations
			const now = Date.now();
			data.promise.then(() => {
				let key = this._keys.for(textModel, false);
				let avg = this._requestDurations.get(key);
				if (!avg) {
					avg = new MovingAverage();
					this._requestDurations.set(key, avg);
				}
				avg.update(Date.now() - now);
			});
295 296
		}

297
		if (data!.model) {
298
			// resolved -> return data
299
			return Promise.resolve(data.model!);
300 301
		}

302
		// increase usage counter
303
		data!.promiseCnt += 1;
304

305 306
		token.onCancellationRequested(() => {
			// last -> cancel provider request, remove cached promise
307 308
			if (--data!.promiseCnt === 0) {
				data!.source.cancel();
309 310 311 312 313
				OutlineModel._requests.delete(key);
			}
		});

		return new Promise((resolve, reject) => {
314 315
			data!.promise.then(model => {
				data!.model = model;
316
				resolve(model);
317 318
			}, err => {
				OutlineModel._requests.delete(key);
319 320
				reject(err);
			});
321 322 323
		});
	}

324 325 326 327 328 329 330 331 332 333 334 335
	static getRequestDelay(textModel: ITextModel | null): number {
		if (!textModel) {
			return 350;
		}
		const avg = this._requestDurations.get(this._keys.for(textModel, false));
		if (!avg) {
			return 350;
		}
		return Math.max(350, Math.floor(1.3 * avg.value));
	}

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

337
		const cts = new CancellationTokenSource(token);
338 339 340
		const result = new OutlineModel(textModel);
		const provider = DocumentSymbolProviderRegistry.ordered(textModel);
		const promises = provider.map((provider, index) => {
341

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

345
			return Promise.resolve(provider.provideDocumentSymbols(result.textModel, cts.token)).then(result => {
346 347
				for (const info of result || []) {
					OutlineModel._makeOutlineElement(info, group);
J
Johannes Rieken 已提交
348 349 350
				}
				return group;
			}, err => {
J
Johannes Rieken 已提交
351
				onUnexpectedExternalError(err);
J
Johannes Rieken 已提交
352 353
				return group;
			}).then(group => {
354 355 356 357 358
				if (!TreeElement.empty(group)) {
					result._groups[id] = group;
				} else {
					group.remove();
				}
J
Johannes Rieken 已提交
359 360 361
			});
		});

362 363 364
		const listener = DocumentSymbolProviderRegistry.onDidChange(() => {
			const newProvider = DocumentSymbolProviderRegistry.ordered(textModel);
			if (!equals(newProvider, provider)) {
365
				cts.cancel();
366 367 368 369
			}
		});

		return Promise.all(promises).then(() => {
370
			if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
371 372 373 374 375 376 377
				return OutlineModel._create(textModel, token);
			} else {
				return result._compact();
			}
		}).finally(() => {
			listener.dispose();
		});
378 379
	}

380
	private static _makeOutlineElement(info: DocumentSymbol, container: OutlineGroup | OutlineElement): void {
381
		let id = TreeElement.findId(info, container);
J
Johannes Rieken 已提交
382 383 384 385 386
		let res = new OutlineElement(id, container, info);
		if (info.children) {
			for (const childInfo of info.children) {
				OutlineModel._makeOutlineElement(childInfo, res);
			}
387
		}
J
Johannes Rieken 已提交
388
		container.children[res.id] = res;
389 390
	}

391
	static get(element: TreeElement | undefined): OutlineModel | undefined {
392 393 394 395 396 397 398 399 400
		while (element) {
			if (element instanceof OutlineModel) {
				return element;
			}
			element = element.parent;
		}
		return undefined;
	}

J
Johannes Rieken 已提交
401 402 403
	readonly id = 'root';
	readonly parent = undefined;

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

407
	protected constructor(readonly textModel: ITextModel) {
J
Johannes Rieken 已提交
408
		super();
P
Peng Lyu 已提交
409 410 411

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

414 415 416 417 418
	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 已提交
419

420
	private _compact(): this {
R
Rudi Chen 已提交
421
		let count = 0;
422 423 424 425
		for (const key in this._groups) {
			let group = this._groups[key];
			if (first(group.children) === undefined) { // empty
				delete this._groups[key];
R
Rudi Chen 已提交
426 427
			} else {
				count += 1;
428 429
			}
		}
R
Rudi Chen 已提交
430 431 432 433
		if (count !== 1) {
			//
			this.children = this._groups;
		} else {
434
			// adopt all elements of the first group
R
Rudi Chen 已提交
435
			let group = first(this._groups);
R
Rudi Chen 已提交
436 437
			for (let key in group!.children) {
				let child = group!.children[key];
438 439 440 441 442
				child.parent = this;
				this.children[child.id] = child;
			}
		}
		return this;
J
Johannes Rieken 已提交
443 444
	}

445
	merge(other: OutlineModel): boolean {
J
Johannes Rieken 已提交
446 447 448 449 450 451 452 453 454 455 456
		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;
	}

457
	getItemEnclosingPosition(position: IPosition, context?: OutlineElement): OutlineElement | undefined {
458

459
		let preferredGroup: OutlineGroup | undefined;
460 461 462 463 464 465 466 467 468 469
		if (context) {
			let candidate = context.parent;
			while (candidate && !preferredGroup) {
				if (candidate instanceof OutlineGroup) {
					preferredGroup = candidate;
				}
				candidate = candidate.parent;
			}
		}

470
		let result: OutlineElement | undefined = undefined;
471
		for (const key in this._groups) {
472 473 474 475
			const group = this._groups[key];
			result = group.getItemEnclosingPosition(position);
			if (result && (!preferredGroup || preferredGroup === group)) {
				break;
J
Johannes Rieken 已提交
476 477
			}
		}
478
		return result;
479 480
	}

481
	getItemById(id: string): TreeElement | undefined {
J
Johannes Rieken 已提交
482
		return TreeElement.getElementById(id, this);
483
	}
484

J
Johannes Rieken 已提交
485
	updateMarker(marker: IOutlineMarker[]): void {
486 487 488 489 490
		// 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) {
491
			this._groups[key].updateMarker(marker.slice(0));
492 493
		}
	}
494
}