Fix jsdoc, add missing documentation.
[guacamole-common-js.git] / src / main / resources / guacamole.js
index 688f225..d566a3d 100644 (file)
@@ -1,22 +1,60 @@
 
-/*
- *  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
+ * 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):
+ * Matt Hortman
+ *
+ * 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 ***** */
+
+/**
+ * Namespace for all Guacamole JavaScript objects.
+ * @namespace
  */
+var Guacamole = Guacamole || {};
 
-function GuacamoleClient(display, tunnel) {
+
+/**
+ * Guacamole protocol client. Given a display element and {@link Guacamole.Tunnel},
+ * automatically handles incoming and outgoing Guacamole instructions via the
+ * provided tunnel, updating the display using one or more canvas elements.
+ * 
+ * @constructor
+ * @param {Guacamole.Tunnel} tunnel The tunnel to use to send and receive
+ *                                  Guacamole instructions.
+ */
+Guacamole.Client = function(tunnel) {
+
+    var guac_client = this;
 
     var STATE_IDLE          = 0;
     var STATE_CONNECTING    = 1;
@@ -26,224 +64,564 @@ function GuacamoleClient(display, tunnel) {
     var STATE_DISCONNECTED  = 5;
 
     var currentState = STATE_IDLE;
-    var stateChangeHandler = null;
+    
+    var currentTimestamp = 0;
+    var pingInterval = null;
+
+    var displayWidth = 0;
+    var displayHeight = 0;
+    var displayScale = 1;
+
+    /**
+     * Translation from Guacamole protocol line caps to Layer line caps.
+     * @private
+     */
+    var lineCap = {
+        0: "butt",
+        1: "round",
+        2: "square"
+    };
 
-    tunnel.setInstructionHandler(doInstruction);
+    /**
+     * Translation from Guacamole protocol line caps to Layer line caps.
+     * @private
+     */
+    var lineJoin = {
+        0: "bevel",
+        1: "miter",
+        2: "round"
+    };
 
-    // Display must be relatively positioned for mouse to be handled properly
+    // Create bounding div 
+    var bounds = document.createElement("div");
+    bounds.style.position = "relative";
+    bounds.style.width = (displayWidth*displayScale) + "px";
+    bounds.style.height = (displayHeight*displayScale) + "px";
+
+    // Create display
+    var display = document.createElement("div");
     display.style.position = "relative";
+    display.style.width = displayWidth + "px";
+    display.style.height = displayHeight + "px";
+
+    // Ensure transformations on display originate at 0,0
+    display.style.transformOrigin =
+    display.style.webkitTransformOrigin =
+    display.style.MozTransformOrigin =
+    display.style.OTransformOrigin =
+    display.style.msTransformOrigin =
+        "0 0";
+
+    // Create default layer
+    var default_layer_container = new Guacamole.Client.LayerContainer(displayWidth, displayHeight);
+
+    // Position default layer
+    var default_layer_container_element = default_layer_container.getElement();
+    default_layer_container_element.style.position = "absolute";
+    default_layer_container_element.style.left = "0px";
+    default_layer_container_element.style.top  = "0px";
+    default_layer_container_element.style.overflow = "hidden";
+
+    // Create cursor layer
+    var cursor = new Guacamole.Client.LayerContainer(0, 0);
+    cursor.getLayer().setChannelMask(Guacamole.Layer.SRC);
+
+    // Position cursor layer
+    var cursor_element = cursor.getElement();
+    cursor_element.style.position = "absolute";
+    cursor_element.style.left = "0px";
+    cursor_element.style.top  = "0px";
+
+    // Add default layer and cursor to display
+    display.appendChild(default_layer_container.getElement());
+    display.appendChild(cursor.getElement());
+
+    // Add display to bounds
+    bounds.appendChild(display);
+
+    // Initially, only default layer exists
+    var layers =  [default_layer_container];
+
+    // No initial buffers
+    var buffers = [];
+
+    tunnel.onerror = function(message) {
+        if (guac_client.onerror)
+            guac_client.onerror(message);
+    };
 
     function setState(state) {
         if (state != currentState) {
             currentState = state;
-            if (stateChangeHandler)
-                stateChangeHandler(currentState);
+            if (guac_client.onstatechange)
+                guac_client.onstatechange(currentState);
         }
     }
 
-    this.setOnStateChangeHandler = function(handler) {
-        stateChangeHandler = handler;
-    };
-
     function isConnected() {
         return currentState == STATE_CONNECTED
             || currentState == STATE_WAITING;
     }
 
-    var cursorImage = null;
     var cursorHotspotX = 0;
     var cursorHotspotY = 0;
 
-    // FIXME: Make object. Clean up.
-    var cursorRectX = 0;
-    var cursorRectY = 0;
-    var cursorRectW = 0;
-    var cursorRectH = 0;
-
-    var cursorHidden = 0;
+    var cursorX = 0;
+    var cursorY = 0;
 
-    function redrawCursor(x, y) {
-
-        // Hide hardware cursor
-        if (cursorHidden == 0) {
-            display.className += " guac-hide-cursor";
-            cursorHidden = 1;
-        }
+    function moveCursor(x, y) {
 
-        // Erase old cursor
-        cursor.clearRect(cursorRectX, cursorRectY, cursorRectW, cursorRectH);
+        // Move cursor layer
+        cursor.translate(x - cursorHotspotX, y - cursorHotspotY);
 
-        // Update rect
-        cursorRectX = x - cursorHotspotX;
-        cursorRectY = y - cursorHotspotY;
-        cursorRectW = cursorImage.width;
-        cursorRectH = cursorImage.height;
+        // Update stored position
+        cursorX = x;
+        cursorY = y;
 
-        // Draw new cursor
-        cursor.drawImage(cursorRectX, cursorRectY, cursorImage);
     }
 
+    /**
+     * Returns an element containing the display of this Guacamole.Client.
+     * Adding the element returned by this function to an element in the body
+     * of a document will cause the client's display to be visible.
+     * 
+     * @return {Element} An element containing ths display of this
+     *                   Guacamole.Client.
+     */
+    this.getDisplay = function() {
+        return bounds;
+    };
+
+    /**
+     * Sends a key event having the given properties as if the user
+     * pressed or released a key.
+     * 
+     * @param {Boolean} pressed Whether the key is pressed (true) or released
+     *                          (false).
+     * @param {Number} keysym The keysym of the key being pressed or released.
+     */
     this.sendKeyEvent = function(pressed, keysym) {
         // Do not send requests if not connected
         if (!isConnected())
             return;
 
-        tunnel.sendMessage("key:" +  keysym + "," + pressed + ";");
+        tunnel.sendMessage("key", keysym, pressed);
     };
 
+    /**
+     * Sends a mouse event having the properties provided by the given mouse
+     * state.
+     * 
+     * @param {Guacamole.Mouse.State} mouseState The state of the mouse to send
+     *                                           in the mouse event.
+     */
     this.sendMouseState = function(mouseState) {
 
         // Do not send requests if not connected
         if (!isConnected())
             return;
 
-        // Draw client-side cursor
-        if (cursorImage != null) {
-            redrawCursor(
-                mouseState.getX(),
-                mouseState.getY()
-            );
-        }
+        // Update client-side cursor
+        moveCursor(
+            Math.floor(mouseState.x),
+            Math.floor(mouseState.y)
+        );
 
         // Build mask
         var buttonMask = 0;
-        if (mouseState.getLeft())   buttonMask |= 1;
-        if (mouseState.getMiddle()) buttonMask |= 2;
-        if (mouseState.getRight())  buttonMask |= 4;
-        if (mouseState.getUp())     buttonMask |= 8;
-        if (mouseState.getDown())   buttonMask |= 16;
+        if (mouseState.left)   buttonMask |= 1;
+        if (mouseState.middle) buttonMask |= 2;
+        if (mouseState.right)  buttonMask |= 4;
+        if (mouseState.up)     buttonMask |= 8;
+        if (mouseState.down)   buttonMask |= 16;
 
         // Send message
-        tunnel.sendMessage("mouse:" + mouseState.getX() + "," + mouseState.getY() + "," + buttonMask + ";");
+        tunnel.sendMessage("mouse", Math.floor(mouseState.x), Math.floor(mouseState.y), buttonMask);
     };
 
+    /**
+     * Sets the clipboard of the remote client to the given text data.
+     * 
+     * @param {String} data The data to send as the clipboard contents.
+     */
     this.setClipboard = function(data) {
 
         // Do not send requests if not connected
         if (!isConnected())
             return;
 
-        tunnel.sendMessage("clipboard:" + escapeGuacamoleString(data) + ";");
+        tunnel.sendMessage("clipboard", data);
     };
 
-    // Handlers
+    /**
+     * Fired whenever the state of this Guacamole.Client changes.
+     * 
+     * @event
+     * @param {Number} state The new state of the client.
+     */
+    this.onstatechange = null;
+
+    /**
+     * Fired when the remote client sends a name update.
+     * 
+     * @event
+     * @param {String} name The new name of this client.
+     */
+    this.onname = null;
+
+    /**
+     * Fired when an error is reported by the remote client, and the connection
+     * is being closed.
+     * 
+     * @event
+     * @param {String} error A human-readable description of the error.
+     */
+    this.onerror = null;
+
+    /**
+     * Fired when the clipboard of the remote client is changing.
+     * 
+     * @event
+     * @param {String} data The new text data of the remote clipboard.
+     */
+    this.onclipboard = null;
+
+    // Layers
+    function getBufferLayer(index) {
+
+        index = -1 - index;
+        var buffer = buffers[index];
+
+        // Create buffer if necessary
+        if (buffer == null) {
+            buffer = new Guacamole.Layer(0, 0);
+            buffer.autosize = 1;
+            buffers[index] = buffer;
+        }
+
+        return buffer;
 
-    var nameHandler = null;
-    this.setNameHandler = function(handler) {
-        nameHandler = handler;
     }
 
-    var errorHandler = null;
-    this.setErrorHandler = function(handler) {
-        errorHandler = handler;
-    };
+    function getLayerContainer(index) {
 
-    var clipboardHandler = null;
-    this.setClipboardHandler = function(handler) {
-        clipboardHandler = handler;
-    };
+        var layer = layers[index];
+        if (layer == null) {
 
-    // Layers
-    var displayWidth = 0;
-    var displayHeight = 0;
+            // Add new layer
+            layer = new Guacamole.Client.LayerContainer(displayWidth, displayHeight);
+            layers[index] = layer;
 
-    var layers = new Array();
-    var buffers = new Array();
-    var cursor = null;
+            // Get and position layer
+            var layer_element = layer.getElement();
+            layer_element.style.position = "absolute";
+            layer_element.style.left = "0px";
+            layer_element.style.top = "0px";
+            layer_element.style.overflow = "hidden";
 
-    this.getLayers = function() {
-        return layers;
-    };
+            // Add to default layer container
+            default_layer_container.getElement().appendChild(layer_element);
+
+        }
+
+        return layer;
+
+    }
 
     function getLayer(index) {
+       
+        // If buffer, just get layer
+        if (index < 0)
+            return getBufferLayer(index);
 
-        // If negative index, use buffer
-        if (index < 0) {
+        // Otherwise, retrieve layer from layer container
+        return getLayerContainer(index).getLayer();
 
-            index = -1 - index;
-            var buffer = buffers[index];
+    }
 
-            // Create buffer if necessary
-            if (buffer == null) {
-                buffer = new Layer(0, 0);
-                buffer.setAutosize(1);
-                buffers[index] = buffer;
-            }
+    /**
+     * Handlers for all defined layer properties.
+     * @private
+     */
+    var layerPropertyHandlers = {
 
-            return buffer;
+        "miter-limit": function(layer, value) {
+            layer.setMiterLimit(parseFloat(value));
         }
 
-        // If non-negative, use visible layer
-        else {
+    };
+    
+    /**
+     * Handlers for all instruction opcodes receivable by a Guacamole protocol
+     * client.
+     * @private
+     */
+    var instructionHandlers = {
 
-            var layer = layers[index];
-            if (layer == null) {
+        "arc": function(parameters) {
 
-                // Add new layer
-                layer = new Layer(displayWidth, displayHeight);
-                layers[index] = layer;
+            var layer = getLayer(parseInt(parameters[0]));
+            var x = parseInt(parameters[1]);
+            var y = parseInt(parameters[2]);
+            var radius = parseInt(parameters[3]);
+            var startAngle = parseFloat(parameters[4]);
+            var endAngle = parseFloat(parameters[5]);
+            var negative = parseInt(parameters[6]);
 
-                // (Re)-add existing layers in order
-                for (var i=0; i<layers.length; i++) {
-                    if (layers[i]) {
+            layer.arc(x, y, radius, startAngle, endAngle, negative != 0);
 
-                        // If already present, remove
-                        if (layers[i].parentNode === display)
-                            display.removeChild(layers[i]);
+        },
 
-                        // Add to end
-                        display.appendChild(layers[i]);
-                    }
-                }
+        "cfill": function(parameters) {
 
-                // Add cursor layer last
-                if (cursor != null) {
-                    if (cursor.parentNode === display)
-                        display.removeChild(cursor);
-                    display.appendChild(cursor);
-                }
+            var channelMask = parseInt(parameters[0]);
+            var layer = getLayer(parseInt(parameters[1]));
+            var r = parseInt(parameters[2]);
+            var g = parseInt(parameters[3]);
+            var b = parseInt(parameters[4]);
+            var a = parseInt(parameters[5]);
+
+            layer.setChannelMask(channelMask);
+
+            layer.fillColor(r, g, b, a);
+
+        },
+
+        "clip": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+
+            layer.clip();
+
+        },
+
+        "clipboard": function(parameters) {
+            if (guac_client.onclipboard) guac_client.onclipboard(parameters[0]);
+        },
+
+        "close": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+
+            layer.close();
+
+        },
+
+        "copy": function(parameters) {
+
+            var srcL = getLayer(parseInt(parameters[0]));
+            var srcX = parseInt(parameters[1]);
+            var srcY = parseInt(parameters[2]);
+            var srcWidth = parseInt(parameters[3]);
+            var srcHeight = parseInt(parameters[4]);
+            var channelMask = parseInt(parameters[5]);
+            var dstL = getLayer(parseInt(parameters[6]));
+            var dstX = parseInt(parameters[7]);
+            var dstY = parseInt(parameters[8]);
+
+            dstL.setChannelMask(channelMask);
+
+            dstL.copy(
+                srcL,
+                srcX,
+                srcY,
+                srcWidth, 
+                srcHeight, 
+                dstX,
+                dstY 
+            );
+
+        },
+
+        "cstroke": function(parameters) {
+
+            var channelMask = parseInt(parameters[0]);
+            var layer = getLayer(parseInt(parameters[1]));
+            var cap = lineCap[parseInt(parameters[2])];
+            var join = lineJoin[parseInt(parameters[3])];
+            var thickness = parseInt(parameters[4]);
+            var r = parseInt(parameters[5]);
+            var g = parseInt(parameters[6]);
+            var b = parseInt(parameters[7]);
+            var a = parseInt(parameters[8]);
+
+            layer.setChannelMask(channelMask);
+
+            layer.strokeColor(cap, join, thickness, r, g, b, a);
+
+        },
+
+        "cursor": function(parameters) {
+
+            cursorHotspotX = parseInt(parameters[0]);
+            cursorHotspotY = parseInt(parameters[1]);
+            var srcL = getLayer(parseInt(parameters[2]));
+            var srcX = parseInt(parameters[3]);
+            var srcY = parseInt(parameters[4]);
+            var srcWidth = parseInt(parameters[5]);
+            var srcHeight = parseInt(parameters[6]);
+
+            // Reset cursor size
+            cursor.resize(srcWidth, srcHeight);
+
+            // Draw cursor to cursor layer
+            cursor.getLayer().copy(
+                srcL,
+                srcX,
+                srcY,
+                srcWidth, 
+                srcHeight, 
+                0,
+                0 
+            );
+
+            // Update cursor position (hotspot may have changed)
+            moveCursor(cursorX, cursorY);
+
+        },
+
+        "curve": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+            var cp1x = parseInt(parameters[1]);
+            var cp1y = parseInt(parameters[2]);
+            var cp2x = parseInt(parameters[3]);
+            var cp2y = parseInt(parameters[4]);
+            var x = parseInt(parameters[5]);
+            var y = parseInt(parameters[6]);
+
+            layer.curveTo(cp1x, cp1y, cp2x, cp2y, x, y);
+
+        },
+
+        "dispose": function(parameters) {
+            
+            var layer_index = parseInt(parameters[0]);
+
+            // If visible layer, remove from parent
+            if (layer_index > 0) {
+
+                // Get container element
+                var layer_container = getLayerContainer(layer_index).getElement();
+
+                // Remove from parent
+                layer_container.parentNode.removeChild(layer_container);
+
+                // Delete reference
+                delete layers[layer_index];
 
-            }
-            else {
-                // Reset size
-                layer.resize(displayWidth, displayHeight);
             }
 
-            return layer;
-        }
+            // If buffer, just delete reference
+            else if (layer_index < 0)
+                delete buffers[-1 - layer_index];
 
-    }
+            // Attempting to dispose the root layer currently has no effect.
 
-    var instructionHandlers = {
+        },
+
+        "distort": function(parameters) {
+
+            var layer_index = parseInt(parameters[0]);
+            var a = parseFloat(parameters[1]);
+            var b = parseFloat(parameters[2]);
+            var c = parseFloat(parameters[3]);
+            var d = parseFloat(parameters[4]);
+            var e = parseFloat(parameters[5]);
+            var f = parseFloat(parameters[6]);
 
+            // Only valid for visible layers (not buffers)
+            if (layer_index >= 0) {
+
+                // Get container element
+                var layer_container = getLayerContainer(layer_index).getElement();
+
+                // Set layer transform 
+                layer_container.transform(a, b, c, d, e, f);
+
+             }
+
+        },
         "error": function(parameters) {
-            if (errorHandler) errorHandler(unescapeGuacamoleString(parameters[0]));
-            disconnect();
+            if (guac_client.onerror) guac_client.onerror(parameters[0]);
+            guac_client.disconnect();
         },
 
-        "name": function(parameters) {
-            if (nameHandler) nameHandler(unescapeGuacamoleString(parameters[0]));
+        "identity": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+
+            layer.setTransform(1, 0, 0, 1, 0, 0);
+
         },
 
-        "clipboard": function(parameters) {
-            if (clipboardHandler) clipboardHandler(unescapeGuacamoleString(parameters[0]));
+        "lfill": function(parameters) {
+
+            var channelMask = parseInt(parameters[0]);
+            var layer = getLayer(parseInt(parameters[1]));
+            var srcLayer = getLayer(parseInt(parameters[2]));
+
+            layer.setChannelMask(channelMask);
+
+            layer.fillLayer(srcLayer);
+
         },
 
-        "size": function(parameters) {
+        "line": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+            var x = parseInt(parameters[1]);
+            var y = parseInt(parameters[2]);
 
-            displayWidth = parseInt(parameters[0]);
-            displayHeight = parseInt(parameters[1]);
+            layer.lineTo(x, y);
 
-            // Update (set) display size
-            display.style.width = displayWidth + "px";
-            display.style.height = displayHeight + "px";
+        },
+
+        "lstroke": function(parameters) {
+
+            var channelMask = parseInt(parameters[0]);
+            var layer = getLayer(parseInt(parameters[1]));
+            var srcLayer = getLayer(parseInt(parameters[2]));
+
+            layer.setChannelMask(channelMask);
+
+            layer.strokeLayer(srcLayer);
+
+        },
 
-            // Set cursor layer width/height
-            if (cursor != null)
-                cursor.resize(displayWidth, displayHeight);
+        "move": function(parameters) {
+            
+            var layer_index = parseInt(parameters[0]);
+            var parent_index = parseInt(parameters[1]);
+            var x = parseInt(parameters[2]);
+            var y = parseInt(parameters[3]);
+            var z = parseInt(parameters[4]);
+
+            // Only valid for non-default layers
+            if (layer_index > 0 && parent_index >= 0) {
+
+                // Get container element
+                var layer_container = getLayerContainer(layer_index);
+                var layer_container_element = layer_container.getElement();
+                var parent = getLayerContainer(parent_index).getElement();
+
+                // Set parent if necessary
+                if (!(layer_container_element.parentNode === parent))
+                    parent.appendChild(layer_container_element);
+
+                // Move layer
+                layer_container.translate(x, y);
+                layer_container_element.style.zIndex = z;
+
+            }
 
         },
 
+        "name": function(parameters) {
+            if (guac_client.onname) guac_client.onname(parameters[0]);
+        },
+
         "png": function(parameters) {
 
             var channelMask = parseInt(parameters[0]);
@@ -266,52 +644,119 @@ function GuacamoleClient(display, tunnel) {
 
         },
 
-        "copy": function(parameters) {
+        "pop": function(parameters) {
 
-            var srcL = getLayer(parseInt(parameters[0]));
-            var srcX = parseInt(parameters[1]);
-            var srcY = parseInt(parameters[2]);
-            var srcWidth = parseInt(parameters[3]);
-            var srcHeight = parseInt(parameters[4]);
-            var channelMask = parseInt(parameters[5]);
-            var dstL = getLayer(parseInt(parameters[6]));
-            var dstX = parseInt(parameters[7]);
-            var dstY = parseInt(parameters[8]);
+            var layer = getLayer(parseInt(parameters[0]));
 
-            dstL.setChannelMask(channelMask);
+            layer.pop();
 
-            dstL.copyRect(
-                srcL,
-                srcX,
-                srcY,
-                srcWidth, 
-                srcHeight, 
-                dstX,
-                dstY 
-            );
+        },
+
+        "push": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+
+            layer.push();
 
         },
+        "rect": function(parameters) {
 
-        "cursor": function(parameters) {
+            var layer = getLayer(parseInt(parameters[0]));
+            var x = parseInt(parameters[1]);
+            var y = parseInt(parameters[2]);
+            var w = parseInt(parameters[3]);
+            var h = parseInt(parameters[4]);
+
+            layer.rect(x, y, w, h);
+
+        },
+        
+        "reset": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+
+            layer.reset();
+
+        },
+        
+        "set": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+            var name = parameters[1];
+            var value = parameters[2];
+
+            // Call property handler if defined
+            var handler = layerPropertyHandlers[name];
+            if (handler)
+                handler(layer, value);
+
+        },
+
+        "shade": function(parameters) {
+            
+            var layer_index = parseInt(parameters[0]);
+            var a = parseInt(parameters[1]);
+
+            // Only valid for visible layers (not buffers)
+            if (layer_index >= 0) {
 
-            var x = parseInt(parameters[0]);
-            var y = parseInt(parameters[1]);
-            var data = parameters[2];
+                // Get container element
+                var layer_container = getLayerContainer(layer_index).getElement();
 
-            if (cursor == null) {
-                cursor = new Layer(displayWidth, displayHeight);
-                display.appendChild(cursor);
+                // Set layer opacity
+                layer_container.style.opacity = a/255.0;
+
+            }
+
+        },
+
+        "size": function(parameters) {
+
+            var layer_index = parseInt(parameters[0]);
+            var width = parseInt(parameters[1]);
+            var height = parseInt(parameters[2]);
+
+            // If not buffer, resize layer and container
+            if (layer_index >= 0) {
+
+                // Resize layer
+                var layer_container = getLayerContainer(layer_index);
+                layer_container.resize(width, height);
+
+                // If layer is default, resize display
+                if (layer_index == 0) {
+
+                    displayWidth = width;
+                    displayHeight = height;
+
+                    // Update (set) display size
+                    display.style.width = displayWidth + "px";
+                    display.style.height = displayHeight + "px";
+
+                    // Update bounds size
+                    bounds.style.width = (displayWidth*displayScale) + "px";
+                    bounds.style.height = (displayHeight*displayScale) + "px";
+
+                }
+
+            }
+
+            // If buffer, resize layer only
+            else {
+                var layer = getBufferLayer(parseInt(parameters[0]));
+                layer.resize(width, height);
             }
 
-            // Start cursor image load
-            var image = new Image();
-            image.onload = function() {
-                cursorImage = image;
-                cursorHotspotX = x;
-                cursorHotspotY = y;
-                redrawCursor(cursorRectX, cursorRectY);
-            };
-            image.src = "data:image/png;base64," + data
+        },
+        
+        "start": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+            var x = parseInt(parameters[1]);
+            var y = parseInt(parameters[2]);
+
+            layer.moveTo(x, y);
 
         },
 
@@ -328,15 +773,19 @@ function GuacamoleClient(display, tunnel) {
                 layersToSync--;
 
                 // Send sync response when layers are finished
-                if (layersToSync == 0)
-                    tunnel.sendMessage("sync:" + timestamp + ";");
+                if (layersToSync == 0) {
+                    if (timestamp != currentTimestamp) {
+                        tunnel.sendMessage("sync", timestamp);
+                        currentTimestamp = timestamp;
+                    }
+                }
 
             }
 
             // Count active, not-ready layers and install sync tracking hooks
             for (var i=0; i<layers.length; i++) {
 
-                var layer = layers[i];
+                var layer = layers[i].getLayer();
                 if (layer && !layer.isReady()) {
                     layersToSync++;
                     layer.sync(syncLayer);
@@ -346,105 +795,386 @@ function GuacamoleClient(display, tunnel) {
 
             // If all layers are ready, then we didn't install any hooks.
             // Send sync message now,
-            if (layersToSync == 0)
-                tunnel.sendMessage("sync:" + timestamp + ";");
+            if (layersToSync == 0) {
+                if (timestamp != currentTimestamp) {
+                    tunnel.sendMessage("sync", timestamp);
+                    currentTimestamp = timestamp;
+                }
+            }
 
         },
+
+        "transfer": function(parameters) {
+
+            var srcL = getLayer(parseInt(parameters[0]));
+            var srcX = parseInt(parameters[1]);
+            var srcY = parseInt(parameters[2]);
+            var srcWidth = parseInt(parameters[3]);
+            var srcHeight = parseInt(parameters[4]);
+            var transferFunction = Guacamole.Client.DefaultTransferFunction[parameters[5]];
+            var dstL = getLayer(parseInt(parameters[6]));
+            var dstX = parseInt(parameters[7]);
+            var dstY = parseInt(parameters[8]);
+
+            dstL.transfer(
+                srcL,
+                srcX,
+                srcY,
+                srcWidth, 
+                srcHeight, 
+                dstX,
+                dstY,
+                transferFunction
+            );
+
+        },
+
+        "transform": function(parameters) {
+
+            var layer = getLayer(parseInt(parameters[0]));
+            var a = parseFloat(parameters[1]);
+            var b = parseFloat(parameters[2]);
+            var c = parseFloat(parameters[3]);
+            var d = parseFloat(parameters[4]);
+            var e = parseFloat(parameters[5]);
+            var f = parseFloat(parameters[6]);
+
+            layer.transform(a, b, c, d, e, f);
+
+        }
       
     };
 
 
-    function doInstruction(opcode, parameters) {
+    tunnel.oninstruction = function(opcode, parameters) {
 
         var handler = instructionHandlers[opcode];
         if (handler)
             handler(parameters);
 
-    }
+    };
 
 
-    function disconnect() {
+    this.disconnect = function() {
 
         // Only attempt disconnection not disconnected.
         if (currentState != STATE_DISCONNECTED
                 && currentState != STATE_DISCONNECTING) {
 
             setState(STATE_DISCONNECTING);
-            tunnel.sendMessage("disconnect;");
-            tunnel.disconnect();
-            setState(STATE_DISCONNECTED);
-        }
 
-    }
+            // Stop ping
+            if (pingInterval)
+                window.clearInterval(pingInterval);
 
-    function escapeGuacamoleString(str) {
+            // Send disconnect message and disconnect
+            tunnel.sendMessage("disconnect");
+            tunnel.disconnect();
+            setState(STATE_DISCONNECTED);
 
-        var escapedString = "";
+        }
 
-        for (var i=0; i<str.length; i++) {
+    };
+    
+    this.connect = function(data) {
 
-            var c = str.charAt(i);
-            if (c == ",")
-                escapedString += "\\c";
-            else if (c == ";")
-                escapedString += "\\s";
-            else if (c == "\\")
-                escapedString += "\\\\";
-            else
-                escapedString += c;
+        setState(STATE_CONNECTING);
 
+        try {
+            tunnel.connect(data);
+        }
+        catch (e) {
+            setState(STATE_IDLE);
+            throw e;
         }
 
-        return escapedString;
+        // Ping every 5 seconds (ensure connection alive)
+        pingInterval = window.setInterval(function() {
+            tunnel.sendMessage("sync", currentTimestamp);
+        }, 5000);
 
-    }
+        setState(STATE_WAITING);
+    };
 
-    function unescapeGuacamoleString(str) {
+    this.scale = function(scale) {
 
-        var unescapedString = "";
+        display.style.transform =
+        display.style.WebkitTransform =
+        display.style.MozTransform =
+        display.style.OTransform =
+        display.style.msTransform =
 
-        for (var i=0; i<str.length; i++) {
+            "scale(" + scale + "," + scale + ")";
 
-            var c = str.charAt(i);
-            if (c == "\\" && i<str.length-1) {
+        displayScale = scale;
 
-                var escapeChar = str.charAt(++i);
-                if (escapeChar == "c")
-                    unescapedString += ",";
-                else if (escapeChar == "s")
-                    unescapedString += ";";
-                else if (escapeChar == "\\")
-                    unescapedString += "\\";
-                else
-                    unescapedString += "\\" + escapeChar;
+        // Update bounds size
+        bounds.style.width = (displayWidth*displayScale) + "px";
+        bounds.style.height = (displayHeight*displayScale) + "px";
 
-            }
-            else
-                unescapedString += c;
+    };
 
-        }
+    this.getScale = function() {
+        return displayScale;
+    };
+
+};
+
+/**
+ * Simple container for Guacamole.Layer, allowing layers to be easily
+ * repositioned and nested. This allows certain operations to be accelerated
+ * through DOM manipulation, rather than raster operations.
+ * 
+ * @constructor
+ * 
+ * @param {Number} width The width of the Layer, in pixels. The canvas element
+ *                       backing this Layer will be given this width.
+ *                       
+ * @param {Number} height The height of the Layer, in pixels. The canvas element
+ *                        backing this Layer will be given this height.
+ */
+Guacamole.Client.LayerContainer = function(width, height) {
+
+    /**
+     * Reference to this LayerContainer.
+     * @private
+     */
+    var layer_container = this;
+
+    // Create layer with given size
+    var layer = new Guacamole.Layer(width, height);
+
+    // Set layer position
+    var canvas = layer.getCanvas();
+    canvas.style.position = "absolute";
+    canvas.style.left = "0px";
+    canvas.style.top = "0px";
+
+    // Create div with given size
+    var div = document.createElement("div");
+    div.appendChild(canvas);
+    div.style.width = width + "px";
+    div.style.height = height + "px";
+
+    /**
+     * Changes the size of this LayerContainer and the contained Layer to the
+     * given width and height.
+     * 
+     * @param {Number} width The new width to assign to this Layer.
+     * @param {Number} height The new height to assign to this Layer.
+     */
+    this.resize = function(width, height) {
+
+        // Resize layer
+        layer.resize(width, height);
+
+        // Resize containing div
+        div.style.width = width + "px";
+        div.style.height = height + "px";
 
-        return unescapedString;
+    };
+  
+    /**
+     * Returns the Layer contained within this LayerContainer.
+     * @returns {Guacamole.Layer} The Layer contained within this LayerContainer.
+     */
+    this.getLayer = function() {
+        return layer;
+    };
 
-    }
+    /**
+     * Returns the element containing the Layer within this LayerContainer.
+     * @returns {Element} The element containing the Layer within this LayerContainer.
+     */
+    this.getElement = function() {
+        return div;
+    };
 
-    this.disconnect = disconnect;
-    this.connect = function(data) {
+    /**
+     * The translation component of this LayerContainer's transform.
+     * @private
+     */
+    var translate = "translate(0px, 0px)"; // (0, 0)
+
+    /**
+     * The arbitrary matrix component of this LayerContainer's transform.
+     * @private
+     */
+    var matrix = "matrix(1, 0, 0, 1, 0, 0)"; // Identity
+
+    /**
+     * Moves the upper-left corner of this LayerContainer to the given X and Y
+     * coordinate.
+     * 
+     * @param {Number} x The X coordinate to move to.
+     * @param {Number} y The Y coordinate to move to.
+     */
+    this.translate = function(x, y) {
+
+        // Generate translation
+        translate = "translate("
+                        + x + "px,"
+                        + y + "px)";
+
+        // Set layer transform 
+        div.style.transform =
+        div.style.WebkitTransform =
+        div.style.MozTransform =
+        div.style.OTransform =
+        div.style.msTransform =
+
+            translate + " " + matrix;
 
-        setState(STATE_CONNECTING);
+    };
 
-        try {
-            tunnel.connect(data);
-        }
-        catch (e) {
-            setState(STATE_IDLE);
-            throw e;
-        }
+    /**
+     * Applies the given affine transform (defined with six values from the
+     * transform's matrix).
+     * 
+     * @param {Number} a The first value in the affine transform's matrix.
+     * @param {Number} b The second value in the affine transform's matrix.
+     * @param {Number} c The third value in the affine transform's matrix.
+     * @param {Number} d The fourth value in the affine transform's matrix.
+     * @param {Number} e The fifth value in the affine transform's matrix.
+     * @param {Number} f The sixth value in the affine transform's matrix.
+     */
+    this.transform = function(a, b, c, d, e, f) {
+
+        // Generate matrix transformation
+        matrix =
+
+            /* a c e
+             * b d f
+             * 0 0 1
+             */
+    
+            "matrix(" + a + "," + b + "," + c + "," + d + "," + e + "," + f + ")";
+
+        // Set layer transform 
+        div.style.transform =
+        div.style.WebkitTransform =
+        div.style.MozTransform =
+        div.style.OTransform =
+        div.style.msTransform =
+
+            translate + " " + matrix;
 
-        setState(STATE_WAITING);
     };
 
-    this.escapeGuacamoleString   = escapeGuacamoleString;
-    this.unescapeGuacamoleString = unescapeGuacamoleString;
+};
+
+/**
+ * Map of all Guacamole binary raster operations to transfer functions.
+ * @private
+ */
+Guacamole.Client.DefaultTransferFunction = {
+
+    /* BLACK */
+    0x0: function (src, dst) {
+        dst.red = dst.green = dst.blue = 0x00;
+    },
+
+    /* WHITE */
+    0xF: function (src, dst) {
+        dst.red = dst.green = dst.blue = 0xFF;
+    },
+
+    /* SRC */
+    0x3: function (src, dst) {
+        dst.red   = src.red;
+        dst.green = src.green;
+        dst.blue  = src.blue;
+        dst.alpha = src.alpha;
+    },
+
+    /* DEST (no-op) */
+    0x5: function (src, dst) {
+        // Do nothing
+    },
+
+    /* Invert SRC */
+    0xC: function (src, dst) {
+        dst.red   = 0xFF & ~src.red;
+        dst.green = 0xFF & ~src.green;
+        dst.blue  = 0xFF & ~src.blue;
+        dst.alpha =  src.alpha;
+    },
+    
+    /* Invert DEST */
+    0xA: function (src, dst) {
+        dst.red   = 0xFF & ~dst.red;
+        dst.green = 0xFF & ~dst.green;
+        dst.blue  = 0xFF & ~dst.blue;
+    },
+
+    /* AND */
+    0x1: function (src, dst) {
+        dst.red   =  ( src.red   &  dst.red);
+        dst.green =  ( src.green &  dst.green);
+        dst.blue  =  ( src.blue  &  dst.blue);
+    },
+
+    /* NAND */
+    0xE: function (src, dst) {
+        dst.red   = 0xFF & ~( src.red   &  dst.red);
+        dst.green = 0xFF & ~( src.green &  dst.green);
+        dst.blue  = 0xFF & ~( src.blue  &  dst.blue);
+    },
+
+    /* OR */
+    0x7: function (src, dst) {
+        dst.red   =  ( src.red   |  dst.red);
+        dst.green =  ( src.green |  dst.green);
+        dst.blue  =  ( src.blue  |  dst.blue);
+    },
+
+    /* NOR */
+    0x8: function (src, dst) {
+        dst.red   = 0xFF & ~( src.red   |  dst.red);
+        dst.green = 0xFF & ~( src.green |  dst.green);
+        dst.blue  = 0xFF & ~( src.blue  |  dst.blue);
+    },
+
+    /* XOR */
+    0x6: function (src, dst) {
+        dst.red   =  ( src.red   ^  dst.red);
+        dst.green =  ( src.green ^  dst.green);
+        dst.blue  =  ( src.blue  ^  dst.blue);
+    },
+
+    /* XNOR */
+    0x9: function (src, dst) {
+        dst.red   = 0xFF & ~( src.red   ^  dst.red);
+        dst.green = 0xFF & ~( src.green ^  dst.green);
+        dst.blue  = 0xFF & ~( src.blue  ^  dst.blue);
+    },
+
+    /* AND inverted source */
+    0x4: function (src, dst) {
+        dst.red   =  0xFF & (~src.red   &  dst.red);
+        dst.green =  0xFF & (~src.green &  dst.green);
+        dst.blue  =  0xFF & (~src.blue  &  dst.blue);
+    },
+
+    /* OR inverted source */
+    0xD: function (src, dst) {
+        dst.red   =  0xFF & (~src.red   |  dst.red);
+        dst.green =  0xFF & (~src.green |  dst.green);
+        dst.blue  =  0xFF & (~src.blue  |  dst.blue);
+    },
+
+    /* AND inverted destination */
+    0x2: function (src, dst) {
+        dst.red   =  0xFF & ( src.red   & ~dst.red);
+        dst.green =  0xFF & ( src.green & ~dst.green);
+        dst.blue  =  0xFF & ( src.blue  & ~dst.blue);
+    },
+
+    /* OR inverted destination */
+    0xB: function (src, dst) {
+        dst.red   =  0xFF & ( src.red   | ~dst.red);
+        dst.green =  0xFF & ( src.green | ~dst.green);
+        dst.blue  =  0xFF & ( src.blue  | ~dst.blue);
+    }
 
-}
+};