links.ts 13.9 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!./links';
A
Alex Dima 已提交
9
import * as nls from 'vs/nls';
A
Alex Dima 已提交
10 11 12 13
import {onUnexpectedError} from 'vs/base/common/errors';
import {KeyCode} from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
import Severity from 'vs/base/common/severity';
14
import URI from 'vs/base/common/uri';
A
Alex Dima 已提交
15 16
import {TPromise} from 'vs/base/common/winjs.base';
import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent';
E
Erich Gamma 已提交
17 18
import {IEditorService, IResourceInput} from 'vs/platform/editor/common/editor';
import {IMessageService} from 'vs/platform/message/common/message';
19
import {Range} from 'vs/editor/common/core/range';
A
Alex Dima 已提交
20 21 22 23
import {EditorAction} from 'vs/editor/common/editorAction';
import {Behaviour} from 'vs/editor/common/editorActionEnablement';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {CommonEditorRegistry, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
A
Alex Dima 已提交
24
import {ILink, LinkProviderRegistry} from 'vs/editor/common/modes';
25
import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService';
A
Alex Dima 已提交
26
import {IEditorMouseEvent, ICodeEditor} from 'vs/editor/browser/editorBrowser';
27
import {getLinks} from 'vs/editor/contrib/links/common/links';
A
Alex Dima 已提交
28
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
29
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
E
Erich Gamma 已提交
30 31 32

class LinkOccurence {

A
Alex Dima 已提交
33
	public static decoration(link:ILink): editorCommon.IModelDeltaDecoration {
E
Erich Gamma 已提交
34 35 36 37 38 39 40 41
		return {
			range: {
				startLineNumber: link.range.startLineNumber,
				startColumn: link.range.startColumn,
				endLineNumber: link.range.startLineNumber,
				endColumn: link.range.endColumn
			},
			options: LinkOccurence._getOptions(link, false)
A
tslint  
Alex Dima 已提交
42
		};
E
Erich Gamma 已提交
43 44
	}

A
Alex Dima 已提交
45
	private static _getOptions(link:ILink, isActive:boolean):editorCommon.IModelDecorationOptions {
E
Erich Gamma 已提交
46 47 48 49 50 51 52 53 54
		var result = '';

		if (isActive) {
			result += LinkDetector.CLASS_NAME_ACTIVE;
		} else {
			result += LinkDetector.CLASS_NAME;
		}

		return {
A
Alex Dima 已提交
55
			stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
E
Erich Gamma 已提交
56 57 58 59 60 61
			inlineClassName: result,
			hoverMessage: LinkDetector.HOVER_MESSAGE_GENERAL
		};
	}

	public decorationId:string;
A
Alex Dima 已提交
62
	public link:ILink;
E
Erich Gamma 已提交
63

A
Alex Dima 已提交
64
	constructor(link:ILink, decorationId:string/*, changeAccessor:editorCommon.IModelDecorationsChangeAccessor*/) {
E
Erich Gamma 已提交
65 66 67 68
		this.link = link;
		this.decorationId = decorationId;
	}

A
Alex Dima 已提交
69
	public activate(changeAccessor: editorCommon.IModelDecorationsChangeAccessor):void {
E
Erich Gamma 已提交
70 71 72
		changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurence._getOptions(this.link, true));
	}

A
Alex Dima 已提交
73
	public deactivate(changeAccessor: editorCommon.IModelDecorationsChangeAccessor):void {
E
Erich Gamma 已提交
74 75 76 77
		changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurence._getOptions(this.link, false));
	}
}

A
Alex Dima 已提交
78
class Link {
79
	range: Range;
A
Alex Dima 已提交
80 81 82 83 84 85 86 87
	url: string;

	constructor(source:ILink) {
		this.range = new Range(source.range.startLineNumber, source.range.startColumn, source.range.endLineNumber, source.range.endColumn);
		this.url = source.url;
	}
}

A
Alex Dima 已提交
88 89 90 91 92 93 94
class LinkDetector implements editorCommon.IEditorContribution {

