Allow multi-touch gestures to cancel long press detection.
[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 touch distance from start exceeds threshold, cancel long press
387         var touch = e.touches[0];
388         if (Math.abs(touch.screenX - long_press_start_x) >= GuacamoleUI.LONG_PRESS_MOVEMENT_THRESHOLD
389             || Math.abs(touch.screenY - long_press_start_y) >= GuacamoleUI.LONG_PRESS_MOVEMENT_THRESHOLD)
390             GuacamoleUI.stopLongPressDetect();
391         
392     }, true);
393
394     // Stop detection if press stops
395     GuacamoleUI.display.addEventListener('touchend', GuacamoleUI.stopLongPressDetect, true);
396
397     // Close menu on mouse movement
398     GuacamoleUI.display.addEventListener('mousemove', GuacamoleUI.startMenuCloseDetect, true);
399     GuacamoleUI.display.addEventListener('mousedown', GuacamoleUI.startMenuCloseDetect, true);
400
401     // Reconnect button
402     GuacamoleUI.buttons.reconnect.onclick = function() {
403         window.location.reload();
404     };
405
406     // On-screen keyboard
407     GuacamoleUI.keyboard = new Guacamole.OnScreenKeyboard("layouts/en-us-qwerty-mobile.xml");
408     GuacamoleUI.containers.keyboard.appendChild(GuacamoleUI.keyboard.getElement());
409
410     // Function for automatically updating keyboard size
411     var lastKeyboardWidth;
412     function updateKeyboardSize() {
413         var currentSize = GuacamoleUI.keyboard.getElement().offsetWidth;
414         if (lastKeyboardWidth != currentSize) {
415             GuacamoleUI.keyboard.resize(currentSize);
416             lastKeyboardWidth = currentSize;
417         }
418     };
419
420     // Turn off autocorrect and autocapitalization on eventTarget
421     GuacamoleUI.eventTarget.setAttribute("autocorrect", "off");
422     GuacamoleUI.eventTarget.setAttribute("autocapitalize", "off");
423
424 })();
425
426 // Tie UI events / behavior to a specific Guacamole client
427 GuacamoleUI.attach = function(guac) {
428
429     var title_prefix = null;
430     var connection_name = "Guacamole"; 
431     
432     var guac_display = guac.getDisplay();
433
434     // Set document title appropriately, based on prefix and connection name
435     function updateTitle() {
436
437         // Use title prefix if present
438         if (title_prefix) {
439             
440             document.title = title_prefix;
441
442             // Include connection name, if present
443             if (connection_name)
444                 document.title += " " + connection_name;
445
446         }
447
448         // Otherwise, just set to connection name
449         else if (connection_name)
450             document.title = connection_name;
451
452     }
453
454     // When mouse enters display, start detection of intent to close menu
455     guac_display.addEventListener('mouseover', GuacamoleUI.startMenuCloseDetect, true);
456
457     guac_display.onclick = function(e) {
458         e.preventDefault();
459         return false;
460     };
461
462     // Mouse
463     var mouse = new Guacamole.Mouse(guac_display);
464     mouse.onmousedown = mouse.onmouseup = mouse.onmousemove =
465         function(mouseState) {
466        
467             // Determine mouse position within view
468             var mouse_view_x = mouseState.x + guac_display.offsetLeft - window.pageXOffset;
469             var mouse_view_y = mouseState.y + guac_display.offsetTop  - window.pageYOffset;
470
471             // Determine viewport dimensioins
472             var view_width  = GuacamoleUI.viewport.offsetWidth;
473             var view_height = GuacamoleUI.viewport.offsetHeight;
474
475             // Determine scroll amounts based on mouse position relative to document
476
477             var scroll_amount_x;
478             if (mouse_view_x > view_width)
479                 scroll_amount_x = mouse_view_x - view_width;
480             else if (mouse_view_x < 0)
481                 scroll_amount_x = mouse_view_x;
482             else
483                 scroll_amount_x = 0;
484
485             var scroll_amount_y;
486             if (mouse_view_y > view_height)
487                 scroll_amount_y = mouse_view_y - view_height;
488             else if (mouse_view_y < 0)
489                 scroll_amount_y = mouse_view_y;
490             else
491                 scroll_amount_y = 0;
492
493             // Scroll (if necessary) to keep mouse on screen.
494             window.scrollBy(scroll_amount_x, scroll_amount_y);
495        
496             // Send mouse event
497             guac.sendMouseState(mouseState);
498             
499         };
500
501     // Keyboard
502     var keyboard = new Guacamole.Keyboard(document);
503
504     // Monitor whether the event target is focused
505     var eventTargetFocused = false;
506
507     // Save length for calculation of changed value
508     var currentLength = GuacamoleUI.eventTarget.value.length;
509
510     GuacamoleUI.eventTarget.onfocus = function() {
511         eventTargetFocused = true;
512         GuacamoleUI.eventTarget.value = "";
513         currentLength = 0;
514     };
515
516     GuacamoleUI.eventTarget.onblur = function() {
517         eventTargetFocused = false;
518     };
519
520     // If text is input directly into event target without typing (as with
521     // voice input, for example), type automatically.
522     GuacamoleUI.eventTarget.oninput = function(e) {
523
524         // Calculate current length and change in length
525         var oldLength = currentLength;
526         currentLength = GuacamoleUI.eventTarget.value.length;
527         
528         // If deleted or replaced text, ignore
529         if (currentLength <= oldLength)
530             return;
531
532         // Get changed text
533         var text = GuacamoleUI.eventTarget.value.substring(oldLength);
534
535         // Send each character
536         for (var i=0; i<text.length; i++) {
537
538             // Get char code
539             var charCode = text.charCodeAt(i);
540
541             // Convert to keysym
542             var keysym = 0x003F; // Default to a question mark
543             if (charCode >= 0x0000 && charCode <= 0x00FF)
544                 keysym = charCode;
545             else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
546                 keysym = 0x01000000 | charCode;
547
548             // Send keysym only if not already pressed
549             if (!keyboard.pressed[keysym]) {
550
551                 // Press and release key
552                 guac.sendKeyEvent(1, keysym);
553                 guac.sendKeyEvent(0, keysym);
554
555             }
556
557         }
558
559     }
560
561     function isTypableCharacter(keysym) {
562         return (keysym & 0xFFFF00) != 0xFF00;
563     }
564
565     function disableKeyboard() {
566         keyboard.onkeydown = null;
567         keyboard.onkeyup = null;
568     }
569
570     function enableKeyboard() {
571
572         keyboard.onkeydown = function (keysym) {
573             guac.sendKeyEvent(1, keysym);
574             return eventTargetFocused && isTypableCharacter(keysym);
575         };
576
577         keyboard.onkeyup = function (keysym) {
578             guac.sendKeyEvent(0, keysym);
579             return eventTargetFocused && isTypableCharacter(keysym);
580         };
581
582     }
583
584     // Enable keyboard by default
585     enableKeyboard();
586
587     // Handle client state change
588     guac.onstatechange = function(clientState) {
589
590         switch (clientState) {
591
592             // Idle
593             case 0:
594                 GuacamoleUI.showStatus("Idle.");
595                 title_prefix = "[Idle]";
596                 break;
597
598             // Connecting
599             case 1:
600                 GuacamoleUI.shadeMenu();
601                 GuacamoleUI.showStatus("Connecting...");
602                 title_prefix = "[Connecting...]";
603                 break;
604
605             // Connected + waiting
606             case 2:
607                 GuacamoleUI.showStatus("Connected, waiting for first update...");
608                 title_prefix = "[Waiting...]";
609                 break;
610
611             // Connected
612             case 3:
613                 GuacamoleUI.hideStatus();
614                 title_prefix = null;
615                 break;
616
617             // Disconnecting
618             case 4:
619                 GuacamoleUI.showStatus("Disconnecting...");
620                 title_prefix = "[Disconnecting...]";
621                 break;
622
623             // Disconnected
624             case 5:
625                 GuacamoleUI.showStatus("Disconnected.");
626                 title_prefix = "[Disconnected]";
627                 break;
628
629             // Unknown status code
630             default:
631                 GuacamoleUI.showStatus("[UNKNOWN STATUS]");
632
633         }
634
635         updateTitle();
636     };
637
638     // Name instruction handler
639     guac.onname = function(name) {
640         connection_name = name;
641         updateTitle();
642     };
643
644     // Error handler
645     guac.onerror = function(error) {
646
647         // Disconnect, if connected
648         guac.disconnect();
649
650         // Display error message
651         GuacamoleUI.showError(error);
652         
653     };
654
655     // Disconnect on close
656     window.onunload = function() {
657         guac.disconnect();
658     };
659
660     // Handle clipboard events
661     GuacamoleUI.clipboard.onchange = function() {
662
663         var text = GuacamoleUI.clipboard.value;
664         guac.setClipboard(text);
665
666     };
667
668     // Ignore keypresses when clipboard is focused
669     GuacamoleUI.clipboard.onfocus = function() {
670         disableKeyboard();
671     };
672
673     // Capture keypresses when clipboard is not focused
674     GuacamoleUI.clipboard.onblur = function() {
675         enableKeyboard();
676     };
677
678     // Server copy handler
679     guac.onclipboard = function(data) {
680         GuacamoleUI.clipboard.value = data;
681     };
682
683     GuacamoleUI.keyboard.onkeydown = function(keysym) {
684         guac.sendKeyEvent(1, keysym);
685     };
686
687     GuacamoleUI.keyboard.onkeyup = function(keysym) {
688         guac.sendKeyEvent(0, keysym);
689     };
690
691     // Send Ctrl-Alt-Delete
692     GuacamoleUI.buttons.ctrlAltDelete.onclick = function() {
693
694         var KEYSYM_CTRL   = 0xFFE3;
695         var KEYSYM_ALT    = 0xFFE9;
696         var KEYSYM_DELETE = 0xFFFF;
697
698         guac.sendKeyEvent(1, KEYSYM_CTRL);
699         guac.sendKeyEvent(1, KEYSYM_ALT);
700         guac.sendKeyEvent(1, KEYSYM_DELETE);
701         guac.sendKeyEvent(0, KEYSYM_DELETE);
702         guac.sendKeyEvent(0, KEYSYM_ALT);
703         guac.sendKeyEvent(0, KEYSYM_CTRL);
704     };
705
706 };