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