Added pre-defined channel mask constants. Setting cursor layer to Guacamole.Layer...
[guacamole-common-js.git] / src / main / resources / layer.js
index 4033abd..fe93e2b 100644 (file)
 
-/*
- *  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 || {};
 
 /**
+ * Channel mask for the composite operation "rout".
+ */
+Guacamole.Layer.ROUT  = 0x2;
+
+/**
+ * Channel mask for the composite operation "atop".
+ */
+Guacamole.Layer.ATOP  = 0x6;
+
+/**
+ * Channel mask for the composite operation "xor".
+ */
+Guacamole.Layer.XOR   = 0xA;
+
+/**
+ * Channel mask for the composite operation "rover".
+ */
+Guacamole.Layer.ROVER = 0xB;
+
+/**
+ * Channel mask for the composite operation "over".
+ */
+Guacamole.Layer.OVER  = 0xE;
+
+/**
+ * Channel mask for the composite operation "plus".
+ */
+Guacamole.Layer.PLUS  = 0xF;
+
+/**
+ * Channel mask for the composite operation "rin".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.RIN   = 0x1;
+
+/**
+ * Channel mask for the composite operation "in".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.IN    = 0x4;
+
+/**
+ * Channel mask for the composite operation "out".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.OUT   = 0x8;
+
+/**
+ * Channel mask for the composite operation "ratop".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.RATOP = 0x9;
+
+/**
+ * Channel mask for the composite operation "src".
+ * Beware that WebKit-based browsers may leave the contents of the destionation
+ * layer where the source layer is transparent, despite the definition of this
+ * operation.
+ */
+Guacamole.Layer.SRC   = 0xC;
+
+/**
  * Abstract ordered drawing surface. Each Layer contains a canvas element and
  * provides simple drawing instructions for drawing to that canvas element,
  * however unlike the canvas element itself, drawing operations on a Layer are
@@ -48,15 +136,13 @@ Guacamole.Layer = function(width, height) {
      * @private
      */
     var display = document.createElement("canvas");
-    display.style.position = "absolute";
-    display.style.left = "0px";
-    display.style.top = "0px";
 
     /**
      * The 2D display context of the canvas element backing this Layer.
      * @private
      */
     var displayContext = display.getContext("2d");
+    displayContext.save();
 
     /**
      * The queue of all pending Tasks. Tasks will be run in order, with new
@@ -99,9 +185,36 @@ Guacamole.Layer = function(width, height) {
      * @param {Number} newHeight The new height to assign to this Layer.
      */
     function resize(newWidth, newHeight) {
+
+
+        // Only preserve old data if width/height are both non-zero
+        var oldData = null;
+        if (width != 0 && height != 0) {
+
+            // Create canvas and context for holding old data
+            oldData = document.createElement("canvas");
+            oldData.width = width;
+            oldData.height = height;
+
+            var oldDataContext = oldData.getContext("2d");
+
+            // Copy image data from current
+            oldDataContext.drawImage(display,
+                    0, 0, width, height,
+                    0, 0, width, height);
+
+        }
+
+        // Resize canvas
         display.width = newWidth;
         display.height = newHeight;
 
+        // Redraw old data, if any
+        if (oldData)
+                displayContext.drawImage(oldData, 
+                    0, 0, width, height,
+                    0, 0, width, height);
+
         width = newWidth;
         height = newHeight;
     }
