8018fb3eca42b7b88e825bd627803e42d5bd5c44
[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                 GuacamoleUI.menu.style.top = offset + "px";
149
150                 if (offset <= -GuacamoleUI.menu.offsetHeight) {
151                     window.clearInterval(shade_interval);
152                     GuacamoleUI.menu.style.visiblity = "hidden";
153                 }
154
155             }, GuacamoleUI.MENU_SHADE_INTERVAL);
156         }
157
158     };
159
160     GuacamoleUI.showMenu = function() {
161
162         if (menu_shaded) {
163
164             var step = Math.floor(GuacamoleUI.menu.offsetHeight / GuacamoleUI.MENU_SHOW_STEPS) + 1;
165             var offset = -GuacamoleUI.menu.offsetHeight;
166             menu_shaded = false;
167             GuacamoleUI.menu.style.visiblity = "";
168
169             window.clearInterval(shade_interval);
170             show_interval = window.setInterval(function() {
171
172                 offset += step;
173
174                 if (offset >= 0) {
175                     offset = 0;
176                     window.clearInterval(show_interval);
177                 }
178
179                 GuacamoleUI.menu.style.top = offset + "px";
180
181             }, GuacamoleUI.MENU_SHOW_INTERVAL);
182         }
183
184     };
185
186     // Show/Hide clipboard
187     GuacamoleUI.buttons.showClipboard.onclick = function() {
188
189         var displayed = GuacamoleUI.containers.clipboard.style.display;
190         if (displayed != "block") {
191             GuacamoleUI.containers.clipboard.style.display = "block";
192             GuacamoleUI.buttons.showClipboard.innerHTML = "Hide Clipboard";
193         }
194         else {
195             GuacamoleUI.containers.clipboard.style.display = "none";
196             GuacamoleUI.buttons.showClipboard.innerHTML = "Show Clipboard";
197             GuacamoleUI.clipboard.onchange();
198         }
199
200     };
201
202     // Assume no native OSK by default
203     GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_GUAC;
204
205     // Show/Hide keyboard
206     var keyboardResizeInterval = null;
207     GuacamoleUI.buttons.showKeyboard.onclick = function() {
208
209         // If Guac OSK shown, hide it.
210         var displayed = GuacamoleUI.containers.keyboard.style.display;
211         if (displayed == "block") {
212             GuacamoleUI.containers.keyboard.style.display = "none";
213             GuacamoleUI.buttons.showKeyboard.textContent = "Show Keyboard";
214
215             window.onresize = null;
216             window.clearInterval(keyboardResizeInterval);
217         }
218         
219         // If not shown ... action depends on OSK mode.
220         else {
221
222             // If we think the platform has a native OSK, use the event target to
223             // cause it to display.
224             if (GuacamoleUI.oskMode == GuacamoleUI.OSK_MODE_NATIVE) {
225
226                 // ...but use the Guac OSK if clicked again
227                 GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_GUAC;
228
229                 // Try to show native OSK by focusing eventTarget.
230                 GuacamoleUI.eventTarget.focus();
231                 return;
232
233             }
234
235             // Ensure event target is NOT focused if we are using the Guac OSK.
236             GuacamoleUI.eventTarget.blur();
237
238             GuacamoleUI.containers.keyboard.style.display = "block";
239             GuacamoleUI.buttons.showKeyboard.textContent = "Hide Keyboard";
240
241             // Automatically update size
242             window.onresize = updateKeyboardSize;
243             keyboardResizeInterval = window.setInterval(updateKeyboardSize, GuacamoleUI.KEYBOARD_AUTO_RESIZE_INTERVAL);
244
245             updateKeyboardSize();
246         }
247         
248
249     };
250
251     // Logout
252     GuacamoleUI.buttons.logout.onclick = function() {
253         window.location.href = "logout";
254     };
255
256     // Timeouts for detecting if users wants menu to open or close
257     var detectMenuOpenTimeout = null;
258     var detectMenuCloseTimeout = null;
259
260     // Clear detection timeouts
261     GuacamoleUI.resetMenuDetect = function() {
262
263         if (detectMenuOpenTimeout != null) {
264             window.clearTimeout(detectMenuOpenTimeout);
265             detectMenuOpenTimeout = null;
266         }
267
268         if (detectMenuCloseTimeout != null) {
269             window.clearTimeout(detectMenuCloseTimeout);
270             detectMenuCloseTimeout = null;
271         }
272
273     };
274
275     // Initiate detection of menu open action. If not canceled through some
276     // user event, menu will open.
277     GuacamoleUI.startMenuOpenDetect = function() {
278
279         if (!detectMenuOpenTimeout) {
280
281             // Clear detection state
282             GuacamoleUI.resetMenuDetect();
283
284             // Wait and then show menu
285             detectMenuOpenTimeout = window.setTimeout(function() {
286
287                 // If menu opened via mouse, do not show native OSK
288                 GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_GUAC;
289
290                 GuacamoleUI.showMenu();
291                 detectMenuOpenTimeout = null;
292             }, GuacamoleUI.MENU_OPEN_DETECT_TIMEOUT);
293
294         }
295
296     };
297
298     // Initiate detection of menu close action. If not canceled through some
299     // user mouse event, menu will close.
300     GuacamoleUI.startMenuCloseDetect = function() {
301
302         if (!detectMenuCloseTimeout) {
303
304             // Clear detection state
305             GuacamoleUI.resetMenuDetect();
306
307             // Wait and then shade menu
308             detectMenuCloseTimeout = window.setTimeout(function() {
309                 GuacamoleUI.shadeMenu();
310                 detectMenuCloseTimeout = null;
311             }, GuacamoleUI.MENU_CLOSE_DETECT_TIMEOUT);
312
313         }
314
315     };
316
317     // Show menu if mouseover any part of menu
318     GuacamoleUI.menu.addEventListener('mouseover', GuacamoleUI.showMenu, true);
319
320     // Stop detecting menu state change intents if mouse is over menu
321     GuacamoleUI.menu.addEventListener('mouseover', GuacamoleUI.resetMenuDetect, true);
322
323     // When mouse hovers over top of screen, start detection of intent to open menu
324     GuacamoleUI.menuControl.addEventListener('mousemove', GuacamoleUI.startMenuOpenDetect, true);
325
326     var long_press_start_x = 0;
327     var long_press_start_y = 0;
328     var menuShowLongPressTimeout = null;
329
330     GuacamoleUI.startLongPressDetect = function() {
331
332         if (!menuShowLongPressTimeout) {
333
334             menuShowLongPressTimeout = window.setTimeout(function() {
335                 
336                 menuShowLongPressTimeout = null;
337
338                 // Assume native OSK if menu shown via long-press
339                 GuacamoleUI.oskMode = GuacamoleUI.OSK_MODE_NATIVE;
340                 GuacamoleUI.showMenu();
341
342             }, GuacamoleUI.LONG_PRESS_DETECT_TIMEOUT);
343
344         }
345     };
346
347     GuacamoleUI.stopLongPressDetect = function() {
348         window.clearTimeout(menuShowLongPressTimeout);
349         menuShowLongPressTimeout = null;
350     };
351
352     // Detect long-press at bottom of screen
353     GuacamoleUI.display.addEventListener('touchstart', function(e) {
354         
355         // Close menu if shown
356         GuacamoleUI.shadeMenu();
357         
358         // Record touch location
359         if (e.touches.length == 1) {
360             var touch = e.touches[0];
361             long_press_start_x = touch.screenX;
362             long_press_start_y = touch.screenY;
363         }
364         
365         // Start detection
366         GuacamoleUI.startLongPressDetect();
367         
368     }, true);
369
370     // Stop detection if touch moves significantly
371     GuacamoleUI.display.addEventListener('touchmove', function(e) {
372         
373         if (e.touches.length == 1) {
374
375             // If touch distance from start exceeds threshold, cancel long press
376             var touch = e.touches[0];
377             if (Math.abs(touch.screenX - long_press_start_x) >= GuacamoleUI.LONG_PRESS_MOVEMENT_THRESHOLD
378                 || Math.abs(touch.screenY - long_press_start_y) >= GuacamoleUI.LONG_PRESS_MOVEMENT_THRESHOLD)
379                 GuacamoleUI.stopLongPressDetect();
380
381         }
382         
383     }, true);
384
385     // Stop detection if press stops
386     GuacamoleUI.display.addEventListener('touchend', GuacamoleUI.stopLongPressDetect, true);
387
388     // Close menu on mouse movement
389     GuacamoleUI.display.addEventListener('mousemove', GuacamoleUI.startMenuCloseDetect, true);
390     GuacamoleUI.display.addEventListener('mousedown', GuacamoleUI.startMenuCloseDetect, true);
391
392     // Reconnect button
393     GuacamoleUI.buttons.reconnect.onclick = function() {
394         window.location.reload();
395     };
396
397     // On-screen keyboard
398     GuacamoleUI.keyboard = new Guacamole.OnScreenKeyboard("layouts/en-us-qwerty-mobile.xml");
399     GuacamoleUI.containers.keyboard.appendChild(GuacamoleUI.keyboard.getElement());
400
401     // Function for automatically updating keyboard size
402     var lastKeyboardWidth;
403     function updateKeyboardSize() {
404         var currentSize = GuacamoleUI.keyboard.getElement().offsetWidth;
405         if (lastKeyboardWidth != currentSize) {
406             GuacamoleUI.keyboard.resize(currentSize);
407             lastKeyboardWidth = currentSize;
408         }
409     };
410
411 })();
412
413 // Tie UI events / behavior to a specific Guacamole client
414 GuacamoleUI.attach = function(guac) {
415
416     var title_prefix = null;
417     var connection_name = "Guacamole"; 
418     
419     var guac_display = guac.getDisplay();
420
421     // Set document title appropriately, based on prefix and connection name
422     function updateTitle() {
423
424         // Use title prefix if present
425         if (title_prefix) {
426             
427             document.title = title_prefix;
428
429             // Include connection name, if present
430             if (connection_name)
431                 document.title += " " + connection_name;
432
433         }
434
435         // Otherwise, just set to connection name
436         else if (connection_name)
437             document.title = connection_name;
438
439     }
440
441     // When mouse enters display, start detection of intent to close menu
442     guac_display.addEventListener('mouseover', GuacamoleUI.startMenuCloseDetect, true);
443
444     guac_display.onclick = function(e) {
445         e.preventDefault();
446         return false;
447     };
448
449     // Mouse
450     var mouse = new Guacamole.Mouse(guac_display);
451     mouse.onmousedown = mouse.onmouseup = mouse.onmousemove =
452         function(mouseState) {
453        
454             // Determine mouse position within view
455             var mouse_view_x = mouseState.x + guac_display.offsetLeft - window.pageXOffset;
456             var mouse_view_y = mouseState.y + guac_display.offsetTop  - window.pageYOffset;
457
458             // Determine viewport dimensioins
459             var view_width  = GuacamoleUI.viewport.offsetWidth;
460             var view_height = GuacamoleUI.viewport.offsetHeight;
461
462             // Determine scroll amounts based on mouse position relative to document
463
464             var scroll_amount_x;
465             if (mouse_view_x > view_width)
466                 scroll_amount_x = mouse_view_x - view_width;
467             else if (mouse_view_x < 0)
468                 scroll_amount_x = mouse_view_x;
469             else
470                 scroll_amount_x = 0;
471
472             var scroll_amount_y;
473             if (mouse_view_y > view_height)
474                 scroll_amount_y = mouse_view_y - view_height;
475             else if (mouse_view_y < 0)
476                 scroll_amount_y = mouse_view_y;
477             else
478                 scroll_amount_y = 0;
479
480             // Scroll (if necessary) to keep mouse on screen.
481             window.scrollBy(scroll_amount_x, scroll_amount_y);
482        
483             // Send mouse event
484             guac.sendMouseState(mouseState);
485             
486         };
487
488     // Keyboard
489     var keyboard = new Guacamole.Keyboard(document);
490     var keysymPressed = [];
491
492     // Monitor whether the event target is focused
493     var eventTargetFocused = false;
494
495     GuacamoleUI.eventTarget.onfocus = function() {
496         eventTargetFocused = true;
497     };
498
499     GuacamoleUI.eventTarget.onblur = function() {
500         eventTargetFocused = false;
501     };
502
503     // Save length for calculation of changed value
504     var currentLength = GuacamoleUI.eventTarget.value.length;
505
506     // If text is input directly into event target without typing (as with
507     // voice input, for example), type automatically.
508     GuacamoleUI.eventTarget.oninput = function(e) {
509
510         // Calculate current length and change in length
511         var newLength = GuacamoleUI.eventTarget.value.length;
512         var changeLength = newLength - currentLength;
513         currentLength = newLength;
514         
515         // If deleted or replaced text, ignore
516         if (changeLength <= 0)
517             return;
518
519         // Get changed text
520         var text = GuacamoleUI.eventTarget.value.substring(
521             GuacamoleUI.eventTarget.selectionStart,
522             GuacamoleUI.eventTarget.selectionStart + changeLength
523         );
524
525         // Send each character
526         for (var i=0; i<text.length; i++) {
527
528             // Get char code
529             var charCode = text.charCodeAt(i);
530
531             // Convert to keysym
532             var keysym = 0x003F; // Default to a question mark
533             if (charCode >= 0x0000 && charCode <= 0x00FF)
534                 keysym = charCode;
535             else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
536                 keysym = 0x01000000 | charCode;
537
538             // Send keysym only if not already pressed
539             if (!keysymPressed[keysym]) {
540
541                 // Press and release key
542                 guac.sendKeyEvent(1, keysym);
543                 guac.sendKeyEvent(0, keysym);
544
545             }
546
547         }
548
549     }
550
551     function isTypableCharacter(keysym) {
552         return (keysym & 0xFFFF00) != 0xFF00;
553     }
554
555     function disableKeyboard() {
556         keyboard.onkeydown = null;
557         keyboard.onkeyup = null;
558     }
559
560     function enableKeyboard() {
561
562         keyboard.onkeydown = function (keysym) {
563             guac.sendKeyEvent(1, keysym);
564             keysymPressed[keysym] = true;
565             return eventTargetFocused && isTypableCharacter(keysym);
566         };
567
568         keyboard.onkeyup = function (keysym) {
569             guac.sendKeyEvent(0, keysym);
570             keysymPressed[keysym] = false;
571             return eventTargetFocused && isTypableCharacter(keysym);
572         };
573
574     }
575
576     // Enable keyboard by default
577     enableKeyboard();
578
579     // Handle client state change
580     guac.onstatechange = function(clientState) {
581
582         switch (clientState) {
583
584             // Idle
585             case 0:
586                 GuacamoleUI.showStatus("Idle.");
587                 title_prefix = "[Idle]";
588                 break;
589
590             // Connecting
591             case 1:
592                 GuacamoleUI.shadeMenu();
593                 GuacamoleUI.showStatus("Connecting...");
594                 title_prefix = "[Connecting...]";
595                 break;
596
597             // Connected + waiting
598             case 2:
599                 GuacamoleUI.showStatus("Connected, waiting for first update...");
600                 title_prefix = "[Waiting...]";
601                 break;
602
603             // Connected
604             case 3:
605                 GuacamoleUI.hideStatus();
606                 title_prefix = null;
607                 break;
608
609             // Disconnecting
610             case 4:
611                 GuacamoleUI.showStatus("Disconnecting...");
612                 title_prefix = "[Disconnecting...]";
613                 break;
614
615             // Disconnected
616             case 5:
617                 GuacamoleUI.showStatus("Disconnected.");
618                 title_prefix = "[Disconnected]";
619                 break;
620
621             // Unknown status code
622             default:
623                 GuacamoleUI.showStatus("[UNKNOWN STATUS]");
624
625         }
626
627         updateTitle();
628     };
629
630     // Name instruction handler
631     guac.onname = function(name) {
632         connection_name = name;
633         updateTitle();
634     };
635
636     // Error handler
637     guac.onerror = function(error) {
638
639         // Disconnect, if connected
640         guac.disconnect();
641
642         // Display error message
643         GuacamoleUI.showError(error);
644         
645     };
646
647     // Disconnect on close
648     window.onunload = function() {
649         guac.disconnect();
650     };
651
652     // Handle clipboard events
653     GuacamoleUI.clipboard.onchange = function() {
654
655         var text = GuacamoleUI.clipboard.value;
656         guac.setClipboard(text);
657
658     };
659
660     // Ignore keypresses when clipboard is focused
661     GuacamoleUI.clipboard.onfocus = function() {
662         disableKeyboard();
663     };
664
665     // Capture keypresses when clipboard is not focused
666     GuacamoleUI.clipboard.onblur = function() {
667         enableKeyboard();
668     };
669
670     // Server copy handler
671     guac.onclipboard = function(data) {
672         GuacamoleUI.clipboard.value = data;
673     };
674
675     GuacamoleUI.keyboard.onkeydown = function(keysym) {
676         guac.sendKeyEvent(1, keysym);
677     };
678
679     GuacamoleUI.keyboard.onkeyup = function(keysym) {
680         guac.sendKeyEvent(0, keysym);
681     };
682
683     // Send Ctrl-Alt-Delete
684     GuacamoleUI.buttons.ctrlAltDelete.onclick = function() {
685
686         var KEYSYM_CTRL   = 0xFFE3;
687         var KEYSYM_ALT    = 0xFFE9;
688         var KEYSYM_DELETE = 0xFFFF;
689
690         guac.sendKeyEvent(1, KEYSYM_CTRL);
691         guac.sendKeyEvent(1, KEYSYM_ALT);
692         guac.sendKeyEvent(1, KEYSYM_DELETE);
693         guac.sendKeyEvent(0, KEYSYM_DELETE);
694         guac.sendKeyEvent(0, KEYSYM_ALT);
695         guac.sendKeyEvent(0, KEYSYM_CTRL);
696     };
697
698 };