142d7ac7fc691748f9d12d8ebd6c25ed8964f40b
[guacamole-common-js.git] / src / main / resources / keyboard.js
1
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
5  * The contents of this file are subject to the Mozilla Public License Version
6  * 1.1 (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  * http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS" basis,
11  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12  * for the specific language governing rights and limitations under the
13  * License.
14  *
15  * The Original Code is guacamole-common-js.
16  *
17  * The Initial Developer of the Original Code is
18  * Michael Jumper.
19  * Portions created by the Initial Developer are Copyright (C) 2010
20  * the Initial Developer. All Rights Reserved.
21  *
22  * Contributor(s):
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 // Guacamole namespace
39 var Guacamole = Guacamole || {};
40
41 /**
42  * Provides cross-browser and cross-keyboard keyboard for a specific element.
43  * Browser and keyboard layout variation is abstracted away, providing events
44  * which represent keys as their corresponding X11 keysym.
45  * 
46  * @constructor
47  * @param {Element} element The Element to use to provide keyboard events.
48  */
49 Guacamole.Keyboard = function(element) {
50
51     /**
52      * Reference to this Guacamole.Keyboard.
53      * @private
54      */
55     var guac_keyboard = this;
56
57     /**
58      * Fired whenever the user presses a key with the element associated
59      * with this Guacamole.Keyboard in focus.
60      * 
61      * @event
62      * @param {Number} keysym The keysym of the key being pressed.
63      * @returns {Boolean} true if the originating event of this keypress should
64      *                    be allowed through to the browser, false or undefined
65      *                    otherwise.
66      */
67     this.onkeydown = null;
68
69     /**
70      * Fired whenever the user releases a key with the element associated
71      * with this Guacamole.Keyboard in focus.
72      * 
73      * @event
74      * @param {Number} keysym The keysym of the key being released.
75      * @returns {Boolean} true if the originating event of this key release 
76      *                    should be allowed through to the browser, false or
77      *                    undefined otherwise.
78      */
79     this.onkeyup = null;
80
81     /**
82      * Map of known JavaScript keycodes which do not map to typable characters
83      * to their unshifted X11 keysym equivalents.
84      * @private
85      */
86     var unshiftedKeySym = {
87         8:   0xFF08, // backspace
88         9:   0xFF09, // tab
89         13:  0xFF0D, // enter
90         16:  0xFFE1, // shift
91         17:  0xFFE3, // ctrl
92         18:  0xFFE9, // alt
93         19:  0xFF13, // pause/break
94         20:  0xFFE5, // caps lock
95         27:  0xFF1B, // escape
96         33:  0xFF55, // page up
97         34:  0xFF56, // page down
98         35:  0xFF57, // end
99         36:  0xFF50, // home
100         37:  0xFF51, // left arrow
101         38:  0xFF52, // up arrow
102         39:  0xFF53, // right arrow
103         40:  0xFF54, // down arrow
104         45:  0xFF63, // insert
105         46:  0xFFFF, // delete
106         91:  0xFFEB, // left window key (super_l)
107         92:  0xFF67, // right window key (menu key?)
108         93:  null,   // select key
109         112: 0xFFBE, // f1
110         113: 0xFFBF, // f2
111         114: 0xFFC0, // f3
112         115: 0xFFC1, // f4
113         116: 0xFFC2, // f5
114         117: 0xFFC3, // f6
115         118: 0xFFC4, // f7
116         119: 0xFFC5, // f8
117         120: 0xFFC6, // f9
118         121: 0xFFC7, // f10
119         122: 0xFFC8, // f11
120         123: 0xFFC9, // f12
121         144: 0xFF7F, // num lock
122         145: 0xFF14  // scroll lock
123     };
124
125     /**
126      * Map of known JavaScript keyidentifiers which do not map to typable
127      * characters to their unshifted X11 keysym equivalents.
128      * @private
129      */
130     var keyidentifier_keysym = {
131         "AllCandidates": 0xFF3D,
132         "Alphanumeric": 0xFF30,
133         "Alt": 0xFFE9,
134         "Attn": 0xFD0E,
135         "AltGraph": 0xFFEA,
136         "CapsLock": 0xFFE5,
137         "Clear": 0xFF0B,
138         "Convert": 0xFF21,
139         "Copy": 0xFD15,
140         "Crsel": 0xFD1C,
141         "CodeInput": 0xFF37,
142         "Control": 0xFFE3,
143         "Down": 0xFF54,
144         "End": 0xFF57,
145         "Enter": 0xFF0D,
146         "EraseEof": 0xFD06,
147         "Execute": 0xFF62,
148         "Exsel": 0xFD1D,
149         "F1": 0xFFBE,
150         "F2": 0xFFBF,
151         "F3": 0xFFC0,
152         "F4": 0xFFC1,
153         "F5": 0xFFC2,
154         "F6": 0xFFC3,
155         "F7": 0xFFC4,
156         "F8": 0xFFC5,
157         "F9": 0xFFC6,
158         "F10": 0xFFC7,
159         "F11": 0xFFC8,
160         "F12": 0xFFC9,
161         "F13": 0xFFCA,
162         "F14": 0xFFCB,
163         "F15": 0xFFCC,
164         "F16": 0xFFCD,
165         "F17": 0xFFCE,
166         "F18": 0xFFCF,
167         "F19": 0xFFD0,
168         "F20": 0xFFD1,
169         "F21": 0xFFD2,
170         "F22": 0xFFD3,
171         "F23": 0xFFD4,
172         "F24": 0xFFD5,
173         "Find": 0xFF68,
174         "FullWidth": null,
175         "HalfWidth": null,
176         "HangulMode": 0xFF31,
177         "HanjaMode": 0xFF34,
178         "Help": 0xFF6A,
179         "Hiragana": 0xFF25,
180         "Home": 0xFF50,
181         "Insert": 0xFF63,
182         "JapaneseHiragana": 0xFF25,
183         "JapaneseKatakana": 0xFF26,
184         "JapaneseRomaji": 0xFF24,
185         "JunjaMode": 0xFF38,
186         "KanaMode": 0xFF2D,
187         "KanjiMode": 0xFF21,
188         "Katakana": 0xFF26,
189         "Left": 0xFF51,
190         "Meta": 0xFFE7,
191         "NumLock": 0xFF7F,
192         "PageDown": 0xFF55,
193         "PageUp": 0xFF56,
194         "Pause": 0xFF13,
195         "PreviousCandidate": 0xFF3E,
196         "PrintScreen": 0xFD1D,
197         "Right": 0xFF53,
198         "RomanCharacters": null,
199         "Scroll": 0xFF14,
200         "Select": 0xFF60,
201         "Shift": 0xFFE1,
202         "Up": 0xFF52,
203         "Undo": 0xFF65,
204         "Win": 0xFFEB
205     };
206
207     /**
208      * Map of known JavaScript keycodes which do not map to typable characters
209      * to their shifted X11 keysym equivalents. Keycodes must only be listed
210      * here if their shifted X11 keysym equivalents differ from their unshifted
211      * equivalents.
212      * @private
213      */
214     var shiftedKeySym = {
215         18:  0xFFE7  // alt
216     };
217
218     /**
219      * All modifiers and their states.
220      */
221     this.modifiers = {
222         
223         /**
224          * Whether shift is currently pressed.
225          */
226         "shift": false,
227         
228         /**
229          * Whether ctrl is currently pressed.
230          */
231         "ctrl" : false,
232         
233         /**
234          * Whether alt is currently pressed.
235          */
236         "alt"  : false
237
238     };
239
240     /**
241      * The state of every key, indexed by keysym. If a particular key is
242      * pressed, the value of pressed for that keysym will be true. If a key
243      * is not currently pressed, the value for that keysym may be false or
244      * undefined.
245      */
246     this.pressed = [];
247
248     var keydownChar = new Array();
249
250     // ID of routine repeating keystrokes. -1 = not repeating.
251     var repeatKeyTimeoutId = -1;
252     var repeatKeyIntervalId = -1;
253
254     // Starts repeating keystrokes
255     function startRepeat(keySym) {
256         repeatKeyIntervalId = setInterval(function() {
257             sendKeyReleased(keySym);
258             sendKeyPressed(keySym);
259         }, 50);
260     }
261
262     // Stops repeating keystrokes
263     function stopRepeat() {
264         if (repeatKeyTimeoutId != -1) clearInterval(repeatKeyTimeoutId);
265         if (repeatKeyIntervalId != -1) clearInterval(repeatKeyIntervalId);
266     }
267
268
269     function getKeySymFromKeyIdentifier(shifted, keyIdentifier) {
270
271         var unicodePrefixLocation = keyIdentifier.indexOf("U+");
272         if (unicodePrefixLocation >= 0) {
273
274             var hex = keyIdentifier.substring(unicodePrefixLocation+2);
275             var codepoint = parseInt(hex, 16);
276             var typedCharacter;
277
278             // Convert case if shifted
279             if (shifted == 0)
280                 typedCharacter = String.fromCharCode(codepoint).toLowerCase();
281             else
282                 typedCharacter = String.fromCharCode(codepoint).toUpperCase();
283
284             // Get codepoint
285             codepoint = typedCharacter.charCodeAt(0);
286
287             return getKeySymFromCharCode(codepoint);
288
289         }
290
291         return keyidentifier_keysym[keyIdentifier];
292
293     }
294
295     function isControlCharacter(codepoint) {
296         return codepoint <= 0x1F || (codepoint >= 0x7F && codepoint <= 0x9F);
297     }
298
299     function getKeySymFromCharCode(codepoint) {
300
301         // Keysyms for control characters
302         if (isControlCharacter(codepoint)) return 0xFF00 | codepoint;
303
304         // Keysyms for ASCII chars
305         if (codepoint >= 0x0000 && codepoint <= 0x00FF)
306             return codepoint;
307
308         // Keysyms for Unicode
309         if (codepoint >= 0x0100 && codepoint <= 0x10FFFF)
310             return 0x01000000 | codepoint;
311
312         return null;
313
314     }
315
316     function getKeySymFromKeyCode(keyCode) {
317
318         var keysym = null;
319         if (!guac_keyboard.modifiers.shift) keysym = unshiftedKeySym[keyCode];
320         else {
321             keysym = shiftedKeySym[keyCode];
322             if (keysym == null) keysym = unshiftedKeySym[keyCode];
323         }
324
325         return keysym;
326
327     }
328
329
330     // Sends a single keystroke over the network
331     function sendKeyPressed(keysym) {
332
333         // Mark key as pressed
334         guac_keyboard.pressed[keysym] = true;
335
336         // Send key event
337         if (keysym != null && guac_keyboard.onkeydown)
338             return guac_keyboard.onkeydown(keysym) != false;
339         
340         return true;
341
342     }
343
344     // Sends a single keystroke over the network
345     function sendKeyReleased(keysym) {
346
347         // Mark key as released
348         guac_keyboard.pressed[keysym] = false;
349
350         // Send key event
351         if (keysym != null && guac_keyboard.onkeyup)
352             return guac_keyboard.onkeyup(keysym) != false;
353
354         return true;
355
356     }
357
358
359     var keydown_code = null;
360
361     var deferred_keypress = null;
362     var keydown_keysym = null;
363     var keypress_keysym = null;
364
365     function fireKeyPress() {
366
367         // Prefer keysym from keypress
368         var keysym = keypress_keysym || keydown_keysym;
369         var keynum = keydown_code;
370
371         if (keydownChar[keynum] != keysym) {
372
373             // If this button is already pressed, release first
374             var lastKeyDownChar = keydownChar[keydown_code];
375             if (lastKeyDownChar)
376                 sendKeyReleased(lastKeyDownChar);
377
378             // Send event
379             keydownChar[keynum] = keysym;
380             sendKeyPressed(keysym);
381
382             // Clear old key repeat, if any.
383             stopRepeat();
384
385             // Start repeating (if not a modifier key) after a short delay
386             if (keynum != 16 && keynum != 17 && keynum != 18)
387                 repeatKeyTimeoutId = setTimeout(function() { startRepeat(keysym); }, 500);
388
389         }
390
391         // Done with deferred key event
392         deferred_keypress = null;
393         keypress_keysym   = null;
394         keydown_keysym    = null;
395         keydown_code      = null;
396
397     }
398
399     function isTypable(keyIdentifier) {
400
401         // Find unicode prefix
402         var unicodePrefixLocation = keyIdentifier.indexOf("U+");
403         if (unicodePrefixLocation == -1)
404             return false;
405
406         // Parse codepoint value
407         var hex = keyIdentifier.substring(unicodePrefixLocation+2);
408         var codepoint = parseInt(hex, 16);
409
410         // If control character, not typable
411         if (isControlCharacter(codepoint)) return false;
412
413         // Otherwise, typable
414         return true;
415
416     }
417
418     // When key pressed
419     element.onkeydown = function(e) {
420
421         // Only intercept if handler set
422         if (!guac_keyboard.onkeydown) return;
423
424         var keynum;
425         if (window.event) keynum = window.event.keyCode;
426         else if (e.which) keynum = e.which;
427
428         // Ctrl/Alt/Shift
429         if (keynum == 16)      guac_keyboard.modifiers.shift = true;
430         else if (keynum == 17) guac_keyboard.modifiers.ctrl  = true;
431         else if (keynum == 18) guac_keyboard.modifiers.alt   = true;
432
433         // Try to get keysym from keycode
434         keydown_keysym = getKeySymFromKeyCode(keynum);
435
436         // Also try to get get keysym from keyIdentifier
437         if (e.keyIdentifier) {
438
439             keydown_keysym = keydown_keysym ||
440                 getKeySymFromKeyIdentifier(guac_keyboard.modifiers.shift, e.keyIdentifier);
441
442             // Prevent default if non-typable character or if modifier combination
443             // likely to be eaten by browser otherwise (NOTE: We must not prevent
444             // default for Ctrl+Alt, as that combination is commonly used for
445             // AltGr. If we receive AltGr, we need to handle keypress, which
446             // means we cannot cancel keydown).
447             if (!isTypable(e.keyIdentifier)
448                     || ( guac_keyboard.modifiers.ctrl && !guac_keyboard.modifiers.alt)
449                     || (!guac_keyboard.modifiers.ctrl &&  guac_keyboard.modifiers.alt))
450                 e.preventDefault();
451             
452         }
453
454         // Set keycode which will be associated with any future keypress
455         keydown_code = keynum;
456
457         // Defer handling of event until after any other pending
458         // key events.
459         if (!deferred_keypress)
460             deferred_keypress = window.setTimeout(fireKeyPress, 0);
461
462     };
463
464     // When key pressed
465     element.onkeypress = function(e) {
466
467         // Only intercept if handler set
468         if (!guac_keyboard.onkeydown) return true;
469
470         var keynum;
471         if (window.event) keynum = window.event.keyCode;
472         else if (e.which) keynum = e.which;
473
474         keypress_keysym = getKeySymFromCharCode(keynum);
475
476         // If event identified as a typable character, and we're holding Ctrl+Alt,
477         // assume Ctrl+Alt is actually AltGr, and release both.
478         if (!isControlCharacter(keynum) && guac_keyboard.modifiers.ctrl && guac_keyboard.modifiers.alt) {
479             sendKeyReleased(0xFFE3);
480             sendKeyReleased(0xFFE9);
481         }
482
483         // Defer handling of event until after any other pending
484         // key events.
485         if (!deferred_keypress)
486             deferred_keypress = window.setTimeout(fireKeyPress, 0);
487
488         return false;
489
490     };
491
492     // When key released
493     element.onkeyup = function(e) {
494
495         // Only intercept if handler set
496         if (!guac_keyboard.onkeyup) return true;
497
498         var keynum;
499         if (window.event) keynum = window.event.keyCode;
500         else if (e.which) keynum = e.which;
501         
502         // Ctrl/Alt/Shift
503         if (keynum == 16)      guac_keyboard.modifiers.shift = false;
504         else if (keynum == 17) guac_keyboard.modifiers.ctrl  = false;
505         else if (keynum == 18) guac_keyboard.modifiers.alt   = false;
506         else
507             stopRepeat();
508
509         // Get corresponding character
510         var lastKeyDownChar = keydownChar[keynum];
511
512         // Clear character record
513         keydownChar[keynum] = null;
514
515         // Send release event
516         return sendKeyReleased(lastKeyDownChar);
517
518     };
519
520     // When focus is lost, clear modifiers.
521     element.onblur = function() {
522         guac_keyboard.modifiers.alt = false;
523         guac_keyboard.modifiers.ctrl = false;
524         guac_keyboard.modifiers.shift = false;
525     };
526
527 };