keybindingServiceImpl.ts 12.3 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7 8
import 'vs/css!./keybindings';

E
Erich Gamma 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import Severity from 'vs/base/common/severity';
import {TPromise} from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import DOM = require('vs/base/browser/dom');
import Keyboard = require('vs/base/browser/keyboardEvent');
import {KeybindingsRegistry} from 'vs/platform/keybinding/common/keybindingsRegistry';
import {KeybindingsUtils} from 'vs/platform/keybinding/common/keybindingsUtils';
import strings = require('vs/base/common/strings');
import Platform = require('vs/base/common/platform');
import {IKeybindingService, IKeybindingScopeLocation, ICommandHandler, IKeybindingItem, IKeybindings, IKeybindingContextRule, IUserFriendlyKeybinding, IKeybindingContextKey} from 'vs/platform/keybinding/common/keybindingService';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IMessageService} from 'vs/platform/message/common/message';
import {IResolveResult, CommonKeybindingResolver} from 'vs/platform/keybinding/common/commonKeybindingResolver';
import {Keybinding, KeyCode} from 'vs/base/common/keyCodes';
24
import {IHTMLContentElement} from 'vs/base/common/htmlContent';
E
Erich Gamma 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 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

var KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';

export class KeybindingContext {
	private _parent: KeybindingContext;
	private _value: any;
	private _id: number;

	constructor(id: number, parent: KeybindingContext) {
		this._id = id;
		this._parent = parent;
		this._value = Object.create(null);
		this._value['_contextId'] = id;
	}

	public setValue(key: string, value: any): void {
//		console.log('SET ' + key + ' = ' + value + ' ON ' + this._id);
		this._value[key] = value;
	}

	public removeValue(key: string): void {
//		console.log('REMOVE ' + key + ' FROM ' + this._id);
		delete this._value[key];
	}

	public getValue(): any {
		var r = this._parent ? this._parent.getValue() : Object.create(null);
		for (var key in this._value) {
			r[key] = this._value[key];
		}
		return r;
	}
}

class KeybindingContextKey<T> implements IKeybindingContextKey<T> {

	private _parent: AbstractKeybindingService;
	private _key: string;
	private _defaultValue: T;

	constructor(parent: AbstractKeybindingService, key: string, defaultValue: T) {
		this._parent = parent;
		this._key = key;
		this._defaultValue = defaultValue;
		if (typeof this._defaultValue !== 'undefined') {
			this._parent.setContext(this._key, this._defaultValue);
		}
	}

	public set(value: T): void {
		this._parent.setContext(this._key, value);
	}

	public reset(): void {
		if (typeof this._defaultValue === 'undefined') {
			this._parent.removeContext(this._key);
		} else {
			this._parent.setContext(this._key, this._defaultValue);
		}
	}

}

88
export abstract class AbstractKeybindingService {
E
Erich Gamma 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
	public serviceId = IKeybindingService;
	protected _myContextId: number;
	protected _instantiationService: IInstantiationService;
	protected _messageService: IMessageService;

	constructor(myContextId: number) {
		this._myContextId = myContextId;
		this._instantiationService = null;
		this._messageService = null;
	}

	public setMessageService(messageService: IMessageService): void {
		this._messageService = messageService;
	}

	public createKey<T>(key: string, defaultValue: T): IKeybindingContextKey<T> {
		return new KeybindingContextKey(this, key, defaultValue);
	}

	public setInstantiationService(instantiationService: IInstantiationService): void {
		this._instantiationService = instantiationService;
	}

	public createScoped(domNode: IKeybindingScopeLocation): IKeybindingService {
		return new ScopedKeybindingService(this, domNode);
	}

	public setContext(key: string, value: any): void {
		this.getContext(this._myContextId).setValue(key, value);
	}

	public removeContext(key: string): void {
		this.getContext(this._myContextId).removeValue(key);
	}

124 125 126 127 128 129 130 131 132
	public abstract getLabelFor(keybinding:Keybinding): string;
	public abstract getHTMLLabelFor(keybinding:Keybinding): IHTMLContentElement[];
	public abstract customKeybindingsCount(): number;
	public abstract getContext(contextId: number): KeybindingContext;
	public abstract createChildContext(parentContextId?: number): number;
	public abstract disposeContext(contextId: number): void;
	public abstract getDefaultKeybindings(): string;
	public abstract lookupKeybindings(commandId: string): Keybinding[];
	public abstract executeCommand(commandId: string, args:any): TPromise<any>;
E
Erich Gamma 已提交
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
}

