outlineModel.ts 12.2 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
	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
		let candidateId: string;
		if (typeof candidate === 'string') {
			candidateId = `${container.id}/${candidate}`;
		} else {
			candidateId = `${container.id}/${candidate.name}`;
R
Rob Lourens 已提交
40
			if (container.children[candidateId] !== undefined) {
41
				candidateId = `${container.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
42 43 44 45
			}
		}

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

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

53
	static getElementById(id: string, element: TreeElement): TreeElement | undefined {
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 90 91 92 93 94 95 96
export interface IOutlineMarker {
	startLineNumber: number;
	startColumn: number;
	endLineNumber: number;
	endColumn: number;
	severity: MarkerSeverity;
}

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

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

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

110
	adopt(parent: TreeElement): OutlineElement {
111 112 113 114
		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 已提交
115 116
}

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

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

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

130
	adopt(parent: TreeElement): OutlineGroup {
131 132 133 134 135
		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;
	}

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

140
	private _getItemEnclosingPosition(position: IPosition, children: { [id: string]: OutlineElement }): OutlineElement | undefined {
J
Johannes Rieken 已提交
141 142
		for (let key in children) {
			let item = children[key];
J
Johannes Rieken 已提交
143
			if (!item.symbol.range || !Range.containsPosition(item.symbol.range, position)) {
J
Johannes Rieken 已提交
144
				continue;
J
Johannes Rieken 已提交
145
			}
J
Johannes Rieken 已提交
146
			return this._getItemEnclosingPosition(position, item.children) || item;
J
Johannes Rieken 已提交
147 148 149
		}
		return undefined;
	}
150

J
Johannes Rieken 已提交
151
	updateMarker(marker: IOutlineMarker[]): void {
152 153 154 155 156
		for (const key in this.children) {
			this._updateMarker(marker, this.children[key]);
		}
	}

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

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

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

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

186 187 188 189
		// 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'
190 191 192
		for (const key in item.children) {
			this._updateMarker(myMarkers, item.children[key]);
		}
193

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

201
		coalesceInPlace(markers);
202
	}
J
Johannes Rieken 已提交
203
}
J
Johannes Rieken 已提交
204

J
Johannes Rieken 已提交
205 206
export class OutlineModel extends TreeElement {

207
	private static readonly _requests = new LRUCache<string, { promiseCnt: number, source: CancellationTokenSource, promise: Promise<any>, model: OutlineModel | undefined }>(9, 0.75);
J
Johannes Rieken 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
	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;
		}
	};

231

232
	static create(textModel: ITextModel, token: CancellationToken): Promise<OutlineModel> {
233

J
Johannes Rieken 已提交
234
		let key = this._keys.for(textModel);
235 236
		let data = OutlineModel._requests.get(key);

237
		if (!data) {
238
			let source = new CancellationTokenSource();
239 240
			data = {
				promiseCnt: 0,
241 242
				source,
				promise: OutlineModel._create(textModel, source.token),
243 244
				model: undefined,
			};
245 246 247
			OutlineModel._requests.set(key, data);
		}

248
		if (data!.model) {
249
			// resolved -> return data
250
			return Promise.resolve(data.model!);
251 252
		}

253
		// increase usage counter
254
		data!.promiseCnt += 1;
255

256 257
		token.onCancellationRequested(() => {
			// last -> cancel provider request, remove cached promise
258 259
			if (--data!.promiseCnt === 0) {
				data!.source.cancel();
260 261 262 263 264
				OutlineModel._requests.delete(key);
			}
		});

		return new Promise((resolve, reject) => {
265 266
			data!.promise.then(model => {
				data!.model = model;
267
				resolve(model);
268 269
			}, err => {
				OutlineModel._requests.delete(key);
270 271
				reject(err);
			});
272 273 274
		});
	}

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

277
		const cts = new CancellationTokenSource(token);
278 279 280
		const result = new OutlineModel(textModel);
		const provider = DocumentSymbolProviderRegistry.ordered(textModel);
		const promises = provider.map((provider, index) => {
281

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

285
			return Promise.resolve(provider.provideDocumentSymbols(result.textModel, cts.token)).then(result => {
286 287
				for (const info of result || []) {
					OutlineModel._makeOutlineElement(info, group);
J
Johannes Rieken 已提交
288 289 290
				}
				return group;
			}, err => {
J
Johannes Rieken 已提交
291
				onUnexpectedExternalError(err);
J
Johannes Rieken 已提交
292 293
				return group;
			}).then(group => {
294 295 296 297 298
				if (!TreeElement.empty(group)) {
					result._groups[id] = group;
				} else {
					group.remove();
				}
J
Johannes Rieken 已提交
299 300 301
			});
		});

302 303 304
		const listener = DocumentSymbolProviderRegistry.onDidChange(() => {
			const newProvider = DocumentSymbolProviderRegistry.ordered(textModel);
			if (!equals(newProvider, provider)) {
305
				cts.cancel();
306 307 308 309
			}
		});

		return Promise.all(promises).then(() => {
310
			if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
311 312 313 314 315 316 317
				return OutlineModel._create(textModel, token);
			} else {
				return result._compact();
			}
		}).finally(() => {
			listener.dispose();
		});
318 319
	}

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

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

J
Johannes Rieken 已提交
341 342 343
	readonly id = 'root';
	readonly parent = undefined;

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

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

351 352 353 354 355
	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 已提交
356

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

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

394
	getItemEnclosingPosition(position: IPosition, context?: OutlineElement): OutlineElement | undefined {
395

396
		let preferredGroup: OutlineGroup | undefined;
397 398 399 400 401 402 403 404 405 406
		if (context) {
			let candidate = context.parent;
			while (candidate && !preferredGroup) {
				if (candidate instanceof OutlineGroup) {
					preferredGroup = candidate;
				}
				candidate = candidate.parent;
			}
		}

407
		let result: OutlineElement | undefined = undefined;
408
		for (const key in this._groups) {
409 410 411 412
			const group = this._groups[key];
			result = group.getItemEnclosingPosition(position);
			if (result && (!preferredGroup || preferredGroup === group)) {
				break;
J
Johannes Rieken 已提交
413 414
			}
		}
415
		return result;
416 417
	}

418
	getItemById(id: string): TreeElement | undefined {
J
Johannes Rieken 已提交
419
		return TreeElement.getElementById(id, this);
420
	}
421

J
Johannes Rieken 已提交
422
	updateMarker(marker: IOutlineMarker[]): void {
423 424 425 426 427
		// 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) {
428
			this._groups[key].updateMarker(marker.slice(0));
429 430
		}
	}
431
}