outlineModel.ts 12.4 KB
Newer Older
J
Johannes Rieken 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7
import { DocumentSymbolProviderRegistry, DocumentSymbolProvider, DocumentSymbol } from 'vs/editor/common/modes';
J
Johannes Rieken 已提交
8
import { ITextModel } from 'vs/editor/common/model';
J
Johannes Rieken 已提交
9
import { fuzzyScore, FuzzyScore } from 'vs/base/common/filters';
J
Johannes Rieken 已提交
10
import { IPosition } from 'vs/editor/common/core/position';
11
import { Range, IRange } from 'vs/editor/common/core/range';
12
import { first, size, forEach } from 'vs/base/common/collections';
13
import { isFalsyOrEmpty, binarySearch, coalesce } from 'vs/base/common/arrays';
14
import { commonPrefixLength } from 'vs/base/common/strings';
15
import { IMarker, MarkerSeverity } from 'vs/platform/markers/common/markers';
J
Johannes Rieken 已提交
16
import { onUnexpectedExternalError } from 'vs/base/common/errors';
17
import { LRUCache } from 'vs/base/common/map';
18
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
J
Johannes Rieken 已提交
19

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

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

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

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

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

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

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

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

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

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

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

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

J
Johannes Rieken 已提交
95 96
	constructor(
		readonly id: string,
97
		public parent: OutlineModel | OutlineGroup | OutlineElement,
98
		readonly symbol: DocumentSymbol
J
Johannes Rieken 已提交
99
	) {
J
Johannes Rieken 已提交
100
		super();
J
Johannes Rieken 已提交
101
	}
102 103 104 105 106 107

	adopt(parent: OutlineModel | OutlineGroup | OutlineElement): OutlineElement {
		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 已提交
108 109
}

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

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

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

123 124 125 126 127 128
	adopt(parent: OutlineModel): OutlineGroup {
		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;
	}

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

J
Johannes Rieken 已提交
136
	private _updateMatches(pattern: string, item: OutlineElement, topMatch: OutlineElement): OutlineElement {
137
		item.score = fuzzyScore(pattern, item.symbol.name, undefined, true);
J
Johannes Rieken 已提交
138
		if (item.score && (!topMatch || item.score[0] > topMatch.score[0])) {
139 140
			topMatch = item;
		}
J
Johannes Rieken 已提交
141 142 143 144
		for (const key in item.children) {
			let child = item.children[key];
			topMatch = this._updateMatches(pattern, child, topMatch);
			if (!item.score && child.score) {
145
				// don't filter parents with unfiltered children
J
Johannes Rieken 已提交
146
				item.score = [0, []];
147
			}
J
Johannes Rieken 已提交
148
		}
149
		return topMatch;
J
Johannes Rieken 已提交
150
	}
J
Johannes Rieken 已提交
151

J
Johannes Rieken 已提交
152 153 154 155 156 157 158
	getItemEnclosingPosition(position: IPosition): OutlineElement {
		return this._getItemEnclosingPosition(position, this.children);
	}

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

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

173 174 175 176 177
	private _updateMarker(markers: IMarker[], item: OutlineElement): void {

		item.marker = undefined;

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

		let myMarkers: IMarker[] = [];
		let myTopSev: MarkerSeverity;

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

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

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

		coalesce(markers, true);
219
	}
J
Johannes Rieken 已提交
220
}
J
Johannes Rieken 已提交
221

J
Johannes Rieken 已提交
222 223
export class OutlineModel extends TreeElement {

224
	private static readonly _requests = new LRUCache<string, { promiseCnt: number, source: CancellationTokenSource, promise: Promise<any>, model: OutlineModel }>(9, .75);
J
Johannes Rieken 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
	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;
		}
	};

248

249
	static create(textModel: ITextModel, token: CancellationToken): Promise<OutlineModel> {
250

J
Johannes Rieken 已提交
251
		let key = this._keys.for(textModel);
252 253
		let data = OutlineModel._requests.get(key);

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

265 266
		if (data.model) {
			// resolved -> return data
267
			return Promise.resolve(data.model);
268 269
		}

270
		// increase usage counter
271
		data.promiseCnt += 1;
272

273 274 275 276 277 278 279 280 281
		token.onCancellationRequested(() => {
			// last -> cancel provider request, remove cached promise
			if (--data.promiseCnt === 0) {
				data.source.cancel();
				OutlineModel._requests.delete(key);
			}
		});

		return new Promise((resolve, reject) => {
282 283 284
			data.promise.then(model => {
				data.model = model;
				resolve(model);
285 286
			}, err => {
				OutlineModel._requests.delete(key);
287 288
				reject(err);
			});
289 290 291
		});
	}

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

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

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

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

319
		return Promise.all(promises).then(() => result._compact());
320 321
	}

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

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

J
Johannes Rieken 已提交
343 344 345
	readonly id = 'root';
	readonly parent = undefined;

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

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

353 354 355 356 357
	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 已提交
358

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

384
	merge(other: OutlineModel): boolean {
J
Johannes Rieken 已提交
385 386 387 388 389 390 391 392 393 394 395
		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;
	}

J
Johannes Rieken 已提交
396 397
	updateMatches(pattern: string): OutlineElement {
		let topMatch: OutlineElement;
398 399
		for (const key in this._groups) {
			topMatch = this._groups[key].updateMatches(pattern, topMatch);
J
Johannes Rieken 已提交
400 401
		}
		return topMatch;
402 403
	}

404 405 406 407 408 409 410 411 412 413 414 415 416 417
	getItemEnclosingPosition(position: IPosition, context?: OutlineElement): OutlineElement {

		let preferredGroup: OutlineGroup;
		if (context) {
			let candidate = context.parent;
			while (candidate && !preferredGroup) {
				if (candidate instanceof OutlineGroup) {
					preferredGroup = candidate;
				}
				candidate = candidate.parent;
			}
		}

		let result: OutlineElement = undefined;
418
		for (const key in this._groups) {
419 420 421 422
			const group = this._groups[key];
			result = group.getItemEnclosingPosition(position);
			if (result && (!preferredGroup || preferredGroup === group)) {
				break;
J
Johannes Rieken 已提交
423 424
			}
		}
425
		return result;
426 427
	}

J
Johannes Rieken 已提交
428 429
	getItemById(id: string): TreeElement {
		return TreeElement.getElementById(id, this);
430
	}
431 432 433 434 435 436 437

	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) {
438
			this._groups[key].updateMarker(marker.slice(0));
439 440
		}
	}
441
}