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

class LinkOccurence {

A
Alex Dima 已提交
32
	public static decoration(link:ILink): editorCommon.IModelDeltaDecoration {
E
Erich Gamma 已提交
33 34 35 36 37 38 39 40
		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 已提交
41
		};
E
Erich Gamma 已提交
42 43
	}

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

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

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

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

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

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

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

A
Alex Dima 已提交
77 78 79 80 81 82 83 84 85 86
class Link {
	range: editorCommon.IEditorRange;
	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;
	}
}

E
Erich Gamma 已提交
87 88
class LinkDetector {
	static RECOMPUTE_TIME = 1000; // ms
A
Alex Dima 已提交
89 90 91
	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 已提交
92 93 94
	static CLASS_NAME = 'detected-link';
	static CLASS_NAME_ACTIVE = 'detected-link-active';

A
Alex Dima 已提交
95 96
	private editor:editorCommon.ICommonCodeEditor;
	private listenersToRemove:ListenerUnbind[];
E
Erich Gamma 已提交
97
	private timeoutPromise:TPromise<void>;
A
Alex Dima 已提交
98
	private computePromise:TPromise<ILink[]>;
E
Erich Gamma 已提交
99
	private activeLinkDecorationId:string;
A
Alex Dima 已提交
100
	private lastMouseEvent:IEditorMouseEvent;
E
Erich Gamma 已提交
101 102
	private editorService:IEditorService;
	private messageService:IMessageService;
103
	private editorWorkerService: IEditorWorkerService;
E
Erich Gamma 已提交
104 105
	private currentOccurences:{ [decorationId:string]:LinkOccurence; };

106
	constructor(
A
Alex Dima 已提交
107
		editor:editorCommon.ICommonCodeEditor,
108 109 110 111
		editorService:IEditorService,
		messageService:IMessageService,
		editorWorkerService: IEditorWorkerService
	) {
E
Erich Gamma 已提交
112 113 114
		this.editor = editor;
		this.editorService = editorService;
		this.messageService = messageService;
115
		this.editorWorkerService = editorWorkerService;
E
Erich Gamma 已提交
116
		this.listenersToRemove = [];
A
Alex Dima 已提交
117 118 119 120 121 122 123
		this.listenersToRemove.push(editor.addListener('change', (e:editorCommon.IModelContentChangedEvent) => this.onChange()));
		this.listenersToRemove.push(editor.addListener(editorCommon.EventType.ModelChanged, (e:editorCommon.IModelContentChangedEvent) => this.onModelChanged()));
		this.listenersToRemove.push(editor.addListener(editorCommon.EventType.ModelModeChanged, (e:editorCommon.IModelModeChangedEvent) => this.onModelModeChanged()));
		this.listenersToRemove.push(this.editor.addListener(editorCommon.EventType.MouseUp, (e:IEditorMouseEvent) => this.onEditorMouseUp(e)));
		this.listenersToRemove.push(this.editor.addListener(editorCommon.EventType.MouseMove, (e:IEditorMouseEvent) => this.onEditorMouseMove(e)));
		this.listenersToRemove.push(this.editor.addListener(editorCommon.EventType.KeyDown, (e:IKeyboardEvent) => this.onEditorKeyDown(e)));
		this.listenersToRemove.push(this.editor.addListener(editorCommon.EventType.KeyUp, (e:IKeyboardEvent) => this.onEditorKeyUp(e)));
E
Erich Gamma 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		this.timeoutPromise = null;
		this.computePromise = null;
		this.currentOccurences = {};
		this.activeLinkDecorationId = null;
		this.beginCompute();
	}

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

A
Alex Dima 已提交
163
		let modePromise:TPromise<ILink[]> = TPromise.as(null);
A
Alex Dima 已提交
164
		if (LinkProviderRegistry.has(this.editor.getModel())) {
165
			modePromise = getLinks(this.editor.getModel());
E
Erich Gamma 已提交
166
		}
167

168
		let standardPromise:TPromise<ILink[]> = this.editorWorkerService.computeLinks(this.editor.getModel().uri);
169 170 171 172 173 174 175 176 177 178

		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 已提交
179
			return LinkDetector._linksUnion(a.map(el => new Link(el)), b.map(el => new Link(el)));
180 181
		});

A
Alex Dima 已提交
182
		this.computePromise.then((links:ILink[]) => {
183 184 185 186 187
			this.updateDecorations(links);
			this.computePromise = null;
		});
	}

