Stop long press detection when scrolling.
[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("viewport"),
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             // Get current viewport scroll
468             var scroll_x = GuacamoleUI.viewport.scrollLeft;
469             var scroll_y = GuacamoleUI.viewport.scrollTop;
470       
471             // Determine mouse position within view
472             var mouse_view_x = mouseState.x + guac_display.offsetLeft - scroll_x;
473             var mouse_view_y = mouseState.y + guac_display.offsetTop  - scroll_y;
474
475             // Determine viewport dimensioins
476             var view_width  = GuacamoleUI.viewport.offsetWidth;
477             var view_height = GuacamoleUI.viewport.offsetHeight;
478
479             // Scroll horizontally if necessary
480             if (mouse_view_x > view_width) {
481                 GuacamoleUI.viewport.scrollLeft += mouse_view_x - view_width;
482                 GuacamoleUI.stopLongPressDetect();
483             }
484             else if (mouse_view_x < 0) {
485                 GuacamoleUI.viewport.scrollLeft += mouse_view_x;
486                 GuacamoleUI.stopLongPressDetect();
487             }
488
489             // Scroll vertically if necessary
490             if (mouse_view_y > view_height) {
491                 GuacamoleUI.viewport.scrollTop += mouse_view_y - view_height;
492                 GuacamoleUI.stopLongPressDetect();
493             }
494             else if (mouse_view_y < 0) {
495                 GuacamoleUI.viewport.scrollTop += mouse_view_y;
496                 GuacamoleUI.stopLongPressDetect();
497             }
498
499             // Send mouse event
500             guac.sendMouseState(mouseState);
501             
502         };
503
504     // Keyboard
505     var keyboard = new Guacamole.Keyboard(document);
506
507     // Monitor whether the event target is focused
508     var eventTargetFocused = false;
509
510     // Save length for calculation of changed value
511     var currentLength = GuacamoleUI.eventTarget.value.length;
512
513     GuacamoleUI.eventTarget.onfocus = function() {
514         eventTargetFocused = true;
515         GuacamoleUI.eventTarget.value = "";
516         currentLength = 0;
517     };
518
519     GuacamoleUI.eventTarget.onblur = function() {
520         eventTargetFocused = false;
521     };
522
523     // If text is input directly into event target without typing (as with
524     // voice input, for example), type automatically.
525     GuacamoleUI.eventTarget.oninput = function(e) {
526
527         // Calculate current length and change in length
528         var oldLength = currentLength;
529         currentLength = GuacamoleUI.eventTarget.value.length;
530         
531         // If deleted or replaced text, ignore
532         if (currentLength <= oldLength)
533             return;
534
535         // Get changed text
536         var text = GuacamoleUI.eventTarget.value.substring(oldLength);
537
538         // Send each character
539         for (var i=0; i<text.length; i++) {
540
541             // Get char code
542             var charCode = text.charCodeAt(i);
543
544             // Convert to keysym
545             var keysym = 0x003F; // Default to a question mark
546             if (charCode >= 0x0000 && charCode <= 0x00FF)
547                 keysym = charCode;
548             else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
549                 keysym = 0x01000000 | charCode;
550
551             // Send keysym only if not already pressed
552             if (!keyboard.pressed[keysym]) {
553
554                 // Press and release key
555                 guac.sendKeyEvent(1, keysym);
556                 guac.sendKeyEvent(0, keysym);
557
558             }
559
560         }
561
562     }
563
564     function isTypableCharacter(keysym) {
565         return (keysym & 0xFFFF00) != 0xFF00;
566     }
567
568     function disableKeyboard() {
569         keyboard.onkeydown = null;
570         keyboard.onkeyup = null;
571     }
572
573     function enableKeyboard() {
574
575         keyboard.onkeydown = function (keysym) {
576             guac.sendKeyEvent(1, keysym);
577             return eventTargetFocused && isTypableCharacter(keysym);
578         };
579
580         keyboard.onkeyup = function (keysym) {
581             guac.sendKeyEvent(0, keysym);
582             return eventTargetFocused && isTypableCharacter(keysym);
583         };
584
585     }
586
587     // Enable keyboard by default
588     enableKeyboard();
589
590     // Handle client state change
591     guac.onstatechange = function(clientState) {
592
593         switch (clientState) {
594
595             // Idle
596             case 0:
597                 GuacamoleUI.showStatus("Idle.");
598                 title_prefix = "[Idle]";
599                 break;
600
601             // Connecting
602             case 1:
603                 GuacamoleUI.shadeMenu();
604                 GuacamoleUI.showStatus("Connecting...");
605                 title_prefix = "[Connecting...]";
606                 break;
607
608             // Connected + waiting
609             case 2:
610                 GuacamoleUI.showStatus("Connected, waiting for first update...");
611                 title_prefix = "[Waiting...]";
612                 break;
613
614             // Connected
615             case 3:
616                 GuacamoleUI.hideStatus();
617                 title_prefix = null;
618                 break;
619
620             // Disconnecting
621             case 4:
622                 GuacamoleUI.showStatus("Disconnecting...");
623                 title_prefix = "[Disconnecting...]";
624                 break;
625
626             // Disconnected
627             case 5:
628                 GuacamoleUI.showStatus("Disconnected.");
629                 title_prefix = "[Disconnected]";
630                 break;
631
632             // Unknown status code
633             default:
634                 GuacamoleUI.showStatus("[UNKNOWN STATUS]");
635
636         }
637
638         updateTitle();
639     };
640
641     // Name instruction handler
642     guac.onname = function(name) {
643         connection_name = name;
644         updateTitle();
645     };
646
647     // Error handler
648     guac.onerror = function(error) {
649
650         // Disconnect, if connected
651         guac.disconnect();
652
653         // Display error message
654         GuacamoleUI.showError(error);
655         
656     };
657
658     // Disconnect on close
659     window.onunload = function() {
660         guac.disconnect();
661     };
662
663     // Handle clipboard events
664     GuacamoleUI.clipboard.onchange = function() {
665
666         var text = GuacamoleUI.clipboard.value;
667         guac.setClipboard(text);
668
669     };
670
671     // Ignore keypresses when clipboard is focused
672     GuacamoleUI.clipboard.onfocus = function() {
673         disableKeyboard();
674     };
675
676     // Capture keypresses when clipboard is not focused
677     GuacamoleUI.clipboard.onblur = function() {
678         enableKeyboard();
679     };
680
681     // Server copy handler
682     guac.onclipboard = function(data) {
683         GuacamoleUI.clipboard.value = data;
684     };
685
686     GuacamoleUI.keyboard.onkeydown = function(keysym) {
687         guac.sendKeyEvent(1, keysym);
688     };
689
690     GuacamoleUI.keyboard.onkeyup = function(keysym) {
691         guac.sendKeyEvent(0, keysym);
692     };
693
694     // Send Ctrl-Alt-Delete
695     GuacamoleUI.buttons.ctrlAltDelete.onclick = function() {
696
697         var KEYSYM_CTRL   = 0xFFE3;
698         var KEYSYM_ALT    = 0xFFE9;
699         var KEYSYM_DELETE = 0xFFFF;
700
701         guac.sendKeyEvent(1, KEYSYM_CTRL);
702         guac.sendKeyEvent(1, KEYSYM_ALT);
703         guac.sendKeyEvent(1, KEYSYM_DELETE);
704         guac.sendKeyEvent(0, KEYSYM_DELETE);
705         guac.sendKeyEvent(0, KEYSYM_ALT);
706         guac.sendKeyEvent(0, KEYSYM_CTRL);
707     };
708
709 };