links.ts 11.4 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
import {IMessageService} from 'vs/platform/message/common/message';
18
import {IOpenerService} from 'vs/platform/opener/common/opener';
A
Alex Dima 已提交
19 20 21 22
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 已提交
23
import {ILink, LinkProviderRegistry} from 'vs/editor/common/modes';
24
import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService';
A
Alex Dima 已提交
25
import {IEditorMouseEvent, ICodeEditor} from 'vs/editor/browser/editorBrowser';
26
import {getLinks} from 'vs/editor/contrib/links/common/links';
A
Alex Dima 已提交
27
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
28
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
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
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 已提交
84
	static RECOMPUTE_TIME = 1000; // ms
A
Alex Dima 已提交
85 86 87
	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 已提交
88 89 90
	static CLASS_NAME = 'detected-link';
	static CLASS_NAME_ACTIVE = 'detected-link-active';

A
Alex Dima 已提交
91
	private editor:ICodeEditor;
A
Alex Dima 已提交
92
	private listenersToRemove:IDisposable[];
E
Erich Gamma 已提交
93
	private timeoutPromise:TPromise<void>;
94
	private computePromise:TPromise<void>;
E
Erich Gamma 已提交
95
	private activeLinkDecorationId:string;
A
Alex Dima 已提交
96
	private lastMouseEvent:IEditorMouseEvent;
97
	private openerService:IOpenerService;
E
Erich Gamma 已提交
98
	private messageService:IMessageService;
99
	private editorWorkerService: IEditorWorkerService;
E
Erich Gamma 已提交
100 101
	private currentOccurences:{ [decorationId:string]:LinkOccurence; };

102
	constructor(
A
Alex Dima 已提交
103
		editor:ICodeEditor,
104
		@IOpenerService openerService:IOpenerService,
A
Alex Dima 已提交
105 106
		@IMessageService messageService:IMessageService,
		@IEditorWorkerService editorWorkerService: IEditorWorkerService
107
	) {
E
Erich Gamma 已提交
108
		this.editor = editor;
109
		this.openerService = openerService;
E
Erich Gamma 已提交
110
		this.messageService = messageService;
111
		this.editorWorkerService = editorWorkerService;
E
Erich Gamma 已提交
112
		this.listenersToRemove = [];
A
Alex Dima 已提交
113
		this.listenersToRemove.push(editor.onDidChangeModelContent((e) => this.onChange()));
A
Alex Dima 已提交
114 115
		this.listenersToRemove.push(editor.onDidChangeModel((e) => this.onModelChanged()));
		this.listenersToRemove.push(editor.onDidChangeModelMode((e) => this.onModelModeChanged()));
116
		this.listenersToRemove.push(LinkProviderRegistry.onDidChange((e) => this.onModelModeChanged()));
A
Alex Dima 已提交
117 118 119 120
		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 已提交
121 122 123 124 125 126 127
		this.timeoutPromise = null;
		this.computePromise = null;
		this.currentOccurences = {};
		this.activeLinkDecorationId = null;
		this.beginCompute();
	}

A
Alex Dima 已提交
128 129 130 131
	public getId(): string {
		return LinkDetector.ID;
	}

E
Erich Gamma 已提交
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 162
	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;
		}
163

164 165
		if (!LinkProviderRegistry.has(this.editor.getModel())) {
			return;
E
Erich Gamma 已提交
166
		}
167

168
		this.computePromise = getLinks(this.editor.getModel()).then(links => {
169 170 171 172 173
			this.updateDecorations(links);
			this.computePromise = null;
		});
	}

