outlineModel.ts 10.3 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 9
import { ITextModel } from 'vs/editor/common/model';
import { asWinJsPromise } from 'vs/base/common/async';
J
Johannes Rieken 已提交
10
import { TPromise } from 'vs/base/common/winjs.base';
J
Johannes Rieken 已提交
11
import { fuzzyScore, FuzzyScore } from 'vs/base/common/filters';
J
Johannes Rieken 已提交
12
import { IPosition } from 'vs/editor/common/core/position';
13
import { Range, IRange } from 'vs/editor/common/core/range';
J
Johannes Rieken 已提交
14
import { first, size } from 'vs/base/common/collections';
15
import { isFalsyOrEmpty, binarySearch } from 'vs/base/common/arrays';
16
import { commonPrefixLength } from 'vs/base/common/strings';
17
import { IMarker, MarkerSeverity } from 'vs/platform/markers/common/markers';
J
Johannes Rieken 已提交
18
import { onUnexpectedExternalError } from 'vs/base/common/errors';
19
import { LRUCache } from 'vs/base/common/map';
J
Johannes Rieken 已提交
20

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

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

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

J
Johannes Rieken 已提交
44
		return id;
45
	}
46

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

	static size(element: TreeElement): number {
		let res = 1;
		for (const key in element.children) {
			res += TreeElement.size(element.children[key]);
		}
		return res;
	}
74 75
}

J
Johannes Rieken 已提交
76
export class OutlineElement extends TreeElement {
J
Johannes Rieken 已提交
77

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

J
Johannes Rieken 已提交
82 83
	constructor(
		readonly id: string,
84
		public parent: OutlineModel | OutlineGroup | OutlineElement,
85
		readonly symbol: DocumentSymbol
J
Johannes Rieken 已提交
86
	) {
J
Johannes Rieken 已提交
87
		super();
J
Johannes Rieken 已提交
88 89 90
	}
}

J
Johannes Rieken 已提交
91
export class OutlineGroup extends TreeElement {
J
Johannes Rieken 已提交
92

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

J
Johannes Rieken 已提交
95
	constructor(
J
Johannes Rieken 已提交
96
		readonly id: string,
97
		public parent: OutlineModel,
J
Johannes Rieken 已提交
98 99
		readonly provider: DocumentSymbolProvider,
		readonly providerIndex: number,
J
Johannes Rieken 已提交
100
	) {
J
Johannes Rieken 已提交
101
		super();
J
Johannes Rieken 已提交
102
	}
J
Johannes Rieken 已提交
103

J
Johannes Rieken 已提交
104 105 106 107
	updateMatches(pattern: string, topMatch: OutlineElement): OutlineElement {
		for (const key in this.children) {
			topMatch = this._updateMatches(pattern, this.children[key], topMatch);
		}
108 109 110
		return topMatch;
	}

J
Johannes Rieken 已提交
111
	private _updateMatches(pattern: string, item: OutlineElement, topMatch: OutlineElement): OutlineElement {
112
		item.score = fuzzyScore(pattern, item.symbol.name, undefined, true);
J
Johannes Rieken 已提交
113
		if (item.score && (!topMatch || item.score[0] > topMatch.score[0])) {
114 115
			topMatch = item;
		}
J
Johannes Rieken 已提交
116 117 118 119
		for (const key in item.children) {
			let child = item.children[key];
			topMatch = this._updateMatches(pattern, child, topMatch);
			if (!item.score && child.score) {
120
				// don't filter parents with unfiltered children
J
Johannes Rieken 已提交
121
				item.score = [0, []];
122
			}
J
Johannes Rieken 已提交
123
		}
124
		return topMatch;
J
Johannes Rieken 已提交
125
	}
J
Johannes Rieken 已提交
126

J
Johannes Rieken 已提交
127 128 129 130 131 132 133
	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];
134
			if (!Range.containsPosition(item.symbol.fullRange, position)) {
J
Johannes Rieken 已提交
135
				continue;
J
Johannes Rieken 已提交
136
			}
J
Johannes Rieken 已提交
137
			return this._getItemEnclosingPosition(position, item.children) || item;
J
Johannes Rieken 已提交
138 139 140
		}
		return undefined;
	}
141 142 143 144 145 146 147

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

148 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.fullRange, Range.compareRangesUsingStarts);
154 155 156
		let start: number;
		if (idx < 0) {
			start = ~idx;
157
			if (start > 0 && Range.areIntersecting(markers[start - 1], item.symbol.fullRange)) {
158 159 160 161 162 163 164 165 166
				start -= 1;
			}
		} else {
			start = idx;
		}

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

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

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

185
		if (myTopSev) {
186 187 188 189 190
			item.marker = {
				count: myMarkers.length,
				topSev: myTopSev
			};
		}
191
	}
