2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
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/
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
15 * The Original Code is guacamole-common-js.
17 * The Initial Developer of the Original Code is
19 * Portions created by the Initial Developer are Copyright (C) 2010
20 * the Initial Developer. All Rights Reserved.
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.
36 * ***** END LICENSE BLOCK ***** */
38 // Guacamole namespace
39 var Guacamole = Guacamole || {};
42 * Abstract ordered drawing surface. Each Layer contains a canvas element and
43 * provides simple drawing instructions for drawing to that canvas element,
44 * however unlike the canvas element itself, drawing operations on a Layer are
45 * guaranteed to run in order, even if such an operation must wait for an image
46 * to load before completing.
50 * @param {Number} width The width of the Layer, in pixels. The canvas element
51 * backing this Layer will be given this width.
53 * @param {Number} height The height of the Layer, in pixels. The canvas element
54 * backing this Layer will be given this height.
56 Guacamole.Layer = function(width, height) {
59 * Reference to this Layer.
65 * The canvas element backing this Layer.
68 var display = document.createElement("canvas");
71 * The 2D display context of the canvas element backing this Layer.
74 var displayContext = display.getContext("2d");
75 displayContext.save();
78 * The queue of all pending Tasks. Tasks will be run in order, with new
79 * tasks added at the end of the queue and old tasks removed from the
80 * front of the queue (FIFO).
83 var tasks = new Array();
86 * Map of all Guacamole channel masks to HTML5 canvas composite operation
87 * names. Not all channel mask combinations are currently implemented.
90 var compositeOperation = {
91 /* 0x0 NOT IMPLEMENTED */
92 0x1: "destination-in",
93 0x2: "destination-out",
94 /* 0x3 NOT IMPLEMENTED */
96 /* 0x5 NOT IMPLEMENTED */
98 /* 0x7 NOT IMPLEMENTED */
100 0x9: "destination-atop",
102 0xB: "destination-over",
104 /* 0xD NOT IMPLEMENTED */
110 * Resizes the canvas element backing this Layer without testing the
111 * new size. This function should only be used internally.
114 * @param {Number} newWidth The new width to assign to this Layer.
115 * @param {Number} newHeight The new height to assign to this Layer.
117 function resize(newWidth, newHeight) {
120 // Only preserve old data if width/height are both non-zero
122 if (width != 0 && height != 0) {
124 // Create canvas and context for holding old data
125 oldData = document.createElement("canvas");
126 oldData.width = width;
127 oldData.height = height;
129 var oldDataContext = oldData.getContext("2d");
131 // Copy image data from current
132 oldDataContext.drawImage(display,
134 0, 0, width, height);
139 display.width = newWidth;
140 display.height = newHeight;
142 // Redraw old data, if any
144 displayContext.drawImage(oldData,
146 0, 0, width, height);
153 * Given the X and Y coordinates of the upper-left corner of a rectangle
154 * and the rectangle's width and height, resize the backing canvas element
155 * as necessary to ensure that the rectangle fits within the canvas
156 * element's coordinate space. This function will only make the canvas
157 * larger. If the rectangle already fits within the canvas element's
158 * coordinate space, the canvas is left unchanged.
161 * @param {Number} x The X coordinate of the upper-left corner of the
163 * @param {Number} y The Y coordinate of the upper-left corner of the
165 * @param {Number} w The width of the the rectangle to fit.
166 * @param {Number} h The height of the the rectangle to fit.
168 function fitRect(x, y, w, h) {
171 var opBoundX = w + x;
172 var opBoundY = h + y;
174 // Determine max width
176 if (opBoundX > width)
177 resizeWidth = opBoundX;
181 // Determine max height
183 if (opBoundY > height)
184 resizeHeight = opBoundY;
186 resizeHeight = height;
188 // Resize if necessary
189 if (resizeWidth != width || resizeHeight != height)
190 resize(resizeWidth, resizeHeight);
195 * A container for an task handler. Each operation which must be ordered
196 * is associated with a Task that goes into a task queue. Tasks in this
197 * queue are executed in order once their handlers are set, while Tasks
198 * without handlers block themselves and any following Tasks from running.
202 * @param {function} taskHandler The function to call when this task
204 * @param {boolean} blocked Whether this task should start blocked.
206 function Task(taskHandler, blocked) {
211 * Whether this Task is blocked.
215 this.blocked = blocked;
218 * The handler this Task is associated with, if any.
222 this.handler = taskHandler;
225 * Unblocks this Task, allowing it to run.
227 this.unblock = function() {
228 task.blocked = false;
229 handlePendingTasks();
235 * If no tasks are pending or running, run the provided handler immediately,
236 * if any. Otherwise, schedule a task to run immediately after all currently
237 * running or pending tasks are complete.
240 * @param {function} handler The function to call when possible, if any.
241 * @param {boolean} blocked Whether the task should start blocked.
242 * @returns {Task} The Task created and added to the queue for future
243 * running, if any, or null if the handler was run
244 * immediately and no Task needed to be created.
246 function scheduleTask(handler, blocked) {
248 // If no pending tasks, just call (if available) and exit
249 if (layer.isReady() && !blocked && handler != null) {
254 // If tasks are pending/executing, schedule a pending task
255 // and return a reference to it.
256 var task = new Task(handler, blocked);
262 var tasksInProgress = false;
265 * Run any Tasks which were pending but are now ready to run and are not
266 * blocked by other Tasks.
269 function handlePendingTasks() {
274 tasksInProgress = true;
276 // Draw all pending tasks.
278 while ((task = tasks[0]) != null && !task.blocked) {
280 if (task.handler) task.handler();
283 tasksInProgress = false;
288 * Set to true if this Layer should resize itself to accomodate the
289 * dimensions of any drawing operation, and false (the default) otherwise.
291 * Note that setting this property takes effect immediately, and thus may
292 * take effect on operations that were started in the past but have not
293 * yet completed. If you wish the setting of this flag to only modify
294 * future operations, you will need to make the setting of this flag an
295 * operation with sync().
298 * // Set autosize to true for all future operations
299 * layer.sync(function() {
300 * layer.autosize = true;
306 this.autosize = false;
309 * Returns the canvas element backing this Layer.
310 * @returns {Element} The canvas element backing this Layer.
312 this.getCanvas = function() {
317 * Returns whether this Layer is ready. A Layer is ready if it has no
318 * pending operations and no operations in-progress.
320 * @returns {Boolean} true if this Layer is ready, false otherwise.
322 this.isReady = function() {
323 return tasks.length == 0;
327 * Changes the size of this Layer to the given width and height. Resizing
328 * is only attempted if the new size provided is actually different from
331 * @param {Number} newWidth The new width to assign to this Layer.
332 * @param {Number} newHeight The new height to assign to this Layer.
334 this.resize = function(newWidth, newHeight) {
335 scheduleTask(function() {
336 if (newWidth != width || newHeight != height)
337 resize(newWidth, newHeight);
342 * Draws the specified image at the given coordinates. The image specified
343 * must already be loaded.
345 * @param {Number} x The destination X coordinate.
346 * @param {Number} y The destination Y coordinate.
347 * @param {Image} image The image to draw. Note that this is an Image
348 * object - not a URL.
350 this.drawImage = function(x, y, image) {
351 scheduleTask(function() {
352 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
353 displayContext.drawImage(image, x, y);
358 * Draws the image at the specified URL at the given coordinates. The image
359 * will be loaded automatically, and this and any future operations will
360 * wait for the image to finish loading.
362 * @param {Number} x The destination X coordinate.
363 * @param {Number} y The destination Y coordinate.
364 * @param {String} url The URL of the image to draw.
366 this.draw = function(x, y, url) {
368 var task = scheduleTask(function() {
369 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
370 displayContext.drawImage(image, x, y);
373 var image = new Image();
374 image.onload = task.unblock;
380 * Run an arbitrary function as soon as currently pending operations
383 * @param {function} handler The function to call once all currently
384 * pending operations are complete.
386 this.sync = function(handler) {
387 return scheduleTask(handler);
391 * Copy a rectangle of image data from one Layer to this Layer. This
392 * operation will copy exactly the image data that will be drawn once all
393 * operations of the source Layer that were pending at the time this
394 * function was called are complete. This operation will not alter the
395 * size of the source Layer even if its autosize property is set to true.
397 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
398 * @param {Number} srcx The X coordinate of the upper-left corner of the
399 * rectangle within the source Layer's coordinate
400 * space to copy data from.
401 * @param {Number} srcy The Y coordinate of the upper-left corner of the
402 * rectangle within the source Layer's coordinate
403 * space to copy data from.
404 * @param {Number} srcw The width of the rectangle within the source Layer's
405 * coordinate space to copy data from.
406 * @param {Number} srch The height of the rectangle within the source
407 * Layer's coordinate space to copy data from.
408 * @param {Number} x The destination X coordinate.
409 * @param {Number} y The destination Y coordinate.
411 this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
415 function doCopyRect() {
416 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
418 var srcCanvas = srcLayer.getCanvas();
419 if (srcCanvas.width != 0 && srcCanvas.height != 0)
420 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
422 // Unblock the copy complete task, if it exists
427 // If we ARE the source layer, no need to sync.
428 // Syncing would result in deadlock.
429 if (layer === srcLayer)
430 scheduleTask(doCopyRect);
432 // Otherwise synchronize copy operation with source layer
435 // Task which will be unblocked only when the source layer is ready
436 // This task will perform the copy
437 var task = scheduleTask(doCopyRect, true);
439 // Task which will unblock the drawing task.
440 var srcReady = srcLayer.sync(task.unblock);
442 // Task which will be unblocked only after the copy has
443 // occurred (this will only be created if the draw task
445 if (srcReady != null) srcLock = srcLayer.sync(null, true);
452 * Clear the specified rectangle of image data.
454 * @param {Number} x The X coordinate of the upper-left corner of the
455 * rectangle to clear.
456 * @param {Number} y The Y coordinate of the upper-left corner of the
457 * rectangle to clear.
458 * @param {Number} w The width of the rectangle to clear.
459 * @param {Number} h The height of the rectangle to clear.
461 this.clearRect = function(x, y, w, h) {
462 scheduleTask(function() {
463 if (layer.autosize != 0) fitRect(x, y, w, h);
464 displayContext.clearRect(x, y, w, h);
469 * Fill the specified rectangle of image data with the specified color.
471 * @param {Number} x The X coordinate of the upper-left corner of the
473 * @param {Number} y The Y coordinate of the upper-left corner of the
475 * @param {Number} w The width of the rectangle to draw.
476 * @param {Number} h The height of the rectangle to draw.
477 * @param {Number} r The red component of the color of the rectangle.
478 * @param {Number} g The green component of the color of the rectangle.
479 * @param {Number} b The blue component of the color of the rectangle.
480 * @param {Number} a The alpha component of the color of the rectangle.
482 this.drawRect = function(x, y, w, h, r, g, b, a) {
483 scheduleTask(function() {
484 if (layer.autosize != 0) fitRect(x, y, w, h);
485 displayContext.fillStyle = "rgba("
486 + r + "," + g + "," + b + "," + a / 255 + ")";
487 displayContext.fillRect(x, y, w, h);
492 * Clip all future drawing operations by the specified rectangle.
494 * @param {Number} x The X coordinate of the upper-left corner of the
495 * rectangle to use for the clipping region.
496 * @param {Number} y The Y coordinate of the upper-left corner of the
497 * rectangle to use for the clipping region.
498 * @param {Number} w The width of the rectangle to use for the clipping region.
499 * @param {Number} h The height of the rectangle to use for the clipping region.
501 this.clipRect = function(x, y, w, h) {
502 scheduleTask(function() {
504 // Clear any current clipping region
505 displayContext.restore();
506 displayContext.save();
508 if (layer.autosize != 0) fitRect(x, y, w, h);
510 // Set new clipping region
511 displayContext.beginPath();
512 displayContext.rect(x, y, w, h);
513 displayContext.clip();
519 * Provides the given filtering function with a writable snapshot of
520 * image data and the current width and height of the Layer.
522 * @param {function} filter A function which accepts an array of image
523 * data (as returned by the canvas element's
524 * display context's getImageData() function),
525 * the width of the Layer, and the height of the
526 * Layer as parameters, in that order. This
527 * function must accomplish its filtering by
528 * modifying the given image data array directly.
530 this.filter = function(filter) {
531 scheduleTask(function() {
532 var imageData = displayContext.getImageData(0, 0, width, height);
533 filter(imageData.data, width, height);
534 displayContext.putImageData(imageData, 0, 0);
539 * Sets the channel mask for future operations on this Layer. The channel
540 * mask is a Guacamole-specific compositing operation identifier with a
541 * single bit representing each of four channels (in order): source image
542 * where destination transparent, source where destination opaque,
543 * destination where source transparent, and destination where source
546 * @param {Number} mask The channel mask for future operations on this
549 this.setChannelMask = function(mask) {
550 scheduleTask(function() {
551 displayContext.globalCompositeOperation = compositeOperation[mask];
555 // Initialize canvas dimensions
556 display.width = width;
557 display.height = height;