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");
77 * The queue of all pending Tasks. Tasks will be run in order, with new
78 * tasks added at the end of the queue and old tasks removed from the
79 * front of the queue (FIFO).
82 var tasks = new Array();
85 * Whether a new path should be started with the next path drawing
88 var pathClosed = true;
91 * The number of states on the state stack.
96 * Map of all Guacamole channel masks to HTML5 canvas composite operation
97 * names. Not all channel mask combinations are currently implemented.
100 var compositeOperation = {
101 /* 0x0 NOT IMPLEMENTED */
102 0x1: "destination-in",
103 0x2: "destination-out",
104 /* 0x3 NOT IMPLEMENTED */
106 /* 0x5 NOT IMPLEMENTED */
108 /* 0x7 NOT IMPLEMENTED */
110 0x9: "destination-atop",
112 0xB: "destination-over",
114 /* 0xD NOT IMPLEMENTED */
120 * Resizes the canvas element backing this Layer without testing the
121 * new size. This function should only be used internally.
124 * @param {Number} newWidth The new width to assign to this Layer.
125 * @param {Number} newHeight The new height to assign to this Layer.
127 function resize(newWidth, newHeight) {
129 // Only preserve old data if width/height are both non-zero
131 if (width != 0 && height != 0) {
133 // Create canvas and context for holding old data
134 oldData = document.createElement("canvas");
135 oldData.width = width;
136 oldData.height = height;
138 var oldDataContext = oldData.getContext("2d");
140 // Copy image data from current
141 oldDataContext.drawImage(display,
143 0, 0, width, height);
147 // Preserve composite operation
148 var oldCompositeOperation = displayContext.globalCompositeOperation;
151 display.width = newWidth;
152 display.height = newHeight;
154 // Redraw old data, if any
156 displayContext.drawImage(oldData,
158 0, 0, width, height);
160 // Restore composite operation
161 displayContext.globalCompositeOperation = oldCompositeOperation;
169 * Given the X and Y coordinates of the upper-left corner of a rectangle
170 * and the rectangle's width and height, resize the backing canvas element
171 * as necessary to ensure that the rectangle fits within the canvas
172 * element's coordinate space. This function will only make the canvas
173 * larger. If the rectangle already fits within the canvas element's
174 * coordinate space, the canvas is left unchanged.
177 * @param {Number} x The X coordinate of the upper-left corner of the
179 * @param {Number} y The Y coordinate of the upper-left corner of the
181 * @param {Number} w The width of the the rectangle to fit.
182 * @param {Number} h The height of the the rectangle to fit.
184 function fitRect(x, y, w, h) {
187 var opBoundX = w + x;
188 var opBoundY = h + y;
190 // Determine max width
192 if (opBoundX > width)
193 resizeWidth = opBoundX;
197 // Determine max height
199 if (opBoundY > height)
200 resizeHeight = opBoundY;
202 resizeHeight = height;
204 // Resize if necessary
205 if (resizeWidth != width || resizeHeight != height)
206 resize(resizeWidth, resizeHeight);
211 * A container for an task handler. Each operation which must be ordered
212 * is associated with a Task that goes into a task queue. Tasks in this
213 * queue are executed in order once their handlers are set, while Tasks
214 * without handlers block themselves and any following Tasks from running.
218 * @param {function} taskHandler The function to call when this task
220 * @param {boolean} blocked Whether this task should start blocked.
222 function Task(taskHandler, blocked) {
227 * Whether this Task is blocked.
231 this.blocked = blocked;
234 * The handler this Task is associated with, if any.
238 this.handler = taskHandler;
241 * Unblocks this Task, allowing it to run.
243 this.unblock = function() {
244 task.blocked = false;
245 handlePendingTasks();
251 * If no tasks are pending or running, run the provided handler immediately,
252 * if any. Otherwise, schedule a task to run immediately after all currently
253 * running or pending tasks are complete.
256 * @param {function} handler The function to call when possible, if any.
257 * @param {boolean} blocked Whether the task should start blocked.
258 * @returns {Task} The Task created and added to the queue for future
259 * running, if any, or null if the handler was run
260 * immediately and no Task needed to be created.
262 function scheduleTask(handler, blocked) {
264 // If no pending tasks, just call (if available) and exit
265 if (layer.isReady() && !blocked) {
266 if (handler) handler();
270 // If tasks are pending/executing, schedule a pending task
271 // and return a reference to it.
272 var task = new Task(handler, blocked);
278 var tasksInProgress = false;
281 * Run any Tasks which were pending but are now ready to run and are not
282 * blocked by other Tasks.
285 function handlePendingTasks() {
290 tasksInProgress = true;
292 // Draw all pending tasks.
294 while ((task = tasks[0]) != null && !task.blocked) {
296 if (task.handler) task.handler();
299 tasksInProgress = false;
304 * Set to true if this Layer should resize itself to accomodate the
305 * dimensions of any drawing operation, and false (the default) otherwise.
307 * Note that setting this property takes effect immediately, and thus may
308 * take effect on operations that were started in the past but have not
309 * yet completed. If you wish the setting of this flag to only modify
310 * future operations, you will need to make the setting of this flag an
311 * operation with sync().
314 * // Set autosize to true for all future operations
315 * layer.sync(function() {
316 * layer.autosize = true;
322 this.autosize = false;
325 * Returns the canvas element backing this Layer.
326 * @returns {Element} The canvas element backing this Layer.
328 this.getCanvas = function() {
333 * Returns whether this Layer is ready. A Layer is ready if it has no
334 * pending operations and no operations in-progress.
336 * @returns {Boolean} true if this Layer is ready, false otherwise.
338 this.isReady = function() {
339 return tasks.length == 0;
343 * Changes the size of this Layer to the given width and height. Resizing
344 * is only attempted if the new size provided is actually different from
347 * @param {Number} newWidth The new width to assign to this Layer.
348 * @param {Number} newHeight The new height to assign to this Layer.
350 this.resize = function(newWidth, newHeight) {
351 scheduleTask(function() {
352 if (newWidth != width || newHeight != height)
353 resize(newWidth, newHeight);
358 * Draws the specified image at the given coordinates. The image specified
359 * must already be loaded.
361 * @param {Number} x The destination X coordinate.
362 * @param {Number} y The destination Y coordinate.
363 * @param {Image} image The image to draw. Note that this is an Image
364 * object - not a URL.
366 this.drawImage = function(x, y, image) {
367 scheduleTask(function() {
368 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
369 displayContext.drawImage(image, x, y);
374 * Draws the image at the specified URL at the given coordinates. The image
375 * will be loaded automatically, and this and any future operations will
376 * wait for the image to finish loading.
378 * @param {Number} x The destination X coordinate.
379 * @param {Number} y The destination Y coordinate.
380 * @param {String} url The URL of the image to draw.
382 this.draw = function(x, y, url) {
384 var task = scheduleTask(function() {
385 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
386 displayContext.drawImage(image, x, y);
389 var image = new Image();
390 image.onload = task.unblock;
396 * Run an arbitrary function as soon as currently pending operations
399 * @param {function} handler The function to call once all currently
400 * pending operations are complete.
401 * @param {boolean} blocked Whether the task should start blocked.
403 this.sync = scheduleTask;
406 * Transfer a rectangle of image data from one Layer to this Layer using the
407 * specified transfer function.
409 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
410 * @param {Number} srcx The X coordinate of the upper-left corner of the
411 * rectangle within the source Layer's coordinate
412 * space to copy data from.
413 * @param {Number} srcy The Y coordinate of the upper-left corner of the
414 * rectangle within the source Layer's coordinate
415 * space to copy data from.
416 * @param {Number} srcw The width of the rectangle within the source Layer's
417 * coordinate space to copy data from.
418 * @param {Number} srch The height of the rectangle within the source
419 * Layer's coordinate space to copy data from.
420 * @param {Number} x The destination X coordinate.
421 * @param {Number} y The destination Y coordinate.
422 * @param {Function} transferFunction The transfer function to use to
423 * transfer data from source to
426 this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
428 var drawComplete = false;
431 function doTransfer() {
432 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
434 var srcCanvas = srcLayer.getCanvas();
435 if (srcCanvas.width != 0 && srcCanvas.height != 0) {
437 // Get image data from src and dst
438 var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
439 var dst = displayContext.getImageData(x , y, srcw, srch);
441 // Apply transfer for each pixel
442 for (var i=0; i<srcw*srch*4; i+=4) {
444 // Get source pixel environment
445 var src_pixel = new Guacamole.Layer.Pixel(
452 // Get destination pixel environment
453 var dst_pixel = new Guacamole.Layer.Pixel(
460 // Apply transfer function
461 transferFunction(src_pixel, dst_pixel);
464 dst.data[i ] = dst_pixel.red;
465 dst.data[i+1] = dst_pixel.green;
466 dst.data[i+2] = dst_pixel.blue;
467 dst.data[i+3] = dst_pixel.alpha;
472 displayContext.putImageData(dst, x, y);
476 // Unblock the source layer now that draw is complete
480 // Flag operation as done
484 // If we ARE the source layer, no need to sync.
485 // Syncing would result in deadlock.
486 if (layer === srcLayer)
487 scheduleTask(doTransfer);
489 // Otherwise synchronize copy operation with source layer
492 // Currently blocked draw task
493 var task = scheduleTask(doTransfer, true);
495 // Unblock draw task once source layer is ready
496 srcLayer.sync(task.unblock);
498 // Block source layer until draw completes
499 // Note that the draw MAY have already been performed at this point,
500 // in which case creating a lock on the source layer will lead to
501 // deadlock (the draw task has already run and will thus never
504 srcLock = srcLayer.sync(null, true);
511 * Copy a rectangle of image data from one Layer to this Layer. This
512 * operation will copy exactly the image data that will be drawn once all
513 * operations of the source Layer that were pending at the time this
514 * function was called are complete. This operation will not alter the
515 * size of the source Layer even if its autosize property is set to true.
517 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
518 * @param {Number} srcx The X coordinate of the upper-left corner of the
519 * rectangle within the source Layer's coordinate
520 * space to copy data from.
521 * @param {Number} srcy The Y coordinate of the upper-left corner of the
522 * rectangle within the source Layer's coordinate
523 * space to copy data from.
524 * @param {Number} srcw The width of the rectangle within the source Layer's
525 * coordinate space to copy data from.
526 * @param {Number} srch The height of the rectangle within the source
527 * Layer's coordinate space to copy data from.
528 * @param {Number} x The destination X coordinate.
529 * @param {Number} y The destination Y coordinate.
531 this.copy = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
533 var drawComplete = false;
537 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
539 var srcCanvas = srcLayer.getCanvas();
540 if (srcCanvas.width != 0 && srcCanvas.height != 0)
541 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
543 // Unblock the source layer now that draw is complete
547 // Flag operation as done
551 // If we ARE the source layer, no need to sync.
552 // Syncing would result in deadlock.
553 if (layer === srcLayer)
554 scheduleTask(doCopy);
556 // Otherwise synchronize copy operation with source layer
559 // Currently blocked draw task
560 var task = scheduleTask(doCopy, true);
562 // Unblock draw task once source layer is ready
563 srcLayer.sync(task.unblock);
565 // Block source layer until draw completes
566 // Note that the draw MAY have already been performed at this point,
567 // in which case creating a lock on the source layer will lead to
568 // deadlock (the draw task has already run and will thus never
571 srcLock = srcLayer.sync(null, true);
578 * Add the specified cubic bezier point to the current path.
580 * @param {Number} x The X coordinate of the point to draw.
581 * @param {Number} y The Y coordinate of the point to draw.
582 * @param {Number} cp1x The X coordinate of the first control point.
583 * @param {Number} cp1y The Y coordinate of the first control point.
584 * @param {Number} cp2x The X coordinate of the second control point.
585 * @param {Number} cp2y The Y coordinate of the second control point.
587 this.path = function(x, y, cp1x, cp1y, cp2x, cp2y) {
588 scheduleTask(function() {
590 // Start a new path if current path is closed
592 displayContext.beginPath();
596 if (layer.autosize != 0) fitRect(x, y, 0, 0);
597 displayContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, y);
603 * Add the specified rectangle to the current path.
605 * @param {Number} x The X coordinate of the upper-left corner of the
607 * @param {Number} y The Y coordinate of the upper-left corner of the
609 * @param {Number} w The width of the rectangle to draw.
610 * @param {Number} h The height of the rectangle to draw.
612 this.rect = function(x, y, w, h) {
613 scheduleTask(function() {
615 // Start a new path if current path is closed
617 displayContext.beginPath();
621 if (layer.autosize != 0) fitRect(x, y, w, h);
622 displayContext.rect(x, y, w, h);
628 * Clip all future drawing operations by the current path. The current path
629 * is implicitly closed. The current path can continue to be reused
630 * for other operations (such as fillColor()) but a new path will be started
631 * once a path drawing operation (path() or rect()) is used.
633 this.clip = function() {
634 scheduleTask(function() {
636 // Set new clipping region
637 displayContext.clip();
639 // Path now implicitly closed
646 * Stroke the current path with the specified color. The current path
647 * is implicitly closed. The current path can continue to be reused
648 * for other operations (such as clip()) but a new path will be started
649 * once a path drawing operation (path() or rect()) is used.
651 * @param {Number} r The red component of the color to fill.
652 * @param {Number} g The green component of the color to fill.
653 * @param {Number} b The blue component of the color to fill.
654 * @param {Number} a The alpha component of the color to fill.
656 this.strokeColor = function(r, g, b, a) {
657 scheduleTask(function() {
660 displayContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
661 displayContext.stroke();
663 // Path now implicitly closed
671 * Fills the current path with the specified color. The current path
672 * is implicitly closed. The current path can continue to be reused
673 * for other operations (such as clip()) but a new path will be started
674 * once a path drawing operation (path() or rect()) is used.
676 * @param {Number} r The red component of the color to fill.
677 * @param {Number} g The green component of the color to fill.
678 * @param {Number} b The blue component of the color to fill.
679 * @param {Number} a The alpha component of the color to fill.
681 this.fillColor = function(r, g, b, a) {
682 scheduleTask(function() {
685 displayContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
686 displayContext.fill();
688 // Path now implicitly closed
695 * Push current layer state onto stack.
697 this.push = function() {
698 scheduleTask(function() {
700 // Save current state onto stack
701 displayContext.save();
708 * Pop layer state off stack.
710 this.pop = function() {
711 scheduleTask(function() {
713 // Restore current state from stack
715 displayContext.restore();
723 * Reset the layer, clearing the stack, the current path, and any transform
726 this.reset = function() {
727 scheduleTask(function() {
730 while (stackSize > 0) {
731 displaycontext.restore();
736 displayContext.setTransform(
743 displayContext.beginPath();
750 * Sets the channel mask for future operations on this Layer.
752 * The channel mask is a Guacamole-specific compositing operation identifier
753 * with a single bit representing each of four channels (in order): source
754 * image where destination transparent, source where destination opaque,
755 * destination where source transparent, and destination where source
758 * @param {Number} mask The channel mask for future operations on this
761 this.setChannelMask = function(mask) {
762 scheduleTask(function() {
763 displayContext.globalCompositeOperation = compositeOperation[mask];
767 // Initialize canvas dimensions
768 display.width = width;
769 display.height = height;
774 * Channel mask for the composite operation "rout".
776 Guacamole.Layer.ROUT = 0x2;
779 * Channel mask for the composite operation "atop".
781 Guacamole.Layer.ATOP = 0x6;
784 * Channel mask for the composite operation "xor".
786 Guacamole.Layer.XOR = 0xA;
789 * Channel mask for the composite operation "rover".
791 Guacamole.Layer.ROVER = 0xB;
794 * Channel mask for the composite operation "over".
796 Guacamole.Layer.OVER = 0xE;
799 * Channel mask for the composite operation "plus".
801 Guacamole.Layer.PLUS = 0xF;
804 * Channel mask for the composite operation "rin".
805 * Beware that WebKit-based browsers may leave the contents of the destionation
806 * layer where the source layer is transparent, despite the definition of this
809 Guacamole.Layer.RIN = 0x1;
812 * Channel mask for the composite operation "in".
813 * Beware that WebKit-based browsers may leave the contents of the destionation
814 * layer where the source layer is transparent, despite the definition of this
817 Guacamole.Layer.IN = 0x4;
820 * Channel mask for the composite operation "out".
821 * Beware that WebKit-based browsers may leave the contents of the destionation
822 * layer where the source layer is transparent, despite the definition of this
825 Guacamole.Layer.OUT = 0x8;
828 * Channel mask for the composite operation "ratop".
829 * Beware that WebKit-based browsers may leave the contents of the destionation
830 * layer where the source layer is transparent, despite the definition of this
833 Guacamole.Layer.RATOP = 0x9;
836 * Channel mask for the composite operation "src".
837 * Beware that WebKit-based browsers may leave the contents of the destionation
838 * layer where the source layer is transparent, despite the definition of this
841 Guacamole.Layer.SRC = 0xC;
845 * Represents a single pixel of image data. All components have a minimum value
846 * of 0 and a maximum value of 255.
850 * @param {Number} r The red component of this pixel.
851 * @param {Number} g The green component of this pixel.
852 * @param {Number} b The blue component of this pixel.
853 * @param {Number} a The alpha component of this pixel.
855 Guacamole.Layer.Pixel = function(r, g, b, a) {
858 * The red component of this pixel, where 0 is the minimum value,
859 * and 255 is the maximum.
864 * The green component of this pixel, where 0 is the minimum value,
865 * and 255 is the maximum.
870 * The blue component of this pixel, where 0 is the minimum value,
871 * and 255 is the maximum.
876 * The alpha component of this pixel, where 0 is the minimum value,
877 * and 255 is the maximum.