	public static ID: string = 'editor.linkDetector';
	public static get(editor:editorCommon.ICommonCodeEditor): LinkDetector {
		return <LinkDetector>editor.getContribution(LinkDetector.ID);
	}

E
Erich Gamma 已提交
95
	static RECOMPUTE_TIME = 1000; // ms
A
Alex Dima 已提交
96 97 98
	static TRIGGER_KEY_VALUE = platform.isMacintosh ? KeyCode.Meta : KeyCode.Ctrl;
	static TRIGGER_MODIFIER = platform.isMacintosh ? 'metaKey' : 'ctrlKey';
	static HOVER_MESSAGE_GENERAL = platform.isMacintosh ? nls.localize('links.navigate.mac', "Cmd + click to follow link") : nls.localize('links.navigate', "Ctrl + click to follow link");
E
Erich Gamma 已提交
99 100 101
	static CLASS_NAME = 'detected-link';
	static CLASS_NAME_ACTIVE = 'detected-link-active';

A
Alex Dima 已提交
102
	private editor:ICodeEditor;
A
Alex Dima 已提交
103
	private listenersToRemove:IDisposable[];
E
Erich Gamma 已提交
104
	private timeoutPromise:TPromise<void>;
A
Alex Dima 已提交
105
	private computePromise:TPromise<ILink[]>;
E
Erich Gamma 已提交
106
	private activeLinkDecorationId:string;
A
Alex Dima 已提交
107
	private lastMouseEvent:IEditorMouseEvent;
E
Erich Gamma 已提交
108 109
	private editorService:IEditorService;
	private messageService:IMessageService;
110
	private editorWorkerService: IEditorWorkerService;
E
Erich Gamma 已提交
111 112
	private currentOccurences:{ [decorationId:string]:LinkOccurence; };

113
	constructor(
A
Alex Dima 已提交
114 115 116 117
		editor:ICodeEditor,
		@IEditorService editorService:IEditorService,
		@IMessageService messageService:IMessageService,
		@IEditorWorkerService editorWorkerService: IEditorWorkerService
118
	) {
E
Erich Gamma 已提交
119 120 121
		this.editor = editor;
		this.editorService = editorService;
		this.messageService = messageService;
122
		this.editorWorkerService = editorWorkerService;
E
Erich Gamma 已提交
123
		this.listenersToRemove = [];
A
Alex Dima 已提交
124 125 126
		this.listenersToRemove.push(editor.onDidChangeModelContent((e:editorCommon.IModelContentChangedEvent) => this.onChange()));
		this.listenersToRemove.push(editor.onDidChangeModel((e) => this.onModelChanged()));
		this.listenersToRemove.push(editor.onDidChangeModelMode((e) => this.onModelModeChanged()));
A
Alex Dima 已提交
127 128 129 130
		this.listenersToRemove.push(this.editor.onMouseUp((e:IEditorMouseEvent) => this.onEditorMouseUp(e)));
		this.listenersToRemove.push(this.editor.onMouseMove((e:IEditorMouseEvent) => this.onEditorMouseMove(e)));
		this.listenersToRemove.push(this.editor.onKeyDown((e:IKeyboardEvent) => this.onEditorKeyDown(e)));
		this.listenersToRemove.push(this.editor.onKeyUp((e:IKeyboardEvent) => this.onEditorKeyUp(e)));
E
Erich Gamma 已提交
131 132 133 134 135 136 137
		this.timeoutPromise = null;
		this.computePromise = null;
		this.currentOccurences = {};
		this.activeLinkDecorationId = null;
		this.beginCompute();
	}

A
Alex Dima 已提交
138 139 140 141
	public getId(): string {
		return LinkDetector.ID;
	}

E
Erich Gamma 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
	public isComputing(): boolean {
		return TPromise.is(this.computePromise);
	}

	private onModelChanged(): void {
		this.lastMouseEvent = null;
		this.currentOccurences = {};
		this.activeLinkDecorationId = null;
		this.stop();
		this.beginCompute();
	}

	private onModelModeChanged(): void {
		this.stop();
		this.beginCompute();
	}

	private onChange():void {
		if (!this.timeoutPromise) {
			this.timeoutPromise = TPromise.timeout(LinkDetector.RECOMPUTE_TIME);
			this.timeoutPromise.then(() => {
				this.timeoutPromise = null;
				this.beginCompute();
			});
		}
	}

	private beginCompute():void {
		if (!this.editor.getModel()) {
			return;
		}
173

A
Alex Dima 已提交
174
		let modePromise:TPromise<ILink[]> = TPromise.as(null);
A
Alex Dima 已提交
175
		if (LinkProviderRegistry.has(this.editor.getModel())) {
176
			modePromise = getLinks(this.editor.getModel());
E
Erich Gamma 已提交
177
		}
178

179
		let standardPromise:TPromise<ILink[]> = this.editorWorkerService.computeLinks(this.editor.getModel().uri);
180 181 182 183 184 185 186 187 188 189

		this.computePromise = TPromise.join([modePromise, standardPromise]).then((r) => {
			let a = r[0];
			let b = r[1];
			if (!a || a.length === 0) {
				return b || [];
			}
			if (!b || b.length === 0) {
				return a || [];
			}
A
Alex Dima 已提交
190
			return LinkDetector._linksUnion(a.map(el => new Link(el)), b.map(el => new Link(el)));
191 192
		});

A
Alex Dima 已提交
193
		this.computePromise.then((links:ILink[]) => {
194 195 196 197 198
			this.updateDecorations(links);
			this.computePromise = null;
		});
	}

A
Alex Dima 已提交
199
	private static _linksUnion(oldLinks: Link[], newLinks: Link[]): Link[] {
200
		// reunite oldLinks with newLinks and remove duplicates
A
Alex Dima 已提交
201
		var result: Link[] = [],
202 203 204 205
			oldIndex: number,
			oldLen: number,
			newIndex: number,
			newLen: number,
A
Alex Dima 已提交
206 207
			oldLink: Link,
			newLink: Link,
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
			comparisonResult: number;

		for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen;) {
			oldLink = oldLinks[oldIndex];
			newLink = newLinks[newIndex];

			if (Range.areIntersectingOrTouching(oldLink.range, newLink.range)) {
				// Remove the oldLink
				oldIndex++;
				continue;
			}

			comparisonResult = Range.compareRangesUsingStarts(oldLink.range, newLink.range);

			if (comparisonResult < 0) {
				// oldLink is before
				result.push(oldLink);
				oldIndex++;
			} else {
				// newLink is before
				result.push(newLink);
				newIndex++;
			}
		}