A
Alex Dima 已提交
174 175
	private updateDecorations(links:ILink[]):void {
		this.editor.changeDecorations((changeAccessor:editorCommon.IModelDecorationsChangeAccessor) => {
E
Erich Gamma 已提交
176
			var oldDecorations:string[] = [];
A
Alex Dima 已提交
177 178 179 180 181
			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 已提交
182 183
			}

A
Alex Dima 已提交
184
			var newDecorations:editorCommon.IModelDeltaDecoration[] = [];
E
Erich Gamma 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
			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 已提交
203
	private onEditorKeyDown(e:IKeyboardEvent):void {
E
Erich Gamma 已提交
204 205 206 207 208
		if (e.keyCode === LinkDetector.TRIGGER_KEY_VALUE && this.lastMouseEvent) {
			this.onEditorMouseMove(this.lastMouseEvent, e);
		}
	}

A
Alex Dima 已提交
209
	private onEditorKeyUp(e:IKeyboardEvent):void {
E
Erich Gamma 已提交
210 211 212 213 214
		if (e.keyCode === LinkDetector.TRIGGER_KEY_VALUE) {
			this.cleanUpActiveLinkDecoration();
		}
	}

A
Alex Dima 已提交
215
	private onEditorMouseMove(mouseEvent: IEditorMouseEvent, withKey?:IKeyboardEvent):void {
E
Erich Gamma 已提交
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 241 242 243 244
		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 已提交
245
	private onEditorMouseUp(mouseEvent: IEditorMouseEvent):void {
E
Erich Gamma 已提交
246 247 248 249 250 251 252 253 254 255
		if (!this.isEnabled(mouseEvent)) {
			return;
		}
		var occurence = this.getLinkOccurence(mouseEvent.target.position);
		if (!occurence) {
			return;
		}
		this.openLinkOccurence(occurence, mouseEvent.event.altKey);
	}

256
	public openLinkOccurence(occurence: LinkOccurence, openToSide: boolean): void {
E
Erich Gamma 已提交
257

258
		if (!this.openerService) {
E
Erich Gamma 已提交
259 260 261
			return;
		}

262
		let url: URI;
E
Erich Gamma 已提交
263
		try {
264
			url = URI.parse(occurence.link.url);
E
Erich Gamma 已提交
265 266
		} catch (err) {
			// invalid url
267
			this.messageService.show(Severity.Warning, nls.localize('invalid.url', 'Invalid URI: cannot open {0}', occurence.link.url));
E
Erich Gamma 已提交
268 269 270
			return;
		}

271
		this.openerService.open(url, { openToSide }).done(null, onUnexpectedError);
E
Erich Gamma 已提交
272 273
	}

A
Alex Dima 已提交
274
	public getLinkOccurence(position: editorCommon.IPosition): LinkOccurence {
E
Erich Gamma 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
		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 已提交
293 294
	private isEnabled(mouseEvent: IEditorMouseEvent, withKey?:IKeyboardEvent):boolean {
		return 	mouseEvent.target.type === editorCommon.MouseTargetType.CONTENT_TEXT &&
295
				(mouseEvent.event[LinkDetector.TRIGGER_MODIFIER] || (withKey && withKey.keyCode === LinkDetector.TRIGGER_KEY_VALUE));
E
Erich Gamma 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309
	}

	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 已提交
310
		this.listenersToRemove = dispose(this.listenersToRemove);
E
Erich Gamma 已提交
311 312 313 314 315 316 317 318
		this.stop();
	}
}

class OpenLinkAction extends EditorAction {

	static ID = 'editor.action.openLink';

319
	constructor(
A
Alex Dima 已提交
320
		descriptor:editorCommon.IEditorActionDescriptorData,
A
Alex Dima 已提交
321
		editor:editorCommon.ICommonCodeEditor
322
	) {
E
Erich Gamma 已提交
323 324 325 326 327 328 329 330
		super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.UpdateOnCursorPositionChange);
	}

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

	public getEnablementState(): boolean {
A
Alex Dima 已提交
331
		if (LinkDetector.get(this.editor).isComputing()) {
E
Erich Gamma 已提交
332 333 334
			// optimistic enablement while state is being computed
			return true;
		}
A
Alex Dima 已提交
335
		return !!LinkDetector.get(this.editor).getLinkOccurence(this.editor.getPosition());
E
Erich Gamma 已提交
336 337 338
	}

	public run():TPromise<any> {
A
Alex Dima 已提交
339
		var link = LinkDetector.get(this.editor).getLinkOccurence(this.editor.getPosition());
E
Erich Gamma 已提交
340
		if(link) {
A
Alex Dima 已提交
341
			LinkDetector.get(this.editor).openLinkOccurence(link, false);
E
Erich Gamma 已提交
342 343 344 345 346
		}
		return TPromise.as(null);
	}
}

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