Set scroll and click thresholds relative to screen pixel density (if readable) and...
[guacamole-common-js.git] / src / main / resources / mouse.js
index 211759d..5475793 100644 (file)
@@ -1,21 +1,39 @@
 
-/*
- *  Guacamole - Clientless Remote Desktop
- *  Copyright (C) 2010  Michael Jumper
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  *
- *  This program is free software: you can redistribute it and/or modify
- *  it under the terms of the GNU Affero General Public License as published by
- *  the Free Software Foundation, either version 3 of the License, or
- *  (at your option) any later version.
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
  *
- *  This program is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU Affero General Public License for more details.
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
  *
- *  You should have received a copy of the GNU Affero General Public License
- *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
+ * The Original Code is guacamole-common-js.
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Jumper.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
 
 // Guacamole namespace
 var Guacamole = Guacamole || {};
@@ -26,8 +44,8 @@ var Guacamole = Guacamole || {};
  * mouse events into a non-browser-specific event provided by the
  * Guacamole.Mouse instance.
  * 
- * Touch event support is planned, but currently only in testing (translate
- * touch events into mouse events).
+ * Touch events are translated into mouse events as if the touches occurred
+ * on a touchpad (drag to push the mouse pointer, tap to click).
  * 
  * @constructor
  * @param {Element} element The Element to use to provide mouse events.
@@ -41,6 +59,24 @@ Guacamole.Mouse = function(element) {
     var guac_mouse = this;
 
     /**
+     * The distance a two-finger touch must move per scrollwheel event, relative
+     * to the distance between the two touches.
+     */
+    this.scrollThreshold = 0.5;
+
+    /**
+     * The maximum number of milliseconds to wait for a touch to end for the
+     * gesture to be considered a click.
+     */
+    this.clickTimingThreshold = 250;
+
+    /**
+     * The maximum number of pixels to allow a touch to move for the gesture to
+     * be considered a click.
+     */
+    this.clickMoveThreshold = 10 * (window.displayPixelRatio || 1);
+
+    /**
      * The current mouse state. The properties of this state are updated when
      * mouse events fire. This state object is also passed in as a parameter to
      * the handler of any mouse events.
@@ -79,6 +115,12 @@ Guacamole.Mouse = function(element) {
      */
        this.onmousemove = null;
 