		for (; oldIndex < oldLen; oldIndex++) {
			result.push(oldLinks[oldIndex]);
		}
		for (; newIndex < newLen; newIndex++) {
			result.push(newLinks[newIndex]);
		}

		return result;
E
Erich Gamma 已提交
241 242
	}

A
Alex Dima 已提交
243 244
	private updateDecorations(links:ILink[]):void {
		this.editor.changeDecorations((changeAccessor:editorCommon.IModelDecorationsChangeAccessor) => {
E
Erich Gamma 已提交
245
			var oldDecorations:string[] = [];
A
Alex Dima 已提交
246 247 248 249 250
			let keys = Object.keys(this.currentOccurences);
			for (let i = 0, len = keys.length; i < len; i++) {
				let decorationId = keys[i];
				let occurance = this.currentOccurences[decorationId];
				oldDecorations.push(occurance.decorationId);
E
Erich Gamma 已提交
251 252
			}

A
Alex Dima 已提交
253
			var newDecorations:editorCommon.IModelDeltaDecoration[] = [];
E
Erich Gamma 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
			if (links) {
				// Not sure why this is sometimes null
				for (var i = 0; i < links.length; i++) {
					newDecorations.push(LinkOccurence.decoration(links[i]));
				}
			}

			var decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);

			this.currentOccurences = {};
			this.activeLinkDecorationId = null;
			for (let i = 0, len = decorations.length; i < len; i++) {
				var occurance = new LinkOccurence(links[i], decorations[i]);
				this.currentOccurences[occurance.decorationId] = occurance;
			}
		});
	}

A
Alex Dima 已提交
272
	private onEditorKeyDown(e:IKeyboardEvent):void {
E
Erich Gamma 已提交
273 274 275 276 277
		if (e.keyCode === LinkDetector.TRIGGER_KEY_VALUE && this.lastMouseEvent) {
			this.onEditorMouseMove(this.lastMouseEvent, e);
		}
	}

A
Alex Dima 已提交
278
	private onEditorKeyUp(e:IKeyboardEvent):void {
E
Erich Gamma 已提交
279 280 281 282 283
		if (e.keyCode === LinkDetector.TRIGGER_KEY_VALUE) {
			this.cleanUpActiveLinkDecoration();
		}
	}

A
Alex Dima 已提交
284
	private onEditorMouseMove(mouseEvent: IEditorMouseEvent, withKey?:IKeyboardEvent):void {
E
Erich Gamma 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
		this.lastMouseEvent = mouseEvent;

		if (this.isEnabled(mouseEvent, withKey)) {
			this.cleanUpActiveLinkDecoration(); // always remove previous link decoration as their can only be one
			var occurence = this.getLinkOccurence(mouseEvent.target.position);
			if (occurence) {
				this.editor.changeDecorations((changeAccessor)=>{
					occurence.activate(changeAccessor);
					this.activeLinkDecorationId = occurence.decorationId;
				});
			}
		} else {
			this.cleanUpActiveLinkDecoration();
		}
	}

	private cleanUpActiveLinkDecoration():void {
		if (this.activeLinkDecorationId) {
			var occurence = this.currentOccurences[this.activeLinkDecorationId];
			if (occurence) {
				this.editor.changeDecorations((changeAccessor)=>{
					occurence.deactivate(changeAccessor);
				});
			}

			this.activeLinkDecorationId = null;
		}
	}

