Fix non-left mouse button clicks (there may not be one touchstart event per touch...
[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
167     var touch_buttons = {
168         1: "left",
169         2: "right",
170         3: "middle"
171     };
172
173     var gesture_in_progress = false;
174     var click_release_timeout = null;
175
176     element.addEventListener("touchend", function(e) {
177         
178         cancelEvent(e);
179             
180         // If we're handling a gesture AND this is the last touch
181         if (gesture_in_progress && e.touches.length == 0) {
182             
183             var time = new Date().getTime();
184
185             // Get corresponding mouse button
186             var button = touch_buttons[touch_count];
187
188             // If mouse already down, release anad clear timeout
189             if (guac_mouse.currentState[button]) {
190
191                 // Fire button up event
192                 guac_mouse.currentState[button] = false;
193                 if (guac_mouse.onmouseup)
194                     guac_mouse.onmouseup(guac_mouse.currentState);
195
196                 // Clear timeout, if set
197                 if (click_release_timeout) {
198                     window.clearTimeout(click_release_timeout);
199                     click_release_timeout = null;
200                 }
201
202             }
203
204             // If single tap detected (based on time and distance)
205             if (time - last_touch_time <= guac_mouse.clickTimingThreshold
206                     && pixels_moved < guac_mouse.clickMoveThreshold) {
207
208                 // Fire button down event
209                 guac_mouse.currentState[button] = true;
210                 if (guac_mouse.onmousedown)
211                     guac_mouse.onmousedown(guac_mouse.currentState);
212
213                 // Delay mouse up - mouse up should be canceled if
214                 // touchstart within timeout.
215                 click_release_timeout = window.setTimeout(function() {
216                     
217                     // Fire button up event
218                     guac_mouse.currentState[button] = false;
219                     if (guac_mouse.onmouseup)
220                         guac_mouse.onmouseup(guac_mouse.currentState);
221                     
222                     // Gesture now over
223                     gesture_in_progress = false;
224
225                 }, guac_mouse.clickTimingThreshold);
226
227             }
228
229             // If we're not waiting to see if this is a click, stop gesture
230             if (!click_release_timeout)
231                 gesture_in_progress = false;
232
233         }
234
235     }, false);
236
237     element.addEventListener("touchstart", function(e) {
238
239         cancelEvent(e);
240
241         // Track number of touches, but no more than three
242         touch_count = Math.min(e.touches.length, 3);
243
244         // Clear timeout, if set
245         if (click_release_timeout) {
246             window.clearTimeout(click_release_timeout);
247             click_release_timeout = null;
248         }
249
250         // Record initial touch location and time for touch movement
251         // and tap gestures
252         if (!gesture_in_progress) {
253
254             // Stop mouse events while touching
255             gesture_in_progress = true;
256
257             // Record touch location and time
258             var starting_touch = e.touches[0];
259             last_touch_x = starting_touch.clientX;
260             last_touch_y = starting_touch.clientY;
261             last_touch_time = new Date().getTime();
262             pixels_moved = 0;
263
264         }
265
266     }, false);
267
268     element.addEventListener("touchmove", function(e) {
269
270         cancelEvent(e);
271
272         // Get change in touch location
273         var touch = e.touches[0];
274         var delta_x = touch.clientX - last_touch_x;
275         var delta_y = touch.clientY - last_touch_y;
276
277         // Track pixels moved
278         pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
279
280         // If only one touch involved, this is mouse move
281         if (touch_count == 1) {
282
283             // Calculate average velocity in Manhatten pixels per millisecond
284             var velocity = pixels_moved / (new Date().getTime() - last_touch_time);
285
286             // Scale mouse movement relative to velocity
287             var scale = 1 + velocity;
288
289             // Update mouse location
290             guac_mouse.currentState.x += delta_x*scale;
291             guac_mouse.currentState.y += delta_y*scale;
292
293             // Prevent mouse from leaving screen
294
295             if (guac_mouse.currentState.x < 0)
296                 guac_mouse.currentState.x = 0;
297             else if (guac_mouse.currentState.x >= element.offsetWidth)
298                 guac_mouse.currentState.x = element.offsetWidth - 1;
299
300             if (guac_mouse.currentState.y < 0)
301                 guac_mouse.currentState.y = 0;
302             else if (guac_mouse.currentState.y >= element.offsetHeight)
303                 guac_mouse.currentState.y = element.offsetHeight - 1;
304
305             // Fire movement event, if defined
306             if (guac_mouse.onmousemove)
307                 guac_mouse.onmousemove(guac_mouse.currentState);
308
309             // Update touch location
310             last_touch_x = touch.clientX;
311             last_touch_y = touch.clientY;
312
313         }
314
315         // Interpret two-finger swipe as scrollwheel
316         else if (touch_count == 2) {
317
318             // If change in location passes threshold for scroll
319             if (Math.abs(delta_y) >= guac_mouse.scrollThreshold) {
320
321                 // Decide button based on Y movement direction
322                 var button;
323                 if (delta_y > 0) button = "down";
324                 else             button = "up";
325
326                 // Fire button down event
327                 guac_mouse.currentState[button] = true;
328                 if (guac_mouse.onmousedown)
329                     guac_mouse.onmousedown(guac_mouse.currentState);
330
331                 // Fire button up event
332                 guac_mouse.currentState[button] = false;
333                 if (guac_mouse.onmouseup)
334                     guac_mouse.onmouseup(guac_mouse.currentState);
335
336                 // Only update touch location after a scroll has been
337                 // detected
338                 last_touch_x = touch.clientX;
339                 last_touch_y = touch.clientY;
340
341             }
342
343         }
344
345     }, false);
346
347
348     element.addEventListener("mousedown", function(e) {
349
350         // Don't handle if we aren't supposed to
351         if (gesture_in_progress) return;
352
353         cancelEvent(e);
354
355         switch (e.button) {
356             case 0:
357                 guac_mouse.currentState.left = true;
358                 break;
359             case 1:
360                 guac_mouse.currentState.middle = true;
361                 break;
362             case 2:
363                 guac_mouse.currentState.right = true;
364                 break;
365         }
366
367         if (guac_mouse.onmousedown)
368             guac_mouse.onmousedown(guac_mouse.currentState);
369
370     }, false);
371
372
373     element.addEventListener("mouseup", function(e) {
374
375         // Don't handle if we aren't supposed to
376         if (gesture_in_progress) return;
377
378         cancelEvent(e);
379
380         switch (e.button) {
381             case 0:
382                 guac_mouse.currentState.left = false;
383                 break;
384             case 1:
385                 guac_mouse.currentState.middle = false;
386                 break;
387             case 2:
388                 guac_mouse.currentState.right = false;
389                 break;
390         }
391
392         if (guac_mouse.onmouseup)
393             guac_mouse.onmouseup(guac_mouse.currentState);
394
395     }, false);
396
397     element.addEventListener("mouseout", function(e) {
398
399         // Don't handle if we aren't supposed to
400         if (gesture_in_progress) return;
401
402         // Get parent of the element the mouse pointer is leaving
403         if (!e) e = window.event;
404
405         // Check that mouseout is due to actually LEAVING the element
406         var target = e.relatedTarget || e.toElement;
407         while (target != null) {
408             if (target === element)
409                 return;
410             target = target.parentNode;
411         }
412
413         cancelEvent(e);
414
415         // Release all buttons
416         if (guac_mouse.currentState.left
417             || guac_mouse.currentState.middle
418             || guac_mouse.currentState.right) {
419
420             guac_mouse.currentState.left = false;
421             guac_mouse.currentState.middle = false;
422             guac_mouse.currentState.right = false;
423
424             if (guac_mouse.onmouseup)
425                 guac_mouse.onmouseup(guac_mouse.currentState);
426         }
427
428     }, false);
429
430     // Override selection on mouse event element.
431     element.addEventListener("selectstart", function(e) {
432         cancelEvent(e);
433     }, false);
434
435     // Scroll wheel support
436     function mousewheel_handler(e) {
437
438         // Don't handle if we aren't supposed to
439         if (gesture_in_progress) return;
440
441         var delta = 0;
442         if (e.detail)
443             delta = e.detail;
444         else if (e.wheelDelta)
445             delta = -event.wheelDelta;
446
447         // Up
448         if (delta < 0) {
449             if (guac_mouse.onmousedown) {
450                 guac_mouse.currentState.up = true;
451                 guac_mouse.onmousedown(guac_mouse.currentState);
452             }
453
454             if (guac_mouse.onmouseup) {
455                 guac_mouse.currentState.up = false;
456                 guac_mouse.onmouseup(guac_mouse.currentState);
457             }
458         }
459
460         // Down
461         if (delta > 0) {
462             if (guac_mouse.onmousedown) {
463                 guac_mouse.currentState.down = true;
464                 guac_mouse.onmousedown(guac_mouse.currentState);
465             }
466
467             if (guac_mouse.onmouseup) {
468                 guac_mouse.currentState.down = false;
469                 guac_mouse.onmouseup(guac_mouse.currentState);
470             }
471         }
472
473         cancelEvent(e);
474
475     }
476     element.addEventListener('DOMMouseScroll', mousewheel_handler, false);
477     element.addEventListener('mousewheel',     mousewheel_handler, false);
478
479 };
480
481 /**
482  * Simple container for properties describing the state of a mouse.
483  * 
484  * @constructor
485  * @param {Number} x The X position of the mouse pointer in pixels.
486  * @param {Number} y The Y position of the mouse pointer in pixels.
487  * @param {Boolean} left Whether the left mouse button is pressed. 
488  * @param {Boolean} middle Whether the middle mouse button is pressed. 
489  * @param {Boolean} right Whether the right mouse button is pressed. 
490  * @param {Boolean} up Whether the up mouse button is pressed (the fourth
491  *                     button, usually part of a scroll wheel). 
492  * @param {Boolean} down Whether the down mouse button is pressed (the fifth
493  *                       button, usually part of a scroll wheel). 
494  */
495 Guacamole.Mouse.State = function(x, y, left, middle, right, up, down) {
496
497     /**
498      * The current X position of the mouse pointer.
499      * @type Number
500      */
501     this.x = x;
502
503     /**
504      * The current Y position of the mouse pointer.
505      * @type Number
506      */
507     this.y = y;
508
509     /**
510      * Whether the left mouse button is currently pressed.
511      * @type Boolean
512      */
513     this.left = left;
514
515     /**
516      * Whether the middle mouse button is currently pressed.
517      * @type Boolean
518      */
519     this.middle = middle
520
521     /**
522      * Whether the right mouse button is currently pressed.
523      * @type Boolean
524      */
525     this.right = right;
526
527     /**
528      * Whether the up mouse button is currently pressed. This is the fourth
529      * mouse button, associated with upward scrolling of the mouse scroll
530      * wheel.
531      * @type Boolean
532      */
533     this.up = up;
534
535     /**
536      * Whether the down mouse button is currently pressed. This is the fifth 
537      * mouse button, associated with downward scrolling of the mouse scroll
538      * wheel.
539      * @type Boolean
540      */
541     this.down = down;
542     
543 };
544