export class KeybindingService extends AbstractKeybindingService implements IKeybindingService {

	private _lastContextId: number;
	private _contexts: {
		[contextId:string]: KeybindingContext;
	};

	protected _domNode: HTMLElement;
	private _toDispose: lifecycle.IDisposable;
	private _resolver: KeybindingResolver;
	private _currentChord: number;
	private _currentChordStatusMessage: lifecycle.IDisposable;

	constructor(domNode: HTMLElement) {
		this._lastContextId = -1;
		super((++this._lastContextId));
		this._domNode = domNode;
		this._contexts = Object.create(null);
		this._contexts[String(this._myContextId)] = new KeybindingContext(this._myContextId, null);
		this._toDispose = DOM.addDisposableListener(this._domNode, DOM.EventType.KEY_DOWN, (e:KeyboardEvent) => {
			var keyEvent = new Keyboard.StandardKeyboardEvent(e);
			this._dispatch(keyEvent);
		});

		this._createOrUpdateResolver(true);
		this._currentChord = 0;
		this._currentChordStatusMessage = null;
	}

	public dispose(): void {
		this._toDispose.dispose();
		this._toDispose = null;
	}

169 170 171 172
	public getLabelFor(keybinding:Keybinding): string {
		return keybinding._toUSLabel();
	}

173 174 175 176
	public getHTMLLabelFor(keybinding:Keybinding): IHTMLContentElement[] {
		return keybinding._toUSHTMLLabel();
	}

E
Erich Gamma 已提交
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
	protected updateResolver(): void {
		this._createOrUpdateResolver(false);
	}

	private _createOrUpdateResolver(isFirstTime:boolean): void {
		this._resolver = new KeybindingResolver(KeybindingsRegistry.getDefaultKeybindings(), this._getExtraKeybindings(isFirstTime));
	}

	protected _getExtraKeybindings(isFirstTime:boolean): IKeybindingItem[] {
		return [];
	}

	public getDefaultKeybindings(): string {
		return this._resolver.getDefaultKeybindings() + '\n\n' + this._getAllCommandsAsComment();
	}

	public customKeybindingsCount(): number {
		return 0;
	}

	public lookupKeybindings(commandId: string): Keybinding[] {
		return this._resolver.lookupKeybinding(commandId);
	}

	private _getAllCommandsAsComment(): string {
		var boundCommands = this._resolver.getDefaultBoundCommands();
203
		var unboundCommands = Object.keys(KeybindingsRegistry.getCommands()).filter(commandId => commandId[0] !== '_' && !boundCommands[commandId]);
E
Erich Gamma 已提交
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
		var pretty = unboundCommands.join('\n// - ');

		return '// ' + nls.localize('unboundCommands', "Here are other available commands: ") + '\n// - ' + pretty;
	}

	protected _getCommandHandler(commandId:string): ICommandHandler {
		return KeybindingsRegistry.getCommands()[commandId];
	}

	private _dispatch(e: DOM.IKeyboardEvent): void {
		var isModifierKey = (e.keyCode === KeyCode.Ctrl || e.keyCode === KeyCode.Shift || e.keyCode === KeyCode.Alt || e.keyCode === KeyCode.Meta);
		if (isModifierKey) {
			return;
		}

		var contextId = this._findContextAttr(e.target);
		var context = this.getContext(contextId);
		var contextValue = context.getValue();
//		console.log(JSON.stringify(contextValue, null, '\t'));

		var resolveResult = this._resolver.resolveKeyboardEvent(contextValue, this._currentChord, e);

		if (resolveResult && resolveResult.enterChord) {
			e.preventDefault();
			this._currentChord = resolveResult.enterChord;
			if (this._messageService) {
230
				let firstPartLabel = this.getLabelFor(new Keybinding(this._currentChord));
E
Erich Gamma 已提交
231 232 233 234 235 236 237
				this._currentChordStatusMessage = this._messageService.setStatusMessage(nls.localize('first.chord', "({0}) was pressed. Waiting for second key of chord...", firstPartLabel));
			}
			return;
		}

		if (this._messageService && this._currentChord) {
			if (!resolveResult || !resolveResult.commandId) {
238 239
				let firstPartLabel = this.getLabelFor(new Keybinding(this._currentChord));
				let chordPartLabel = this.getLabelFor(new Keybinding(e.asKeybinding()));
E
Erich Gamma 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
				this._messageService.setStatusMessage(nls.localize('missing.chord', "The key combination ({0}, {1}) is not a command.", firstPartLabel, chordPartLabel), 10 * 1000 /* 10s */);
				e.preventDefault();
			}
		}
		if (this._currentChordStatusMessage) {
			this._currentChordStatusMessage.dispose();
			this._currentChordStatusMessage = null;
		}
		this._currentChord = 0;

		if (resolveResult && resolveResult.commandId) {
			if (!/^\^/.test(resolveResult.commandId)) {
				e.preventDefault();
			}
			var commandId = resolveResult.commandId.replace(/^\^/, '');
			this._invokeHandler(commandId, { context: contextValue }).done(undefined, err => {
				this._messageService.show(Severity.Warning, err);
			});
		}
	}

