outlineModel.ts 11.5 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 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';
16
import { IMarker, 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
export class OutlineElement extends TreeElement {
J
Johannes Rieken 已提交
90

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

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

102
	adopt(parent: TreeElement): OutlineElement {
103 104 105 106
		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 已提交
107 108
}

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

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

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

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

128
	getItemEnclosingPosition(position: IPosition): OutlineElement | undefined {
J
Johannes Rieken 已提交
129
		return position ? this._getItemEnclosingPosition(position, this.children) : undefined;
J
Johannes Rieken 已提交
130 131
	}

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

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

149 150 151 152
	private _updateMarker(markers: IMarker[], item: OutlineElement): void {
		item.marker = undefined;

		// find the proper start index to check for item/marker overlap.
153
		let idx = binarySearch<IRange>(markers, item.symbol.range, Range.compareRangesUsingStarts);
154 155 156
		let start: number;
		if (idx < 0) {
			start = ~idx;
157
			if (start > 0 && Range.areIntersecting(markers[start - 1], item.symbol.range)) {
158 159 160 161 162 163 164
				start -= 1;
			}
		} else {
			start = idx;
		}

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

167
		for (; start < markers.length && Range.areIntersecting(item.symbol.range, markers[start]); start++) {
168 169
			// remove markers intersecting with this outline element
			// and store them in a 'private' array.
170
			let marker = markers[start];
171
			myMarkers.push(marker);
172
			(markers as Array<IMarker | undefined>)[start] = undefined;
173 174
			if (!myTopSev || marker.severity > myTopSev) {
				myTopSev = marker.severity;
175 176 177
			}
		}

178 179 180 181
		// 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'
182 183 184
		for (const key in item.children) {
			this._updateMarker(myMarkers, item.children[key]);
		}
185

186
		if (myTopSev) {
187 188 189 190 191
			item.marker = {
				count: myMarkers.length,
				topSev: myTopSev
			};
		}
192

193
		coalesceInPlace(markers);
194
	}
J
Johannes Rieken 已提交
195
}
J
Johannes Rieken 已提交
196

J
Johannes Rieken 已提交
197 198
export class OutlineModel extends TreeElement {

199
	private static readonly _requests = new LRUCache<string, { promiseCnt: number, source: CancellationTokenSource, promise: Promise<any>, model: OutlineModel | undefined }>(9, 0.75);
J
Johannes Rieken 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
	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;
		}
	};

223

224
	static create(textModel: ITextModel, token: CancellationToken): Promise<OutlineModel> {
225

J
Johannes Rieken 已提交
226
		let key = this._keys.for(textModel);
227 228
		let data = OutlineModel._requests.get(key);

229
		if (!data) {
230
			let source = new CancellationTokenSource();
231 232
			data = {
				promiseCnt: 0,
233 234
				source,
				promise: OutlineModel._create(textModel, source.token),
235 236
				model: undefined,
			};
237 238 239
			OutlineModel._requests.set(key, data);
		}

240
		if (data!.model) {
241
			// resolved -> return data
242
			return Promise.resolve(data.model!);
243 244
		}

245
		// increase usage counter
246
		data!.promiseCnt += 1;
247

248 249
		token.onCancellationRequested(() => {
			// last -> cancel provider request, remove cached promise
250 251
			if (--data!.promiseCnt === 0) {
				data!.source.cancel();
252 253 254 255 256
				OutlineModel._requests.delete(key);
			}
		});

		return new Promise((resolve, reject) => {
257 258
			data!.promise.then(model => {
				data!.model = model;
259
				resolve(model);
260 261
			}, err => {
				OutlineModel._requests.delete(key);
262 263
				reject(err);
			});
264 265 266
		});
	}

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

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

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

275
			return Promise.resolve(provider.provideDocumentSymbols(result.textModel, token)).then(result => {
276 277
				for (const info of result || []) {
					OutlineModel._makeOutlineElement(info, group);
J
Johannes Rieken 已提交
278 279 280
				}
				return group;
			}, err => {
J
Johannes Rieken 已提交
281
				onUnexpectedExternalError(err);
J
Johannes Rieken 已提交
282 283
				return group;
			}).then(group => {
284 285 286 287 288
				if (!TreeElement.empty(group)) {
					result._groups[id] = group;
				} else {
					group.remove();
				}
J
Johannes Rieken 已提交
289 290 291
			});
		});

292
		return Promise.all(promises).then(() => result._compact());
293 294
	}

295
	private static _makeOutlineElement(info: DocumentSymbol, container: OutlineGroup | OutlineElement): void {
296
		let id = TreeElement.findId(info, container);
J
Johannes Rieken 已提交
297 298 299 300 301
		let res = new OutlineElement(id, container, info);
		if (info.children) {
			for (const childInfo of info.children) {
				OutlineModel._makeOutlineElement(childInfo, res);
			}
302
		}
J
Johannes Rieken 已提交
303
		container.children[res.id] = res;
304 305
	}

306
	static get(element: TreeElement | undefined): OutlineModel | undefined {
307 308 309 310 311 312 313 314 315
		while (element) {
			if (element instanceof OutlineModel) {
				return element;
			}
			element = element.parent;
		}
		return undefined;
	}

J
Johannes Rieken 已提交
316 317 318
	readonly id = 'root';
	readonly parent = undefined;

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

322
	protected constructor(readonly textModel: ITextModel) {
J
Johannes Rieken 已提交
323 324 325
		super();
	}

326 327 328 329 330
	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 已提交
331

332
	private _compact(): this {
R
Rudi Chen 已提交
333
		let count = 0;
334 335 336 337
		for (const key in this._groups) {
			let group = this._groups[key];
			if (first(group.children) === undefined) { // empty
				delete this._groups[key];
R
Rudi Chen 已提交
338 339
			} else {
				count += 1;
340 341
			}
		}
R
Rudi Chen 已提交
342 343 344 345
		if (count !== 1) {
			//
			this.children = this._groups;
		} else {
346
			// adopt all elements of the first group
R
Rudi Chen 已提交
347
			let group = first(this._groups);
R
Rudi Chen 已提交
348 349
			for (let key in group!.children) {
				let child = group!.children[key];
350 351 352 353 354
				child.parent = this;
				this.children[child.id] = child;
			}
		}
		return this;
J
Johannes Rieken 已提交
355 356
	}

357
	merge(other: OutlineModel): boolean {
J
Johannes Rieken 已提交
358 359 360 361 362 363 364 365 366 367 368
		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;
	}

369
	getItemEnclosingPosition(position: IPosition, context?: OutlineElement): OutlineElement | undefined {
370

371
		let preferredGroup: OutlineGroup | undefined;
372 373 374 375 376 377 378 379 380 381
		if (context) {
			let candidate = context.parent;
			while (candidate && !preferredGroup) {
				if (candidate instanceof OutlineGroup) {
					preferredGroup = candidate;
				}
				candidate = candidate.parent;
			}
		}

382
		let result: OutlineElement | undefined = undefined;
383
		for (const key in this._groups) {
384 385 386 387
			const group = this._groups[key];
			result = group.getItemEnclosingPosition(position);
			if (result && (!preferredGroup || preferredGroup === group)) {
				break;
J
Johannes Rieken 已提交
388 389
			}
		}
390
		return result;
391 392
	}

393
	getItemById(id: string): TreeElement | undefined {
J
Johannes Rieken 已提交
394
		return TreeElement.getElementById(id, this);
395
	}
396 397 398 399 400 401 402

	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) {
403
			this._groups[key].updateMarker(marker.slice(0));
404 405
		}
	}
406
}