+    function cancelEvent(e) {
+        e.stopPropagation();
+        if (e.preventDefault) e.preventDefault();
+        e.returnValue = false;
+    }
+
     function moveMouse(pageX, pageY) {
 
         guac_mouse.currentState.x = pageX - element.offsetLeft;
@@ -87,10 +129,13 @@ Guacamole.Mouse = function(element) {
         // This is all JUST so we can get the mouse position within the element
         var parent = element.offsetParent;
         while (parent) {
-            if (parent.offsetLeft && parent.offsetTop) {
+
+            if (parent.offsetLeft)
                 guac_mouse.currentState.x -= parent.offsetLeft;
+
+            if (parent.offsetTop)
                 guac_mouse.currentState.y -= parent.offsetTop;
-            }
+
             parent = parent.offsetParent;
         }
 
@@ -101,44 +146,54 @@ Guacamole.Mouse = function(element) {
 
 
     // Block context menu so right-click gets sent properly
-    element.oncontextmenu = function(e) {
-        return false;
-    };
+    element.addEventListener("contextmenu", function(e) {
+        cancelEvent(e);
+    }, false);
 
-    element.onmousemove = function(e) {
+    element.addEventListener("mousemove", function(e) {
 
         // Don't handle if we aren't supposed to
         if (gesture_in_progress) return;
 
-        e.stopPropagation();
+        cancelEvent(e);
 
         moveMouse(e.pageX, e.pageY);
 
-    };
+    }, false);
 
+    var touch_count = 0;
     var last_touch_x = 0;
     var last_touch_y = 0;
     var last_touch_time = 0;
     var pixels_moved = 0;
+    var touch_distance = 0;
+
+    var touch_buttons = {
+        1: "left",
+        2: "right",
+        3: "middle"
+    };
 
     var gesture_in_progress = false;
     var click_release_timeout = null;
 
-    element.ontouchend = function(e) {
+    element.addEventListener("touchend", function(e) {
         
-        // If we're handling a gesture
-        if (gesture_in_progress) {
+        // If we're handling a gesture AND this is the last touch
+        if (gesture_in_progress && e.touches.length == 0) {
             
-            e.stopPropagation();
-            e.preventDefault();
+            cancelEvent(e);
             
             var time = new Date().getTime();
 
+            // Get corresponding mouse button
+            var button = touch_buttons[touch_count];
+
             // If mouse already down, release anad clear timeout
-            if (guac_mouse.currentState.left) {
+            if (guac_mouse.currentState[button]) {
 
-                // Fire left button up event
-                guac_mouse.currentState.left = false;
+                // Fire button up event
+                guac_mouse.currentState[button] = false;
                 if (guac_mouse.onmouseup)
                     guac_mouse.onmouseup(guac_mouse.currentState);
 
@@ -151,10 +206,11 @@ Guacamole.Mouse = function(element) {
             }
 
             // If single tap detected (based on time and distance)
-            if (time - last_touch_time <= 250 && pixels_moved < 10) {
+            if (time - last_touch_time <= guac_mouse.clickTimingThreshold
+                    && pixels_moved < guac_mouse.clickMoveThreshold) {
 
-                // Fire left button down event
-                guac_mouse.currentState.left = true;
+                // Fire button down event
+                guac_mouse.currentState[button] = true;
                 if (guac_mouse.onmousedown)
                     guac_mouse.onmousedown(guac_mouse.currentState);
 
@@ -162,30 +218,32 @@ Guacamole.Mouse = function(element) {
                 // touchstart within timeout.
                 click_release_timeout = window.setTimeout(function() {
                     
-                    // Fire left button up event
-                    guac_mouse.currentState.left = false;
+                    // Fire button up event
+                    guac_mouse.currentState[button] = false;
                     if (guac_mouse.onmouseup)
                         guac_mouse.onmouseup(guac_mouse.currentState);
                     
                     // Allow mouse events now that touching is over
                     gesture_in_progress = false;
             
-                }, 250);
+                }, guac_mouse.clickTimingThreshold);
 
             }
 
         }
 
-    };
+    }, false);
+
+    element.addEventListener("touchstart", function(e) {
 
-    element.ontouchstart = function(e) {
+        // Track number of touches, but no more than three
+        touch_count = Math.min(e.touches.length, 3);
 
-        // Record initial touch location and time for single-touch movement
+        // Record initial touch location and time for touch movement
         // and tap gestures
         if (e.touches.length == 1) {
 
-            e.stopPropagation();
-            e.preventDefault();
+            cancelEvent(e);
 
             // Stop mouse events while touching
             gesture_in_progress = true;
@@ -198,58 +256,101 @@ Guacamole.Mouse = function(element) {
 
             // Record touch location and time
             var starting_touch = e.touches[0];
-            last_touch_x = starting_touch.pageX;
-            last_touch_y = starting_touch.pageY;
+            last_touch_x = starting_touch.screenX;
+            last_touch_y = starting_touch.screenY;
             last_touch_time = new Date().getTime();
             pixels_moved = 0;
 
-            // TODO: Handle different buttons
+        }
 
+        else if (e.touches.length == 2) {
+            var diff_x = e.touches[0].screenX - e.touches[1].screenX;
+            var diff_y = e.touches[0].screenY - e.touches[1].screenY;
+            touch_distance = Math.sqrt(diff_x*diff_x + diff_y*diff_y);
         }
 
-    };
+    }, false);
 
-    element.ontouchmove = function(e) {
+    element.addEventListener("touchmove", function(e) {
 
-        // Handle single-touch movement gesture (touchpad mouse move)
-        if (e.touches.length == 1) {
+        cancelEvent(e);
 
-            e.stopPropagation();
-            e.preventDefault();
+        // Get change in touch location
+        var touch = e.touches[0];
+        var delta_x = touch.screenX - last_touch_x;
+        var delta_y = touch.screenY - last_touch_y;
 
-            // Get change in touch location
-            var touch = e.touches[0];
-            var delta_x = touch.pageX - last_touch_x;
-            var delta_y = touch.pageY - last_touch_y;
+        // Track pixels moved
+        pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
 
-            // Track pixels moved
-            pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
+        // If only one touch involved, this is mouse move
+        if (touch_count == 1) {
 
             // Update mouse location
             guac_mouse.currentState.x += delta_x;
             guac_mouse.currentState.y += delta_y;
 
-            // FIXME: Prevent mouse from leaving screen
+            // Prevent mouse from leaving screen
+
+            if (guac_mouse.currentState.x < 0)
+                guac_mouse.currentState.x = 0;
+            else if (guac_mouse.currentState.x >= element.offsetWidth)
+                guac_mouse.currentState.x = element.offsetWidth - 1;
+
+            if (guac_mouse.currentState.y < 0)
+                guac_mouse.currentState.y = 0;
+            else if (guac_mouse.currentState.y >= element.offsetHeight)
+                guac_mouse.currentState.y = element.offsetHeight - 1;
 
             // Fire movement event, if defined
             if (guac_mouse.onmousemove)
                 guac_mouse.onmousemove(guac_mouse.currentState);
 
             // Update touch location
-            last_touch_x = touch.pageX;
-            last_touch_y = touch.pageY;
+            last_touch_x = touch.screenX;
+            last_touch_y = touch.screenY;
 
         }
 
-    };
+        // Interpret two-finger touch as scrollwheel
+        else if (touch_count == 2) {
+
+            // If change in location passes threshold for scroll
+            if (Math.abs(delta_y) >= touch_distance * guac_mouse.scrollThreshold) {
+
+                // Decide button based on Y movement direction
+                var button;
+                if (delta_y > 0) button = "down";
+                else             button = "up";
+
+                // Fire button down event
+                guac_mouse.currentState[button] = true;
+                if (guac_mouse.onmousedown)
+                    guac_mouse.onmousedown(guac_mouse.currentState);
+
+                // Fire button up event
+                guac_mouse.currentState[button] = false;
+                if (guac_mouse.onmouseup)
+                    guac_mouse.onmouseup(guac_mouse.currentState);
+
+                // Only update touch location after a scroll has been
+                // detected
+                last_touch_x = touch.screenX;
+                last_touch_y = touch.screenY;
+
+            }
+
+        }
 
+    }, false);
 
-    element.onmousedown = function(e) {
+
+    element.addEventListener("mousedown", function(e) {
 
         // Don't handle if we aren't supposed to
         if (gesture_in_progress) return;
 
-        e.stopPropagation();
+        cancelEvent(e);
 
         switch (e.button) {
             case 0:
@@ -266,15 +367,15 @@ Guacamole.Mouse = function(element) {
         if (guac_mouse.onmousedown)
             guac_mouse.onmousedown(guac_mouse.currentState);
 
-    };
+    }, false);
 
 
-    element.onmouseup = function(e) {
+    element.addEventListener("mouseup", function(e) {
 
         // Don't handle if we aren't supposed to
         if (gesture_in_progress) return;
 
-        e.stopPropagation();
+        cancelEvent(e);
 
         switch (e.button) {
             case 0:
@@ -291,14 +392,25 @@ Guacamole.Mouse = function(element) {
         if (guac_mouse.onmouseup)
             guac_mouse.onmouseup(guac_mouse.currentState);
 
-    };
+    }, false);
 
-    element.onmouseout = function(e) {
+    element.addEventListener("mouseout", function(e) {
 
         // Don't handle if we aren't supposed to
         if (gesture_in_progress) return;
 
-        e.stopPropagation();
+        // Get parent of the element the mouse pointer is leaving
+               if (!e) e = window.event;
+
+        // Check that mouseout is due to actually LEAVING the element
+        var target = e.relatedTarget || e.toElement;
+        while (target != null) {
+            if (target === element)
+                return;
+            target = target.parentNode;
+        }
+
+        cancelEvent(e);
 
         // Release all buttons
         if (guac_mouse.currentState.left
@@ -313,15 +425,15 @@ Guacamole.Mouse = function(element) {
                 guac_mouse.onmouseup(guac_mouse.currentState);
         }
 
-    };
+    }, false);
 
     // Override selection on mouse event element.
-    element.onselectstart = function() {
-        return false;
-    };
+    element.addEventListener("selectstart", function(e) {
+        cancelEvent(e);
+    }, false);
 
     // Scroll wheel support
-    element.onmousewheel = function(e) {
+    function mousewheel_handler(e) {
 
         // Don't handle if we aren't supposed to
         if (gesture_in_progress) return;
@@ -358,14 +470,11 @@ Guacamole.Mouse = function(element) {
             }
         }
 
-        if (e.preventDefault)
-            e.preventDefault();
-
-        e.returnValue = false;
-
-    };
+        cancelEvent(e);
 
-    element.addEventListener('DOMMouseScroll', element.onmousewheel, false);
+    }
+    element.addEventListener('DOMMouseScroll', mousewheel_handler, false);
+    element.addEventListener('mousewheel',     mousewheel_handler, false);
 
 };