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