links.ts 14.3 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';
E
Erich Gamma 已提交
10 11 12
import {TPromise} from 'vs/base/common/winjs.base';
import Platform = require('vs/base/common/platform');
import Errors = require('vs/base/common/errors');
13
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
14 15
import Keyboard = require('vs/base/browser/keyboardEvent');
import {CommonEditorRegistry, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
A
Alex Dima 已提交
16 17
import {EditorAction} from 'vs/editor/common/editorAction';
import {Behaviour} from 'vs/editor/common/editorActionEnablement';
E
Erich Gamma 已提交
18
import EventEmitter = require('vs/base/common/eventEmitter');
A
Alex Dima 已提交
19 20 21
import * as EditorBrowser from 'vs/editor/browser/editorBrowser';
import * as EditorCommon from 'vs/editor/common/editorCommon';
import * as Modes from 'vs/editor/common/modes';
E
Erich Gamma 已提交
22 23 24 25
import {IEditorService, IResourceInput} from 'vs/platform/editor/common/editor';
import {IMessageService} from 'vs/platform/message/common/message';
import Severity from 'vs/base/common/severity';
import {KeyCode} from 'vs/base/common/keyCodes';
26 27
import {Range} from 'vs/editor/common/core/range';
import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService';
E
Erich Gamma 已提交
28 29 30 31 32 33 34 35 36 37 38 39

class LinkOccurence {

	public static decoration(link:Modes.ILink): EditorCommon.IModelDeltaDecoration {
		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 已提交
40
		};
E
Erich Gamma 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	}

	private static _getOptions(link:Modes.ILink, isActive:boolean):EditorCommon.IModelDecorationOptions {
		var result = '';
		if (link.extraInlineClassName) {
			result = link.extraInlineClassName + ' ';
		}

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

		return {
			stickiness: EditorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
			inlineClassName: result,
			hoverMessage: LinkDetector.HOVER_MESSAGE_GENERAL
		};
	}

	public decorationId:string;
	public link:Modes.ILink;

	constructor(link:Modes.ILink, decorationId:string/*, changeAccessor:EditorCommon.IModelDecorationsChangeAccessor*/) {
		this.link = link;
		this.decorationId = decorationId;
	}

	public activate(changeAccessor: EditorCommon.IModelDecorationsChangeAccessor):void {
		changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurence._getOptions(this.link, true));
	}

	public deactivate(changeAccessor: EditorCommon.IModelDecorationsChangeAccessor):void {
		changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurence._getOptions(this.link, false));
	}
}

class LinkDetector {
	static RECOMPUTE_TIME = 1000; // ms
	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");
	static CLASS_NAME = 'detected-link';
	static CLASS_NAME_ACTIVE = 'detected-link-active';

	private editor:EditorCommon.ICommonCodeEditor;
	private listenersToRemove:EventEmitter.ListenerUnbind[];
	private timeoutPromise:TPromise<void>;
	private computePromise:TPromise<Modes.ILink[]>;
	private activeLinkDecorationId:string;
A
Alex Dima 已提交
92
	private lastMouseEvent:EditorBrowser.IEditorMouseEvent;
E
Erich Gamma 已提交
93 94
	private editorService:IEditorService;
	private messageService:IMessageService;
95
	private editorWorkerService: IEditorWorkerService;
E
Erich Gamma 已提交
96 97
	private currentOccurences:{ [decorationId:string]:LinkOccurence; };

98 99 100 101 102 103
	constructor(
		editor:EditorCommon.ICommonCodeEditor,
		editorService:IEditorService,
		messageService:IMessageService,
		editorWorkerService: IEditorWorkerService
	) {
E
Erich Gamma 已提交
104 105 106
		this.editor = editor;
		this.editorService = editorService;
		this.messageService = messageService;
107
		this.editorWorkerService = editorWorkerService;
E
Erich Gamma 已提交
108 109 110 111 112 113 114 115 116
		this.listenersToRemove = [];
		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(editor.addListener(EditorCommon.EventType.ModelModeSupportChanged, (e: EditorCommon.IModeSupportChangedEvent) => {
			if (e.linkSupport) {
				this.onModelModeChanged();
			}
		}));
A
Alex Dima 已提交
117 118
		this.listenersToRemove.push(this.editor.addListener(EditorCommon.EventType.MouseUp, (e:EditorBrowser.IEditorMouseEvent) => this.onEditorMouseUp(e)));
		this.listenersToRemove.push(this.editor.addListener(EditorCommon.EventType.MouseMove, (e:EditorBrowser.IEditorMouseEvent) => this.onEditorMouseMove(e)));
A
Cleanup  
Alex Dima 已提交
119 120
		this.listenersToRemove.push(this.editor.addListener(EditorCommon.EventType.KeyDown, (e:Keyboard.IKeyboardEvent) => this.onEditorKeyDown(e)));
		this.listenersToRemove.push(this.editor.addListener(EditorCommon.EventType.KeyUp, (e:Keyboard.IKeyboardEvent) => this.onEditorKeyUp(e)));
E
Erich Gamma 已提交
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 146 147 148 149 150 151 152 153 154 155 156 157 158
		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;
		}
159 160 161