J
Johannes Rieken 已提交
192
}
J
Johannes Rieken 已提交
193

J
Johannes Rieken 已提交
194 195
export class OutlineModel extends TreeElement {

196
	private static readonly _requests = new LRUCache<string, { promiseCnt: number, promise: TPromise<any>, model: OutlineModel }>(9, .75);
197

198
	static create(textModel: ITextModel): TPromise<OutlineModel> {
199 200 201 202

		let key = `${textModel.id}/${textModel.getVersionId()}/${DocumentSymbolProviderRegistry.all(textModel).length}`;
		let data = OutlineModel._requests.get(key);

203
		if (!data) {
204 205 206 207 208
			data = {
				promiseCnt: 0,
				promise: OutlineModel._create(textModel),
				model: undefined,
			};
209 210 211
			OutlineModel._requests.set(key, data);
		}

212 213 214 215 216
		if (data.model) {
			// resolved -> return data
			return TPromise.as(data.model);
		}

217
		// increase usage counter
218
		data.promiseCnt += 1;
219 220

		return new TPromise((resolve, reject) => {
221 222 223
			data.promise.then(model => {
				data.model = model;
				resolve(model);
224 225
			}, err => {
				OutlineModel._requests.delete(key);
226 227
				reject(err);
			});
228
		}, () => {
229
			// last -> cancel provider request, remove cached promise
230
			if (--data.promiseCnt === 0) {
231
				data.promise.cancel();
232
				OutlineModel._requests.delete(key);
233 234 235 236 237
			}
		});
	}

	static _create(textModel: ITextModel): TPromise<OutlineModel> {
J
Johannes Rieken 已提交
238

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

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

J
Johannes Rieken 已提交
245
			return asWinJsPromise(token => provider.provideDocumentSymbols(result.textModel, token)).then(result => {
J
Johannes Rieken 已提交
246 247 248 249
				if (!isFalsyOrEmpty(result)) {
					for (const info of result) {
						OutlineModel._makeOutlineElement(info, group);
					}
J
Johannes Rieken 已提交
250 251 252
				}
				return group;
			}, err => {
J
Johannes Rieken 已提交
253
				onUnexpectedExternalError(err);
J
Johannes Rieken 已提交
254 255
				return group;
			}).then(group => {
J
Johannes Rieken 已提交
256
				result._groups[id] = group;
J
Johannes Rieken 已提交
257 258 259
			});
		});

J
Johannes Rieken 已提交
260 261 262 263 264 265 266 267 268 269
		return TPromise.join(promises).then(() => {

			let count = 0;
			for (const key in result._groups) {
				let group = result._groups[key];
				if (first(group.children) === undefined) { // empty
					delete result._groups[key];
				} else {
					count += 1;
				}
270 271
			}

J
Johannes Rieken 已提交
272 273 274 275 276 277 278 279 280 281 282 283
			if (count !== 1) {
				//
				result.children = result._groups;

			} else {
				// adopt all elements of the first group
				let group = first(result._groups);
				for (let key in group.children) {
					let child = group.children[key];
					child.parent = result;
					result.children[child.id] = child;
				}
284
			}
J
Johannes Rieken 已提交
285 286

			return result;
287
		});
288 289
	}

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

301 302 303 304 305 306 307 308 309 310
	static get(element: TreeElement): OutlineModel {
		while (element) {
			if (element instanceof OutlineModel) {
				return element;
			}
			element = element.parent;
		}
		return undefined;
	}

J
Johannes Rieken 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
	readonly id = 'root';
	readonly parent = undefined;

	private _groups: { [id: string]: OutlineGroup; } = Object.create(null);
	children: { [id: string]: OutlineGroup | OutlineElement; } = Object.create(null);

	private constructor(readonly textModel: ITextModel) {
		super();
	}

	dispose(): void {

	}

	adopt(other: OutlineModel): boolean {
		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 已提交
337 338
	updateMatches(pattern: string): OutlineElement {
		let topMatch: OutlineElement;
339 340
		for (const key in this._groups) {
			topMatch = this._groups[key].updateMatches(pattern, topMatch);
J
Johannes Rieken 已提交
341 342
		}
		return topMatch;
343 344
	}

J
Johannes Rieken 已提交
345
	getItemEnclosingPosition(position: IPosition): OutlineElement {
346 347
		for (const key in this._groups) {
			let result = this._groups[key].getItemEnclosingPosition(position);
J
Johannes Rieken 已提交
348 349 350 351 352
			if (result) {
				return result;
			}
		}
		return undefined;
353 354
	}

J
Johannes Rieken 已提交
355 356
	getItemById(id: string): TreeElement {
		return TreeElement.getElementById(id, this);
357
	}
358 359 360 361 362 363 364 365 366 367

	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) {
			this._groups[key].updateMarker(marker);
		}
	}
368
}