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