		let modePromise:TPromise<Modes.ILink[]> = TPromise.as(null);
		let mode = this.editor.getModel().getMode();
E
Erich Gamma 已提交
162
		if (mode.linkSupport) {
163
			modePromise = mode.linkSupport.computeLinks(this.editor.getModel().getAssociatedResource());
E
Erich Gamma 已提交
164
		}
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 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

		let standardPromise:TPromise<Modes.ILink[]> = this.editorWorkerService.computeLinks(this.editor.getModel().getAssociatedResource());

		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 || [];
			}
			return LinkDetector._linksUnion(a, b);
		});

		this.computePromise.then((links:Modes.ILink[]) => {
			this.updateDecorations(links);
			this.computePromise = null;
		});
	}

	private static _linksUnion(oldLinks: Modes.ILink[], newLinks: Modes.ILink[]): Modes.ILink[] {
		// reunite oldLinks with newLinks and remove duplicates
		var result: Modes.ILink[] = [],
			oldIndex: number,
			oldLen: number,
			newIndex: number,
			newLen: number,
			oldLink: Modes.ILink,
			newLink: Modes.ILink,
			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 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
	}

	private updateDecorations(links:Modes.ILink[]):void {
		this.editor.changeDecorations((changeAccessor:EditorCommon.IModelDecorationsChangeAccessor) => {
			var oldDecorations:string[] = [];
			for (var decorationId in this.currentOccurences) {
				if (this.currentOccurences.hasOwnProperty(decorationId)) {
					var occurance = this.currentOccurences[decorationId];
					oldDecorations.push(occurance.decorationId);
				}
			}

			var newDecorations:EditorCommon.IModelDeltaDecoration[] = [];
			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
Cleanup  
Alex Dima 已提交
259
	private onEditorKeyDown(e:Keyboard.IKeyboardEvent):void {
E
Erich Gamma 已提交
260 261 262 263 264
		if (e.keyCode === LinkDetector.TRIGGER_KEY_VALUE && this.lastMouseEvent) {
			this.onEditorMouseMove(this.lastMouseEvent, e);
		}
	}

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

A
Alex Dima 已提交
271
	private onEditorMouseMove(mouseEvent: EditorBrowser.IEditorMouseEvent, withKey?:Keyboard.IKeyboardEvent):void {
E
Erich Gamma 已提交
272 273 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
		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 已提交
301
	private onEditorMouseUp(mouseEvent: EditorBrowser.IEditorMouseEvent):void {
E
Erich Gamma 已提交
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 339
		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);
			}
		}

340
		var url: URI;
E
Erich Gamma 已提交
341
		try {
342
			url = URI.parse(absoluteUrl);
E
Erich Gamma 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
		} 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 }
			};
		}

		this.editorService.openEditor(input, openToSide).done(null, Errors.onUnexpectedError);
	}

	public getLinkOccurence(position: EditorCommon.IPosition): LinkOccurence {
		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 已提交
381
	private isEnabled(mouseEvent: EditorBrowser.IEditorMouseEvent, withKey?:Keyboard.IKeyboardEvent):boolean {
E
Erich Gamma 已提交
382
		return 	mouseEvent.target.type === EditorCommon.MouseTargetType.CONTENT_TEXT &&
383
				(mouseEvent.event[LinkDetector.TRIGGER_MODIFIER] || (withKey && withKey.keyCode === LinkDetector.TRIGGER_KEY_VALUE));
E
Erich Gamma 已提交
384 385 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
	}

	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;

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

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

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

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