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