gotoError.ts 17.1 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import 'vs/css!./gotoError';
A
Alex Dima 已提交
9
import * as nls from 'vs/nls';
A
Alex Dima 已提交
10 11
import {onUnexpectedError} from 'vs/base/common/errors';
import {Emitter} from 'vs/base/common/event';
A
Alexandru Dima 已提交
12
import {KeyCode, KeyMod} from 'vs/base/common/keyCodes';
A
Alex Dima 已提交
13
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
14
import Severity from 'vs/base/common/severity';
A
Alex Dima 已提交
15
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
16
import {TPromise} from 'vs/base/common/winjs.base';
A
Alex Dima 已提交
17
import * as dom from 'vs/base/browser/dom';
18
import {ICommandService} from 'vs/platform/commands/common/commands';
A
Alex Dima 已提交
19
import {RawContextKey, IContextKey, IContextKeyService} from 'vs/platform/contextkey/common/contextkey';
A
Alex Dima 已提交
20 21 22
import {IMarker, IMarkerService} from 'vs/platform/markers/common/markers';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {Position} from 'vs/editor/common/core/position';
23
import {Range} from 'vs/editor/common/core/range';
A
Alex Dima 已提交
24
import * as editorCommon from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
25
import {editorAction, ServicesAccessor, IActionOptions, EditorAction, EditorCommand, CommonEditorRegistry} from 'vs/editor/common/editorCommonExtensions';
A
Alex Dima 已提交
26
import {ICodeEditor} from 'vs/editor/browser/editorBrowser';
27
import {editorContribution} from 'vs/editor/browser/editorBrowserExtensions';
28
import {ZoneWidget} from 'vs/editor/contrib/zoneWidget/browser/zoneWidget';
29
import {getCodeActions, IQuickFix2} from 'vs/editor/contrib/quickFix/common/quickFix';
E
Erich Gamma 已提交
30

A
Alex Dima 已提交
31
import EditorContextKeys = editorCommon.EditorContextKeys;
A
Alex Dima 已提交
32

E
Erich Gamma 已提交
33 34
class MarkerModel {

A
Alex Dima 已提交
35
	private _editor: ICodeEditor;
E
Erich Gamma 已提交
36 37
	private _markers: IMarker[];
	private _nextIdx: number;
A
Alex Dima 已提交
38
	private _toUnbind: IDisposable[];
E
Erich Gamma 已提交
39 40 41 42
	private _ignoreSelectionChange: boolean;
	private _onCurrentMarkerChanged: Emitter<IMarker>;
	private _onMarkerSetChanged: Emitter<MarkerModel>;

A
Alex Dima 已提交
43
	constructor(editor: ICodeEditor, markers: IMarker[]) {
E
Erich Gamma 已提交
44 45 46 47 48 49 50 51 52 53
		this._editor = editor;
		this._markers = null;
		this._nextIdx = -1;
		this._toUnbind = [];
		this._ignoreSelectionChange = false;
		this._onCurrentMarkerChanged = new Emitter<IMarker>();
		this._onMarkerSetChanged = new Emitter<MarkerModel>();
		this.setMarkers(markers);

		// listen on editor
A
Alex Dima 已提交
54
		this._toUnbind.push(this._editor.onDidDispose(() => this.dispose()));
A
Alex Dima 已提交
55
		this._toUnbind.push(this._editor.onDidChangeCursorPosition(() => {
E
Erich Gamma 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
			if (!this._ignoreSelectionChange) {
				this._nextIdx = -1;
			}
		}));
	}

	public get onCurrentMarkerChanged() {
		return this._onCurrentMarkerChanged.event;
	}

	public get onMarkerSetChanged() {
		return this._onMarkerSetChanged.event;
	}

