Use event-queue heuristics to detect and ignore mouse events caused by touch events.
[guacamole-common-js.git] / src / main / resources / mouse.js
1
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
5  * The contents of this file are subject to the Mozilla Public License Version
6  * 1.1 (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  * http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS" basis,
11  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12  * for the specific language governing rights and limitations under the
13  * License.
14  *
15  * The Original Code is guacamole-common-js.
16  *
17  * The Initial Developer of the Original Code is
18  * Michael Jumper.
19  * Portions created by the Initial Developer are Copyright (C) 2010
20  * the Initial Developer. All Rights Reserved.
21  *
22  * Contributor(s):
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 // Guacamole namespace
39 var Guacamole = Guacamole || {};
40
41 /**
42  * Provides cross-browser mouse events for a given element. The events of
43  * the given element are automatically populated with handlers that translate
44  * mouse events into a non-browser-specific event provided by the
45  * Guacamole.Mouse instance.
46  * 
47  * @constructor
48  * @param {Element} element The Element to use to provide mouse events.
49  */
50 Guacamole.Mouse = function(element) {
51
52     /**
53      * Reference to this Guacamole.Mouse.
54      * @private
55      */
56     var guac_mouse = this;
57
58     /**
59      * The current mouse state. The properties of this state are updated when
60      * mouse events fire. This state object is also passed in as a parameter to
61      * the handler of any mouse events.
62      * 
63      * @type Guacamole.Mouse.State
64      */
65     this.currentState = new Guacamole.Mouse.State(
66         0, 0, 
67         false, false, false, false, false
68     );
69
70     /**
71      * Fired whenever the user presses a mouse button down over the element
72      * associated with this Guacamole.Mouse.
73      * 
74      * @event
75      * @param {Guacamole.Mouse.State} state The current mouse state.
76      */
77         this.onmousedown = null;
78
79     /**
80      * Fired whenever the user releases a mouse button down over the element
81      * associated with this Guacamole.Mouse.
82      * 
83      * @event
84      * @param {Guacamole.Mouse.State} state The current mouse state.
85      */
86         this.onmouseup = null;
87
88     /**
89      * Fired whenever the user moves the mouse over the element associated with
90      * this Guacamole.Mouse.
91      * 
92      * @event
93      * @param {Guacamole.Mouse.State} state The current mouse state.
94      */
95         this.onmousemove = null;
96
97     /**
98      * Zero-delay timeout set when mouse events are fired, and canceled when
99      * touch events are detected, in order to prevent touch events registering
100      * as mouse events (some browsers will do this).
101      */
102     var deferred_mouse_event = null;
103
104     /**
105      * Flag which, when set to true, will cause all mouse events to be
106      * ignored. Used to temporarily ignore events when generated by
107      * touch events, and not by a mouse.
108      */
109     var ignore_mouse = false;
110
111     /**
112      * Forces all mouse events to be ignored until the event queue is flushed.
113      */
114     function ignorePendingMouseEvents() {
115
116         // Cancel deferred event
117         if (deferred_mouse_event) {
118             window.clearTimeout(deferred_mouse_event);
119             deferred_mouse_event = null;
120         }
121
122         // Ignore all other events until end of event loop
123         ignore_mouse = true;
124         window.setTimeout(function() {
125             ignore_mouse = false;
126         }, 0);
127
128     }
129
130     function cancelEvent(e) {
131         e.stopPropagation();
132         if (e.preventDefault) e.preventDefault();
133         e.returnValue = false;
134     }
135
136     function moveMouse(clientX, clientY) {
137
138         guac_mouse.currentState.x = clientX - element.offsetLeft;
139         guac_mouse.currentState.y = clientY - element.offsetTop;
140
141         // This is all JUST so we can get the mouse position within the element
142         var parent = element.offsetParent;
143         while (parent && !(parent === document.body)) {
144             guac_mouse.currentState.x -= parent.offsetLeft - parent.scrollLeft;
145             guac_mouse.currentState.y -= parent.offsetTop  - parent.scrollTop;
146
147             parent = parent.offsetParent;
148         }
149
150         // Offset by document scroll amount
151         var documentScrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
152         var documentScrollTop = document.body.scrollTop || document.documentElement.scrollTop;
153
154         guac_mouse.currentState.x -= parent.offsetLeft - documentScrollLeft;
155         guac_mouse.currentState.y -= parent.offsetTop  - documentScrollTop;
156
157         if (guac_mouse.onmousemove)
158             deferred_mouse_event = window.setTimeout(function() {
159                 guac_mouse.onmousemove(guac_mouse.currentState);
160                 deferred_mouse_event = null;
161             }, 0);
162
163     }
164
165
166     // Block context menu so right-click gets sent properly
167     element.addEventListener("contextmenu", function(e) {
168         cancelEvent(e);
169     }, false);
170
171     element.addEventListener("mousemove", function(e) {
172
173         cancelEvent(e);
174
175         // If artificial event detected, ignore currently pending events
176         if (deferred_mouse_event)
177             ignorePendingMouseEvents();
178
179         if (ignore_mouse)
180             return;
181
182         moveMouse(e.clientX, e.clientY);
183
184     }, false);
185
186     element.addEventListener("mousedown", function(e) {
187
188         cancelEvent(e);
189
190         // If artificial event detected, ignore currently pending events
191         if (deferred_mouse_event)
192             ignorePendingMouseEvents();
193
194         if (ignore_mouse)
195             return;
196
197         switch (e.button) {
198             case 0:
199                 guac_mouse.currentState.left = true;
200                 break;
201             case 1:
202                 guac_mouse.currentState.middle = true;
203                 break;
204             case 2:
205                 guac_mouse.currentState.right = true;
206                 break;
207         }
208
209         if (guac_mouse.onmousedown)
210             deferred_mouse_event = window.setTimeout(function() {
211                 guac_mouse.onmousedown(guac_mouse.currentState);
212                 deferred_mouse_event = null;
213             }, 0);
214
215     }, false);
216
217     element.addEventListener("mouseup", function(e) {
218
219         cancelEvent(e);
220
221         // If artificial event detected, ignore currently pending events
222         if (deferred_mouse_event)
223             ignorePendingMouseEvents();
224
225         if (ignore_mouse)
226             return;
227
228         switch (e.button) {
229             case 0:
230                 guac_mouse.currentState.left = false;
231                 break;
232             case 1:
233                 guac_mouse.currentState.middle = false;
234                 break;
235             case 2:
236                 guac_mouse.currentState.right = false;
237                 break;
238         }
239
240         if (guac_mouse.onmouseup)
241             deferred_mouse_event = window.setTimeout(function() {
242                 guac_mouse.onmouseup(guac_mouse.currentState);
243                 deferred_mouse_event = null;
244             }, 0);
245
246     }, false);
247
248     element.addEventListener("mouseout", function(e) {
249
250         // Get parent of the element the mouse pointer is leaving
251         if (!e) e = window.event;
252
253         // Check that mouseout is due to actually LEAVING the element
254         var target = e.relatedTarget || e.toElement;
255         while (target != null) {
256             if (target === element)
257                 return;
258             target = target.parentNode;
259         }
260
261         cancelEvent(e);
262
263         // Release all buttons
264         if (guac_mouse.currentState.left
265             || guac_mouse.currentState.middle
266             || guac_mouse.currentState.right) {
267
268             guac_mouse.currentState.left = false;
269             guac_mouse.currentState.middle = false;
270             guac_mouse.currentState.right = false;
271
272             if (guac_mouse.onmouseup)
273                 guac_mouse.onmouseup(guac_mouse.currentState);
274         }
275
276     }, false);
277
278     // Override selection on mouse event element.
279     element.addEventListener("selectstart", function(e) {
280         cancelEvent(e);
281     }, false);
282
283
284     // Ignore all pending mouse events when touch events are the apparent source
285     element.addEventListener("touchmove",  ignorePendingMouseEvents, false);
286     element.addEventListener("touchstart", ignorePendingMouseEvents, false);
287     element.addEventListener("touchend",   ignorePendingMouseEvents, false);
288
289     // Scroll wheel support
290     function mousewheel_handler(e) {
291
292         var delta = 0;
293         if (e.detail)
294             delta = e.detail;
295         else if (e.wheelDelta)
296             delta = -event.wheelDelta;
297
298         // Up
299         if (delta < 0) {
300             if (guac_mouse.onmousedown) {
301                 guac_mouse.currentState.up = true;
302                 guac_mouse.onmousedown(guac_mouse.currentState);
303             }
304
305             if (guac_mouse.onmouseup) {
306                 guac_mouse.currentState.up = false;
307                 guac_mouse.onmouseup(guac_mouse.currentState);
308             }
309         }
310
311         // Down
312         if (delta > 0) {
313             if (guac_mouse.onmousedown) {
314                 guac_mouse.currentState.down = true;
315                 guac_mouse.onmousedown(guac_mouse.currentState);
316             }
317
318             if (guac_mouse.onmouseup) {
319                 guac_mouse.currentState.down = false;
320                 guac_mouse.onmouseup(guac_mouse.currentState);
321             }
322         }
323
324         cancelEvent(e);
325
326     }
327     element.addEventListener('DOMMouseScroll', mousewheel_handler, false);
328     element.addEventListener('mousewheel',     mousewheel_handler, false);
329
330 };
331
332
333 /**
334  * Provides cross-browser relative touch event translation for a given element.
335  * 
336  * Touch events are translated into mouse events as if the touches occurred
337  * on a touchpad (drag to push the mouse pointer, tap to click).
338  * 
339  * @constructor
340  * @param {Element} element The Element to use to provide touch events.
341  */
342 Guacamole.Mouse.Touchpad = function(element) {
343
344     /**
345      * Reference to this Guacamole.Mouse.Touchpad.
346      * @private
347      */
348     var guac_touchpad = this;
349
350     /**
351      * The distance a two-finger touch must move per scrollwheel event, in
352      * pixels.
353      */
354     this.scrollThreshold = 20 * (window.devicePixelRatio || 1);
355
356     /**
357      * The maximum number of milliseconds to wait for a touch to end for the
358      * gesture to be considered a click.
359      */
360     this.clickTimingThreshold = 250;
361
362     /**
363      * The maximum number of pixels to allow a touch to move for the gesture to
364      * be considered a click.
365      */
366     this.clickMoveThreshold = 10 * (window.devicePixelRatio || 1);
367
368     /**
369      * The current mouse state. The properties of this state are updated when
370      * mouse events fire. This state object is also passed in as a parameter to
371      * the handler of any mouse events.
372      * 
373      * @type Guacamole.Mouse.State
374      */
375     this.currentState = new Guacamole.Mouse.State(
376         0, 0, 
377         false, false, false, false, false
378     );
379
380     /**
381      * Fired whenever a mouse button is effectively pressed. This can happen
382      * as part of a "click" gesture initiated by the user by tapping one
383      * or more fingers over the touchpad element, as part of a "scroll"
384      * gesture initiated by dragging two fingers up or down, etc.
385      * 
386      * @event
387      * @param {Guacamole.Mouse.State} state The current mouse state.
388      */
389         this.onmousedown = null;
390
391     /**
392      * Fired whenever a mouse button is effectively released. This can happen
393      * as part of a "click" gesture initiated by the user by tapping one
394      * or more fingers over the touchpad element, as part of a "scroll"
395      * gesture initiated by dragging two fingers up or down, etc.
396      * 
397      * @event
398      * @param {Guacamole.Mouse.State} state The current mouse state.
399      */
400         this.onmouseup = null;
401
402     /**
403      * Fired whenever the user moves the mouse by dragging their finger over
404      * the touchpad element.
405      * 
406      * @event
407      * @param {Guacamole.Mouse.State} state The current mouse state.
408      */
409         this.onmousemove = null;
410
411     var touch_count = 0;
412     var last_touch_x = 0;
413     var last_touch_y = 0;
414     var last_touch_time = 0;
415     var pixels_moved = 0;
416
417     var touch_buttons = {
418         1: "left",
419         2: "right",
420         3: "middle"
421     };
422
423     var gesture_in_progress = false;
424     var click_release_timeout = null;
425
426     element.addEventListener("touchend", function(e) {
427         
428         e.stopPropagation();
429         e.preventDefault();
430             
431         // If we're handling a gesture AND this is the last touch
432         if (gesture_in_progress && e.touches.length == 0) {
433             
434             var time = new Date().getTime();
435
436             // Get corresponding mouse button
437             var button = touch_buttons[touch_count];
438
439             // If mouse already down, release anad clear timeout
440             if (guac_touchpad.currentState[button]) {
441
442                 // Fire button up event
443                 guac_touchpad.currentState[button] = false;
444                 if (guac_touchpad.onmouseup)
445                     guac_touchpad.onmouseup(guac_touchpad.currentState);
446
447                 // Clear timeout, if set
448                 if (click_release_timeout) {
449                     window.clearTimeout(click_release_timeout);
450                     click_release_timeout = null;
451                 }
452
453             }
454
455             // If single tap detected (based on time and distance)
456             if (time - last_touch_time <= guac_touchpad.clickTimingThreshold
457                     && pixels_moved < guac_touchpad.clickMoveThreshold) {
458
459                 // Fire button down event
460                 guac_touchpad.currentState[button] = true;
461                 if (guac_touchpad.onmousedown)
462                     guac_touchpad.onmousedown(guac_touchpad.currentState);
463
464                 // Delay mouse up - mouse up should be canceled if
465                 // touchstart within timeout.
466                 click_release_timeout = window.setTimeout(function() {
467                     
468                     // Fire button up event
469                     guac_touchpad.currentState[button] = false;
470                     if (guac_touchpad.onmouseup)
471                         guac_touchpad.onmouseup(guac_touchpad.currentState);
472                     
473                     // Gesture now over
474                     gesture_in_progress = false;
475
476                 }, guac_touchpad.clickTimingThreshold);
477
478             }
479
480             // If we're not waiting to see if this is a click, stop gesture
481             if (!click_release_timeout)
482                 gesture_in_progress = false;
483
484         }
485
486     }, false);
487
488     element.addEventListener("touchstart", function(e) {
489
490         e.stopPropagation();
491         e.preventDefault();
492
493         // Track number of touches, but no more than three
494         touch_count = Math.min(e.touches.length, 3);
495
496         // Clear timeout, if set
497         if (click_release_timeout) {
498             window.clearTimeout(click_release_timeout);
499             click_release_timeout = null;
500         }
501
502         // Record initial touch location and time for touch movement
503         // and tap gestures
504         if (!gesture_in_progress) {
505
506             // Stop mouse events while touching
507             gesture_in_progress = true;
508
509             // Record touch location and time
510             var starting_touch = e.touches[0];
511             last_touch_x = starting_touch.clientX;
512             last_touch_y = starting_touch.clientY;
513             last_touch_time = new Date().getTime();
514             pixels_moved = 0;
515
516         }
517
518     }, false);
519
520     element.addEventListener("touchmove", function(e) {
521
522         e.stopPropagation();
523         e.preventDefault();
524
525         // Get change in touch location
526         var touch = e.touches[0];
527         var delta_x = touch.clientX - last_touch_x;
528         var delta_y = touch.clientY - last_touch_y;
529
530         // Track pixels moved
531         pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
532
533         // If only one touch involved, this is mouse move
534         if (touch_count == 1) {
535
536             // Calculate average velocity in Manhatten pixels per millisecond
537             var velocity = pixels_moved / (new Date().getTime() - last_touch_time);
538
539             // Scale mouse movement relative to velocity
540             var scale = 1 + velocity;
541
542             // Update mouse location
543             guac_touchpad.currentState.x += delta_x*scale;
544             guac_touchpad.currentState.y += delta_y*scale;
545
546             // Prevent mouse from leaving screen
547
548             if (guac_touchpad.currentState.x < 0)
549                 guac_touchpad.currentState.x = 0;
550             else if (guac_touchpad.currentState.x >= element.offsetWidth)
551                 guac_touchpad.currentState.x = element.offsetWidth - 1;
552
553             if (guac_touchpad.currentState.y < 0)
554                 guac_touchpad.currentState.y = 0;
555             else if (guac_touchpad.currentState.y >= element.offsetHeight)
556                 guac_touchpad.currentState.y = element.offsetHeight - 1;
557
558             // Fire movement event, if defined
559             if (guac_touchpad.onmousemove)
560                 guac_touchpad.onmousemove(guac_touchpad.currentState);
561
562             // Update touch location
563             last_touch_x = touch.clientX;
564             last_touch_y = touch.clientY;
565
566         }
567
568         // Interpret two-finger swipe as scrollwheel
569         else if (touch_count == 2) {
570
571             // If change in location passes threshold for scroll
572             if (Math.abs(delta_y) >= guac_touchpad.scrollThreshold) {
573
574                 // Decide button based on Y movement direction
575                 var button;
576                 if (delta_y > 0) button = "down";
577                 else             button = "up";
578
579                 // Fire button down event
580                 guac_touchpad.currentState[button] = true;
581                 if (guac_touchpad.onmousedown)
582                     guac_touchpad.onmousedown(guac_touchpad.currentState);
583
584                 // Fire button up event
585                 guac_touchpad.currentState[button] = false;
586                 if (guac_touchpad.onmouseup)
587                     guac_touchpad.onmouseup(guac_touchpad.currentState);
588
589                 // Only update touch location after a scroll has been
590                 // detected
591                 last_touch_x = touch.clientX;
592                 last_touch_y = touch.clientY;
593
594             }
595
596         }
597
598     }, false);
599
600 };
601
602 /**
603  * Provides cross-browser absolute touch event translation for a given element.
604  * 
605  * Touch events are translated into mouse events as if the touches occurred
606  * on a touchscreen (tapping anywhere on the screen clicks at that point,
607  * long-press to right-click).
608  * 
609  * @constructor
610  * @param {Element} element The Element to use to provide touch events.
611  */
612 Guacamole.Mouse.Touchscreen = function(element) {
613
614     /**
615      * Reference to this Guacamole.Mouse.Touchscreen.
616      * @private
617      */
618     var guac_touchscreen = this;
619
620     /**
621      * The distance a two-finger touch must move per scrollwheel event, in
622      * pixels.
623      */
624     this.scrollThreshold = 20 * (window.devicePixelRatio || 1);
625
626     /**
627      * The current mouse state. The properties of this state are updated when
628      * mouse events fire. This state object is also passed in as a parameter to
629      * the handler of any mouse events.
630      * 
631      * @type Guacamole.Mouse.State
632      */
633     this.currentState = new Guacamole.Mouse.State(
634         0, 0, 
635         false, false, false, false, false
636     );
637
638     /**
639      * Fired whenever a mouse button is effectively pressed. This can happen
640      * as part of a "mousedown" gesture initiated by the user by pressing one
641      * finger over the touchscreen element, as part of a "scroll" gesture
642      * initiated by dragging two fingers up or down, etc.
643      * 
644      * @event
645      * @param {Guacamole.Mouse.State} state The current mouse state.
646      */
647         this.onmousedown = null;
648
649     /**
650      * Fired whenever a mouse button is effectively released. This can happen
651      * as part of a "mouseup" gesture initiated by the user by removing the
652      * finger pressed against the touchscreen element, or as part of a "scroll"
653      * gesture initiated by dragging two fingers up or down, etc.
654      * 
655      * @event
656      * @param {Guacamole.Mouse.State} state The current mouse state.
657      */
658         this.onmouseup = null;
659
660     /**
661      * Fired whenever the user moves the mouse by dragging their finger over
662      * the touchscreen element. Note that unlike Guacamole.Mouse.Touchpad,
663      * dragging a finger over the touchscreen element will always cause
664      * the mouse button to be effectively down, as if clicking-and-dragging.
665      * 
666      * @event
667      * @param {Guacamole.Mouse.State} state The current mouse state.
668      */
669         this.onmousemove = null;
670
671     element.addEventListener("touchend", function(e) {
672         
673         e.stopPropagation();
674         e.preventDefault();
675
676         // Release button
677         guac_touchscreen.currentState.left = false;
678
679         // Fire release event when the last touch is released, if event defined
680         if (e.touches.length == 0 && guac_touchscreen.onmouseup)
681             guac_touchscreen.onmouseup(guac_touchscreen.currentState);
682
683     }, false);
684
685     element.addEventListener("touchstart", function(e) {
686
687         e.stopPropagation();
688         e.preventDefault();
689
690         // Get touch
691         var touch = e.touches[0];
692
693         // Update state
694         guac_touchscreen.currentState.left = true;
695         guac_touchscreen.currentState.x = touch.clientX;
696         guac_touchscreen.currentState.y = touch.clientY;
697
698         // Fire press event, if defined
699         if (guac_touchscreen.onmousedown)
700             guac_touchscreen.onmousedown(guac_touchscreen.currentState);
701
702
703     }, false);
704
705     element.addEventListener("touchmove", function(e) {
706
707         e.stopPropagation();
708         e.preventDefault();
709
710         // Get touch
711         var touch = e.touches[0];
712
713         // Update state
714         guac_touchscreen.currentState.x = touch.clientX;
715         guac_touchscreen.currentState.y = touch.clientY;
716
717         // Fire movement event, if defined
718         if (guac_touchscreen.onmousemove)
719             guac_touchscreen.onmousemove(guac_touchscreen.currentState);
720
721     }, false);
722
723 };
724
725 /**
726  * Simple container for properties describing the state of a mouse.
727  * 
728  * @constructor
729  * @param {Number} x The X position of the mouse pointer in pixels.
730  * @param {Number} y The Y position of the mouse pointer in pixels.
731  * @param {Boolean} left Whether the left mouse button is pressed. 
732  * @param {Boolean} middle Whether the middle mouse button is pressed. 
733  * @param {Boolean} right Whether the right mouse button is pressed. 
734  * @param {Boolean} up Whether the up mouse button is pressed (the fourth
735  *                     button, usually part of a scroll wheel). 
736  * @param {Boolean} down Whether the down mouse button is pressed (the fifth
737  *                       button, usually part of a scroll wheel). 
738  */
739 Guacamole.Mouse.State = function(x, y, left, middle, right, up, down) {
740
741     /**
742      * The current X position of the mouse pointer.
743      * @type Number
744      */
745     this.x = x;
746
747     /**
748      * The current Y position of the mouse pointer.
749      * @type Number
750      */
751     this.y = y;
752
753     /**
754      * Whether the left mouse button is currently pressed.
755      * @type Boolean
756      */
757     this.left = left;
758
759     /**
760      * Whether the middle mouse button is currently pressed.
761      * @type Boolean
762      */
763     this.middle = middle
764
765     /**
766      * Whether the right mouse button is currently pressed.
767      * @type Boolean
768      */
769     this.right = right;
770
771     /**
772      * Whether the up mouse button is currently pressed. This is the fourth
773      * mouse button, associated with upward scrolling of the mouse scroll
774      * wheel.
775      * @type Boolean
776      */
777     this.up = up;
778
779     /**
780      * Whether the down mouse button is currently pressed. This is the fifth 
781      * mouse button, associated with downward scrolling of the mouse scroll
782      * wheel.
783      * @type Boolean
784      */
785     this.down = down;
786     
787 };
788