A
Alex Dima 已提交
314
	private onEditorMouseUp(mouseEvent: IEditorMouseEvent):void {
E
Erich Gamma 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
		if (!this.isEnabled(mouseEvent)) {
			return;
		}
		var occurence = this.getLinkOccurence(mouseEvent.target.position);
		if (!occurence) {
			return;
		}
		this.openLinkOccurence(occurence, mouseEvent.event.altKey);
	}

	public openLinkOccurence(occurence:LinkOccurence, openToSide:boolean):void {

		if (!this.editorService) {
			return;
		}

		var link = occurence.link;
		var absoluteUrl = link.url;
		var hashIndex = absoluteUrl.indexOf('#');
		var lineNumber = -1;
		var column = -1;
		if (hashIndex >= 0) {
			var hash = absoluteUrl.substr(hashIndex + 1);
			var selection = hash.split(',');

			if (selection.length > 0) {
				lineNumber = Number(selection[0]);
			}

			if (selection.length > 1) {
				column = Number(selection[1]);
			}

			if (lineNumber >= 0 || column >= 0) {
				absoluteUrl = absoluteUrl.substr(0, hashIndex);
			}
		}

353
		var url: URI;
E
Erich Gamma 已提交
354
		try {
355
			url = URI.parse(absoluteUrl);
E
Erich Gamma 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
		} catch (err) {
			// invalid url
			this.messageService.show(Severity.Warning, nls.localize('invalid.url', 'Invalid URI: cannot open {0}', absoluteUrl));
			return;
		}

		var input:IResourceInput = {
			resource: url
		};

		if (lineNumber >= 0) {
			input.options = {
				selection: { startLineNumber: lineNumber, startColumn: column }
			};
		}

A
Alex Dima 已提交
372
		this.editorService.openEditor(input, openToSide).done(null, onUnexpectedError);
E
Erich Gamma 已提交
373 374
	}

A
Alex Dima 已提交
375
	public getLinkOccurence(position: editorCommon.IPosition): LinkOccurence {
E
Erich Gamma 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
		var decorations = this.editor.getModel().getDecorationsInRange({
			startLineNumber: position.lineNumber,
			startColumn: position.column,
			endLineNumber: position.lineNumber,
			endColumn: position.column
		}, null, true);

		for (var i = 0; i < decorations.length; i++) {
			var decoration = decorations[i];
			var currentOccurence = this.currentOccurences[decoration.id];
			if (currentOccurence) {
				return currentOccurence;
			}
		}

		return null;
	}

A
Alex Dima 已提交
394 395
	private isEnabled(mouseEvent: IEditorMouseEvent, withKey?:IKeyboardEvent):boolean {
		return 	mouseEvent.target.type === editorCommon.MouseTargetType.CONTENT_TEXT &&
396
				(mouseEvent.event[LinkDetector.TRIGGER_MODIFIER] || (withKey && withKey.keyCode === LinkDetector.TRIGGER_KEY_VALUE));
E
Erich Gamma 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410
	}

	private stop():void {
		if (this.timeoutPromise) {
			this.timeoutPromise.cancel();
			this.timeoutPromise = null;
		}
		if (this.computePromise) {
			this.computePromise.cancel();
			this.computePromise = null;
		}
	}

	public dispose():void {
A
Alex Dima 已提交
411
		this.listenersToRemove = dispose(this.listenersToRemove);
E
Erich Gamma 已提交
412 413 414 415 416 417 418 419
		this.stop();
	}
}

class OpenLinkAction extends EditorAction {

	static ID = 'editor.action.openLink';

420
	constructor(
A
Alex Dima 已提交
421
		descriptor:editorCommon.IEditorActionDescriptorData,
A
Alex Dima 已提交
422
		editor:editorCommon.ICommonCodeEditor
423
	) {
E
Erich Gamma 已提交
424 425 426 427 428 429 430 431
		super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.UpdateOnCursorPositionChange);
	}

	public dispose(): void {
		super.dispose();
	}

	public getEnablementState(): boolean {
A
Alex Dima 已提交
432
		if (LinkDetector.get(this.editor).isComputing()) {
E
Erich Gamma 已提交
433 434 435
			// optimistic enablement while state is being computed
			return true;
		}
A
Alex Dima 已提交
436
		return !!LinkDetector.get(this.editor).getLinkOccurence(this.editor.getPosition());
E
Erich Gamma 已提交
437 438 439
	}

	public run():TPromise<any> {
A
Alex Dima 已提交
440
		var link = LinkDetector.get(this.editor).getLinkOccurence(this.editor.getPosition());
E
Erich Gamma 已提交
441
		if(link) {
A
Alex Dima 已提交
442
			LinkDetector.get(this.editor).openLinkOccurence(link, false);
E
Erich Gamma 已提交
443 444 445 446 447
		}
		return TPromise.as(null);
	}
}

448
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(OpenLinkAction, OpenLinkAction.ID, nls.localize('label', "Open Link"), void 0, 'Open Link'));
A
Alex Dima 已提交
449
EditorBrowserRegistry.registerEditorContribution(LinkDetector);