	public setMarkers(markers: IMarker[]): void {
		// assign
		this._markers = markers || [];

		// sort markers
75
		this._markers.sort((left, right) => Severity.compare(left.severity, right.severity) || Range.compareRangesUsingStarts(left, right));
E
Erich Gamma 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

		this._nextIdx = -1;
		this._onMarkerSetChanged.fire(this);
	}

	public withoutWatchingEditorPosition(callback: () => void): void {
		this._ignoreSelectionChange = true;
		try {
			callback();
		} finally {
			this._ignoreSelectionChange = false;
		}
	}

	private initIdx(fwd: boolean): void {
		var found = false;
		var position = this._editor.getPosition();
		for (var i = 0, len = this._markers.length; i < len && !found; i++) {
			var pos = { lineNumber: this._markers[i].startLineNumber, column: this._markers[i].startColumn };
			if (position.isBeforeOrEqual(pos)) {
				this._nextIdx = i + (fwd ? 0 : -1);
				found = true;
			}
		}
		if (!found) {
			// after the last change
			this._nextIdx = fwd ? 0 : this._markers.length - 1;
		}
		if (this._nextIdx < 0) {
			this._nextIdx = this._markers.length - 1;
		}
	}

	private move(fwd: boolean): void {
		if (!this.canNavigate()) {
			this._onCurrentMarkerChanged.fire(undefined);
			return;
		}

		if (this._nextIdx === -1) {
			this.initIdx(fwd);

		} else if (fwd) {
			this._nextIdx += 1;
			if (this._nextIdx >= this._markers.length) {
				this._nextIdx = 0;
			}
		} else {
			this._nextIdx -= 1;
			if (this._nextIdx < 0) {
				this._nextIdx = this._markers.length - 1;
			}
		}
		var marker = this._markers[this._nextIdx];
		this._onCurrentMarkerChanged.fire(marker);
	}

	public canNavigate(): boolean {
		return this._markers.length > 0;
	}

	public next(): void {
		this.move(true);
	}

	public previous(): void {
		this.move(false);
	}

145 146 147 148
	public findMarkerAtPosition(pos: editorCommon.IPosition): IMarker {
		for (const marker of this._markers) {
			if (Range.containsPosition(marker, pos)) {
				return marker;
E
Erich Gamma 已提交
149 150 151 152
			}
		}
	}

153 154 155
	public get stats(): { errors: number; others: number; } {
		let errors = 0;
		let others = 0;
E
Erich Gamma 已提交
156

157 158 159 160 161 162 163 164
		for (let marker of this._markers) {
			if (marker.severity === Severity.Error) {
				errors += 1;
			} else {
				others += 1;
			}
		}
		return { errors, others };
E
Erich Gamma 已提交
165 166
	}

J
Johannes Rieken 已提交
167 168 169 170 171 172 173 174
	public get total() {
		return this._markers.length;
	}

	public indexOf(marker: IMarker): number {
		return 1 + this._markers.indexOf(marker);
	}

E
Erich Gamma 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188
	public reveal(): void {

		if (this._nextIdx === -1) {
			return;
		}

		this.withoutWatchingEditorPosition(() => {
			var pos = new Position(this._markers[this._nextIdx].startLineNumber, this._markers[this._nextIdx].startColumn);
			this._editor.setPosition(pos);
			this._editor.revealPositionInCenter(pos);
		});
	}

	public dispose(): void {
A
Alex Dima 已提交
189
		this._toUnbind = dispose(this._toUnbind);
E
Erich Gamma 已提交
190 191 192
	}
}

193 194 195 196 197 198 199 200 201
class FixesWidget {

	domNode: HTMLDivElement;

	private _disposeOnUpdate: IDisposable[] = [];
	private _listener: IDisposable;

