Split Guacamole.Mouse into Guacamole.Mouse (mouse event handling) and Guacamole.Mouse...
[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.
277      * @private
278      */
279     var guac_mouse = 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 the user presses a mouse button down over the element
313      * associated with this Guacamole.Mouse.
314      * 
315      * @event
316      * @param {Guacamole.Mouse.State} state The current mouse state.
317      */
318         this.onmousedown = null;
319
320     /**
321      * Fired whenever the user releases a mouse button down over the element
322      * associated with this Guacamole.Mouse.
323      * 
324      * @event
325      * @param {Guacamole.Mouse.State} state The current mouse state.
326      */
327         this.onmouseup = null;
328
329     /**
330      * Fired whenever the user moves the mouse over the element associated with
331      * this Guacamole.Mouse.
332      * 
333      * @event
334      * @param {Guacamole.Mouse.State} state The current mouse state.
335      */
336         this.onmousemove = null;
337
338     function cancelEvent(e) {
339         e.stopPropagation();
340         if (e.preventDefault) e.preventDefault();
341         e.returnValue = false;
342     }
343
344     var touch_count = 0;
345     var last_touch_x = 0;
346     var last_touch_y = 0;
347     var last_touch_time = 0;
348     var pixels_moved = 0;
349
350     var touch_buttons = {
351         1: "left",
352         2: "right",
353         3: "middle"
354     };
355
356     var gesture_in_progress = false;
357     var click_release_timeout = null;
358
359     element.addEventListener("touchend", function(e) {
360         
361         cancelEvent(e);
362             
363         // If we're handling a gesture AND this is the last touch
364         if (gesture_in_progress && e.touches.length == 0) {
365             
366             var time = new Date().getTime();
367
368             // Get corresponding mouse button
369             var button = touch_buttons[touch_count];
370
371             // If mouse already down, release anad clear timeout
372             if (guac_mouse.currentState[button]) {
373
374                 // Fire button up event
375                 guac_mouse.currentState[button] = false;
376                 if (guac_mouse.onmouseup)
377                     guac_mouse.onmouseup(guac_mouse.currentState);
378
379                 // Clear timeout, if set
380                 if (click_release_timeout) {
381                     window.clearTimeout(click_release_timeout);
382                     click_release_timeout = null;
383                 }
384
385             }
386
387             // If single tap detected (based on time and distance)
388             if (time - last_touch_time <= guac_mouse.clickTimingThreshold
389                     && pixels_moved < guac_mouse.clickMoveThreshold) {
390
391                 // Fire button down event
392                 guac_mouse.currentState[button] = true;
393                 if (guac_mouse.onmousedown)
394                     guac_mouse.onmousedown(guac_mouse.currentState);
395
396                 // Delay mouse up - mouse up should be canceled if
397                 // touchstart within timeout.
398                 click_release_timeout = window.setTimeout(function() {
399                     
400                     // Fire button up event
401                     guac_mouse.currentState[button] = false;
402                     if (guac_mouse.onmouseup)
403                         guac_mouse.onmouseup(guac_mouse.currentState);
404                     
405                     // Gesture now over
406                     gesture_in_progress = false;
407
408                 }, guac_mouse.clickTimingThreshold);
409
410             }
411
412             // If we're not waiting to see if this is a click, stop gesture
413             if (!click_release_timeout)
414                 gesture_in_progress = false;
415
416         }
417
418     }, false);
419
420     element.addEventListener("touchstart", function(e) {
421
422         cancelEvent(e);
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         cancelEvent(e);
454
455         // Get change in touch location
456         var touch = e.touches[0];
457         var delta_x = touch.clientX - last_touch_x;
458         var delta_y = touch.clientY - last_touch_y;
459
460         // Track pixels moved
461         pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
462
463         // If only one touch involved, this is mouse move
464         if (touch_count == 1) {
465
466             // Calculate average velocity in Manhatten pixels per millisecond
467             var velocity = pixels_moved / (new Date().getTime() - last_touch_time);
468
469             // Scale mouse movement relative to velocity
470             var scale = 1 + velocity;
471
472             // Update mouse location
473             guac_mouse.currentState.x += delta_x*scale;
474             guac_mouse.currentState.y += delta_y*scale;
475
476             // Prevent mouse from leaving screen
477
478             if (guac_mouse.currentState.x < 0)
479                 guac_mouse.currentState.x = 0;
480             else if (guac_mouse.currentState.x >= element.offsetWidth)
481                 guac_mouse.currentState.x = element.offsetWidth - 1;
482
483             if (guac_mouse.currentState.y < 0)
484                 guac_mouse.currentState.y = 0;
485             else if (guac_mouse.currentState.y >= element.offsetHeight)
486                 guac_mouse.currentState.y = element.offsetHeight - 1;
487
488             // Fire movement event, if defined
489             if (guac_mouse.onmousemove)
490                 guac_mouse.onmousemove(guac_mouse.currentState);
491
492             // Update touch location
493             last_touch_x = touch.clientX;
494             last_touch_y = touch.clientY;
495
496         }
497
498         // Interpret two-finger swipe as scrollwheel
499         else if (touch_count == 2) {
500
501             // If change in location passes threshold for scroll
502             if (Math.abs(delta_y) >= guac_mouse.scrollThreshold) {
503
504                 // Decide button based on Y movement direction
505                 var button;
506                 if (delta_y > 0) button = "down";
507                 else             button = "up";
508
509                 // Fire button down event
510                 guac_mouse.currentState[button] = true;
511                 if (guac_mouse.onmousedown)
512                     guac_mouse.onmousedown(guac_mouse.currentState);
513
514                 // Fire button up event
515                 guac_mouse.currentState[button] = false;
516                 if (guac_mouse.onmouseup)
517                     guac_mouse.onmouseup(guac_mouse.currentState);
518
519                 // Only update touch location after a scroll has been
520                 // detected
521                 last_touch_x = touch.clientX;
522                 last_touch_y = touch.clientY;
523
524             }
525
526         }
527
528     }, false);
529
530 };
531
532 /**
533  * Simple container for properties describing the state of a mouse.
534  * 
535  * @constructor
536  * @param {Number} x The X position of the mouse pointer in pixels.
537  * @param {Number} y The Y position of the mouse pointer in pixels.
538  * @param {Boolean} left Whether the left mouse button is pressed. 
539  * @param {Boolean} middle Whether the middle mouse button is pressed. 
540  * @param {Boolean} right Whether the right mouse button is pressed. 
541  * @param {Boolean} up Whether the up mouse button is pressed (the fourth
542  *                     button, usually part of a scroll wheel). 
543  * @param {Boolean} down Whether the down mouse button is pressed (the fifth
544  *                       button, usually part of a scroll wheel). 
545  */
546 Guacamole.Mouse.State = function(x, y, left, middle, right, up, down) {
547
548     /**
549      * The current X position of the mouse pointer.
550      * @type Number
551      */
552     this.x = x;
553
554     /**
555      * The current Y position of the mouse pointer.
556      * @type Number
557      */
558     this.y = y;
559
560     /**
561      * Whether the left mouse button is currently pressed.
562      * @type Boolean
563      */
564     this.left = left;
565
566     /**
567      * Whether the middle mouse button is currently pressed.
568      * @type Boolean
569      */
570     this.middle = middle
571
572     /**
573      * Whether the right mouse button is currently pressed.
574      * @type Boolean
575      */
576     this.right = right;
577
578     /**
579      * Whether the up mouse button is currently pressed. This is the fourth
580      * mouse button, associated with upward scrolling of the mouse scroll
581      * wheel.
582      * @type Boolean
583      */
584     this.up = up;
585
586     /**
587      * Whether the down mouse button is currently pressed. This is the fifth 
588      * mouse button, associated with downward scrolling of the mouse scroll
589      * wheel.
590      * @type Boolean
591      */
592     this.down = down;
593     
594 };
595