@@ -158,16 +271,34 @@ Guacamole.Layer = function(width, height) {
      * @private
      * @param {function} taskHandler The function to call when this task 
      *                               runs, if any.
+     * @param {boolean} blocked Whether this task should start blocked.
      */
-    function Task(taskHandler) {
-        
+    function Task(taskHandler, blocked) {
+       
+        var task = this;
+       
+        /**
+         * Whether this Task is blocked.
+         * 
+         * @type boolean
+         */
+        this.blocked = blocked;
+
         /**
          * The handler this Task is associated with, if any.
          * 
          * @type function
          */
         this.handler = taskHandler;
-        
+       
+        /**
+         * Unblocks this Task, allowing it to run.
+         */
+        this.unblock = function() {
+            task.blocked = false;
+            handlePendingTasks();
+        }
+
     }
 
     /**
@@ -177,26 +308,29 @@ Guacamole.Layer = function(width, height) {
      * 
      * @private
      * @param {function} handler The function to call when possible, if any.
+     * @param {boolean} blocked Whether the task should start blocked.
      * @returns {Task} The Task created and added to the queue for future
      *                 running, if any, or null if the handler was run
      *                 immediately and no Task needed to be created.
      */
-    function scheduleTask(handler) {
+    function scheduleTask(handler, blocked) {
         
         // If no pending tasks, just call (if available) and exit
-        if (layer.isReady() && handler != null) {
-            handler();
+        if (layer.isReady() && !blocked) {
+            if (handler) handler();
             return null;
         }
 
         // If tasks are pending/executing, schedule a pending task
         // and return a reference to it.
-        var task = new Task(handler);
+        var task = new Task(handler, blocked);
         tasks.push(task);
         return task;
         
     }
 
+    var tasksInProgress = false;
+
     /**
      * Run any Tasks which were pending but are now ready to run and are not
      * blocked by other Tasks.
@@ -204,13 +338,20 @@ Guacamole.Layer = function(width, height) {
      */
     function handlePendingTasks() {
 
+        if (tasksInProgress)
+            return;
+
+        tasksInProgress = true;
+
         // Draw all pending tasks.
         var task;
-        while ((task = tasks[0]) != null && task.handler) {
-            task.handler();
+        while ((task = tasks[0]) != null && !task.blocked) {
             tasks.shift();
+            if (task.handler) task.handler();
         }
 
+        tasksInProgress = false;
+
     }
 
     /**
@@ -278,7 +419,7 @@ Guacamole.Layer = function(width, height) {
      */
     this.drawImage = function(x, y, image) {
         scheduleTask(function() {
-            if (autosize != 0) fitRect(x, y, image.width, image.height);
+            if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
             displayContext.drawImage(image, x, y);
         });
     };
@@ -293,21 +434,14 @@ Guacamole.Layer = function(width, height) {
      * @param {String} url The URL of the image to draw.
      */
     this.draw = function(x, y, url) {
-        var task = scheduleTask(null);
-
-        var image = new Image();
-        image.onload = function() {
 
-            task.handler = function() {
-                if (autosize != 0) fitRect(x, y, image.width, image.height);
-                displayContext.drawImage(image, x, y);
-            };
-
-            // As this task originally had no handler and may have blocked
-            // other tasks, handle any blocked tasks.
-            handlePendingTasks();
+        var task = scheduleTask(function() {
+            if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
+            displayContext.drawImage(image, x, y);
+        }, true);
 
-        };
+        var image = new Image();
+        image.onload = task.unblock;
         image.src = url;
 
     };
@@ -318,10 +452,9 @@ Guacamole.Layer = function(width, height) {
      * 
      * @param {function} handler The function to call once all currently
      *                           pending operations are complete.
+     * @param {boolean} blocked Whether the task should start blocked.
      */
-    this.sync = function(handler) {
-        scheduleTask(handler);
-    };
+    this.sync = scheduleTask;
 
     /**
      * Copy a rectangle of image data from one Layer to this Layer. This
@@ -346,9 +479,22 @@ Guacamole.Layer = function(width, height) {
      */
     this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
 
+        var drawComplete = false;
+        var srcLock = null;
+
         function doCopyRect() {
-            if (autosize != 0) fitRect(x, y, srcw, srch);
-            displayContext.drawImage(srcLayer, srcx, srcy, srcw, srch, x, y, srcw, srch);
+            if (layer.autosize != 0) fitRect(x, y, srcw, srch);
+
+            var srcCanvas = srcLayer.getCanvas();
+            if (srcCanvas.width != 0 && srcCanvas.height != 0)
+                displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
+
+            // Unblock the source layer now that draw is complete
+            if (srcLock != null) 
+                srcLock.unblock();
+
+            // Flag operation as done
+            drawComplete = true;
         }
 
         // If we ARE the source layer, no need to sync.
@@ -358,16 +504,21 @@ Guacamole.Layer = function(width, height) {
 
         // Otherwise synchronize copy operation with source layer
         else {
-            var task = scheduleTask(null);
-            srcLayer.sync(function() {
-                
-                task.handler = doCopyRect;
+            
+            // Currently blocked draw task
+            var task = scheduleTask(doCopyRect, true);
 
-                // As this task originally had no handler and may have blocked
-                // other tasks, handle any blocked tasks.
-                handlePendingTasks();
+            // Unblock draw task once source layer is ready
+            srcLayer.sync(task.unblock);
+
+            // Block source layer until draw completes
+            // Note that the draw MAY have already been performed at this point,
+            // in which case creating a lock on the source layer will lead to
+            // deadlock (the draw task has already run and will thus never
+            // clear the lock)
+            if (!drawComplete)
+                srcLock = srcLayer.sync(null, true);
 
-            });
         }
 
     };
@@ -384,12 +535,62 @@ Guacamole.Layer = function(width, height) {
      */
     this.clearRect = function(x, y, w, h) {
         scheduleTask(function() {
-            if (autosize != 0) fitRect(x, y, w, h);
+            if (layer.autosize != 0) fitRect(x, y, w, h);
             displayContext.clearRect(x, y, w, h);
         });
     };
 
     /**
+     * Fill the specified rectangle of image data with the specified color.
+     * 
+     * @param {Number} x The X coordinate of the upper-left corner of the
+     *                   rectangle to draw.
+     * @param {Number} y The Y coordinate of the upper-left corner of the
+     *                   rectangle to draw.
+     * @param {Number} w The width of the rectangle to draw.
+     * @param {Number} h The height of the rectangle to draw.
+     * @param {Number} r The red component of the color of the rectangle.
+     * @param {Number} g The green component of the color of the rectangle.
+     * @param {Number} b The blue component of the color of the rectangle.
+     * @param {Number} a The alpha component of the color of the rectangle.
+     */
+    this.drawRect = function(x, y, w, h, r, g, b, a) {
+        scheduleTask(function() {
+            if (layer.autosize != 0) fitRect(x, y, w, h);
+            displayContext.fillStyle = "rgba("
+                        + r + "," + g + "," + b + "," + a / 255 + ")";
+            displayContext.fillRect(x, y, w, h);
+        });
+    };
+
+    /**
+     * Clip all future drawing operations by the specified rectangle.
+     * 
+     * @param {Number} x The X coordinate of the upper-left corner of the
+     *                   rectangle to use for the clipping region.
+     * @param {Number} y The Y coordinate of the upper-left corner of the
+     *                   rectangle to use for the clipping region.
+     * @param {Number} w The width of the rectangle to use for the clipping region.
+     * @param {Number} h The height of the rectangle to use for the clipping region.
+     */
+    this.clipRect = function(x, y, w, h) {
+        scheduleTask(function() {
+
+            // Clear any current clipping region
+            displayContext.restore();
+            displayContext.save();
+
+            if (layer.autosize != 0) fitRect(x, y, w, h);
+
+            // Set new clipping region
+            displayContext.beginPath();
+            displayContext.rect(x, y, w, h);
+            displayContext.clip();
+
+        });
+    };
+
+    /**
      * Provides the given filtering function with a writable snapshot of
      * image data and the current width and height of the Layer.
      * 
@@ -427,7 +628,7 @@ Guacamole.Layer = function(width, height) {
     };
 
     // Initialize canvas dimensions
-    resize(width, height);
-
-}
+    display.width = width;
+    display.height = height;
 
+};