	constructor(
		container: HTMLElement,
202
		private _markerWidget: MarkerNavigationWidget,
203
		@ICommandService private _commandService: ICommandService
204 205 206 207 208 209
	) {
		this.domNode = document.createElement('div');
		container.appendChild(this.domNode);

		this._listener = dom.addStandardDisposableListener(container, 'keydown', (e) => {
			switch (e.asKeybinding()) {
A
Alexandru Dima 已提交
210
				case KeyCode.LeftArrow:
211 212 213 214
					this._move(true);
					e.preventDefault();
					e.stopPropagation();
					break;
A
Alexandru Dima 已提交
215
				case KeyCode.RightArrow:
216 217 218 219 220 221 222 223 224 225 226 227 228
					this._move(false);
					e.preventDefault();
					e.stopPropagation();
					break;
			}
		});
	}

	dispose(): void {
		this._disposeOnUpdate = dispose(this._disposeOnUpdate);
		this._listener = dispose(this._listener);
	}

229
	update(marker: IMarker): TPromise<any> {
230 231
		this._disposeOnUpdate = dispose(this._disposeOnUpdate);
		this.domNode.style.display = 'none';
232 233 234 235
		if (marker) {
			const fixes = getCodeActions(this._markerWidget.editor.getModel(), Range.lift(marker));
			return fixes.then(fixes => this._doUpdate(fixes), onUnexpectedError);
		}
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
	}

	private _doUpdate(fixes: IQuickFix2[]): void {

		dom.clearNode(this.domNode);

		if (!fixes || fixes.length === 0) {
			return;
		}

		// light bulb and label
		let quickfixhead = document.createElement('span');
		quickfixhead.className = 'quickfixhead';
		quickfixhead.appendChild(document.createTextNode(fixes.length > 1
			? nls.localize('quickfix.multiple.label', 'Suggested fixes: ')
			: nls.localize('quickfix.single.label', 'Suggested fix: ')));
		this.domNode.appendChild(quickfixhead);

		// each fix as entry
		const container = document.createElement('span');
		container.className = 'quickfixcontainer';

		fixes.forEach((fix, idx, arr) => {

			if (idx > 0) {
				let separator = document.createElement('span');
				separator.appendChild(document.createTextNode(', '));
				container.appendChild(separator);
			}

			let entry = document.createElement('a');
			entry.tabIndex = 0;
			entry.className = `quickfixentry`;
			entry.dataset['idx'] = String(idx);
			entry.dataset['next'] = String(idx < arr.length - 1 ? idx + 1 : 0);
			entry.dataset['prev'] = String(idx > 0 ? idx - 1 : arr.length - 1);
			entry.appendChild(document.createTextNode(fix.command.title));
273
			this._disposeOnUpdate.push(dom.addDisposableListener(entry, dom.EventType.CLICK, (e) => {
274
				this._commandService.executeCommand(fix.command.id, ...fix.command.arguments);
275 276
				this._markerWidget.focus();
				e.preventDefault();
277 278 279
			}));
			this._disposeOnUpdate.push(dom.addStandardDisposableListener(entry, 'keydown', (e) => {
				switch (e.asKeybinding()) {
A
Alexandru Dima 已提交
280 281
					case KeyCode.Enter:
					case KeyCode.Space:
282
						this._commandService.executeCommand(fix.command.id, ...fix.command.arguments);
283
						this._markerWidget.focus();
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
						e.preventDefault();
						e.stopPropagation();
				}
			}));
			container.appendChild(entry);
		});

		this.domNode.appendChild(container);
		this.domNode.style.display = '';
	}

	private _move(left: boolean): void {
		let target: HTMLElement;
		if (document.activeElement.classList.contains('quickfixentry')) {
			let current = <HTMLElement> document.activeElement;
			let idx = left ? current.dataset['prev'] : current.dataset['next'];
			target = <HTMLElement>this.domNode.querySelector(`a[data-idx='${idx}']`);
		} else {
			target = <HTMLElement> this.domNode.querySelector('.quickfixentry');
		}
		target.focus();
	}
}

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
class MessageWidget {

	domNode: HTMLDivElement;

