Fixed regression with key repeat.
[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 keycodes which do not map to typable characters
127      * to their shifted X11 keysym equivalents. Keycodes must only be listed
128      * here if their shifted X11 keysym equivalents differ from their unshifted
129      * equivalents.
130      * @private
131      */
132     var shiftedKeySym = {
133         18:  0xFFE7  // alt
134     };
135
136     // Single key state/modifier buffer
137     var modShift = false;
138     var modCtrl = false;
139     var modAlt = false;
140
141     var keydownChar = new Array();
142
143     // ID of routine repeating keystrokes. -1 = not repeating.
144     var repeatKeyTimeoutId = -1;
145     var repeatKeyIntervalId = -1;
146
147     // Starts repeating keystrokes
148     function startRepeat(keySym) {
149         repeatKeyIntervalId = setInterval(function() {
150             sendKeyReleased(keySym);
151             sendKeyPressed(keySym);
152         }, 50);
153     }
154
155     // Stops repeating keystrokes
156     function stopRepeat() {
157         if (repeatKeyTimeoutId != -1) clearInterval(repeatKeyTimeoutId);
158         if (repeatKeyIntervalId != -1) clearInterval(repeatKeyIntervalId);
159     }
160
161
162     function getKeySymFromKeyIdentifier(shifted, keyIdentifier) {
163
164         var unicodePrefixLocation = keyIdentifier.indexOf("U+");
165         if (unicodePrefixLocation >= 0) {
166
167             var hex = keyIdentifier.substring(unicodePrefixLocation+2);
168             var codepoint = parseInt(hex, 16);
169             var typedCharacter;
170
171             // Convert case if shifted
172             if (shifted == 0)
173                 typedCharacter = String.fromCharCode(codepoint).toLowerCase();
174             else
175                 typedCharacter = String.fromCharCode(codepoint).toUpperCase();
176
177             // Get codepoint
178             codepoint = typedCharacter.charCodeAt(0);
179
180             return getKeySymFromCharCode(codepoint);
181
182         }
183
184         return null;
185
186     }
187
188     function getKeySymFromCharCode(keyCode) {
189
190         if (keyCode >= 0x0000 && keyCode <= 0x00FF)
191             return keyCode;
192
193         if (keyCode >= 0x0100 && keyCode <= 0x10FFFF)
194             return 0x01000000 | keyCode;
195
196         return null;
197
198     }
199
200     function getKeySymFromKeyCode(keyCode) {
201
202         var keysym = null;
203         if (!modShift) keysym = unshiftedKeySym[keyCode];
204         else {
205             keysym = shiftedKeySym[keyCode];
206             if (keysym == null) keysym = unshiftedKeySym[keyCode];
207         }
208
209         return keysym;
210
211     }
212
213
214     // Sends a single keystroke over the network
215     function sendKeyPressed(keysym) {
216         if (keysym != null && guac_keyboard.onkeydown)
217             return guac_keyboard.onkeydown(keysym) != false;
218         return true;
219     }
220
221     // Sends a single keystroke over the network
222     function sendKeyReleased(keysym) {
223         if (keysym != null && guac_keyboard.onkeyup)
224             return guac_keyboard.onkeyup(keysym) != false;
225         return true;
226     }
227
228
229     var KEYDOWN = 1;
230     var KEYPRESS = 2;
231
232     var keySymSource = null;
233
234     // When key pressed
235     var keydownCode = null;
236     element.onkeydown = function(e) {
237
238         // Only intercept if handler set
239         if (!guac_keyboard.onkeydown) return true;
240
241         var keynum;
242         if (window.event) keynum = window.event.keyCode;
243         else if (e.which) keynum = e.which;
244
245         // Ctrl/Alt/Shift
246         if (keynum == 16)
247             modShift = true;
248         else if (keynum == 17)
249             modCtrl = true;
250         else if (keynum == 18)
251             modAlt = true;
252
253         var keysym = getKeySymFromKeyCode(keynum);
254         if (keysym) {
255             // Get keysyms and events from KEYDOWN
256             keySymSource = KEYDOWN;
257         }
258
259         // If modifier keys are held down, and we have keyIdentifier
260         else if ((modCtrl || modAlt) && e.keyIdentifier) {
261
262             // Get keysym from keyIdentifier
263             keysym = getKeySymFromKeyIdentifier(modShift, e.keyIdentifier);
264
265             // Get keysyms and events from KEYDOWN
266             keySymSource = KEYDOWN;
267
268         }
269
270         else
271             // Get keysyms and events from KEYPRESS
272             keySymSource = KEYPRESS;
273
274         keydownCode = keynum;
275
276         // Ignore key if we don't need to use KEYPRESS.
277         // Send key event here
278         if (keySymSource == KEYDOWN) {
279
280             if (keydownChar[keynum] != keysym) {
281
282                 // Send event
283                 keydownChar[keynum] = keysym;
284                 var returnValue = sendKeyPressed(keysym);
285
286                 // Clear old key repeat, if any.
287                 stopRepeat();
288
289                 // Start repeating (if not a modifier key) after a short delay
290                 if (keynum != 16 && keynum != 17 && keynum != 18)
291                     repeatKeyTimeoutId = setTimeout(function() { startRepeat(keysym); }, 500);
292
293                 // Use return code provided by handler
294                 return returnValue;
295
296             }
297
298             // Default to canceling event if no keypress is being sent, but
299             // source of events is keydown.
300             return false;
301
302         }
303
304         return true;
305
306     };
307
308     // When key pressed
309     element.onkeypress = function(e) {
310
311         // Only intercept if handler set
312         if (!guac_keyboard.onkeydown) return true;
313
314         if (keySymSource != KEYPRESS) return false;
315
316         var keynum;
317         if (window.event) keynum = window.event.keyCode;
318         else if (e.which) keynum = e.which;
319
320         var keysym = getKeySymFromCharCode(keynum);
321         if (keysym && keydownChar[keynum] != keysym) {
322
323             // If this button already pressed, release first
324             var lastKeyDownChar = keydownChar[keydownCode];
325             if (lastKeyDownChar)
326                 sendKeyReleased(lastKeyDownChar);
327
328             keydownChar[keydownCode] = keysym;
329
330             // Clear old key repeat, if any.
331             stopRepeat();
332
333             // Send key event
334             var returnValue = sendKeyPressed(keysym);
335
336             // Start repeating (if not a modifier key) after a short delay
337             repeatKeyTimeoutId = setTimeout(function() { startRepeat(keysym); }, 500);
338
339             return returnValue;
340         }
341
342         // Default to canceling event if no keypress is being sent, but
343         // source of events is keypress.
344         return false;
345
346     };
347
348     // When key released
349     element.onkeyup = function(e) {
350
351         // Only intercept if handler set
352         if (!guac_keyboard.onkeyup) return true;
353
354         var keynum;
355         if (window.event) keynum = window.event.keyCode;
356         else if (e.which) keynum = e.which;
357         
358         // Ctrl/Alt/Shift
359         if (keynum == 16)
360             modShift = false;
361         else if (keynum == 17)
362             modCtrl = false;
363         else if (keynum == 18)
364             modAlt = false;
365         else
366             stopRepeat();
367
368         // Get corresponding character
369         var lastKeyDownChar = keydownChar[keynum];
370
371         // Clear character record
372         keydownChar[keynum] = null;
373
374         // Send release event
375         return sendKeyReleased(lastKeyDownChar);
376
377     };
378
379     // When focus is lost, clear modifiers.
380     element.onblur = function() {
381         modAlt = false;
382         modCtrl = false;
383         modShift = false;
384     };
385
386 };