	protected _invokeHandler(commandId: string, args: any): TPromise<any> {

		let handler = this._getCommandHandler(commandId);
		if (!handler) {
			return TPromise.wrapError(new Error(`No handler found for the command: '${commandId}'`));
		}
J
Johannes Rieken 已提交
267 268 269 270 271 272
		try {
			let result = this._instantiationService.invokeFunction(handler, args);
			return TPromise.as(result);
		} catch (err) {
			return TPromise.wrapError(err);
		}
E
Erich Gamma 已提交
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
	}

	private _findContextAttr(domNode: HTMLElement): number {
		while (domNode) {
			if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
				return parseInt(domNode.getAttribute(KEYBINDING_CONTEXT_ATTR), 10);
			}
			domNode = domNode.parentElement;
		}
		return this._myContextId;
	}

	public getContext(contextId: number): KeybindingContext {
		return this._contexts[String(contextId)];
	}

	public createChildContext(parentContextId: number = this._myContextId): number {
		var id = (++this._lastContextId);
		this._contexts[String(id)] = new KeybindingContext(id, this.getContext(parentContextId));
		return id;
	}

	public disposeContext(contextId:number): void {
		delete this._contexts[String(contextId)];
	}

299
	public executeCommand(commandId: string, args:any = {}): TPromise<any> {
E
Erich Gamma 已提交
300 301 302 303 304 305 306 307
		if (!args.context) {
			var contextId = this._findContextAttr(<HTMLElement>document.activeElement);
			var context = this.getContext(contextId);
			var contextValue = context.getValue();

			args.context = contextValue;
		}

308
		return this._invokeHandler(commandId, args);
E
Erich Gamma 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	}
}

class ScopedKeybindingService extends AbstractKeybindingService {

	private _parent: AbstractKeybindingService;
	private _domNode: IKeybindingScopeLocation;

	constructor(parent: AbstractKeybindingService, domNode:IKeybindingScopeLocation) {
		this._parent = parent;
		this._domNode = domNode;
		super(this._parent.createChildContext());
		this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
	}

	public dispose(): void {
		this._parent.disposeContext(this._myContextId);
		this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
	}

329 330 331 332
	public getLabelFor(keybinding:Keybinding): string {
		return this._parent.getLabelFor(keybinding);
	}

333 334 335 336
	public getHTMLLabelFor(keybinding:Keybinding): IHTMLContentElement[] {
		return this._parent.getHTMLLabelFor(keybinding);
	}

E
Erich Gamma 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
	public getDefaultKeybindings(): string {
		return this._parent.getDefaultKeybindings();
	}

	public customKeybindingsCount(): number {
		return this._parent.customKeybindingsCount();
	}

	public lookupKeybindings(commandId: string): Keybinding[]{
		return this._parent.lookupKeybindings(commandId);
	}

	public getContext(contextId: number): KeybindingContext {
		return this._parent.getContext(contextId);
	}

	public createChildContext(parentContextId: number = this._myContextId): number {
		return this._parent.createChildContext(parentContextId);
	}

	public disposeContext(contextId:number): void {
		this._parent.disposeContext(contextId);
	}

361 362
	public executeCommand(commandId: string, args:any): TPromise<any> {
		return this._parent.executeCommand(commandId, args);
E
Erich Gamma 已提交
363 364 365 366 367 368 369 370
	}
}

export class KeybindingResolver extends CommonKeybindingResolver {
	public resolveKeyboardEvent(context: any, currentChord: number, key: DOM.IKeyboardEvent): IResolveResult {
		return this.resolve(context, currentChord, key.asKeybinding());
	}
}