	constructor(container: HTMLElement) {
		this.domNode = document.createElement('div');
		this.domNode.className = 'block descriptioncontainer';
		this.domNode.setAttribute('aria-live', 'assertive');
		this.domNode.setAttribute('role', 'alert');
		container.appendChild(this.domNode);
	}

	update({source, message}: IMarker): void {
		if (source) {
			const indent = new Array(source.length + 3 + 1).join(' ');
			message = `[${source}] ` + message.replace(/\r\n|\r|\n/g, function () {
				return '\n' + indent;
			});
		}
		this.domNode.innerText = message;
	}
}

331
class MarkerNavigationWidget extends ZoneWidget {
E
Erich Gamma 已提交
332

333
	private _parentContainer: HTMLElement;
334
	private _container: HTMLElement;
335
	private _title: HTMLElement;
336
	private _message: MessageWidget;
337
	private _fixesWidget: FixesWidget;
A
Alex Dima 已提交
338
	private _callOnDispose: IDisposable[] = [];
E
Erich Gamma 已提交
339

340
	constructor(editor: ICodeEditor, private _model: MarkerModel, private _commandService: ICommandService) {
341
		super(editor, { showArrow: true, showFrame: true, isAccessible: true });
E
Erich Gamma 已提交
342 343 344 345
		this.create();
		this._wireModelAndView();
	}

346 347 348 349 350 351 352 353 354
	dispose(): void {
		this._callOnDispose = dispose(this._callOnDispose);
		super.dispose();
	}

	focus(): void {
		this._parentContainer.focus();
	}

355
	protected _fillContainer(container: HTMLElement): void {
356 357 358 359
		this._parentContainer = container;
		dom.addClass(container, 'marker-widget');
		this._parentContainer.tabIndex = 0;
		this._parentContainer.setAttribute('role', 'tooltip');
360

361 362
		this._container = document.createElement('div');
		container.appendChild(this._container);
363

364 365 366 367
		this._title = document.createElement('div');
		this._title.className = 'block title';
		this._container.appendChild(this._title);

368 369
		this._message = new MessageWidget(this._container);
		this.editor.applyFontInfo(this._message.domNode);
370

371
		this._fixesWidget = new FixesWidget(this._container, this, this._commandService);
372
		this._fixesWidget.domNode.classList.add('fixes');
373
		this._callOnDispose.push(this._fixesWidget);
374 375
	}

376
	public show(where: editorCommon.IPosition, heightInLines: number): void {
377
		super.show(where, heightInLines);
378
		this.focus();
E
Erich Gamma 已提交
379 380 381
	}

	private _wireModelAndView(): void {
382
		// listen to events
E
Erich Gamma 已提交
383
		this._model.onCurrentMarkerChanged(this.showAtMarker, this, this._callOnDispose);
384
		this._model.onMarkerSetChanged(this._onMarkersChanged, this, this._callOnDispose);
E
Erich Gamma 已提交
385 386 387 388 389 390 391 392
	}

	public showAtMarker(marker: IMarker): void {

		if (!marker) {
			return;
		}

393 394 395 396 397
		// update:
		// * title
		// * message
		// * quick fixes
		this._container.classList.remove('stale');
398 399
		this._title.innerHTML = nls.localize('title.wo_source', "({0}/{1})", this._model.indexOf(marker), this._model.total);
		this._message.update(marker);
400
		this._fixesWidget.update(marker).then(() => this._relayout());
401

402
		this._model.withoutWatchingEditorPosition(() => {
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
			// update frame color (only applied on 'show')
			switch (marker.severity) {
				case Severity.Error:
					this.options.frameColor = '#ff5a5a';
					break;
				case Severity.Warning:
				case Severity.Info:
					this.options.frameColor = '#5aac5a';
					break;
			}

			this.show({
				lineNumber: marker.startLineNumber,
				column: marker.startColumn
			}, this.computeRequiredHeight());
		});
420 421
	}

422 423 424 425 426
	private _onMarkersChanged(): void {

		const marker = this._model.findMarkerAtPosition(this.position);

		if (marker) {
427 428 429 430 431 432 433 434 435
			this._container.classList.remove('stale');
			this._message.update(marker);
			this._relayout();
			this._fixesWidget.update(marker).then(() => this._relayout());

		} else {
			this._container.classList.add('stale');
			this._fixesWidget.update(marker);
			this._relayout();
436 437 438
		}
	}

439 440 441 442 443 444 445 446
	protected _relayout(): void {
		super._relayout(this.computeRequiredHeight());
	}

