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 function to apply when drawing arbitrary source pixels over
81 var transferFunction = null;
84 * The queue of all pending Tasks. Tasks will be run in order, with new
85 * tasks added at the end of the queue and old tasks removed from the
86 * front of the queue (FIFO).
89 var tasks = new Array();
92 * Map of all Guacamole channel masks to HTML5 canvas composite operation
93 * names. Not all channel mask combinations are currently implemented.
96 var compositeOperation = {
97 /* 0x0 NOT IMPLEMENTED */
98 0x1: "destination-in",
99 0x2: "destination-out",
100 /* 0x3 NOT IMPLEMENTED */
102 /* 0x5 NOT IMPLEMENTED */
104 /* 0x7 NOT IMPLEMENTED */
106 0x9: "destination-atop",
108 0xB: "destination-over",
110 /* 0xD NOT IMPLEMENTED */
116 * Map of all Guacamole binary raster operations to transfer functions.
119 var binaryCompositeTransferFunction = {
121 0x10: function (src, dst) { return 0x00; }, /* BLACK */
122 0x1F: function (src, dst) { return 0xFF; }, /* WHITE */
124 0x13: function (src, dst) { return src; }, /* SRC */
125 0x15: function (src, dst) { return dst; }, /* DEST */
126 0x1C: function (src, dst) { return ~src; }, /* NSRC */
127 0x1A: function (src, dst) { return ~dst; }, /* NDEST */
129 0x11: function (src, dst) { return src & dst; }, /* AND */
130 0x1E: function (src, dst) { return ~(src & dst); }, /* NAND */
132 0x17: function (src, dst) { return src | dst; }, /* OR */
133 0x18: function (src, dst) { return ~(src | dst); }, /* NOR */
135 0x16: function (src, dst) { return src ^ dst; }, /* XOR */
136 0x19: function (src, dst) { return ~(src ^ dst); }, /* XNOR */
138 0x14: function (src, dst) { return ~src & dst; }, /* AND inverted source */
139 0x1D: function (src, dst) { return ~src | dst; }, /* OR inverted source */
140 0x12: function (src, dst) { return src & ~dst; }, /* AND inverted destination */
141 0x1B: function (src, dst) { return src | ~dst; } /* OR inverted destination */
146 * Resizes the canvas element backing this Layer without testing the
147 * new size. This function should only be used internally.
150 * @param {Number} newWidth The new width to assign to this Layer.
151 * @param {Number} newHeight The new height to assign to this Layer.
153 function resize(newWidth, newHeight) {
155 // Only preserve old data if width/height are both non-zero
157 if (width != 0 && height != 0) {
159 // Create canvas and context for holding old data
160 oldData = document.createElement("canvas");
161 oldData.width = width;
162 oldData.height = height;
164 var oldDataContext = oldData.getContext("2d");
166 // Copy image data from current
167 oldDataContext.drawImage(display,
169 0, 0, width, height);
173 // Preserve composite operation
174 var oldCompositeOperation = displayContext.globalCompositeOperation;
177 display.width = newWidth;
178 display.height = newHeight;
180 // Redraw old data, if any
182 displayContext.drawImage(oldData,
184 0, 0, width, height);
186 // Restore composite operation
187 displayContext.globalCompositeOperation = oldCompositeOperation;
195 * Given the X and Y coordinates of the upper-left corner of a rectangle
196 * and the rectangle's width and height, resize the backing canvas element
197 * as necessary to ensure that the rectangle fits within the canvas
198 * element's coordinate space. This function will only make the canvas
199 * larger. If the rectangle already fits within the canvas element's
200 * coordinate space, the canvas is left unchanged.
203 * @param {Number} x The X coordinate of the upper-left corner of the
205 * @param {Number} y The Y coordinate of the upper-left corner of the
207 * @param {Number} w The width of the the rectangle to fit.
208 * @param {Number} h The height of the the rectangle to fit.
210 function fitRect(x, y, w, h) {
213 var opBoundX = w + x;
214 var opBoundY = h + y;
216 // Determine max width
218 if (opBoundX > width)
219 resizeWidth = opBoundX;
223 // Determine max height
225 if (opBoundY > height)
226 resizeHeight = opBoundY;
228 resizeHeight = height;
230 // Resize if necessary
231 if (resizeWidth != width || resizeHeight != height)
232 resize(resizeWidth, resizeHeight);
237 * A container for an task handler. Each operation which must be ordered
238 * is associated with a Task that goes into a task queue. Tasks in this
239 * queue are executed in order once their handlers are set, while Tasks
240 * without handlers block themselves and any following Tasks from running.
244 * @param {function} taskHandler The function to call when this task
246 * @param {boolean} blocked Whether this task should start blocked.
248 function Task(taskHandler, blocked) {
253 * Whether this Task is blocked.
257 this.blocked = blocked;
260 * The handler this Task is associated with, if any.
264 this.handler = taskHandler;
267 * Unblocks this Task, allowing it to run.
269 this.unblock = function() {
270 task.blocked = false;
271 handlePendingTasks();
277 * If no tasks are pending or running, run the provided handler immediately,
278 * if any. Otherwise, schedule a task to run immediately after all currently
279 * running or pending tasks are complete.
282 * @param {function} handler The function to call when possible, if any.
283 * @param {boolean} blocked Whether the task should start blocked.
284 * @returns {Task} The Task created and added to the queue for future
285 * running, if any, or null if the handler was run
286 * immediately and no Task needed to be created.
288 function scheduleTask(handler, blocked) {
290 // If no pending tasks, just call (if available) and exit
291 if (layer.isReady() && !blocked) {
292 if (handler) handler();
296 // If tasks are pending/executing, schedule a pending task
297 // and return a reference to it.
298 var task = new Task(handler, blocked);
304 var tasksInProgress = false;
307 * Run any Tasks which were pending but are now ready to run and are not
308 * blocked by other Tasks.
311 function handlePendingTasks() {
316 tasksInProgress = true;
318 // Draw all pending tasks.
320 while ((task = tasks[0]) != null && !task.blocked) {
322 if (task.handler) task.handler();
325 tasksInProgress = false;
330 * Set to true if this Layer should resize itself to accomodate the
331 * dimensions of any drawing operation, and false (the default) otherwise.
333 * Note that setting this property takes effect immediately, and thus may
334 * take effect on operations that were started in the past but have not
335 * yet completed. If you wish the setting of this flag to only modify
336 * future operations, you will need to make the setting of this flag an
337 * operation with sync().
340 * // Set autosize to true for all future operations
341 * layer.sync(function() {
342 * layer.autosize = true;
348 this.autosize = false;
351 * Returns the canvas element backing this Layer.
352 * @returns {Element} The canvas element backing this Layer.
354 this.getCanvas = function() {
359 * Returns whether this Layer is ready. A Layer is ready if it has no
360 * pending operations and no operations in-progress.
362 * @returns {Boolean} true if this Layer is ready, false otherwise.
364 this.isReady = function() {
365 return tasks.length == 0;
369 * Changes the size of this Layer to the given width and height. Resizing
370 * is only attempted if the new size provided is actually different from
373 * @param {Number} newWidth The new width to assign to this Layer.
374 * @param {Number} newHeight The new height to assign to this Layer.
376 this.resize = function(newWidth, newHeight) {
377 scheduleTask(function() {
378 if (newWidth != width || newHeight != height)
379 resize(newWidth, newHeight);
384 * Draws the specified image at the given coordinates. The image specified
385 * must already be loaded.
387 * @param {Number} x The destination X coordinate.
388 * @param {Number} y The destination Y coordinate.
389 * @param {Image} image The image to draw. Note that this is an Image
390 * object - not a URL.
392 this.drawImage = function(x, y, image) {
393 scheduleTask(function() {
394 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
395 displayContext.drawImage(image, x, y);
400 * Draws the image at the specified URL at the given coordinates. The image
401 * will be loaded automatically, and this and any future operations will
402 * wait for the image to finish loading.
404 * @param {Number} x The destination X coordinate.
405 * @param {Number} y The destination Y coordinate.
406 * @param {String} url The URL of the image to draw.
408 this.draw = function(x, y, url) {
410 var task = scheduleTask(function() {
411 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
412 displayContext.drawImage(image, x, y);
415 var image = new Image();
416 image.onload = task.unblock;
422 * Run an arbitrary function as soon as currently pending operations
425 * @param {function} handler The function to call once all currently
426 * pending operations are complete.
427 * @param {boolean} blocked Whether the task should start blocked.
429 this.sync = scheduleTask;
432 * Copy a rectangle of image data from one Layer to this Layer. This
433 * operation will copy exactly the image data that will be drawn once all
434 * operations of the source Layer that were pending at the time this
435 * function was called are complete. This operation will not alter the
436 * size of the source Layer even if its autosize property is set to true.
438 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
439 * @param {Number} srcx The X coordinate of the upper-left corner of the
440 * rectangle within the source Layer's coordinate
441 * space to copy data from.
442 * @param {Number} srcy The Y coordinate of the upper-left corner of the
443 * rectangle within the source Layer's coordinate
444 * space to copy data from.
445 * @param {Number} srcw The width of the rectangle within the source Layer's
446 * coordinate space to copy data from.
447 * @param {Number} srch The height of the rectangle within the source
448 * Layer's coordinate space to copy data from.
449 * @param {Number} x The destination X coordinate.
450 * @param {Number} y The destination Y coordinate.
452 this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
454 var drawComplete = false;
457 function doCopyRect() {
458 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
460 var srcCanvas = srcLayer.getCanvas();
461 if (srcCanvas.width != 0 && srcCanvas.height != 0)
462 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
464 // Unblock the source layer now that draw is complete
468 // Flag operation as done
472 // If we ARE the source layer, no need to sync.
473 // Syncing would result in deadlock.
474 if (layer === srcLayer)
475 scheduleTask(doCopyRect);
477 // Otherwise synchronize copy operation with source layer
480 // Currently blocked draw task
481 var task = scheduleTask(doCopyRect, true);
483 // Unblock draw task once source layer is ready
484 srcLayer.sync(task.unblock);
486 // Block source layer until draw completes
487 // Note that the draw MAY have already been performed at this point,
488 // in which case creating a lock on the source layer will lead to
489 // deadlock (the draw task has already run and will thus never
492 srcLock = srcLayer.sync(null, true);
499 * Clear the specified rectangle of image data.
501 * @param {Number} x The X coordinate of the upper-left corner of the
502 * rectangle to clear.
503 * @param {Number} y The Y coordinate of the upper-left corner of the
504 * rectangle to clear.
505 * @param {Number} w The width of the rectangle to clear.
506 * @param {Number} h The height of the rectangle to clear.
508 this.clearRect = function(x, y, w, h) {
509 scheduleTask(function() {
510 if (layer.autosize != 0) fitRect(x, y, w, h);
511 displayContext.clearRect(x, y, w, h);
516 * Fill the specified rectangle of image data with the specified color.
518 * @param {Number} x The X coordinate of the upper-left corner of the
520 * @param {Number} y The Y coordinate of the upper-left corner of the
522 * @param {Number} w The width of the rectangle to draw.
523 * @param {Number} h The height of the rectangle to draw.
524 * @param {Number} r The red component of the color of the rectangle.
525 * @param {Number} g The green component of the color of the rectangle.
526 * @param {Number} b The blue component of the color of the rectangle.
527 * @param {Number} a The alpha component of the color of the rectangle.
529 this.drawRect = function(x, y, w, h, r, g, b, a) {
530 scheduleTask(function() {
531 if (layer.autosize != 0) fitRect(x, y, w, h);
532 displayContext.fillStyle = "rgba("
533 + r + "," + g + "," + b + "," + a / 255 + ")";
534 displayContext.fillRect(x, y, w, h);
539 * Clip all future drawing operations by the specified rectangle.
541 * @param {Number} x The X coordinate of the upper-left corner of the
542 * rectangle to use for the clipping region.
543 * @param {Number} y The Y coordinate of the upper-left corner of the
544 * rectangle to use for the clipping region.
545 * @param {Number} w The width of the rectangle to use for the clipping region.
546 * @param {Number} h The height of the rectangle to use for the clipping region.
548 this.clipRect = function(x, y, w, h) {
549 scheduleTask(function() {
551 // Clear any current clipping region
552 displayContext.restore();
553 displayContext.save();
555 if (layer.autosize != 0) fitRect(x, y, w, h);
557 // Set new clipping region
558 displayContext.beginPath();
559 displayContext.rect(x, y, w, h);
560 displayContext.clip();
566 * Provides the given filtering function with a writable snapshot of
567 * image data and the current width and height of the Layer.
569 * @param {function} filter A function which accepts an array of image
570 * data (as returned by the canvas element's
571 * display context's getImageData() function),
572 * the width of the Layer, and the height of the
573 * Layer as parameters, in that order. This
574 * function must accomplish its filtering by
575 * modifying the given image data array directly.
577 this.filter = function(filter) {
578 scheduleTask(function() {
579 var imageData = displayContext.getImageData(0, 0, width, height);
580 filter(imageData.data, width, height);
581 displayContext.putImageData(imageData, 0, 0);
586 * Sets the composite operation for future operations on this Layer. This
587 * operation is either a channel mask, or the ID of a binary raster
590 * The channel mask is a Guacamole-specific compositing operation identifier
591 * with a single bit representing each of four channels (in order): source
592 * image where destination transparent, source where destination opaque,
593 * destination where source transparent, and destination where source
596 * @param {Number} operation The composite operation (channel mask or binary
597 * raster operation) for future operations on this
600 this.setCompositeOperation = function(operation) {
601 scheduleTask(function() {
603 // If channel mask, set composite operation only
604 if (operation <= 0xF) {
605 displayContext.globalCompositeOperation = compositeOperation[operation];
606 transferFunction = null;
609 // Otherwise, set binary raster operation
611 displayContext.globalCompositeOperation = "source-over";
612 transferFunction = binaryCompositeTransferFunction[operation];
618 // Initialize canvas dimensions
619 display.width = width;
620 display.height = height;
625 * Channel mask for the composite operation "rout".
627 Guacamole.Layer.ROUT = 0x2;
630 * Channel mask for the composite operation "atop".
632 Guacamole.Layer.ATOP = 0x6;
635 * Channel mask for the composite operation "xor".
637 Guacamole.Layer.XOR = 0xA;
640 * Channel mask for the composite operation "rover".
642 Guacamole.Layer.ROVER = 0xB;
645 * Channel mask for the composite operation "over".
647 Guacamole.Layer.OVER = 0xE;
650 * Channel mask for the composite operation "plus".
652 Guacamole.Layer.PLUS = 0xF;
655 * Channel mask for the composite operation "rin".
656 * Beware that WebKit-based browsers may leave the contents of the destionation
657 * layer where the source layer is transparent, despite the definition of this
660 Guacamole.Layer.RIN = 0x1;
663 * Channel mask for the composite operation "in".
664 * Beware that WebKit-based browsers may leave the contents of the destionation
665 * layer where the source layer is transparent, despite the definition of this
668 Guacamole.Layer.IN = 0x4;
671 * Channel mask for the composite operation "out".
672 * Beware that WebKit-based browsers may leave the contents of the destionation
673 * layer where the source layer is transparent, despite the definition of this
676 Guacamole.Layer.OUT = 0x8;
679 * Channel mask for the composite operation "ratop".
680 * Beware that WebKit-based browsers may leave the contents of the destionation
681 * layer where the source layer is transparent, despite the definition of this
684 Guacamole.Layer.RATOP = 0x9;
687 * Channel mask for the composite operation "src".
688 * Beware that WebKit-based browsers may leave the contents of the destionation
689 * layer where the source layer is transparent, despite the definition of this
692 Guacamole.Layer.SRC = 0xC;