A
Alex Dima 已提交
188
	private static _linksUnion(oldLinks: Link[], newLinks: Link[]): Link[] {
189
		// reunite oldLinks with newLinks and remove duplicates
A
Alex Dima 已提交
190
		var result: Link[] = [],
191 192 193 194
			oldIndex: number,
			oldLen: number,
			newIndex: number,
			newLen: number,
A
Alex Dima 已提交
195 196
			oldLink: Link,
			newLink: Link,
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
			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 已提交
230 231
	}

A
Alex Dima 已提交
232 233
	private updateDecorations(links:ILink[]):void {
		this.editor.changeDecorations((changeAccessor:editorCommon.IModelDecorationsChangeAccessor) => {
E
Erich Gamma 已提交
234
			var oldDecorations:string[] = [];
A
Alex Dima 已提交
235 236 237 238 239
			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 已提交
240 241
			}

A
Alex Dima 已提交
242
			var newDecorations:editorCommon.IModelDeltaDecoration[] = [];
E
Erich Gamma 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
			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 已提交
261
	private onEditorKeyDown(e:IKeyboardEvent):void {
E
Erich Gamma 已提交
262 263 264 265 266
		if (e.keyCode === LinkDetector.TRIGGER_KEY_VALUE && this.lastMouseEvent) {
			this.onEditorMouseMove(this.lastMouseEvent, e);
		}
	}

A
Alex Dima 已提交
267
	private onEditorKeyUp(e:IKeyboardEvent):void {
E
Erich Gamma 已提交
268 269 270 271 272
		if (e.keyCode === LinkDetector.TRIGGER_KEY_VALUE) {
			this.cleanUpActiveLinkDecoration();
		}
	}

A
Alex Dima 已提交
273
	private onEditorMouseMove(mouseEvent: IEditorMouseEvent, withKey?:IKeyboardEvent):void {
E
Erich Gamma 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
		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 已提交
303
	private onEditorMouseUp(mouseEvent: IEditorMouseEvent):void {
E
Erich Gamma 已提交
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 339 340 341
		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);
			}
		}

342
		var url: URI;
E
Erich Gamma 已提交
343
		try {
344
			url = URI.parse(absoluteUrl);
E
Erich Gamma 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
		} 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 已提交
361
		this.editorService.openEditor(input, openToSide).done(null, onUnexpectedError);
E
Erich Gamma 已提交
362 363
	}

A
Alex Dima 已提交
364
	public getLinkOccurence(position: editorCommon.IPosition): LinkOccurence {
E
Erich Gamma 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
		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 已提交
383 384
	private isEnabled(mouseEvent: IEditorMouseEvent, withKey?:IKeyboardEvent):boolean {
		return 	mouseEvent.target.type === editorCommon.MouseTargetType.CONTENT_TEXT &&
385
				(mouseEvent.event[LinkDetector.TRIGGER_MODIFIER] || (withKey && withKey.keyCode === LinkDetector.TRIGGER_KEY_VALUE));
E
Erich Gamma 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	}

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

	public dispose():void {
		this.listenersToRemove.forEach((element) => {
			element();
		});
		this.listenersToRemove = [];
		this.stop();
	}
}

class OpenLinkAction extends EditorAction {

	static ID = 'editor.action.openLink';

	private _linkDetector: LinkDetector;

414
	constructor(
A
Alex Dima 已提交
415 416
		descriptor:editorCommon.IEditorActionDescriptorData,
		editor:editorCommon.ICommonCodeEditor,
E
Erich Gamma 已提交
417
		@IEditorService editorService:IEditorService,
418 419 420
		@IMessageService messageService:IMessageService,
		@IEditorWorkerService editorWorkerService: IEditorWorkerService
	) {
E
Erich Gamma 已提交
421 422
		super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.UpdateOnCursorPositionChange);

423
		this._linkDetector = new LinkDetector(editor, editorService, messageService, editorWorkerService);
E
Erich Gamma 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
	}

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

	public getEnablementState(): boolean {
		if(this._linkDetector.isComputing()) {
			// optimistic enablement while state is being computed
			return true;
		}
		return !!this._linkDetector.getLinkOccurence(this.editor.getPosition());
	}

	public run():TPromise<any> {
		var link = this._linkDetector.getLinkOccurence(this.editor.getPosition());
		if(link) {
			this._linkDetector.openLinkOccurence(link, false);
		}
		return TPromise.as(null);
	}
}

448
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(OpenLinkAction, OpenLinkAction.ID, nls.localize('label', "Open Link"), void 0, 'Open Link'));