	private computeRequiredHeight() {
		// minimum one line content, add one line for zone widget decorations
		const lineHeight = this.editor.getConfiguration().lineHeight || 12;
		return Math.max(1, Math.ceil(this._container.clientHeight / lineHeight)) + 1;
E
Erich Gamma 已提交
447 448 449
	}
}

A
Alex Dima 已提交
450
class MarkerNavigationAction extends EditorAction {
E
Erich Gamma 已提交
451 452 453

	private _isNext: boolean;

454 455
	constructor(next: boolean, opts:IActionOptions) {
		super(opts);
E
Erich Gamma 已提交
456 457 458
		this._isNext = next;
	}

A
Alex Dima 已提交
459 460 461
	public run(accessor:ServicesAccessor, editor:editorCommon.ICommonCodeEditor): void {
		const telemetryService = accessor.get(ITelemetryService);

462 463 464 465 466 467
		let controller = MarkerController.get(editor);
		if (!controller) {
			return;
		}

		let model = controller.getOrCreateModel();
A
Alex Dima 已提交
468
		telemetryService.publicLog('zoneWidgetShown', { mode: 'go to error' });
E
Erich Gamma 已提交
469 470 471 472 473 474 475 476 477 478 479
		if (model) {
			if (this._isNext) {
				model.next();
			} else {
				model.previous();
			}
			model.reveal();
		}
	}
}

480
@editorContribution
A
Alex Dima 已提交
481
class MarkerController implements editorCommon.IEditorContribution {
E
Erich Gamma 已提交
482

483
	private static ID = 'editor.contrib.markerController';
E
Erich Gamma 已提交
484

A
Alex Dima 已提交
485 486
	public static get(editor: editorCommon.ICommonCodeEditor): MarkerController {
		return editor.getContribution<MarkerController>(MarkerController.ID);
E
Erich Gamma 已提交
487 488
	}

489
	private _editor: ICodeEditor;
E
Erich Gamma 已提交
490 491
	private _model: MarkerModel;
	private _zone: MarkerNavigationWidget;
A
Alex Dima 已提交
492
	private _callOnClose: IDisposable[] = [];
A
Alex Dima 已提交
493
	private _markersNavigationVisible: IContextKey<boolean>;
E
Erich Gamma 已提交
494

495
	constructor(
496 497
		editor: ICodeEditor,
		@IMarkerService private _markerService: IMarkerService,
498
		@IContextKeyService private _contextKeyService: IContextKeyService,
499
		@ICommandService private _commandService: ICommandService
500 501
	) {
		this._editor = editor;
502
		this._markersNavigationVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService);
E
Erich Gamma 已提交
503 504 505 506 507 508 509 510 511 512 513 514
	}

	public getId(): string {
		return MarkerController.ID;
	}

	public dispose(): void {
		this._cleanUp();
	}

	private _cleanUp(): void {
		this._markersNavigationVisible.reset();
J
Joao Moreno 已提交
515
		this._callOnClose = dispose(this._callOnClose);
516
		this._zone = null;
E
Erich Gamma 已提交
517 518 519 520 521 522 523 524 525 526
		this._model = null;
	}

	public getOrCreateModel(): MarkerModel {

		if (this._model) {
			return this._model;
		}

		var markers = this._getMarkers();
527
		this._model = new MarkerModel(this._editor, markers);
528
		this._zone = new MarkerNavigationWidget(this._editor, this._model, this._commandService);
E
Erich Gamma 已提交
529 530 531
		this._markersNavigationVisible.set(true);

		this._callOnClose.push(this._model);
532
		this._callOnClose.push(this._zone);
E
Erich Gamma 已提交
533

534
		this._callOnClose.push(this._editor.onDidChangeModel(() => this._cleanUp()));
E
Erich Gamma 已提交
535
		this._model.onCurrentMarkerChanged(marker => !marker && this._cleanUp(), undefined, this._callOnClose);
536 537 538
		this._markerService.onMarkerChanged(this._onMarkerChanged, this, this._callOnClose);
		return this._model;
	}
