d940a9f4b0c7aa1868ed94df0833d713d84f6f9f
[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 // Guacamole namespace
39 var Guacamole = Guacamole || {};
40
41 /**
42  * Dynamic on-screen keyboard. Given the URL to an XML keyboard layout file,
43  * this object will download and use the XML to construct a clickable on-screen
44  * keyboard with its own key events.
45  * 
46  * @constructor
47  * @param {String} url The URL of an XML keyboard layout file.
48  */
49 Guacamole.OnScreenKeyboard = function(url) {
50
51     var on_screen_keyboard = this;
52
53     var scaledElements = [];
54     
55     var modifiers = {};
56     var currentModifier = 1;
57
58     // Returns a unique power-of-two value for the modifier with the
59     // given name. The same value will be returned for the same modifier.
60     function getModifier(name) {
61         
62         var value = modifiers[name];
63         if (!value) {
64
65             // Get current modifier, advance to next
66             value = currentModifier;
67             currentModifier <<= 1;
68
69             // Store value of this modifier
70             modifiers[name] = value;
71
72         }
73
74         return value;
75             
76     }
77
78     function ScaledElement(element, width, height, scaleFont) {
79
80         this.width = width;
81         this.height = height;
82
83         this.scale = function(pixels) {
84             element.style.width      = (width  * pixels) + "px";
85             element.style.height     = (height * pixels) + "px";
86
87             if (scaleFont) {
88                 element.style.lineHeight = (height * pixels) + "px";
89                 element.style.fontSize   = pixels + "px";
90             }
91         }
92
93     }
94
95     // For each child of element, call handler defined in next
96     function parseChildren(element, next) {
97
98         var children = element.childNodes;
99         for (var i=0; i<children.length; i++) {
100
101             // Get child node
102             var child = children[i];
103
104             // Do not parse text nodes
105             if (!child.tagName)
106                 continue;
107
108             // Get handler for node
109             var handler = next[child.tagName];
110
111             // Call handler if defined
112             if (handler)
113                 handler(child);
114
115             // Throw exception if no handler
116             else
117                 throw new Error(
118                       "Unexpected " + child.tagName
119                     + " within " + element.tagName
120                 );
121
122         }
123
124     }
125
126     // Create keyboard
127     var keyboard = document.createElement("div");
128     keyboard.className = "guac-keyboard";
129
130     // Retrieve keyboard XML
131     var xmlhttprequest = new XMLHttpRequest();
132     xmlhttprequest.open("GET", url, false);
133     xmlhttprequest.send(null);
134
135     var xml = xmlhttprequest.responseXML;
136
137     if (xml) {
138
139         function parse_row(e) {
140             
141             var row = document.createElement("div");
142             row.className = "guac-keyboard-row";
143
144             parseChildren(e, {
145                 
146                 "column": function(e) {
147                     row.appendChild(parse_column(e));
148                 },
149                 
150                 "gap": function parse_gap(e) {
151
152                     // Get attributes
153                     var gap_size = e.attributes["size"];
154
155                     // Create element
156                     var gap = document.createElement("div");
157                     gap.className = "guac-keyboard-gap";
158
159                     // Set gap size
160                     var gap_units = 1;
161                     if (gap_size)
162                         gap_units = parseFloat(gap_size.value);
163
164                     scaledElements.push(new ScaledElement(gap, gap_units, gap_units));
165                     row.appendChild(gap);
166
167                 },
168                 
169                 "key": function parse_key(e) {
170                     
171                     // Get attributes
172                     var key_size = e.attributes["size"];
173                     var key_class = e.attributes["class"];
174
175                     // Create element
176                     var key_element = document.createElement("div");
177                     key_element.className = "guac-keyboard-key";
178
179                     // Append class if specified
180                     if (key_class)
181                         key_element.className += " " + key_class.value;
182
183                     // Position keys using container div
184                     var key_container_element = document.createElement("div");
185                     key_container_element.className = "guac-keyboard-key-container";
186                     key_container_element.appendChild(key_element);
187
188                     // Create key
189                     var key = new Guacamole.OnScreenKeyboard.Key();
190
191                     // Set key size
192                     var key_units = 1;
193                     if (key_size)
194                         key_units = parseFloat(key_size.value);
195
196                     key.size = key_units;
197
198                     parseChildren(e, {
199                         "cap": function parse_cap(e) {
200
201                             // Get attributes
202                             var required = e.attributes["if"];
203                             var modifier = e.attributes["modifier"];
204                             var keysym   = e.attributes["keysym"];
205                             var sticky   = e.attributes["sticky"];
206                             var cap_class = e.attributes["class"];
207                             
208                             // Get content of key cap
209                             var content = e.textContent;
210                             
211                             // Get keysym
212                             var real_keysym = null;
213                             if (keysym)
214                                 real_keysym = parseInt(keysym.value);
215
216                             // If no keysym specified, try to get from key content
217                             else if (content.length == 1) {
218
219                                 var charCode = content.charCodeAt(0);
220                                 if (charCode >= 0x0000 && charCode <= 0x00FF)
221                                     real_keysym = charCode;
222                                 else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
223                                     real_keysym = 0x01000000 | charCode;
224
225                             }
226                             
227                             // Create cap
228                             var cap = new Guacamole.OnScreenKeyboard.Cap(content, real_keysym);
229
230                             if (modifier)
231                                 cap.modifier = modifier.value;
232                             
233                             // Create cap element
234                             var cap_element = document.createElement("div");
235                             cap_element.className = "guac-keyboard-cap";
236                             cap_element.textContent = content;
237                             key_element.appendChild(cap_element);
238
239                             // Append class if specified
240                             if (cap_class)
241                                 cap_element.className += " " + cap_class.value;
242
243                             // Get modifier value
244                             var modifierValue = 0;
245                             if (required) {
246
247                                 // Get modifier value for specified comma-delimited
248                                 // list of required modifiers.
249                                 var requirements = required.value.split(",");
250                                 for (var i=0; i<requirements.length; i++) {
251                                     modifierValue |= getModifier(requirements[i]);
252                                     cap_element.classList.add("guac-keyboard-requires-" + requirements[i]);
253                                     key_element.classList.add("guac-keyboard-uses-" + requirements[i]);
254                                 }
255
256                             }
257
258                             // Store cap
259                             key.modifierMask |= modifierValue;
260                             key.caps[modifierValue] = cap;
261
262                         }
263                     });
264
265                     scaledElements.push(new ScaledElement(key_container_element, key_units, 1, true));
266                     row.appendChild(key_container_element);
267
268                     // Set up click handler for key
269                     function press(e) {
270
271                         // Press key if not yet pressed
272                         if (!key.pressed) {
273
274                             key_element.classList.add("guac-keyboard-pressed");
275
276                             // Get current cap based on modifier state
277                             var cap = key.getCap(on_screen_keyboard.modifiers);
278
279                             // Update modifier state
280                             if (cap.modifier) {
281
282                                 // Construct classname for modifier
283                                 var modifierClass = "guac-keyboard-modifier-" + cap.modifier;
284                                 var modifierFlag = getModifier(cap.modifier);
285
286                                 // Toggle modifier state
287                                 on_screen_keyboard.modifiers ^= modifierFlag;
288
289                                 // Activate modifier if pressed
290                                 if (on_screen_keyboard.modifiers & modifierFlag)
291                                     keyboard.classList.add(modifierClass);
292
293                                 // Deactivate if not pressed
294                                 else
295                                     keyboard.classList.remove(modifierClass);
296
297                             }
298
299                             // Send key event
300                             if (on_screen_keyboard.onkeydown && cap.keysym)
301                                 on_screen_keyboard.onkeydown(cap.keysym);
302
303                             // Mark key as pressed
304                             key.pressed = true;
305
306                         }
307
308                         e.preventDefault();
309
310                     };
311
312                     key_element.addEventListener("mousedown", press, true);
313                     key_element.addEventListener("touchstart", press, true);
314
315                     function release(e) {
316
317                         // Release key if currently pressed
318                         if (key.pressed) {
319
320                             // Get current cap based on modifier state
321                             var cap = key.getCap(on_screen_keyboard.modifiers);
322
323                             key_element.classList.remove("guac-keyboard-pressed");
324
325                             // Send key event
326                             if (on_screen_keyboard.onkeyup && cap.keysym)
327                                 on_screen_keyboard.onkeyup(cap.keysym);
328
329                             // Mark key as released
330                             key.pressed = false;
331
332                         }
333
334                         e.preventDefault();
335
336                     };
337
338                     key_element.addEventListener("mouseup", release, true);
339                     key_element.addEventListener("mouseout", release, true);
340                     key_element.addEventListener("touchend", release, true);
341
342                 }
343                 
344             });
345
346             return row;
347
348         }
349
350         function parse_column(e) {
351             
352             var col = document.createElement("div");
353             col.className = "guac-keyboard-column";
354
355             var align = col.attributes["align"];
356
357             if (align)
358                 col.style.textAlign = align.value;
359
360             // Columns can only contain rows
361             parseChildren(e, {
362                 "row": function(e) {
363                     col.appendChild(parse_row(e));
364                 }
365             });
366
367             return col;
368
369         }
370
371
372         // Parse document
373         var keyboard_element = xml.documentElement;
374         if (keyboard_element.tagName != "keyboard")
375             throw new Error("Root element must be keyboard");
376
377         // Get attributes
378         if (!keyboard_element.attributes["size"])
379             throw new Error("size attribute is required for keyboard");
380         
381         var keyboard_size = parseFloat(keyboard_element.attributes["size"].value);
382         
383         parseChildren(keyboard_element, {
384             
385             "row": function(e) {
386                 keyboard.appendChild(parse_row(e));
387             },
388             
389             "column": function(e) {
390                 keyboard.appendChild(parse_column(e));
391             }
392             
393         });
394
395     }
396
397     // Do not allow selection or mouse movement to propagate/register.
398     keyboard.onselectstart =
399     keyboard.onmousemove   =
400     keyboard.onmouseup     =
401     keyboard.onmousedown   =
402     function(e) {
403         e.stopPropagation();
404         return false;
405     };
406
407     /**
408      * State of all modifiers.
409      */
410     this.modifiers = 0;
411
412     this.onkeydown = null;
413     this.onkeyup   = null;
414
415     this.getElement = function() {
416         return keyboard;
417     };
418
419     this.resize = function(width) {
420
421         // Get pixel size of a unit
422         var unit = Math.floor(width * 10 / keyboard_size) / 10;
423
424         // Resize all scaled elements
425         for (var i=0; i<scaledElements.length; i++) {
426             var scaledElement = scaledElements[i];
427             scaledElement.scale(unit)
428         }
429
430     };
431
432 };
433
434 Guacamole.OnScreenKeyboard.Key = function() {
435
436     var key = this;
437
438     /**
439      * Whether this key is currently pressed.
440      */
441     this.pressed = false;
442
443     /**
444      * Width of the key, relative to the size of the keyboard.
445      */
446     this.size = 1;
447
448     /**
449      * An associative map of all caps by modifier.
450      */
451     this.caps = {};
452
453     /**
454      * Bit mask with all modifiers that affect this key set.
455      */
456     this.modifierMask = 0;
457
458     /**
459      * Given the bitwise OR of all active modifiers, returns the key cap
460      * which applies.
461      */
462     this.getCap = function(modifier) {
463         return key.caps[modifier & key.modifierMask];
464     };
465
466 }
467
468 Guacamole.OnScreenKeyboard.Cap = function(text, keysym, modifier) {
469     
470     /**
471      * Modifier represented by this keycap
472      */
473     this.modifier = null;
474     
475     /**
476      * The text to be displayed within this keycap
477      */
478     this.text = text;
479
480     /**
481      * The keysym this cap sends when its associated key is pressed/released
482      */
483     this.keysym = keysym;
484
485     // Set modifier if provided
486     if (modifier) this.modifier = modifier;
487     
488 }