gotoError.ts 15.7 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 12
import {onUnexpectedError} from 'vs/base/common/errors';
import {Emitter} from 'vs/base/common/event';
import {CommonKeybindings, KeyCode, KeyMod} from 'vs/base/common/keyCodes';
J
Joao Moreno 已提交
13
import {IDisposable, cAll, dispose} from 'vs/base/common/lifecycle';
14
import Severity from 'vs/base/common/severity';
A
Alex Dima 已提交
15 16
import * as strings from 'vs/base/common/strings';
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
17
import {TPromise} from 'vs/base/common/winjs.base';
A
Alex Dima 已提交
18 19 20 21 22 23
import * as dom from 'vs/base/browser/dom';
import {renderHtml} from 'vs/base/browser/htmlContentRenderer';
import {IKeybindingContextKey, IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
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';
24
import {Range} from 'vs/editor/common/core/range';
A
Alex Dima 已提交
25 26
import {EditorAction} from 'vs/editor/common/editorAction';
import {Behaviour} from 'vs/editor/common/editorActionEnablement';
A
Alex Dima 已提交
27 28 29 30 31
import * as editorCommon from 'vs/editor/common/editorCommon';
import {CommonEditorRegistry, ContextKey, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
import {ICodeEditor} from 'vs/editor/browser/editorBrowser';
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
import {IOptions, ZoneWidget} from 'vs/editor/contrib/zoneWidget/browser/zoneWidget';
32
import {getCodeActions} from 'vs/editor/contrib/quickFix/common/quickFix';
E
Erich Gamma 已提交
33 34 35

class MarkerModel {

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

A
Alex Dima 已提交
44
	constructor(editor: ICodeEditor, markers: IMarker[]) {
E
Erich Gamma 已提交
45 46 47 48 49 50 51 52 53 54
		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 已提交
55 56
		this._toUnbind.push(this._editor.addListener(editorCommon.EventType.Disposed, () => this.dispose()));
		this._toUnbind.push(this._editor.addListener(editorCommon.EventType.CursorPositionChanged, () => {
E
Erich Gamma 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
			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
76
		this._markers.sort((left, right) => Severity.compare(left.severity, right.severity) || Range.compareRangesUsingStarts(left, right));
E
Erich Gamma 已提交
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 145

		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);
	}

A
Alex Dima 已提交
146
	public goTo(pos: editorCommon.IPosition): void {
E
Erich Gamma 已提交
147 148 149
		for (var i = 0; i < this._markers.length; i++) {
			var marker = this._markers[i];
			if (marker.startLineNumber <= pos.lineNumber && marker.endLineNumber >= pos.lineNumber
150
				&& marker.startColumn <= pos.column && marker.endColumn >= pos.column) {
E
Erich Gamma 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
				this._onCurrentMarkerChanged.fire(marker);
				return;
			}
		}
		return null;
	}

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

	public length(): number {
		return this._markers.length;
	}

	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 已提交
180
		this._toUnbind = cAll(this._toUnbind);
E
Erich Gamma 已提交
181 182 183
	}
}

A
Alex Dima 已提交
184
var zoneOptions: IOptions = {
E
Erich Gamma 已提交
185
	showFrame: true,
186 187
	showArrow: true,
	isAccessible: true
E
Erich Gamma 已提交
188 189
};

A
Alex Dima 已提交
190
class MarkerNavigationWidget extends ZoneWidget {
E
Erich Gamma 已提交
191

192 193 194
	private _container: HTMLElement;
	private _element: HTMLElement;
	private _quickFixSection: HTMLElement;
A
Alex Dima 已提交
195 196
	private _callOnDispose: IDisposable[] = [];
	private _localCleanup: IDisposable[] = [];
197
	private _quickFixEntries: HTMLElement[];
E
Erich Gamma 已提交
198

199
	constructor(editor: ICodeEditor, private _model: MarkerModel, private _keybindingService: IKeybindingService) {
E
Erich Gamma 已提交
200 201 202 203 204
		super(editor, zoneOptions);
		this.create();
		this._wireModelAndView();
	}

J
Johannes Rieken 已提交
205
	protected _fillContainer(container: HTMLElement): void {
206 207
		this._container = container;

A
Alex Dima 已提交
208
		dom.addClass(this._container, 'marker-widget');
209 210 211 212 213 214 215 216 217 218 219 220
		this._container.tabIndex = 0;
		this._container.setAttribute('role', 'tooltip');

		this._element = document.createElement('div');
		this._element.className = 'descriptioncontainer';
		this._element.setAttribute('aria-live', 'assertive');
		this._element.setAttribute('role', 'alert');
		this._container.appendChild(this._element);

		this._quickFixSection = document.createElement('div');
		this._container.appendChild(this._quickFixSection);

A
Alex Dima 已提交
221
		this._callOnDispose.push(dom.addStandardDisposableListener(this._container, 'keydown', (e) => {
222
			switch (e.asKeybinding()) {
223 224 225 226 227 228 229 230 231 232
				case CommonKeybindings.LEFT_ARROW:
					this._goLeft();
					e.preventDefault();
					e.stopPropagation();
					break;
				case CommonKeybindings.RIGHT_ARROW:
					this._goRight();
					e.preventDefault();
					e.stopPropagation();
					break;
E
Erich Gamma 已提交
233

234 235 236
			}
		}));
	}
E
Erich Gamma 已提交
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
	private _goLeft(): void {
		if (!this._quickFixEntries) {
			return;
		}
		let idx = this._quickFixEntries.indexOf(<HTMLElement>document.activeElement);
		if (idx === -1) {
			idx = 1;
		}
		idx = (idx + this._quickFixEntries.length - 1) % this._quickFixEntries.length;
		this._quickFixEntries[idx].focus();
	}

	private _goRight(): void {
		if (!this._quickFixEntries) {
			return;
		}
		let idx = this._quickFixEntries.indexOf(<HTMLElement>document.activeElement);
		idx = (idx + 1) % this._quickFixEntries.length;
		this._quickFixEntries[idx].focus();
	}

259
	public show(where: editorCommon.IPosition, heightInLines: number): void {
260 261
		super.show(where, heightInLines);
		this._container.focus();
E
Erich Gamma 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275
	}

	private _wireModelAndView(): void {
		this._model.onCurrentMarkerChanged(this.showAtMarker, this, this._callOnDispose);
	}

	public showAtMarker(marker: IMarker): void {

		if (!marker) {
			return;
		}

		// set color
		switch (marker.severity) {
276
			case Severity.Error:
E
Erich Gamma 已提交
277 278
				this.options.frameColor = '#ff5a5a';
				break;
279 280
			case Severity.Warning:
			case Severity.Info:
E
Erich Gamma 已提交
281 282 283 284
				this.options.frameColor = '#5aac5a';
				break;
		}

J
Joao Moreno 已提交
285
		this._localCleanup = dispose(this._localCleanup);
286

E
Erich Gamma 已提交
287
		// update label and show
288 289 290 291
		let text = strings.format('({0}/{1}) ', this._model.indexOf(marker) + 1, this._model.length());
		if (marker.source) {
			text = `${text}[${marker.source}] `;
		}
A
Alex Dima 已提交
292
		dom.clearNode(this._element);
293
		this._element.appendChild(document.createTextNode(text));
A
Alex Dima 已提交
294
		this._element.appendChild(renderHtml(marker.message));
295
		this._quickFixSection.style.display = 'none';
E
Erich Gamma 已提交
296

297
		getCodeActions(this.editor.getModel(), Range.lift(marker)).then(result => {
298 299 300 301 302 303 304 305 306 307 308 309 310 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 337 338
			dom.clearNode(this._quickFixSection);

			if (result.length > 0) {

				this._localCleanup.push({
					dispose: () => {
						this._quickFixEntries = [];
					}
				});

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

				this._quickFixEntries = [];
				let quickfixcontainer = document.createElement('span');
				quickfixcontainer.className = 'quickfixcontainer';
				result.forEach((fix, idx, arr) => {
					var container = quickfixcontainer;
					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.appendChild(document.createTextNode(fix.command.title));
					this._localCleanup.push(dom.addDisposableListener(entry, dom.EventType.CLICK, () => {
						this._keybindingService.executeCommand(fix.command.id, ...fix.command.arguments);
						return true;
					}));
					this._localCleanup.push(dom.addStandardDisposableListener(entry, 'keydown', (e) => {
						switch (e.asKeybinding()) {
							case CommonKeybindings.ENTER:
							case CommonKeybindings.SPACE:
								this._keybindingService.executeCommand(fix.command.id, ...fix.command.arguments);
								e.preventDefault();
								e.stopPropagation();
339
						}
340 341
					}));
					container.appendChild(entry);
342

343 344 345
					this._quickFixEntries.push(entry);
				});
				this._quickFixSection.appendChild(quickfixcontainer);
E
Erich Gamma 已提交
346

347 348 349 350 351 352
				this._quickFixSection.style.display = '';
				this.show(new Position(marker.startLineNumber, marker.startColumn), 4);
			}
		}, onUnexpectedError);

		this._model.withoutWatchingEditorPosition(() => this.show(new Position(marker.startLineNumber, marker.startColumn), 3));
E
Erich Gamma 已提交
353 354 355
	}

	public dispose(): void {
J
Joao Moreno 已提交
356
		this._callOnDispose = dispose(this._callOnDispose);
E
Erich Gamma 已提交
357 358 359 360 361 362 363 364
		super.dispose();
	}
}

class MarkerNavigationAction extends EditorAction {

	private _isNext: boolean;

365
	private telemetryService: ITelemetryService;
E
Erich Gamma 已提交
366

367
	constructor(descriptor: editorCommon.IEditorActionDescriptorData, editor: editorCommon.ICommonCodeEditor, next: boolean, @ITelemetryService telemetryService: ITelemetryService) {
E
Erich Gamma 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
		super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.Writeable | Behaviour.UpdateOnModelChange);
		this.telemetryService = telemetryService;
		this._isNext = next;
	}

	public run(): TPromise<boolean> {
		var model = MarkerController.getMarkerController(this.editor).getOrCreateModel();
		this.telemetryService.publicLog('zoneWidgetShown', { mode: 'go to error' });
		if (model) {
			if (this._isNext) {
				model.next();
			} else {
				model.previous();
			}
			model.reveal();
		}
		return TPromise.as(true);
	}
}

A
Alex Dima 已提交
388
class MarkerController implements editorCommon.IEditorContribution {
E
Erich Gamma 已提交
389 390 391

	static ID = 'editor.contrib.markerController';

392
	static getMarkerController(editor: editorCommon.ICommonCodeEditor): MarkerController {
E
Erich Gamma 已提交
393 394 395
		return <MarkerController>editor.getContribution(MarkerController.ID);
	}

396
	private _editor: ICodeEditor;
E
Erich Gamma 已提交
397 398
	private _model: MarkerModel;
	private _zone: MarkerNavigationWidget;
A
Alex Dima 已提交
399
	private _callOnClose: IDisposable[] = [];
E
Erich Gamma 已提交
400 401
	private _markersNavigationVisible: IKeybindingContextKey<boolean>;

402
	constructor(
403 404 405 406 407 408
		editor: ICodeEditor,
		@IMarkerService private _markerService: IMarkerService,
		@IKeybindingService private _keybindingService: IKeybindingService
	) {
		this._editor = editor;
		this._markersNavigationVisible = this._keybindingService.createKey(CONTEXT_MARKERS_NAVIGATION_VISIBLE, false);
E
Erich Gamma 已提交
409 410 411 412 413 414 415 416 417 418 419 420
	}

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

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

	private _cleanUp(): void {
		this._markersNavigationVisible.reset();
J
Joao Moreno 已提交
421
		this._callOnClose = dispose(this._callOnClose);
E
Erich Gamma 已提交
422 423 424 425 426 427 428 429 430 431 432
		this._zone = null;
		this._model = null;
	}

	public getOrCreateModel(): MarkerModel {

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

		var markers = this._getMarkers();
433 434
		this._model = new MarkerModel(this._editor, markers);
		this._zone = new MarkerNavigationWidget(this._editor, this._model, this._keybindingService);
E
Erich Gamma 已提交
435 436 437 438 439
		this._markersNavigationVisible.set(true);

		this._callOnClose.push(this._model);
		this._callOnClose.push(this._zone);

440
		this._callOnClose.push(this._editor.addListener2(editorCommon.EventType.ModelChanged, () => {
E
Erich Gamma 已提交
441 442 443 444
			this._cleanUp();
		}));

		this._model.onCurrentMarkerChanged(marker => !marker && this._cleanUp(), undefined, this._callOnClose);
445 446 447
		this._markerService.onMarkerChanged(this._onMarkerChanged, this, this._callOnClose);
		return this._model;
	}
E
Erich Gamma 已提交
448 449 450

	public closeMarkersNavigation(): void {
		this._cleanUp();
451
		this._editor.focus();
E
Erich Gamma 已提交
452 453 454
	}

	private _onMarkerChanged(changedResources: URI[]): void {
455
		if (!changedResources.some(r => this._editor.getModel().getAssociatedResource().toString() === r.toString())) {
E
Erich Gamma 已提交
456 457 458 459 460 461
			return;
		}
		this._model.setMarkers(this._getMarkers());
	}

	private _getMarkers(): IMarker[] {
462 463
		var resource = this._editor.getModel().getAssociatedResource(),
			markers = this._markerService.read({ resource: resource });
E
Erich Gamma 已提交
464 465 466 467 468 469 470 471

		return markers;
	}
}

class NextMarkerAction extends MarkerNavigationAction {
	public static ID = 'editor.action.marker.next';

472
	constructor(descriptor: editorCommon.IEditorActionDescriptorData, editor: editorCommon.ICommonCodeEditor, @ITelemetryService telemetryService: ITelemetryService) {
E
Erich Gamma 已提交
473 474 475 476 477 478 479
		super(descriptor, editor, true, telemetryService);
	}
}

class PrevMarkerAction extends MarkerNavigationAction {
	public static ID = 'editor.action.marker.prev';

480
	constructor(descriptor: editorCommon.IEditorActionDescriptorData, editor: editorCommon.ICommonCodeEditor, @ITelemetryService telemetryService: ITelemetryService) {
E
Erich Gamma 已提交
481 482 483 484 485 486 487 488 489 490
		super(descriptor, editor, false, telemetryService);
	}
}

var CONTEXT_MARKERS_NAVIGATION_VISIBLE = 'markersNavigationVisible';

// register actions
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(NextMarkerAction, NextMarkerAction.ID, nls.localize('markerAction.next.label', "Go to Next Error or Warning"), {
	context: ContextKey.EditorFocus,
	primary: KeyCode.F8
491
}, 'Go to Next Error or Warning'));
E
Erich Gamma 已提交
492 493 494
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(PrevMarkerAction, PrevMarkerAction.ID, nls.localize('markerAction.previous.label', "Go to Previous Error or Warning"), {
	context: ContextKey.EditorFocus,
	primary: KeyMod.Shift | KeyCode.F8
495
}, 'Go to Previous Error or Warning'));
496
CommonEditorRegistry.registerEditorCommand('closeMarkersNavigation', CommonEditorRegistry.commandWeight(50), { primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] }, false, CONTEXT_MARKERS_NAVIGATION_VISIBLE, (ctx, editor, args) => {
E
Erich Gamma 已提交
497 498 499 500 501
	var controller = MarkerController.getMarkerController(editor);
	controller.closeMarkersNavigation();
});

EditorBrowserRegistry.registerEditorContribution(MarkerController);