defineKeybinding.ts 15.0 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
import {renderHtml} from 'vs/base/browser/htmlContentRenderer';
27

A
Alex Dima 已提交
28 29 30
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");
31 32
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.");
33 34

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

36 37 38 39 40 41 42 43 44
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;
45
	private _keybindingService:IKeybindingService;
46 47 48
	private _launchWidget: DefineKeybindingLauncherWidget;
	private _defineWidget: DefineKeybindingWidget;
	private _toDispose: IDisposable[];
49 50
	private _modelToDispose: IDisposable[];
	private _updateDecorations: RunOnceScheduler;
51 52 53 54 55 56

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

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

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

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

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

	public dispose(): void {
83
		this._modelToDispose = disposeAll(this._modelToDispose);
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
		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);
	}
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 178

	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 => {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
			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));
			}
196 197
			return {
				range: m.range,
198
				options: DefineKeybindingController._decorationOptions(msg, isError)
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

	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
			}
		}
	}
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
}

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) {
248
			extra += ' ('+keybindingService.getLabelFor(keybinding[0])+')';
249
		}
A
Alex Dima 已提交
250
		this._domNode.appendChild(document.createTextNode(NLS_LAUNCH_MESSAGE + extra));
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

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

290 291

class DefineKeybindingWidget implements EditorBrowser.IOverlayWidget {
292 293

	private static ID = 'editor.contrib.defineKeybindingWidget';
294 295
	private static WIDTH = 340;
	private static HEIGHT = 90;
296 297

	private _editor: EditorBrowser.ICodeEditor;
298
	private _keybindingService:IKeybindingService;
299 300 301 302 303 304

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

	private _messageNode: HTMLElement;
	private _inputNode: HTMLInputElement;
305
	private _outputNode: HTMLElement;
306 307 308

	private _lastKeybinding: Keybinding;
	private _onAccepted: (keybinding:string) => void;
309
	private _isVisible: boolean;
310

311
	constructor(editor:EditorBrowser.ICodeEditor, keybindingService:IKeybindingService, onAccepted:(keybinding:string) => void) {
312
		this._editor = editor;
313
		this._keybindingService = keybindingService;
314 315 316 317 318 319
		this._onAccepted = onAccepted;
		this._toDispose = [];
		this._lastKeybinding = null;

		this._domNode = document.createElement('div');
		this._domNode.className = 'defineKeybindingWidget';
320 321 322 323 324
		DomUtils.StyleMutator.setWidth(this._domNode, DefineKeybindingWidget.WIDTH);
		DomUtils.StyleMutator.setHeight(this._domNode, DefineKeybindingWidget.HEIGHT);

		this._domNode.style.display = 'none';
		this._isVisible = false;
325 326 327

		this._messageNode = document.createElement('div');
		this._messageNode.className = 'message';
A
Alex Dima 已提交
328
		this._messageNode.innerText = NLS_DEFINE_MESSAGE;
329 330 331 332 333 334
		this._domNode.appendChild(this._messageNode);

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

335 336 337 338
		this._outputNode = document.createElement('div');
		this._outputNode.className = 'output';
		this._domNode.appendChild(this._outputNode);

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
		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;

360 361
			this._inputNode.value = this._lastKeybinding.toUserSettingsLabel().toLowerCase();
			this._inputNode.title = 'keyCode: ' + keyEvent.browserEvent.keyCode;
362 363 364 365

			DomUtils.clearNode(this._outputNode);
			let htmlkb = this._keybindingService.getHTMLLabelFor(this._lastKeybinding);
			htmlkb.forEach((item) => this._outputNode.appendChild(renderHtml(item)));
366
		}));
367 368 369 370 371
		this._toDispose.push(this._editor.addListener2(EditorCommon.EventType.ConfigurationChanged, (e) => {
			if (this._isVisible) {
				this._layout();
			}
		}))
372 373 374

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

375
		this._editor.addOverlayWidget(this);
376 377 378
	}

	public dispose(): void {
379
		this._editor.removeOverlayWidget(this);
380 381 382 383 384 385 386 387 388 389 390
		this._toDispose = disposeAll(this._toDispose);
	}

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

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

391
	public getPosition(): EditorBrowser.IOverlayWidgetPosition {
392
		return {
393
			preference: null
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 421 422 423
	private _show(): void {
		if (this._isVisible) {
			return;
		}
		this._isVisible = true;
		this._layout();
		this._domNode.style.display = 'block';
	}

	private _hide(): void {
		if (!this._isVisible) {
			return;
		}
		this._isVisible = false;
		this._domNode.style.display = 'none';
	}

	private _layout(): void {
		let editorLayout = this._editor.getLayoutInfo();

		let top = Math.round((editorLayout.height - DefineKeybindingWidget.HEIGHT) / 2);
		DomUtils.StyleMutator.setTop(this._domNode, top);

		let left = Math.round((editorLayout.width - DefineKeybindingWidget.WIDTH) / 2);
		DomUtils.StyleMutator.setLeft(this._domNode, left);
	}

424
	public start(): void {
425
		this._editor.revealPositionInCenterIfOutsideViewport(this._editor.getPosition());
426

427
		this._show();
428 429

		this._lastKeybinding = null;
430
		this._inputNode.value = '';
431 432 433 434 435
		this._inputNode.focus();
	}

	private _stop(): void {
		this._editor.focus();
436
		this._hide();
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
	}
}

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 {
464 465 466
	if (editor.getConfiguration().readOnly) {
		return false;
	}
467 468 469 470 471 472 473 474 475
	let model = editor.getModel();
	if (!model) {
		return false;
	}
	let url = model.getAssociatedResource().toString();
	return INTERESTING_FILE.test(url);
}

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