a0c39797e277f951b351655f8714b35ac9c3be40
[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     function cancelEvent(e) {
98         e.stopPropagation();
99         if (e.preventDefault) e.preventDefault();
100         e.returnValue = false;
101     }
102
103     function moveMouse(clientX, clientY) {
104
105         guac_mouse.currentState.x = clientX - element.offsetLeft;
106         guac_mouse.currentState.y = clientY - element.offsetTop;
107
108         // This is all JUST so we can get the mouse position within the element
109         var parent = element.offsetParent;
110         while (parent && !(parent === document.body)) {
111             guac_mouse.currentState.x -= parent.offsetLeft - parent.scrollLeft;
112             guac_mouse.currentState.y -= parent.offsetTop  - parent.scrollTop;
113
114             parent = parent.offsetParent;
115         }
116
117         // Offset by document scroll amount
118         var documentScrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
119         var documentScrollTop = document.body.scrollTop || document.documentElement.scrollTop;
120
121         guac_mouse.currentState.x -= parent.offsetLeft - documentScrollLeft;
122         guac_mouse.currentState.y -= parent.offsetTop  - documentScrollTop;
123
124         if (guac_mouse.onmousemove)
125             guac_mouse.onmousemove(guac_mouse.currentState);
126
127     }
128
129
130     // Block context menu so right-click gets sent properly
131     element.addEventListener("contextmenu", function(e) {
132         cancelEvent(e);
133     }, false);
134
135     element.addEventListener("mousemove", function(e) {
136
137         cancelEvent(e);
138
139         moveMouse(e.clientX, e.clientY);
140
141     }, false);
142
143     element.addEventListener("mousedown", function(e) {
144
145         cancelEvent(e);
146
147         switch (e.button) {
148             case 0:
149                 guac_mouse.currentState.left = true;
150                 break;
151             case 1:
152                 guac_mouse.currentState.middle = true;
153                 break;
154             case 2:
155                 guac_mouse.currentState.right = true;
156                 break;
157         }
158
159         if (guac_mouse.onmousedown)
160             guac_mouse.onmousedown(guac_mouse.currentState);
161
162     }, false);
163
164     element.addEventListener("mouseup", function(e) {
165
166         cancelEvent(e);
167
168         switch (e.button) {
169             case 0:
170                 guac_mouse.currentState.left = false;
171                 break;
172             case 1:
173                 guac_mouse.currentState.middle = false;
174                 break;
175             case 2:
176                 guac_mouse.currentState.right = false;
177                 break;
178         }
179
180         if (guac_mouse.onmouseup)
181             guac_mouse.onmouseup(guac_mouse.currentState);
182
183     }, false);
184
185     element.addEventListener("mouseout", function(e) {
186
187         // Get parent of the element the mouse pointer is leaving
188         if (!e) e = window.event;
189
190         // Check that mouseout is due to actually LEAVING the element
191         var target = e.relatedTarget || e.toElement;
192         while (target != null) {
193             if (target === element)
194                 return;
195             target = target.parentNode;
196         }
197
198         cancelEvent(e);
199
200         // Release all buttons
201         if (guac_mouse.currentState.left
202             || guac_mouse.currentState.middle
203             || guac_mouse.currentState.right) {
204
205             guac_mouse.currentState.left = false;
206             guac_mouse.currentState.middle = false;
207             guac_mouse.currentState.right = false;
208
209             if (guac_mouse.onmouseup)
210                 guac_mouse.onmouseup(guac_mouse.currentState);
211         }
212
213     }, false);
214
215     // Override selection on mouse event element.
216     element.addEventListener("selectstart", function(e) {
217         cancelEvent(e);
218     }, false);
219
220     // Scroll wheel support
221     function mousewheel_handler(e) {
222
223         var delta = 0;
224         if (e.detail)
225             delta = e.detail;
226         else if (e.wheelDelta)
227             delta = -event.wheelDelta;
228
229         // Up
230         if (delta < 0) {
231             if (guac_mouse.onmousedown) {
232                 guac_mouse.currentState.up = true;
233                 guac_mouse.onmousedown(guac_mouse.currentState);
234             }
235
236             if (guac_mouse.onmouseup) {
237                 guac_mouse.currentState.up = false;
238                 guac_mouse.onmouseup(guac_mouse.currentState);
239             }
240         }
241
242         // Down
243         if (delta > 0) {
244             if (guac_mouse.onmousedown) {
245                 guac_mouse.currentState.down = true;
246                 guac_mouse.onmousedown(guac_mouse.currentState);
247             }
248
249             if (guac_mouse.onmouseup) {
250                 guac_mouse.currentState.down = false;
251                 guac_mouse.onmouseup(guac_mouse.currentState);
252             }
253         }
254
255         cancelEvent(e);
256
257     }
258     element.addEventListener('DOMMouseScroll', mousewheel_handler, false);
259     element.addEventListener('mousewheel',     mousewheel_handler, false);
260
261 };
262
263
264 /**
265  * Provides cross-browser touch event translation for a given element.
266  * 
267  * Touch events are translated into mouse events as if the touches occurred
268  * on a touchpad (drag to push the mouse pointer, tap to click).
269  * 
270  * @constructor
271  * @param {Element} element The Element to use to provide touch events.
272  */
273 Guacamole.Mouse.Touchpad = function(element) {
274
275     /**
276      * Reference to this Guacamole.Mouse.Touchpad.
277      * @private
278      */
279     var guac_touchpad = this;
280
281     /**
282      * The distance a two-finger touch must move per scrollwheel event, in
283      * pixels.
284      */
285     this.scrollThreshold = 20 * (window.devicePixelRatio || 1);
286
287     /**
288      * The maximum number of milliseconds to wait for a touch to end for the
289      * gesture to be considered a click.
290      */
291     this.clickTimingThreshold = 250;
292
293     /**
294      * The maximum number of pixels to allow a touch to move for the gesture to
295      * be considered a click.
296      */
297     this.clickMoveThreshold = 10 * (window.devicePixelRatio || 1);
298
299     /**
300      * The current mouse state. The properties of this state are updated when
301      * mouse events fire. This state object is also passed in as a parameter to
302      * the handler of any mouse events.
303      * 
304      * @type Guacamole.Mouse.State
305      */
306     this.currentState = new Guacamole.Mouse.State(
307         0, 0, 
308         false, false, false, false, false
309     );
310
311     /**
312      * Fired whenever a mouse button is effectively pressed. This can happen
313      * as part of a "click" gesture initiated by the user by tapping one
314      * or more fingers over the touchpad element, as part of a "scroll"
315      * gesture initiated by dragging two fingers up or down, etc.
316      * 
317      * @event
318      * @param {Guacamole.Mouse.State} state The current mouse state.
319      */
320         this.onmousedown = null;
321
322     /**
323      * Fired whenever a mouse button is effectively released. This can happen
324      * as part of a "click" gesture initiated by the user by tapping one
325      * or more fingers over the touchpad element, as part of a "scroll"
326      * gesture initiated by dragging two fingers up or down, etc.
327      * 
328      * @event
329      * @param {Guacamole.Mouse.State} state The current mouse state.
330      */
331         this.onmouseup = null;
332
333     /**
334      * Fired whenever the user moves the mouse by dragging their finger over
335      * the touchpad element.
336      * 
337      * @event
338      * @param {Guacamole.Mouse.State} state The current mouse state.
339      */
340         this.onmousemove = null;
341
342     var touch_count = 0;
343     var last_touch_x = 0;
344     var last_touch_y = 0;
345     var last_touch_time = 0;
346     var pixels_moved = 0;
347
348     var touch_buttons = {
349         1: "left",
350         2: "right",
351         3: "middle"
352     };
353
354     var gesture_in_progress = false;
355     var click_release_timeout = null;
356
357     element.addEventListener("touchend", function(e) {
358         
359         e.stopPropagation();
360         e.preventDefault();
361             
362         // If we're handling a gesture AND this is the last touch
363         if (gesture_in_progress && e.touches.length == 0) {
364             
365             var time = new Date().getTime();
366
367             // Get corresponding mouse button
368             var button = touch_buttons[touch_count];
369
370             // If mouse already down, release anad clear timeout
371             if (guac_touchpad.currentState[button]) {
372
373                 // Fire button up event
374                 guac_touchpad.currentState[button] = false;
375                 if (guac_touchpad.onmouseup)
376                     guac_touchpad.onmouseup(guac_touchpad.currentState);
377
378                 // Clear timeout, if set
379                 if (click_release_timeout) {
380                     window.clearTimeout(click_release_timeout);
381                     click_release_timeout = null;
382                 }
383
384             }
385
386             // If single tap detected (based on time and distance)
387             if (time - last_touch_time <= guac_touchpad.clickTimingThreshold
388                     && pixels_moved < guac_touchpad.clickMoveThreshold) {
389
390                 // Fire button down event
391                 guac_touchpad.currentState[button] = true;
392                 if (guac_touchpad.onmousedown)
393                     guac_touchpad.onmousedown(guac_touchpad.currentState);
394
395                 // Delay mouse up - mouse up should be canceled if
396                 // touchstart within timeout.
397                 click_release_timeout = window.setTimeout(function() {
398                     
399                     // Fire button up event
400                     guac_touchpad.currentState[button] = false;
401                     if (guac_touchpad.onmouseup)
402                         guac_touchpad.onmouseup(guac_touchpad.currentState);
403                     
404                     // Gesture now over
405                     gesture_in_progress = false;
406
407                 }, guac_touchpad.clickTimingThreshold);
408
409             }
410
411             // If we're not waiting to see if this is a click, stop gesture
412             if (!click_release_timeout)
413                 gesture_in_progress = false;
414
415         }
416
417     }, false);
418
419     element.addEventListener("touchstart", function(e) {
420
421         e.stopPropagation();
422         e.preventDefault();
423
424         // Track number of touches, but no more than three
425         touch_count = Math.min(e.touches.length, 3);
426
427         // Clear timeout, if set
428         if (click_release_timeout) {
429             window.clearTimeout(click_release_timeout);
430             click_release_timeout = null;
431         }
432
433         // Record initial touch location and time for touch movement
434         // and tap gestures
435         if (!gesture_in_progress) {
436
437             // Stop mouse events while touching
438             gesture_in_progress = true;
439
440             // Record touch location and time
441             var starting_touch = e.touches[0];
442             last_touch_x = starting_touch.clientX;
443             last_touch_y = starting_touch.clientY;
444             last_touch_time = new Date().getTime();
445             pixels_moved = 0;
446
447         }
448
449     }, false);
450
451     element.addEventListener("touchmove", function(e) {
452
453         e.stopPropagation();
454         e.preventDefault();
455
456         // Get change in touch location
457         var touch = e.touches[0];
458         var delta_x = touch.clientX - last_touch_x;
459         var delta_y = touch.clientY - last_touch_y;
460
461         // Track pixels moved
462         pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
463
464         // If only one touch involved, this is mouse move
465         if (touch_count == 1) {
466
467             // Calculate average velocity in Manhatten pixels per millisecond
468             var velocity = pixels_moved / (new Date().getTime() - last_touch_time);
469
470             // Scale mouse movement relative to velocity
471             var scale = 1 + velocity;
472
473             // Update mouse location
474             guac_touchpad.currentState.x += delta_x*scale;
475             guac_touchpad.currentState.y += delta_y*scale;
476
477             // Prevent mouse from leaving screen
478
479             if (guac_touchpad.currentState.x < 0)
480                 guac_touchpad.currentState.x = 0;
481             else if (guac_touchpad.currentState.x >= element.offsetWidth)
482                 guac_touchpad.currentState.x = element.offsetWidth - 1;
483
484             if (guac_touchpad.currentState.y < 0)
485                 guac_touchpad.currentState.y = 0;
486             else if (guac_touchpad.currentState.y >= element.offsetHeight)
487                 guac_touchpad.currentState.y = element.offsetHeight - 1;
488
489             // Fire movement event, if defined
490             if (guac_touchpad.onmousemove)
491                 guac_touchpad.onmousemove(guac_touchpad.currentState);
492
493             // Update touch location
494             last_touch_x = touch.clientX;
495             last_touch_y = touch.clientY;
496
497         }
498
499         // Interpret two-finger swipe as scrollwheel
500         else if (touch_count == 2) {
501
502             // If change in location passes threshold for scroll
503             if (Math.abs(delta_y) >= guac_touchpad.scrollThreshold) {
504
505                 // Decide button based on Y movement direction
506                 var button;
507                 if (delta_y > 0) button = "down";
508                 else             button = "up";
509
510                 // Fire button down event
511                 guac_touchpad.currentState[button] = true;
512                 if (guac_touchpad.onmousedown)
513                     guac_touchpad.onmousedown(guac_touchpad.currentState);
514
515                 // Fire button up event
516                 guac_touchpad.currentState[button] = false;
517                 if (guac_touchpad.onmouseup)
518                     guac_touchpad.onmouseup(guac_touchpad.currentState);
519
520                 // Only update touch location after a scroll has been
521                 // detected
522                 last_touch_x = touch.clientX;
523                 last_touch_y = touch.clientY;
524
525             }
526
527         }
528
529     }, false);
530
531 };
532
533 /**
534  * Simple container for properties describing the state of a mouse.
535  * 
536  * @constructor
537  * @param {Number} x The X position of the mouse pointer in pixels.
538  * @param {Number} y The Y position of the mouse pointer in pixels.
539  * @param {Boolean} left Whether the left mouse button is pressed. 
540  * @param {Boolean} middle Whether the middle mouse button is pressed. 
541  * @param {Boolean} right Whether the right mouse button is pressed. 
542  * @param {Boolean} up Whether the up mouse button is pressed (the fourth
543  *                     button, usually part of a scroll wheel). 
544  * @param {Boolean} down Whether the down mouse button is pressed (the fifth
545  *                       button, usually part of a scroll wheel). 
546  */
547 Guacamole.Mouse.State = function(x, y, left, middle, right, up, down) {
548
549     /**
550      * The current X position of the mouse pointer.
551      * @type Number
552      */
553     this.x = x;
554
555     /**
556      * The current Y position of the mouse pointer.
557      * @type Number
558      */
559     this.y = y;
560
561     /**
562      * Whether the left mouse button is currently pressed.
563      * @type Boolean
564      */
565     this.left = left;
566
567     /**
568      * Whether the middle mouse button is currently pressed.
569      * @type Boolean
570      */
571     this.middle = middle
572
573     /**
574      * Whether the right mouse button is currently pressed.
575      * @type Boolean
576      */
577     this.right = right;
578
579     /**
580      * Whether the up mouse button is currently pressed. This is the fourth
581      * mouse button, associated with upward scrolling of the mouse scroll
582      * wheel.
583      * @type Boolean
584      */
585     this.up = up;
586
587     /**
588      * Whether the down mouse button is currently pressed. This is the fifth 
589      * mouse button, associated with downward scrolling of the mouse scroll
590      * wheel.
591      * @type Boolean
592      */
593     this.down = down;
594     
595 };
596