defineKeybinding.ts 13.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*---------------------------------------------------------------------------------------------
 *  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!./defineKeybinding';
import nls = require('vs/nls');
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
import DomUtils = require('vs/base/browser/dom');
import EditorBrowser = require('vs/editor/browser/editorBrowser');
import EditorCommon = require('vs/editor/common/editorCommon');
import {disposeAll, IDisposable} from 'vs/base/common/lifecycle';
import {INullService} from 'vs/platform/instantiation/common/instantiation';
import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent';
import {KeyMod, KeyCode, CommonKeybindings, Keybinding} from 'vs/base/common/keyCodes';
import Snippet = require('vs/editor/contrib/snippet/common/snippet');
import {EditorAction, Behaviour} from 'vs/editor/common/editorAction';
import {CommonEditorRegistry, ContextKey, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
import {TPromise} from 'vs/base/common/winjs.base';
import {IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
23 24 25
import {RunOnceScheduler} from 'vs/base/common/async';
import {IOSupport} from 'vs/platform/keybinding/common/commonKeybindingResolver';
import {IHTMLContentElement} from 'vs/base/common/htmlContent';
26

A
Alex Dima 已提交
27 28 29
const NLS_LAUNCH_MESSAGE = nls.localize('defineKeybinding.start', "Define Keybinding");
const NLS_DEFINE_MESSAGE = nls.localize('defineKeybinding.initial', "Press desired key combination and ENTER");
const NLS_DEFINE_ACTION_LABEL = nls.localize('DefineKeybindingAction',"Define Keybinding");
30 31
const NLS_KB_LAYOUT_INFO_MESSAGE = nls.localize('defineKeybinding.kbLayoutInfoMessage', "For your current keyboard layout press ");
const NLS_KB_LAYOUT_ERROR_MESSAGE = nls.localize('defineKeybinding.kbLayoutErrorMessage', "You won't be able to produce this key combination under your current keyboard layout.");
32 33

const INTERESTING_FILE = /keybindings\.json$/;
A
Alex Dima 已提交
34

35 36 37 38 39 40 41 42 43
export class DefineKeybindingController implements EditorCommon.IEditorContribution {

	static ID = 'editor.contrib.defineKeybinding';

	static get(editor:EditorCommon.ICommonCodeEditor): DefineKeybindingController {
		return <DefineKeybindingController>editor.getContribution(DefineKeybindingController.ID);
	}

	private _editor: EditorBrowser.ICodeEditor;
44
	private _keybindingService:IKeybindingService;
45 46 47
	private _launchWidget: DefineKeybindingLauncherWidget;
	private _defineWidget: DefineKeybindingWidget;
	private _toDispose: IDisposable[];
48 49
	private _modelToDispose: IDisposable[];
	private _updateDecorations: RunOnceScheduler;
50 51 52 53 54 55

	constructor(
		editor:EditorBrowser.ICodeEditor,
		@IKeybindingService keybindingService:IKeybindingService
	) {
		this._editor = editor;
56
		this._keybindingService = keybindingService;
57 58 59 60 61 62 63 64 65 66
		this._toDispose = [];
		this._launchWidget = new DefineKeybindingLauncherWidget(this._editor, keybindingService, () => this.launch());
		this._defineWidget = new DefineKeybindingWidget(this._editor, (keybinding) => this._onAccepted(keybinding));

		this._toDispose.push(this._editor.addListener2(EditorCommon.EventType.ModelChanged, (e) => {
			if (isInterestingEditorModel(this._editor)) {
				this._launchWidget.show();
			} else {
				this._launchWidget.hide();
			}
67
			this._onModel();
68
		}));
69 70 71 72 73 74

		this._updateDecorations = new RunOnceScheduler(() => this._updateDecorationsNow(), 500);
		this._toDispose.push(this._updateDecorations);

		this._modelToDispose = [];
		this._onModel();
75 76 77 78 79 80 81
	}

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

	public dispose(): void {
82
		this._modelToDispose = disposeAll(this._modelToDispose);
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
		this._toDispose = disposeAll(this._toDispose);
		this._launchWidget.dispose();
		this._launchWidget = null;
		this._defineWidget.dispose();
		this._defineWidget = null;
	}

	public launch(): void {
		if (isInterestingEditorModel(this._editor)) {
			this._defineWidget.start();
		}
	}

	private _onAccepted(keybinding:string): void {
		let snippetText = [
			'{',
			'\t"key": "' + keybinding + '",',
			'\t"command": "{{commandId}}",',
			'\t"when": "{{editorTextFocus}}"',
			'}{{}}'
		].join('\n');

		Snippet.get(this._editor).run(new Snippet.CodeSnippet(snippetText), 0, 0);
	}
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 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 173 174 175 176 177

	private _onModel(): void {
		this._modelToDispose = disposeAll(this._modelToDispose);

		let model = this._editor.getModel();
		if (!model) {
			return;
		}

		let url = model.getAssociatedResource().toString();
		if (!INTERESTING_FILE.test(url)) {
			return;
		}

		this._modelToDispose.push(model.addListener2(EditorCommon.EventType.ModelContentChanged2, (e) => this._updateDecorations.schedule()));
		this._modelToDispose.push({
			dispose: () => {
				this._dec = this._editor.deltaDecorations(this._dec, []);
				this._updateDecorations.cancel();
			}
		});
		this._updateDecorations.schedule();
	}

	private static _cachedKeybindingRegex: string = null;
	private static _getKeybindingRegex(): string {
		if (!this._cachedKeybindingRegex) {
			let numpadKey = "numpad(0|1|2|3|4|5|6|7|8|9|_multiply|_add|_subtract|_decimal|_divide)";
			let punctKey = "`|\\-|=|\\[|\\]|\\\\\\\\|;|'|,|\\.|\\/";
			let specialKey = "left|up|right|down|pageup|pagedown|end|home|tab|enter|escape|space|backspace|delete|pausebreak|capslock|insert";
			let casualKey = "[a-z]|[0-9]|f(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15)";
			let key = '((' + [numpadKey, punctKey, specialKey, casualKey].join(')|(') + '))';
			let mod = '((ctrl|shift|alt|cmd|win|meta)\\+)*';
			let keybinding = '(' + mod + key + ')';

			this._cachedKeybindingRegex = '"\\s*(' + keybinding + '(\\s+' + keybinding +')?' + ')\\s*"';
		}
		return this._cachedKeybindingRegex;
	}

	private _dec:string[] = [];
	private _updateDecorationsNow(): void {
		let model = this._editor.getModel();
		let regex = DefineKeybindingController._getKeybindingRegex();

		var m = model.findMatches(regex, false, true, false, false);

		let data = m.map((range) => {
			let text = model.getValueInRange(range);

			let strKeybinding = text.substring(1, text.length - 1);
			strKeybinding = strKeybinding.replace(/\\\\/g, '\\');

			let numKeybinding = IOSupport.readKeybinding(strKeybinding);

			let keybinding = new Keybinding(numKeybinding);

			return {
				strKeybinding: strKeybinding,
				keybinding: keybinding,
				usLabel: keybinding._toUSLabel(),
				label: this._keybindingService.getLabelFor(keybinding),
				range: range
			};
		});

		data = data.filter((entry) => {
			return (entry.usLabel !== entry.label);
		});

		this._dec = this._editor.deltaDecorations(this._dec, data.map((m) : EditorCommon.IModelDeltaDecoration => {
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
			let isError:boolean;
			let msg:IHTMLContentElement[];

			if (!m.label) {
				isError = true;
				msg = [{
					tagName: 'span',
					text: NLS_KB_LAYOUT_ERROR_MESSAGE
				}];
			} else {
				isError = false;
				msg = [{
					tagName: 'span',
					text: NLS_KB_LAYOUT_INFO_MESSAGE
				}];
				msg = msg.concat(this._keybindingService.getHTMLLabelFor(m.keybinding));
			}
195 196
			return {
				range: m.range,
197
				options: DefineKeybindingController._decorationOptions(msg, isError)
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

	private static _decorationOptions(msg:IHTMLContentElement[], isError:boolean): EditorCommon.IModelDecorationOptions {
		if (isError) {
			return {
				stickiness: EditorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
				className: 'keybindingError',
				htmlMessage: msg,
				inlineClassName: 'inlineKeybindingError',
				overviewRuler: {
					color: 'rgba(250, 100, 100, 0.6)',
					darkColor: 'rgba(250, 100, 100, 0.6)',
					position: EditorCommon.OverviewRulerLane.Right
				}
			}
		}
		return {
			stickiness: EditorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
			className: 'keybindingInfo',
			htmlMessage: msg,
			inlineClassName: 'inlineKeybindingInfo',
			overviewRuler: {
				color: 'rgba(100, 100, 250, 0.6)',
				darkColor: 'rgba(100, 100, 250, 0.6)',
				position: EditorCommon.OverviewRulerLane.Right
			}
		}
	}
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
}

class DefineKeybindingLauncherWidget implements EditorBrowser.IOverlayWidget {

	private static ID = 'editor.contrib.defineKeybindingLauncherWidget';

	private _editor: EditorBrowser.ICodeEditor;

	private _domNode: HTMLElement;
	private _toDispose: IDisposable[];

	constructor(editor:EditorBrowser.ICodeEditor, keybindingService:IKeybindingService, onLaunch:()=>void) {
		this._editor = editor;
		this._domNode = document.createElement('div');
		this._domNode.className = 'defineKeybindingLauncher';
		this._domNode.style.display = 'none';
		let keybinding = keybindingService.lookupKeybindings(DefineKeybindingAction.ID);
		let extra = '';
		if (keybinding.length > 0) {
247
			extra += ' ('+keybindingService.getLabelFor(keybinding[0])+')';
248
		}
A
Alex Dima 已提交
249
		this._domNode.appendChild(document.createTextNode(NLS_LAUNCH_MESSAGE + extra));
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

		this._toDispose = [];
		this._toDispose.push(DomUtils.addDisposableListener(this._domNode, 'click', (e) => {
			onLaunch();
		}))

		this._editor.addOverlayWidget(this);
	}

	public dispose(): void {
		this._editor.removeOverlayWidget(this);
		this._toDispose = disposeAll(this._toDispose);
	}

	public show(): void {
		this._domNode.style.display = 'block';
	}

	public hide(): void {
		this._domNode.style.display = 'none';
	}

	// ----- IOverlayWidget API

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

	public getDomNode(): HTMLElement {
		return this._domNode;
	}

	public getPosition(): EditorBrowser.IOverlayWidgetPosition {
		return {
			preference: EditorBrowser.OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER
		};
	}
}

class DefineKeybindingWidget implements EditorBrowser.IContentWidget {

	private static ID = 'editor.contrib.defineKeybindingWidget';

	private _editor: EditorBrowser.ICodeEditor;

	private _domNode: HTMLElement;
	private _toDispose: IDisposable[];
	private _position: EditorCommon.IPosition;

	private _messageNode: HTMLElement;
	private _inputNode: HTMLInputElement;

	private _lastKeybinding: Keybinding;
	private _onAccepted: (keybinding:string) => void;

	constructor(editor:EditorBrowser.ICodeEditor, onAccepted:(keybinding:string) => void) {
		this._editor = editor;
		this._onAccepted = onAccepted;
		this._toDispose = [];
		this._position = null;
		this._lastKeybinding = null;

		this._domNode = document.createElement('div');
		this._domNode.className = 'defineKeybindingWidget';

		this._messageNode = document.createElement('div');
		this._messageNode.className = 'message';
A
Alex Dima 已提交
317
		this._messageNode.innerText = NLS_DEFINE_MESSAGE;
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
		this._domNode.appendChild(this._messageNode);

		this._inputNode = document.createElement('input');
		this._inputNode.className = 'input';
		this._domNode.appendChild(this._inputNode);

		this._toDispose.push(DomUtils.addDisposableListener(this._inputNode, 'keydown', (e) => {
			let keyEvent = new StandardKeyboardEvent(e);
			keyEvent.preventDefault();
			keyEvent.stopPropagation();

			let kb = new Keybinding(keyEvent.asKeybinding());
			switch (kb.value) {
				case CommonKeybindings.ENTER:
					if (this._lastKeybinding) {
						this._onAccepted(this._lastKeybinding.toUserSettingsLabel());
					}
					this._stop();
					return;

				case CommonKeybindings.ESCAPE:
					this._stop();
					return;
			}

			this._lastKeybinding = kb;

345 346
			this._inputNode.value = this._lastKeybinding.toUserSettingsLabel().toLowerCase();
			this._inputNode.title = 'keyCode: ' + keyEvent.browserEvent.keyCode;
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 381 382 383 384 385
		}));

		this._toDispose.push(DomUtils.addDisposableListener(this._inputNode, 'blur', (e) => this._stop()));

		this._editor.addContentWidget(this);
	}

	public dispose(): void {
		this._editor.removeContentWidget(this);
		this._toDispose = disposeAll(this._toDispose);
	}

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

	public getDomNode(): HTMLElement {
		return this._domNode;
	}

	public getPosition(): EditorBrowser.IContentWidgetPosition {
		if (!this._position) {
			return null;
		}
		return {
			position: this._position,
			preference: [EditorBrowser.ContentWidgetPositionPreference.BELOW]
		};
	}

	public start(): void {
		this._position = this._editor.getPosition();
		this._editor.revealPositionInCenterIfOutsideViewport(this._position);
		this._editor.layoutContentWidget(this);

		// Force a view render
		this._editor.getOffsetForColumn(this._position.lineNumber, this._position.column);

		this._lastKeybinding = null;
386
		this._inputNode.value = '';
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 414 415 416 417 418 419 420
		this._inputNode.focus();
	}

	private _stop(): void {
		this._editor.focus();
		this._position = null;
		this._editor.layoutContentWidget(this);
	}
}

export class DefineKeybindingAction extends EditorAction {

	static ID = 'editor.action.defineKeybinding';

	constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
		super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.UpdateOnModelChange | Behaviour.Writeable);
	}

	public isSupported(): boolean {
		if (!super.isSupported()) {
			return false;
		}
		return isInterestingEditorModel(this.editor);
	}

	public run(): TPromise<boolean> {
		var controller = DefineKeybindingController.get(this.editor);
		controller.launch();
		return TPromise.as(true);
	}

}

function isInterestingEditorModel(editor:EditorCommon.ICommonCodeEditor): boolean {
421 422 423
	if (editor.getConfiguration().readOnly) {
		return false;
	}
424 425 426 427 428 429 430 431 432
	let model = editor.getModel();
	if (!model) {
		return false;
	}
	let url = model.getAssociatedResource().toString();
	return INTERESTING_FILE.test(url);
}

EditorBrowserRegistry.registerEditorContribution(DefineKeybindingController);
A
Alex Dima 已提交
433
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(DefineKeybindingAction, DefineKeybindingAction.ID, NLS_DEFINE_ACTION_LABEL, {
434 435 436
	context: ContextKey.EditorFocus,
	primary: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_K)
}));