05aa3a9115983d90a5b58e83cdef3ff34c310b0d
[guacamole.git] / src / main / webapp / scripts / interface.js
1
2 // UI Definition
3 var GuacamoleUI = {
4
5     /* Detection Constants */
6     
7     "LONG_PRESS_DETECT_TIMEOUT"     : 800, /* milliseconds */
8     "LONG_PRESS_MOVEMENT_THRESHOLD" : 10,  /* pixels */
9     "MENU_CLOSE_DETECT_TIMEOUT"     : 500, /* milliseconds */
10     "MENU_OPEN_DETECT_TIMEOUT"      : 325, /* milliseconds */
11     "KEYBOARD_AUTO_RESIZE_INTERVAL" : 30,  /* milliseconds */
12
13     /* Animation Constants */
14
15     "MENU_SHADE_STEPS"    : 10, /* frames */
16     "MENU_SHADE_INTERVAL" : 30, /* milliseconds */
17     "MENU_SHOW_STEPS"     : 5,  /* frames */
18     "MENU_SHOW_INTERVAL"  : 30, /* milliseconds */
19
20     /* OSK Mode Constants */
21     "OSK_MODE_NATIVE" : 1, /* "Show Keyboard" will show the platform's native OSK */
22     "OSK_MODE_GUAC"   : 2, /* "Show Keyboard" will show Guac's built-in OSK */
23
24     /* UI Elements */
25
26     "viewport"    : document.getElementById("viewportClone"),
27     "display"     : document.getElementById("display"),
28     "menu"        : document.getElementById("menu"),
29     "menuControl" : document.getElementById("menuControl"),
30     "touchMenu"   : document.getElementById("touchMenu"),
31     "logo"        : document.getElementById("status-logo"),
32     "eventTarget" : document.getElementById("eventTarget"),
33
34     "buttons": {
35
36         "showClipboard": document.getElementById("showClipboard"),
37         "showKeyboard" : document.getElementById("showKeyboard"),
38         "ctrlAltDelete": document.getElementById("ctrlAltDelete"),
39         "reconnect"    : document.getElementById("reconnect"),
40         "logout"       : document.getElementById("logout")
41
42     },
43
44     "containers": {
45         "state"    : document.getElementById("statusDialog"),
46         "clipboard": document.getElementById("clipboardDiv"),
47         "keyboard" : document.getElementById("keyboardContainer")
48     },
49     
50     "state"     : document.getElementById("statusText"),
51     "clipboard" : document.getElementById("clipboard")
52
53 };
54
55 // Constant UI initialization and behavior
56 (function() {
57
58     var menu_shaded = false;
59
60     var shade_interval = null;
61     var show_interval = null;
62
63     // Cache error image (might not be available when error occurs)
64     var guacErrorImage = new Image();
65     guacErrorImage.src = "images/noguacamole-logo-24.png";
66
67     // Function for adding a class to an element
68     var addClass;
69
70     // Function for removing a class from an element
71     var removeClass;
72
73     // If Node.classList is supported, implement addClass/removeClass using that
74     if (Node.classList) {
75
76         addClass = function(element, classname) {
77             element.classList.add(classname);
78         };
79         
80         removeClass = function(element, classname) {
81             element.classList.remove(classname);
82         };
83         
84     }
85
86     // Otherwise, implement own
87     else {
88
89         addClass = function(element, classname) {
90
91             // Simply add new class
92             element.className += " " + classname;
93
94         };
95         
96         removeClass = function(element, classname) {
97
98             // Filter out classes with given name
99             element.className = element.className.replace(/([^ ]+)[ ]*/g,
100                 function(match, testClassname, spaces, offset, string) {
101
102                     // If same class, remove
103                     if (testClassname == classname)
104                         return "";
105
106                     // Otherwise, allow
107                     return match;
108                     
109                 }
110             );
111
112         };
113         
114     }
115
116
117     GuacamoleUI.hideStatus = function() {
118         removeClass(document.body, "guac-error");
119         GuacamoleUI.containers.state.style.visibility = "hidden";
120         GuacamoleUI.display.style.opacity = "1";
121     };
122     
123     GuacamoleUI.showStatus = function(text) {
124         removeClass(document.body, "guac-error");
125         GuacamoleUI.containers.state.style.visibility = "visible";
126         GuacamoleUI.state.textContent = text;
127         GuacamoleUI.display.style.opacity = "1";
128     };
129     
130     GuacamoleUI.showError = function(error) {
131         addClass(document.body, "guac-error");
132         GuacamoleUI.state.textContent = error;
133         GuacamoleUI.display.style.opacity = "0.1";
134     };
135
136     GuacamoleUI.shadeMenu = function() {
137
138         if (!menu_shaded) {
139
140             var step = Math.floor(GuacamoleUI.menu.offsetHeight / GuacamoleUI.MENU_SHADE_STEPS) + 1;
141             var offset = 0;
142             menu_shaded = true;
143
144             window.clearInterval(show_interval);
145             shade_interval = window.setInterval(function() {
146
147                 offset -= step;
148
149                 GuacamoleUI.menu.style.transform =
150                 GuacamoleUI.menu.style.WebkitTransform =
151                 GuacamoleUI.menu.style.MozTransform =
152                 GuacamoleUI.menu.style.OTransform =
153                 GuacamoleUI.menu.style.msTransform =
154
155                     "translateY(" + offset + "px)";
156
157                 if (offset <= -GuacamoleUI.menu.offsetHeight) {
158                     window.clearInterval(shade_interval);
159                     GuacamoleUI.menu.style.visiblity = "hidden";
160                 }
161
162             }, GuacamoleUI.MENU_SHADE_INTERVAL);
163         }
164
165     };
166
167     GuacamoleUI.showMenu = function() {
168
169         if (menu_shaded) {
170
171             var step = Math.floor(GuacamoleUI.menu.offsetHeight / GuacamoleUI.MENU_SHOW_STEPS) + 1;
172             var offset = -GuacamoleUI.menu.offsetHeight;
173             menu_shaded = false;
174             GuacamoleUI.menu.style.visiblity = "";
175
176             window.clearInterval(shade_interval);
177             show_interval = window.setInterval(function() {
178
179                 offset += step;
180
181                 if (offset >= 0) {
182                     offset = 0;
183                     window.clearInterval(show_interval);
184                 }
185
186                 GuacamoleUI.menu.style.transform =
187                 GuacamoleUI.menu.style.WebkitTransform =
188                 GuacamoleUI.menu.style.MozTransform =
189                 GuacamoleUI.menu.style.OTransform =
190                 GuacamoleUI.menu.style.msTransform =
191
192                     "translateY(" + offset + "px)";
193
194             }, GuacamoleUI.MENU_SHOW_INTERVAL);
195         }
196
197     };
198
199     // Show/Hide clipboard
200     GuacamoleUI.buttons.showClipboard.onclick = function() {
201
202         var displayed = GuacamoleUI.containers.clipboard.style.display;
203         if (displayed != "block") {
204             GuacamoleUI.containers.clipboard.style.display = "block";
205             GuacamoleUI.buttons.showClipboard.innerHTML = "Hide Clipboard";
206         }
207         else {
208             GuacamoleUI.containers.clipboard.style.display = "none";
209             GuacamoleUI.buttons.showClipboard.innerHTML = "Show Clipboard";
210             GuacamoleUI.clipboard.onchange();
211         }
212
213     };
214
215     // Assume no native OSK by default
216     GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_GUAC;
217
218     // Show/Hide keyboard
219     var keyboardResizeInterval = null;
220     GuacamoleUI.buttons.showKeyboard.onclick = function() {
221
222         // If Guac OSK shown, hide it.
223         var displayed = GuacamoleUI.containers.keyboard.style.display;
224         if (displayed == "block") {
225             GuacamoleUI.containers.keyboard.style.display = "none";
226             GuacamoleUI.buttons.showKeyboard.textContent = "Show Keyboard";
227
228             window.onresize = null;
229             window.clearInterval(keyboardResizeInterval);
230         }
231         
232         // If not shown ... action depends on OSK mode.
233         else {
234
235             // If we think the platform has a native OSK, use the event target to
236             // cause it to display.
237             if (GuacamoleUI.oskMode == GuacamoleUI.OSK_MODE_NATIVE) {
238
239                 // ...but use the Guac OSK if clicked again
240                 GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_GUAC;
241
242                 // Try to show native OSK by focusing eventTarget.
243                 GuacamoleUI.eventTarget.focus();
244                 return;
245
246             }
247
248             // Ensure event target is NOT focused if we are using the Guac OSK.
249             GuacamoleUI.eventTarget.blur();
250
251             GuacamoleUI.containers.keyboard.style.display = "block";
252             GuacamoleUI.buttons.showKeyboard.textContent = "Hide Keyboard";
253
254             // Automatically update size
255             window.onresize = updateKeyboardSize;
256             keyboardResizeInterval = window.setInterval(updateKeyboardSize, GuacamoleUI.KEYBOARD_AUTO_RESIZE_INTERVAL);
257
258             updateKeyboardSize();
259         }
260         
261
262     };
263
264     // Logout
265     GuacamoleUI.buttons.logout.onclick = function() {
266         window.location.href = "logout";
267     };
268
269     // Timeouts for detecting if users wants menu to open or close
270     var detectMenuOpenTimeout = null;
271     var detectMenuCloseTimeout = null;
272
273     // Clear detection timeouts
274     GuacamoleUI.resetMenuDetect = function() {
275
276         if (detectMenuOpenTimeout != null) {
277             window.clearTimeout(detectMenuOpenTimeout);
278             detectMenuOpenTimeout = null;
279         }
280
281         if (detectMenuCloseTimeout != null) {
282             window.clearTimeout(detectMenuCloseTimeout);
283             detectMenuCloseTimeout = null;
284         }
285
286     };
287
288     // Initiate detection of menu open action. If not canceled through some
289     // user event, menu will open.
290     GuacamoleUI.startMenuOpenDetect = function() {
291
292         if (!detectMenuOpenTimeout) {
293
294             // Clear detection state
295             GuacamoleUI.resetMenuDetect();
296
297             // Wait and then show menu
298             detectMenuOpenTimeout = window.setTimeout(function() {
299
300                 // If menu opened via mouse, do not show native OSK
301                 GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_GUAC;
302
303                 GuacamoleUI.showMenu();
304                 detectMenuOpenTimeout = null;
305             }, GuacamoleUI.MENU_OPEN_DETECT_TIMEOUT);
306
307         }
308
309     };
310
311     // Initiate detection of menu close action. If not canceled through some
312     // user mouse event, menu will close.
313     GuacamoleUI.startMenuCloseDetect = function() {
314
315         if (!detectMenuCloseTimeout) {
316
317             // Clear detection state
318             GuacamoleUI.resetMenuDetect();
319
320             // Wait and then shade menu
321             detectMenuCloseTimeout = window.setTimeout(function() {
322                 GuacamoleUI.shadeMenu();
323                 detectMenuCloseTimeout = null;
324             }, GuacamoleUI.MENU_CLOSE_DETECT_TIMEOUT);
325
326         }
327
328     };
329
330     // Show menu if mouseover any part of menu
331     GuacamoleUI.menu.addEventListener('mouseover', GuacamoleUI.showMenu, true);
332
333     // Stop detecting menu state change intents if mouse is over menu
334     GuacamoleUI.menu.addEventListener('mouseover', GuacamoleUI.resetMenuDetect, true);
335
336     // When mouse hovers over top of screen, start detection of intent to open menu
337     GuacamoleUI.menuControl.addEventListener('mousemove', GuacamoleUI.startMenuOpenDetect, true);
338
339     var long_press_start_x = 0;
340     var long_press_start_y = 0;
341     var menuShowLongPressTimeout = null;
342
343     GuacamoleUI.startLongPressDetect = function() {
344
345         if (!menuShowLongPressTimeout) {
346
347             menuShowLongPressTimeout = window.setTimeout(function() {
348                 
349                 menuShowLongPressTimeout = null;
350
351                 // Assume native OSK if menu shown via long-press
352                 GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_NATIVE;
353                 GuacamoleUI.showMenu();
354
355             }, GuacamoleUI.LONG_PRESS_DETECT_TIMEOUT);
356
357         }
358     };
359
360     GuacamoleUI.stopLongPressDetect = function() {
361         window.clearTimeout(menuShowLongPressTimeout);
362         menuShowLongPressTimeout = null;
363     };
364
365     // Detect long-press at bottom of screen
366     GuacamoleUI.display.addEventListener('touchstart', function(e) {
367         
368         // Close menu if shown
369         GuacamoleUI.shadeMenu();
370         
371         // Record touch location
372         if (e.touches.length == 1) {
373             var touch = e.touches[0];
374             long_press_start_x = touch.screenX;
375             long_press_start_y = touch.screenY;
376         }
377         
378         // Start detection
379         GuacamoleUI.startLongPressDetect();
380         
381     }, true);
382
383     // Stop detection if touch moves significantly
384     GuacamoleUI.display.addEventListener('touchmove', function(e) {
385         
386         if (e.touches.length == 1) {
387
388             // If touch distance from start exceeds threshold, cancel long press
389             var touch = e.touches[0];
390             if (Math.abs(touch.screenX - long_press_start_x) >= GuacamoleUI.LONG_PRESS_MOVEMENT_THRESHOLD
391                 || Math.abs(touch.screenY - long_press_start_y) >= GuacamoleUI.LONG_PRESS_MOVEMENT_THRESHOLD)
392                 GuacamoleUI.stopLongPressDetect();
393
394         }
395         
396     }, true);
397
398     // Stop detection if press stops
399     GuacamoleUI.display.addEventListener('touchend', GuacamoleUI.stopLongPressDetect, true);
400
401     // Close menu on mouse movement
402     GuacamoleUI.display.addEventListener('mousemove', GuacamoleUI.startMenuCloseDetect, true);
403     GuacamoleUI.display.addEventListener('mousedown', GuacamoleUI.startMenuCloseDetect, true);
404
405     // Reconnect button
406     GuacamoleUI.buttons.reconnect.onclick = function() {
407         window.location.reload();
408     };
409
410     // On-screen keyboard
411     GuacamoleUI.keyboard = new Guacamole.OnScreenKeyboard("layouts/en-us-qwerty-mobile.xml");
412     GuacamoleUI.containers.keyboard.appendChild(GuacamoleUI.keyboard.getElement());
413
414     // Function for automatically updating keyboard size
415     var lastKeyboardWidth;
416     function updateKeyboardSize() {
417         var currentSize = GuacamoleUI.keyboard.getElement().offsetWidth;
418         if (lastKeyboardWidth != currentSize) {
419             GuacamoleUI.keyboard.resize(currentSize);
420             lastKeyboardWidth = currentSize;
421         }
422     };
423
424     // Turn off autocorrect and autocapitalization on eventTarget
425     GuacamoleUI.eventTarget.setAttribute("autocorrect", "off");
426     GuacamoleUI.eventTarget.setAttribute("autocapitalize", "off");
427
428 })();
429
430 // Tie UI events / behavior to a specific Guacamole client
431 GuacamoleUI.attach = function(guac) {
432
433     var title_prefix = null;
434     var connection_name = "Guacamole"; 
435     
436     var guac_display = guac.getDisplay();
437
438     // Set document title appropriately, based on prefix and connection name
439     function updateTitle() {
440
441         // Use title prefix if present
442         if (title_prefix) {
443             
444             document.title = title_prefix;
445
446             // Include connection name, if present
447             if (connection_name)
448                 document.title += " " + connection_name;
449
450         }
451
452         // Otherwise, just set to connection name
453         else if (connection_name)
454             document.title = connection_name;
455
456     }
457
458     // When mouse enters display, start detection of intent to close menu
459     guac_display.addEventListener('mouseover', GuacamoleUI.startMenuCloseDetect, true);
460
461     guac_display.onclick = function(e) {
462         e.preventDefault();
463         return false;
464     };
465
466     // Mouse
467     var mouse = new Guacamole.Mouse(guac_display);
468     mouse.onmousedown = mouse.onmouseup = mouse.onmousemove =
469         function(mouseState) {
470        
471             // Determine mouse position within view
472             var mouse_view_x = mouseState.x + guac_display.offsetLeft - window.pageXOffset;
473             var mouse_view_y = mouseState.y + guac_display.offsetTop  - window.pageYOffset;
474
475             // Determine viewport dimensioins
476             var view_width  = GuacamoleUI.viewport.offsetWidth;
477             var view_height = GuacamoleUI.viewport.offsetHeight;
478
479             // Determine scroll amounts based on mouse position relative to document
480
481             var scroll_amount_x;
482             if (mouse_view_x > view_width)
483                 scroll_amount_x = mouse_view_x - view_width;
484             else if (mouse_view_x < 0)
485                 scroll_amount_x = mouse_view_x;
486             else
487                 scroll_amount_x = 0;
488
489             var scroll_amount_y;
490             if (mouse_view_y > view_height)
491                 scroll_amount_y = mouse_view_y - view_height;
492             else if (mouse_view_y < 0)
493                 scroll_amount_y = mouse_view_y;
494             else
495                 scroll_amount_y = 0;
496
497             // Scroll (if necessary) to keep mouse on screen.
498             window.scrollBy(scroll_amount_x, scroll_amount_y);
499        
500             // Send mouse event
501             guac.sendMouseState(mouseState);
502             
503         };
504
505     // Keyboard
506     var keyboard = new Guacamole.Keyboard(document);
507
508     // Monitor whether the event target is focused
509     var eventTargetFocused = false;
510
511     GuacamoleUI.eventTarget.onfocus = function() {
512         eventTargetFocused = true;
513     };
514
515     GuacamoleUI.eventTarget.onblur = function() {
516         eventTargetFocused = false;
517     };
518
519     // Save length for calculation of changed value
520     var currentLength = GuacamoleUI.eventTarget.value.length;
521
522     // If text is input directly into event target without typing (as with
523     // voice input, for example), type automatically.
524     GuacamoleUI.eventTarget.oninput = function(e) {
525
526         // Calculate current length and change in length
527         var newLength = GuacamoleUI.eventTarget.value.length;
528         var changeLength = newLength - currentLength;
529         currentLength = newLength;
530         
531         // If deleted or replaced text, ignore
532         if (changeLength <= 0)
533             return;
534
535         // Get changed text
536         var text = GuacamoleUI.eventTarget.value.substring(
537             GuacamoleUI.eventTarget.selectionStart,
538             GuacamoleUI.eventTarget.selectionStart + changeLength
539         );
540
541         // Send each character
542         for (var i=0; i<text.length; i++) {
543
544             // Get char code
545             var charCode = text.charCodeAt(i);
546
547             // Convert to keysym
548             var keysym = 0x003F; // Default to a question mark
549             if (charCode >= 0x0000 && charCode <= 0x00FF)
550                 keysym = charCode;
551             else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
552                 keysym = 0x01000000 | charCode;
553
554             // Send keysym only if not already pressed
555             if (!keyboard.pressed[keysym]) {
556
557                 // Press and release key
558                 guac.sendKeyEvent(1, keysym);
559                 guac.sendKeyEvent(0, keysym);
560
561             }
562
563         }
564
565     }
566
567     function isTypableCharacter(keysym) {
568         return (keysym & 0xFFFF00) != 0xFF00;
569     }
570
571     function disableKeyboard() {
572         keyboard.onkeydown = null;
573         keyboard.onkeyup = null;
574     }
575
576     function enableKeyboard() {
577
578         keyboard.onkeydown = function (keysym) {
579             guac.sendKeyEvent(1, keysym);
580             return eventTargetFocused && isTypableCharacter(keysym);
581         };
582
583         keyboard.onkeyup = function (keysym) {
584             guac.sendKeyEvent(0, keysym);
585             return eventTargetFocused && isTypableCharacter(keysym);
586         };
587
588     }
589
590     // Enable keyboard by default
591     enableKeyboard();
592
593     // Handle client state change
594     guac.onstatechange = function(clientState) {
595
596         switch (clientState) {
597
598             // Idle
599             case 0:
600                 GuacamoleUI.showStatus("Idle.");
601                 title_prefix = "[Idle]";
602                 break;
603
604             // Connecting
605             case 1:
606                 GuacamoleUI.shadeMenu();
607                 GuacamoleUI.showStatus("Connecting...");
608                 title_prefix = "[Connecting...]";
609                 break;
610
611             // Connected + waiting
612             case 2:
613                 GuacamoleUI.showStatus("Connected, waiting for first update...");
614                 title_prefix = "[Waiting...]";
615                 break;
616
617             // Connected
618             case 3:
619                 GuacamoleUI.hideStatus();
620                 title_prefix = null;
621                 break;
622
623             // Disconnecting
624             case 4:
625                 GuacamoleUI.showStatus("Disconnecting...");
626                 title_prefix = "[Disconnecting...]";
627                 break;
628
629             // Disconnected
630             case 5:
631                 GuacamoleUI.showStatus("Disconnected.");
632                 title_prefix = "[Disconnected]";
633                 break;
634
635             // Unknown status code
636             default:
637                 GuacamoleUI.showStatus("[UNKNOWN STATUS]");
638
639         }
640
641         updateTitle();
642     };
643
644     // Name instruction handler
645     guac.onname = function(name) {
646         connection_name = name;
647         updateTitle();
648     };
649
650     // Error handler
651     guac.onerror = function(error) {
652
653         // Disconnect, if connected
654         guac.disconnect();
655
656         // Display error message
657         GuacamoleUI.showError(error);
658         
659     };
660
661     // Disconnect on close
662     window.onunload = function() {
663         guac.disconnect();
664     };
665
666     // Handle clipboard events
667     GuacamoleUI.clipboard.onchange = function() {
668
669         var text = GuacamoleUI.clipboard.value;
670         guac.setClipboard(text);
671
672     };
673
674     // Ignore keypresses when clipboard is focused
675     GuacamoleUI.clipboard.onfocus = function() {
676         disableKeyboard();
677     };
678
679     // Capture keypresses when clipboard is not focused
680     GuacamoleUI.clipboard.onblur = function() {
681         enableKeyboard();
682     };
683
684     // Server copy handler
685     guac.onclipboard = function(data) {
686         GuacamoleUI.clipboard.value = data;
687     };
688
689     GuacamoleUI.keyboard.onkeydown = function(keysym) {
690         guac.sendKeyEvent(1, keysym);
691     };
692
693     GuacamoleUI.keyboard.onkeyup = function(keysym) {
694         guac.sendKeyEvent(0, keysym);
695     };
696
697     // Send Ctrl-Alt-Delete
698     GuacamoleUI.buttons.ctrlAltDelete.onclick = function() {
699
700         var KEYSYM_CTRL   = 0xFFE3;
701         var KEYSYM_ALT    = 0xFFE9;
702         var KEYSYM_DELETE = 0xFFFF;
703
704         guac.sendKeyEvent(1, KEYSYM_CTRL);
705         guac.sendKeyEvent(1, KEYSYM_ALT);
706         guac.sendKeyEvent(1, KEYSYM_DELETE);
707         guac.sendKeyEvent(0, KEYSYM_DELETE);
708         guac.sendKeyEvent(0, KEYSYM_ALT);
709         guac.sendKeyEvent(0, KEYSYM_CTRL);
710     };
711
712 };