E
Erich Gamma 已提交
539 540

	public closeMarkersNavigation(): void {
541 542
		this._cleanUp();
		this._editor.focus();
E
Erich Gamma 已提交
543 544 545
	}

	private _onMarkerChanged(changedResources: URI[]): void {
546
		if (!changedResources.some(r => this._editor.getModel().uri.toString() === r.toString())) {
E
Erich Gamma 已提交
547 548 549 550 551 552
			return;
		}
		this._model.setMarkers(this._getMarkers());
	}

	private _getMarkers(): IMarker[] {
553
		var resource = this._editor.getModel().uri,
554
			markers = this._markerService.read({ resource: resource });
E
Erich Gamma 已提交
555 556 557 558 559

		return markers;
	}
}

A
Alex Dima 已提交
560
@editorAction
E
Erich Gamma 已提交
561
class NextMarkerAction extends MarkerNavigationAction {
A
Alex Dima 已提交
562
	constructor() {
563 564 565 566 567 568 569 570 571 572
		super(true, {
			id: 'editor.action.marker.next',
			label: nls.localize('markerAction.next.label', "Go to Next Error or Warning"),
			alias: 'Go to Next Error or Warning',
			precondition: EditorContextKeys.Writable,
			kbOpts: {
				kbExpr: EditorContextKeys.Focus,
				primary: KeyCode.F8
			}
		});
E
Erich Gamma 已提交
573 574 575
	}
}

A
Alex Dima 已提交
576
@editorAction
E
Erich Gamma 已提交
577
class PrevMarkerAction extends MarkerNavigationAction {
A
Alex Dima 已提交
578
	constructor() {
579 580 581 582 583 584 585 586 587 588
		super(false, {
			id: 'editor.action.marker.prev',
			label: nls.localize('markerAction.previous.label', "Go to Previous Error or Warning"),
			alias: 'Go to Previous Error or Warning',
			precondition: EditorContextKeys.Writable,
			kbOpts: {
				kbExpr: EditorContextKeys.Focus,
				primary: KeyMod.Shift | KeyCode.F8
			}
		});
E
Erich Gamma 已提交
589 590 591
	}
}

A
Alex Dima 已提交
592
var CONTEXT_MARKERS_NAVIGATION_VISIBLE = new RawContextKey<boolean>('markersNavigationVisible', false);
A
Alex Dima 已提交
593

A
Alex Dima 已提交
594
const MarkerCommand = EditorCommand.bindToContribution<MarkerController>(MarkerController.get);
E
Erich Gamma 已提交
595

596
CommonEditorRegistry.registerEditorCommand(new MarkerCommand({
597 598 599 600 601 602
	id: 'closeMarkersNavigation',
	precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE,
	handler: x => x.closeMarkersNavigation(),
	kbOpts: {
		weight: CommonEditorRegistry.commandWeight(50),
		kbExpr: EditorContextKeys.Focus,
A
Alex Dima 已提交
603 604 605
		primary: KeyCode.Escape,
		secondary: [KeyMod.Shift | KeyCode.Escape]
	}
606
}));