Fix jsdoc, add missing documentation.
[guacamole-common-js.git] / src / main / resources / oskeyboard.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 guac-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 /**
39  * Namespace for all Guacamole JavaScript objects.
40  * @namespace
41  */
42 var Guacamole = Guacamole || {};
43
44 /**
45  * Dynamic on-screen keyboard. Given the URL to an XML keyboard layout file,
46  * this object will download and use the XML to construct a clickable on-screen
47  * keyboard with its own key events.
48  * 
49  * @constructor
50  * @param {String} url The URL of an XML keyboard layout file.
51  */
52 Guacamole.OnScreenKeyboard = function(url) {
53
54     var on_screen_keyboard = this;
55
56     /**
57      * State of all modifiers. This is the bitwise OR of all active modifier
58      * values.
59      * 
60      * @private
61      */
62     var modifiers = 0;
63
64     var scaledElements = [];
65     
66     var modifiers = {};
67     var currentModifier = 1;
68
69     /**
70      * Adds a class to an element.
71      * 
72      * @private
73      * @function
74      * @param {Element} element The element to add a class to.
75      * @param {String} classname The name of the class to add.
76      */
77     var addClass;
78
79     /**
80      * Removes a class from an element.
81      * 
82      * @private
83      * @function
84      * @param {Element} element The element to remove a class from.
85      * @param {String} classname The name of the class to remove.
86      */
87     var removeClass;
88
89     // If Node.classList is supported, implement addClass/removeClass using that
90     if (Node.classList) {
91
92         /** @ignore */
93         addClass = function(element, classname) {
94             element.classList.add(classname);
95         };
96         
97         /** @ignore */
98         removeClass = function(element, classname) {
99             element.classList.remove(classname);
100         };
101         
102     }
103
104     // Otherwise, implement own
105     else {
106
107         /** @ignore */
108         addClass = function(element, classname) {
109
110             // Simply add new class
111             element.className += " " + classname;
112
113         };
114         
115         /** @ignore */
116         removeClass = function(element, classname) {
117
118             // Filter out classes with given name
119             element.className = element.className.replace(/([^ ]+)[ ]*/g,
120                 function(match, testClassname, spaces, offset, string) {
121
122                     // If same class, remove
123                     if (testClassname == classname)
124                         return "";
125
126                     // Otherwise, allow
127                     return match;
128                     
129                 }
130             );
131
132         };
133         
134     }
135
136     // Returns a unique power-of-two value for the modifier with the
137     // given name. The same value will be returned for the same modifier.
138     function getModifier(name) {
139         
140         var value = modifiers[name];
141         if (!value) {
142
143             // Get current modifier, advance to next
144             value = currentModifier;
145             currentModifier <<= 1;
146
147             // Store value of this modifier
148             modifiers[name] = value;
149
150         }
151
152         return value;
153             
154     }
155
156     function ScaledElement(element, width, height, scaleFont) {
157
158         this.width = width;
159         this.height = height;
160
161         this.scale = function(pixels) {
162             element.style.width      = (width  * pixels) + "px";
163             element.style.height     = (height * pixels) + "px";
164
165             if (scaleFont) {
166                 element.style.lineHeight = (height * pixels) + "px";
167                 element.style.fontSize   = pixels + "px";
168             }
169         }
170
171     }
172
173     // For each child of element, call handler defined in next
174     function parseChildren(element, next) {
175
176         var children = element.childNodes;
177         for (var i=0; i<children.length; i++) {
178
179             // Get child node
180             var child = children[i];
181
182             // Do not parse text nodes
183             if (!child.tagName)
184                 continue;
185
186             // Get handler for node
187             var handler = next[child.tagName];
188
189             // Call handler if defined
190             if (handler)
191                 handler(child);
192
193             // Throw exception if no handler
194             else
195                 throw new Error(
196                       "Unexpected " + child.tagName
197                     + " within " + element.tagName
198                 );
199
200         }
201
202     }
203
204     // Create keyboard
205     var keyboard = document.createElement("div");
206     keyboard.className = "guac-keyboard";
207
208     // Retrieve keyboard XML
209     var xmlhttprequest = new XMLHttpRequest();
210     xmlhttprequest.open("GET", url, false);
211     xmlhttprequest.send(null);
212
213     var xml = xmlhttprequest.responseXML;
214
215     if (xml) {
216
217         function parse_row(e) {
218             
219             var row = document.createElement("div");
220             row.className = "guac-keyboard-row";
221
222             parseChildren(e, {
223                 
224                 "column": function(e) {
225                     row.appendChild(parse_column(e));
226                 },
227                 
228                 "gap": function parse_gap(e) {
229
230                     // Create element
231                     var gap = document.createElement("div");
232                     gap.className = "guac-keyboard-gap";
233
234                     // Set gap size
235                     var gap_units = 1;
236                     if (e.getAttribute("size"))
237                         gap_units = parseFloat(e.getAttribute("size"));
238
239                     scaledElements.push(new ScaledElement(gap, gap_units, gap_units));
240                     row.appendChild(gap);
241
242                 },
243                 
244                 "key": function parse_key(e) {
245                     
246                     // Create element
247                     var key_element = document.createElement("div");
248                     key_element.className = "guac-keyboard-key";
249
250                     // Append class if specified
251                     if (e.getAttribute("class"))
252                         key_element.className += " " + e.getAttribute("class");
253
254                     // Position keys using container div
255                     var key_container_element = document.createElement("div");
256                     key_container_element.className = "guac-keyboard-key-container";
257                     key_container_element.appendChild(key_element);
258
259                     // Create key
260                     var key = new Guacamole.OnScreenKeyboard.Key();
261
262                     // Set key size
263                     var key_units = 1;
264                     if (e.getAttribute("size"))
265                         key_units = parseFloat(e.getAttribute("size"));
266
267                     key.size = key_units;
268
269                     parseChildren(e, {
270                         "cap": function parse_cap(e) {
271
272                             // TODO: Handle "sticky" attribute
273                             
274                             // Get content of key cap
275                             var content = e.textContent || e.text;
276
277                             // If read as blank, assume cap is a single space.
278                             if (content.length == 0)
279                                 content = " ";
280                             
281                             // Get keysym
282                             var real_keysym = null;
283                             if (e.getAttribute("keysym"))
284                                 real_keysym = parseInt(e.getAttribute("keysym"));
285
286                             // If no keysym specified, try to get from key content
287                             else if (content.length == 1) {
288
289                                 var charCode = content.charCodeAt(0);
290                                 if (charCode >= 0x0000 && charCode <= 0x00FF)
291                                     real_keysym = charCode;
292                                 else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
293                                     real_keysym = 0x01000000 | charCode;
294
295                             }
296                             
297                             // Create cap
298                             var cap = new Guacamole.OnScreenKeyboard.Cap(content, real_keysym);
299
300                             if (e.getAttribute("modifier"))
301                                 cap.modifier = e.getAttribute("modifier");
302                             
303                             // Create cap element
304                             var cap_element = document.createElement("div");
305                             cap_element.className = "guac-keyboard-cap";
306                             cap_element.textContent = content;
307                             key_element.appendChild(cap_element);
308
309                             // Append class if specified
310                             if (e.getAttribute("class"))
311                                 cap_element.className += " " + e.getAttribute("class");
312
313                             // Get modifier value
314                             var modifierValue = 0;
315                             if (e.getAttribute("if")) {
316
317                                 // Get modifier value for specified comma-delimited
318                                 // list of required modifiers.
319                                 var requirements = e.getAttribute("if").split(",");
320                                 for (var i=0; i<requirements.length; i++) {
321                                     modifierValue |= getModifier(requirements[i]);
322                                     addClass(cap_element, "guac-keyboard-requires-" + requirements[i]);
323                                     addClass(key_element, "guac-keyboard-uses-" + requirements[i]);
324                                 }
325
326                             }
327
328                             // Store cap
329                             key.modifierMask |= modifierValue;
330                             key.caps[modifierValue] = cap;
331
332                         }
333                     });
334
335                     scaledElements.push(new ScaledElement(key_container_element, key_units, 1, true));
336                     row.appendChild(key_container_element);
337
338                     // Set up click handler for key
339                     function press(e) {
340
341                         // Press key if not yet pressed
342                         if (!key.pressed) {
343
344                             addClass(key_element, "guac-keyboard-pressed");
345
346                             // Get current cap based on modifier state
347                             var cap = key.getCap(modifiers);
348
349                             // Update modifier state
350                             if (cap.modifier) {
351
352                                 // Construct classname for modifier
353                                 var modifierClass = "guac-keyboard-modifier-" + cap.modifier;
354                                 var modifierFlag = getModifier(cap.modifier);
355
356                                 // Toggle modifier state
357                                 modifiers ^= modifierFlag;
358
359                                 // Activate modifier if pressed
360                                 if (modifiers & modifierFlag) {
361                                     
362                                     addClass(keyboard, modifierClass);
363                                     
364                                     // Send key event
365                                     if (on_screen_keyboard.onkeydown && cap.keysym)
366                                         on_screen_keyboard.onkeydown(cap.keysym);
367
368                                 }
369
370                                 // Deactivate if not pressed
371                                 else {
372
373                                     removeClass(keyboard, modifierClass);
374                                     
375                                     // Send key event
376                                     if (on_screen_keyboard.onkeyup && cap.keysym)
377                                         on_screen_keyboard.onkeyup(cap.keysym);
378
379                                 }
380
381                             }
382
383                             // If not modifier, send key event now
384                             else if (on_screen_keyboard.onkeydown && cap.keysym)
385                                 on_screen_keyboard.onkeydown(cap.keysym);
386
387                             // Mark key as pressed
388                             key.pressed = true;
389
390                         }
391
392                         e.preventDefault();
393
394                     };
395
396                     function release(e) {
397
398                         // Release key if currently pressed
399                         if (key.pressed) {
400
401                             // Get current cap based on modifier state
402                             var cap = key.getCap(modifiers);
403
404                             removeClass(key_element, "guac-keyboard-pressed");
405
406                             // Send key event if not a modifier key
407                             if (!cap.modifier && on_screen_keyboard.onkeyup && cap.keysym)
408                                 on_screen_keyboard.onkeyup(cap.keysym);
409
410                             // Mark key as released
411                             key.pressed = false;
412
413                         }
414
415                         e.preventDefault();
416
417                     };
418
419                     key_element.addEventListener("mousedown", press, true);
420                     key_element.addEventListener("touchstart", press, true);
421
422                     key_element.addEventListener("mouseup", release, true);
423                     key_element.addEventListener("mouseout", release, true);
424                     key_element.addEventListener("touchend", release, true);
425
426                 }
427                 
428             });
429
430             return row;
431
432         }
433
434         function parse_column(e) {
435             
436             var col = document.createElement("div");
437             col.className = "guac-keyboard-column";
438
439             if (col.getAttribute("align"))
440                 col.style.textAlign = col.getAttribute("align");
441
442             // Columns can only contain rows
443             parseChildren(e, {
444                 "row": function(e) {
445                     col.appendChild(parse_row(e));
446                 }
447             });
448
449             return col;
450
451         }
452
453
454         // Parse document
455         var keyboard_element = xml.documentElement;
456         if (keyboard_element.tagName != "keyboard")
457             throw new Error("Root element must be keyboard");
458
459         // Get attributes
460         if (!keyboard_element.getAttribute("size"))
461             throw new Error("size attribute is required for keyboard");
462         
463         var keyboard_size = parseFloat(keyboard_element.getAttribute("size"));
464         
465         parseChildren(keyboard_element, {
466             
467             "row": function(e) {
468                 keyboard.appendChild(parse_row(e));
469             },
470             
471             "column": function(e) {
472                 keyboard.appendChild(parse_column(e));
473             }
474             
475         });
476
477     }
478
479     // Do not allow selection or mouse movement to propagate/register.
480     keyboard.onselectstart =
481     keyboard.onmousemove   =
482     keyboard.onmouseup     =
483     keyboard.onmousedown   =
484     function(e) {
485         e.stopPropagation();
486         return false;
487     };
488
489     /**
490      * Fired whenever the user presses a key on this Guacamole.OnScreenKeyboard.
491      * 
492      * @event
493      * @param {Number} keysym The keysym of the key being pressed.
494      */
495     this.onkeydown = null;
496
497     /**
498      * Fired whenever the user releases a key on this Guacamole.OnScreenKeyboard.
499      * 
500      * @event
501      * @param {Number} keysym The keysym of the key being released.
502      */
503     this.onkeyup   = null;
504
505     /**
506      * Returns the element containing the entire on-screen keyboard.
507      * @returns {Element} The element containing the entire on-screen keyboard.
508      */
509     this.getElement = function() {
510         return keyboard;
511     };
512
513     /**
514      * Resizes all elements within this Guacamole.OnScreenKeyboard such that
515      * the width is close to but does not exceed the specified width. The
516      * height of the keyboard is determined based on the width.
517      * 
518      * @param {Number} width The width to resize this Guacamole.OnScreenKeyboard
519      *                       to, in pixels.
520      */
521     this.resize = function(width) {
522
523         // Get pixel size of a unit
524         var unit = Math.floor(width * 10 / keyboard_size) / 10;
525
526         // Resize all scaled elements
527         for (var i=0; i<scaledElements.length; i++) {
528             var scaledElement = scaledElements[i];
529             scaledElement.scale(unit)
530         }
531
532     };
533
534 };
535
536
537 /**
538  * Basic representation of a single key of a keyboard. Each key has a set of
539  * caps associated with tuples of modifiers. The cap determins what happens
540  * when a key is pressed, while it is the state of modifier keys that determines
541  * what cap is in effect on any particular key.
542  * 
543  * @constructor
544  */
545 Guacamole.OnScreenKeyboard.Key = function() {
546
547     var key = this;
548
549     /**
550      * Whether this key is currently pressed.
551      */
552     this.pressed = false;
553
554     /**
555      * Width of the key, relative to the size of the keyboard.
556      */
557     this.size = 1;
558
559     /**
560      * An associative map of all caps by modifier.
561      */
562     this.caps = {};
563
564     /**
565      * Bit mask with all modifiers that affect this key set.
566      */
567     this.modifierMask = 0;
568
569     /**
570      * Given the bitwise OR of all active modifiers, returns the key cap
571      * which applies.
572      */
573     this.getCap = function(modifier) {
574         return key.caps[modifier & key.modifierMask];
575     };
576
577 };
578
579 /**
580  * Basic representation of a cap of a key. The cap is the visible part of a key
581  * and determines the active behavior of a key when pressed. The state of all
582  * modifiers on the keyboard determines the active cap for all keys, thus
583  * each cap is associated with a set of modifiers.
584  * 
585  * @constructor
586  * @param {String} text The text to be displayed within this cap.
587  * @param {Number} keysym The keysym this cap sends when its associated key is
588  *                        pressed or released.
589  * @param {String} modifier The modifier represented by this cap.
590  */
591 Guacamole.OnScreenKeyboard.Cap = function(text, keysym, modifier) {
592     
593     /**
594      * Modifier represented by this keycap
595      */
596     this.modifier = null;
597     
598     /**
599      * The text to be displayed within this keycap
600      */
601     this.text = text;
602
603     /**
604      * The keysym this cap sends when its associated key is pressed/released
605      */
606     this.keysym = keysym;
607
608     // Set modifier if provided
609     if (modifier) this.modifier = modifier;
610     
611 };