blob: 12efd0035c286c9ac3bc02b65708f7da478cd589 [file] [log] [blame]
rgindafeaf3142012-01-31 15:14:20 -08001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
rgindacbbd7482012-06-13 15:06:16 -07005'use strict';
6
7lib.rtdep('hterm.Keyboard.KeyMap');
8
rgindafeaf3142012-01-31 15:14:20 -08009/**
10 * Keyboard handler.
11 *
12 * Consumes onKey* events and invokes onVTKeystroke on the associated
13 * hterm.Terminal object.
14 *
15 * See also: [XTERM] as referenced in vt.js.
16 *
17 * @param {hterm.Terminal} The Terminal object associated with this keyboard.
18 */
19hterm.Keyboard = function(terminal) {
20 // The parent vt interpreter.
21 this.terminal = terminal;
22
23 // The element we're currently capturing keyboard events for.
24 this.keyboardElement_ = null;
25
26 // The event handlers we are interested in, and their bound callbacks, saved
27 // so they can be uninstalled with removeEventListener, when required.
28 this.handlers_ = [
Andrew de los Reyes574e10e2013-04-04 09:31:57 -070029 ['blur', this.onBlur_.bind(this)],
Robert Ginda11390c52012-09-13 14:53:34 -070030 ['keydown', this.onKeyDown_.bind(this)],
Andrew de los Reyes574e10e2013-04-04 09:31:57 -070031 ['keypress', this.onKeyPress_.bind(this)],
32 ['keyup', this.onKeyUp_.bind(this)],
Robert Ginda11390c52012-09-13 14:53:34 -070033 ['textInput', this.onTextInput_.bind(this)]
rgindafeaf3142012-01-31 15:14:20 -080034 ];
35
36 /**
37 * The current key map.
38 */
rgindacbbd7482012-06-13 15:06:16 -070039 this.keyMap = new hterm.Keyboard.KeyMap(this);
rgindafeaf3142012-01-31 15:14:20 -080040
41 /**
rginda4bba5e12012-06-20 16:15:30 -070042 * If true, Shift-Insert will fall through to the browser as a paste.
43 * If false, the keystroke will be sent to the host.
44 */
Robert Ginda57f03b42012-09-13 11:02:48 -070045 this.shiftInsertPaste = true;
rginda4bba5e12012-06-20 16:15:30 -070046
47 /**
rgindafeaf3142012-01-31 15:14:20 -080048 * If true, home/end will control the terminal scrollbar and shift home/end
49 * will send the VT keycodes. If false then home/end sends VT codes and
50 * shift home/end scrolls.
51 */
Robert Ginda57f03b42012-09-13 11:02:48 -070052 this.homeKeysScroll = false;
rgindafeaf3142012-01-31 15:14:20 -080053
54 /**
55 * Same as above, except for page up/page down.
56 */
Robert Ginda57f03b42012-09-13 11:02:48 -070057 this.pageKeysScroll = false;
rgindafeaf3142012-01-31 15:14:20 -080058
59 /**
60 * Enable/disable application keypad.
61 *
62 * This changes the way numeric keys are sent from the keyboard.
63 */
64 this.applicationKeypad = false;
65
66 /**
67 * Enable/disable the application cursor mode.
68 *
69 * This changes the way cursor keys are sent from the keyboard.
70 */
71 this.applicationCursor = false;
72
73 /**
74 * If true, the backspace should send BS ('\x08', aka ^H). Otherwise
75 * the backspace key should send '\x7f'.
76 */
Robert Ginda57f03b42012-09-13 11:02:48 -070077 this.backspaceSendsBackspace = false;
rgindafeaf3142012-01-31 15:14:20 -080078
79 /**
80 * Set whether the meta key sends a leading escape or not.
81 */
Robert Ginda57f03b42012-09-13 11:02:48 -070082 this.metaSendsEscape = true;
rginda30f20f62012-04-05 16:36:19 -070083
84 /**
rginda39bdf6f2012-04-10 16:50:55 -070085 * Controls how the alt key is handled.
86 *
87 * escape....... Send an ESC prefix.
88 * 8-bit........ Add 128 to the unshifted character as in xterm.
89 * browser-key.. Wait for the keypress event and see what the browser says.
90 * (This won't work well on platforms where the browser
91 * performs a default action for some alt sequences.)
rginda30f20f62012-04-05 16:36:19 -070092 *
93 * This setting only matters when alt is distinct from meta (altIsMeta is
94 * false.)
95 */
Robert Ginda57f03b42012-09-13 11:02:48 -070096 this.altSendsWhat = 'escape';
rginda42ad71d2012-02-16 14:06:28 -080097
98 /**
99 * Set whether the alt key acts as a meta key, instead of producing 8-bit
100 * characters.
rginda30f20f62012-04-05 16:36:19 -0700101 *
102 * True to enable, false to disable, null to autodetect based on platform.
rginda42ad71d2012-02-16 14:06:28 -0800103 */
Robert Ginda57f03b42012-09-13 11:02:48 -0700104 this.altIsMeta = false;
Andrew de los Reyes574e10e2013-04-04 09:31:57 -0700105
106 /**
107 * If true, tries to detect DEL key events that are from alt-backspace on
108 * Chrome OS vs from a true DEL key press.
109 *
110 * Background: At the time of writing, on Chrome OS, alt-backspace is mapped
111 * to DEL. Some users may be happy with this, but others may be frustrated
112 * that it's impossible to do meta-backspace. If the user enables this pref,
113 * we use a trick to tell a true DEL keypress from alt-backspace: on
114 * alt-backspace, we will see the alt key go down, then get a DEL keystroke
115 * that indicates that alt is not pressed. See http://crbug.com/174410 .
116 */
117 this.altBackspaceIsMetaBackspace = false;
118
119 /**
120 * Used to keep track of the current alt-key state, which is necessary for
121 * the altBackspaceIsMetaBackspace preference above.
122 */
123 this.altIsPressed = false;
Andrew de los Reyes6af23ae2013-04-04 14:17:50 -0700124
125 /**
126 * If true, Chrome OS media keys will be mapped to their F-key equivalent.
127 * E.g. "Back" will be mapped to F1. If false, Chrome will handle the keys.
128 */
129 this.mediaKeysAreFKeys = false;
rgindafeaf3142012-01-31 15:14:20 -0800130};
131
132/**
rgindafeaf3142012-01-31 15:14:20 -0800133 * Special handling for keyCodes in a keyboard layout.
134 */
135hterm.Keyboard.KeyActions = {
136 /**
137 * Call preventDefault and stopPropagation for this key event and nothing
138 * else.
139 */
140 CANCEL: new String('CANCEL'),
141
142 /**
143 * This performs the default terminal action for the key. If used in the
144 * 'normal' action and the the keystroke represents a printable key, the
145 * character will be sent to the host. If used in one of the modifier
146 * actions, the terminal will perform the normal action after (possibly)
147 * altering it.
148 *
149 * - If the normal sequence starts with CSI, the sequence will be adjusted
150 * to include the modifier parameter as described in [XTERM] in the final
151 * table of the "PC-Style Function Keys" section.
152 *
153 * - If the control key is down and the key represents a printable character,
154 * and the uppercase version of the unshifted keycap is between
155 * 64 (ASCII '@') and 95 (ASCII '_'), then the uppercase version of the
156 * unshifted keycap minus 64 is sent. This makes '^@' send '\x00' and
157 * '^_' send '\x1f'. (Note that one higher that 0x1f is 0x20, which is
158 * the first printable ASCII value.)
159 *
160 * - If the alt key is down and the key represents a printable character then
161 * the value of the character is shifted up by 128.
162 *
163 * - If meta is down and configured to send an escape, '\x1b' will be sent
164 * before the normal action is performed.
165 */
166 DEFAULT: new String('DEFAULT'),
167
168 /**
169 * Causes the terminal to opt out of handling the key event, instead letting
170 * the browser deal with it.
171 */
172 PASS: new String('PASS'),
173
174 /**
175 * Insert the first or second character of the keyCap, based on e.shiftKey.
176 * The key will be handled in onKeyDown, and e.preventDefault() will be
177 * called.
178 *
179 * It is useful for a modified key action, where it essentially strips the
180 * modifier while preventing the browser from reacting to the key.
181 */
182 STRIP: new String('STRIP')
183};
184
185/**
186 * Capture keyboard events sent to the associated element.
187 *
188 * This enables the keyboard. Captured events are consumed by this class
189 * and will not perform their default action or bubble to other elements.
190 *
191 * Passing a null element will uninstall the keyboard handlers.
192 *
193 * @param {HTMLElement} element The element whose events should be captured, or
194 * null to disable the keyboard.
195 */
196hterm.Keyboard.prototype.installKeyboard = function(element) {
197 if (element == this.keyboardElement_)
198 return;
199
200 if (element && this.keyboardElement_)
201 this.installKeyboard(null);
202
203 for (var i = 0; i < this.handlers_.length; i++) {
204 var handler = this.handlers_[i];
205 if (element) {
206 element.addEventListener(handler[0], handler[1]);
207 } else {
208 this.keyboardElement_.removeEventListener(handler[0], handler[1]);
209 }
210 }
211
212 this.keyboardElement_ = element;
213};
214
215/**
216 * Disable keyboard event capture.
217 *
218 * This will allow the browser to process key events normally.
219 */
220hterm.Keyboard.prototype.uninstallKeyboard = function() {
221 this.installKeyboard(null);
222};
223
224/**
Robert Ginda11390c52012-09-13 14:53:34 -0700225 * Handle onTextInput events.
226 *
227 * We're not actually supposed to get these, but we do on the Mac in the case
228 * where a third party app sends synthetic keystrokes to Chrome.
229 */
230hterm.Keyboard.prototype.onTextInput_ = function(e) {
231 if (!e.data)
232 return;
233
234 e.data.split('').forEach(this.terminal.onVTKeystroke.bind(this.terminal));
235};
236
237/**
rgindafeaf3142012-01-31 15:14:20 -0800238 * Handle onKeyPress events.
239 */
240hterm.Keyboard.prototype.onKeyPress_ = function(e) {
rginda39bdf6f2012-04-10 16:50:55 -0700241 var code;
242
243 if (e.altKey && this.altSendsWhat == 'browser-key' && e.charCode == 0) {
244 // If we got here because we were expecting the browser to handle an
245 // alt sequence but it didn't do it, then we might be on an OS without
246 // an enabled IME system. In that case we fall back to xterm-like
247 // behavior.
248 //
249 // This happens here only as a fallback. Typically these platforms should
250 // set altSendsWhat to either 'escape' or '8-bit'.
251 var ch = String.fromCharCode(e.keyCode);
252 if (!e.shiftKey)
253 ch = ch.toLowerCase();
254 code = ch.charCodeAt(0) + 128;
255
256 } else if (e.charCode >= 32) {
257 ch = e.charCode;
258 }
259
260 if (ch) {
261 var str = this.terminal.vt.encodeUTF8(String.fromCharCode(ch));
262 this.terminal.onVTKeystroke(str);
263 }
rgindafeaf3142012-01-31 15:14:20 -0800264
265 e.preventDefault();
266 e.stopPropagation();
267};
268
Andrew de los Reyes574e10e2013-04-04 09:31:57 -0700269hterm.Keyboard.prototype.onBlur_ = function(e) {
270 this.altIsPressed = false;
271};
272
273hterm.Keyboard.prototype.onKeyUp_ = function(e) {
274 if (e.keyCode == 18)
275 this.altIsPressed = false;
276};
277
rgindafeaf3142012-01-31 15:14:20 -0800278/**
279 * Handle onKeyDown events.
280 */
281hterm.Keyboard.prototype.onKeyDown_ = function(e) {
Andrew de los Reyes574e10e2013-04-04 09:31:57 -0700282 if (e.keyCode == 18)
283 this.altIsPressed = true;
284
rgindafeaf3142012-01-31 15:14:20 -0800285 var keyDef = this.keyMap.keyDefs[e.keyCode];
286 if (!keyDef) {
287 console.warn('No definition for keyCode: ' + e.keyCode);
288 return;
289 }
290
Robert Ginda21de3762012-09-20 16:38:18 -0700291 // The type of action we're going to use.
292 var resolvedActionType = null;
293
rgindafeaf3142012-01-31 15:14:20 -0800294 var self = this;
295 function getAction(name) {
296 // Get the key action for the given action name. If the action is a
297 // function, dispatch it. If the action defers to the normal action,
298 // resolve that instead.
299
Robert Ginda21de3762012-09-20 16:38:18 -0700300 resolvedActionType = name;
301
rgindafeaf3142012-01-31 15:14:20 -0800302 var action = keyDef[name];
303 if (typeof action == 'function')
304 action = action.apply(self.keyMap, [e, keyDef]);
305
306 if (action === DEFAULT && name != 'normal')
307 action = getAction('normal');
308
309 return action;
310 }
311
312 // Note that we use the triple-equals ('===') operator to test equality for
313 // these constants, in order to distingush usage of the constant from usage
314 // of a literal string that happens to contain the same bytes.
315 var CANCEL = hterm.Keyboard.KeyActions.CANCEL;
316 var DEFAULT = hterm.Keyboard.KeyActions.DEFAULT;
317 var PASS = hterm.Keyboard.KeyActions.PASS;
318 var STRIP = hterm.Keyboard.KeyActions.STRIP;
319
320 var shift = e.shiftKey;
321 var control = e.ctrlKey;
rginda42ad71d2012-02-16 14:06:28 -0800322 var alt = this.altIsMeta ? false : e.altKey;
323 var meta = this.altIsMeta ? (e.altKey || e.metaKey) : e.metaKey;
rgindafeaf3142012-01-31 15:14:20 -0800324
325 var action;
326
327 if (control) {
328 action = getAction('control');
329 } else if (alt) {
330 action = getAction('alt');
rginda42ad71d2012-02-16 14:06:28 -0800331 } else if (meta) {
332 action = getAction('meta');
rgindafeaf3142012-01-31 15:14:20 -0800333 } else {
334 action = getAction('normal');
335 }
336
rginda39bdf6f2012-04-10 16:50:55 -0700337 if (alt && this.altSendsWhat == 'browser-key' && action == DEFAULT) {
338 // When altSendsWhat is 'browser-key', we wait for the keypress event.
339 // In keypress, the browser should have set the event.charCode to the
340 // appropriate character.
341 // TODO(rginda): Character compositions will need some black magic.
342 action = PASS;
343 }
344
rgindafeaf3142012-01-31 15:14:20 -0800345 if (action === PASS || (action === DEFAULT && !(control || alt || meta))) {
346 // If this key is supposed to be handled by the browser, or it is an
347 // unmodified key with the default action, then exit this event handler.
348 // If it's an unmodified key, it'll be handled in onKeyPress where we
349 // can tell for sure which ASCII code to insert.
350 //
351 // This block needs to come before the STRIP test, otherwise we'll strip
352 // the modifier and think it's ok to let the browser handle the keypress.
353 // The browser won't know we're trying to ignore the modifiers and might
354 // perform some default action.
355 return;
356 }
357
358 if (action === STRIP) {
359 alt = control = false;
360 action = keyDef.normal;
361 if (typeof action == 'function')
362 action = action.apply(this.keyMap, [e, keyDef]);
363
364 if (action == DEFAULT && keyDef.keyCap.length == 2)
365 action = keyDef.keyCap.substr((e.shiftKey ? 1 : 0), 1);
366 }
367
368 e.preventDefault();
369 e.stopPropagation();
370
371 if (action === CANCEL)
372 return;
373
rginda42ad71d2012-02-16 14:06:28 -0800374 if (action !== DEFAULT && typeof action != 'string') {
375 console.warn('Invalid action: ' + JSON.stringify(action));
376 return;
377 }
378
Robert Gindacc6d3a72012-09-24 14:06:08 -0700379 // Strip the modifier that is associated with the action, since we assume that
380 // modifier has already been accounted for in the action.
381 if (resolvedActionType == 'control') {
382 control = false;
383 } else if (resolvedActionType == 'alt') {
384 alt = false;
385 } else if (resolvedActionType == 'meta') {
386 meta = false;
387 }
388
389 if (action.substr(0, 2) == '\x1b[' && (alt || control || shift)) {
390 // The action is an escape sequence that and it was triggered in the
391 // presence of a keyboard modifier, we may need to alter the action to
392 // include the modifier before sending it.
rginda42ad71d2012-02-16 14:06:28 -0800393
rgindafeaf3142012-01-31 15:14:20 -0800394 var mod;
395
396 if (shift && !(alt || control)) {
397 mod = ';2';
398 } else if (alt && !(shift || control)) {
399 mod = ';3';
400 } else if (shift && alt && !control) {
401 mod = ';4';
402 } else if (control && !(shift || alt)) {
403 mod = ';5';
404 } else if (shift && control && !alt) {
405 mod = ';6';
406 } else if (alt && control && !shift) {
407 mod = ';7';
408 } else if (shift && alt && control) {
409 mod = ';8';
410 }
411
412 if (action.length == 3) {
413 // Some of the CSI sequences have zero parameters unless modified.
414 action = '\x1b[1' + mod + action.substr(2, 1);
415 } else {
416 // Others always have at least one parameter.
Robert Ginda21de3762012-09-20 16:38:18 -0700417 action = action.substr(0, action.length - 1) + mod +
rgindafeaf3142012-01-31 15:14:20 -0800418 action.substr(action.length - 1);
419 }
Robert Ginda21de3762012-09-20 16:38:18 -0700420
421 } else {
422 // Just send it as-is.
423
424 if (action === DEFAULT) {
425 if (control) {
426 var unshifted = keyDef.keyCap.substr(0, 1);
427 var code = unshifted.charCodeAt(0);
428 if (code >= 64 && code <= 95) {
429 action = String.fromCharCode(code - 64);
430 }
431 } else if (alt && this.altSendsWhat == '8-bit') {
432 var ch = keyDef.keyCap.substr((e.shiftKey ? 1 : 0), 1);
433 var code = ch.charCodeAt(0) + 128;
434 action = this.terminal.vt.encodeUTF8(String.fromCharCode(code));
435 } else {
436 action = keyDef.keyCap.substr((e.shiftKey ? 1 : 0), 1);
437 }
438 }
439
440 // We respect alt/metaSendsEscape even if the keymap action was a literal
441 // string. Otherwise, every overridden alt/meta action would have to
442 // check alt/metaSendsEscape.
Robert Gindacc6d3a72012-09-24 14:06:08 -0700443 if ((alt && this.altSendsWhat == 'escape') ||
444 (meta && this.metaSendsEscape)) {
Robert Ginda21de3762012-09-20 16:38:18 -0700445 action = '\x1b' + action;
446 }
rgindafeaf3142012-01-31 15:14:20 -0800447 }
448
449 this.terminal.onVTKeystroke(action);
450};