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 * Schedules a task within the current layer just as scheduleTast() does,
305 * except that another specified layer will be blocked until this task
306 * completes, and this task will not start until the other layer is
309 * Essentially, a task is scheduled in both layers, and the specified task
310 * will only be performed once both layers are ready, and neither layer may
311 * proceed until this task completes.
313 * Note that there is no way to specify whether the task starts blocked,
314 * as whether the task is blocked depends completely on whether the
315 * other layer is currently ready.
317 * @param {Guacamole.Layer} otherLayer The other layer which must be blocked
318 * until this task completes.
319 * @param {function} handler The function to call when possible.
321 function scheduleTaskSynced(otherLayer, handler) {
323 // If we ARE the other layer, no need to sync.
324 // Syncing would result in deadlock.
325 if (layer === otherLayer)
326 scheduleTask(handler);
328 // Otherwise synchronize operation with other layer
331 var drawComplete = false;
332 var layerLock = null;
334 function performTask() {
339 // Unblock the other layer now that draw is complete
340 if (layerLock != null)
343 // Flag operation as done
348 // Currently blocked draw task
349 var task = scheduleTask(performTask, true);
351 // Unblock draw task once source layer is ready
352 otherLayer.sync(task.unblock);
354 // Block other layer until draw completes
355 // Note that the draw MAY have already been performed at this point,
356 // in which case creating a lock on the other layer will lead to
357 // deadlock (the draw task has already run and will thus never
360 layerLock = otherLayer.sync(null, true);
366 * Set to true if this Layer should resize itself to accomodate the
367 * dimensions of any drawing operation, and false (the default) otherwise.
369 * Note that setting this property takes effect immediately, and thus may
370 * take effect on operations that were started in the past but have not
371 * yet completed. If you wish the setting of this flag to only modify
372 * future operations, you will need to make the setting of this flag an
373 * operation with sync().
376 * // Set autosize to true for all future operations
377 * layer.sync(function() {
378 * layer.autosize = true;
384 this.autosize = false;
387 * Returns the canvas element backing this Layer.
388 * @returns {Element} The canvas element backing this Layer.
390 this.getCanvas = function() {
395 * Returns whether this Layer is ready. A Layer is ready if it has no
396 * pending operations and no operations in-progress.
398 * @returns {Boolean} true if this Layer is ready, false otherwise.
400 this.isReady = function() {
401 return tasks.length == 0;
405 * Changes the size of this Layer to the given width and height. Resizing
406 * is only attempted if the new size provided is actually different from
409 * @param {Number} newWidth The new width to assign to this Layer.
410 * @param {Number} newHeight The new height to assign to this Layer.
412 this.resize = function(newWidth, newHeight) {
413 scheduleTask(function() {
414 if (newWidth != width || newHeight != height)
415 resize(newWidth, newHeight);
420 * Draws the specified image at the given coordinates. The image specified
421 * must already be loaded.
423 * @param {Number} x The destination X coordinate.
424 * @param {Number} y The destination Y coordinate.
425 * @param {Image} image The image to draw. Note that this is an Image
426 * object - not a URL.
428 this.drawImage = function(x, y, image) {
429 scheduleTask(function() {
430 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
431 displayContext.drawImage(image, x, y);
436 * Draws the image at the specified URL at the given coordinates. The image
437 * will be loaded automatically, and this and any future operations will
438 * wait for the image to finish loading.
440 * @param {Number} x The destination X coordinate.
441 * @param {Number} y The destination Y coordinate.
442 * @param {String} url The URL of the image to draw.
444 this.draw = function(x, y, url) {
446 var task = scheduleTask(function() {
447 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
448 displayContext.drawImage(image, x, y);
451 var image = new Image();
452 image.onload = task.unblock;
458 * Run an arbitrary function as soon as currently pending operations
461 * @param {function} handler The function to call once all currently
462 * pending operations are complete.
463 * @param {boolean} blocked Whether the task should start blocked.
465 this.sync = scheduleTask;
468 * Transfer a rectangle of image data from one Layer to this Layer using the
469 * specified transfer function.
471 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
472 * @param {Number} srcx The X coordinate of the upper-left corner of the
473 * rectangle within the source Layer's coordinate
474 * space to copy data from.
475 * @param {Number} srcy The Y coordinate of the upper-left corner of the
476 * rectangle within the source Layer's coordinate
477 * space to copy data from.
478 * @param {Number} srcw The width of the rectangle within the source Layer's
479 * coordinate space to copy data from.
480 * @param {Number} srch The height of the rectangle within the source
481 * Layer's coordinate space to copy data from.
482 * @param {Number} x The destination X coordinate.
483 * @param {Number} y The destination Y coordinate.
484 * @param {Function} transferFunction The transfer function to use to
485 * transfer data from source to
488 this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
489 scheduleTaskSynced(srcLayer, function() {
491 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
493 var srcCanvas = srcLayer.getCanvas();
494 if (srcCanvas.width != 0 && srcCanvas.height != 0) {
496 // Get image data from src and dst
497 var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
498 var dst = displayContext.getImageData(x , y, srcw, srch);
500 // Apply transfer for each pixel
501 for (var i=0; i<srcw*srch*4; i+=4) {
503 // Get source pixel environment
504 var src_pixel = new Guacamole.Layer.Pixel(
511 // Get destination pixel environment
512 var dst_pixel = new Guacamole.Layer.Pixel(
519 // Apply transfer function
520 transferFunction(src_pixel, dst_pixel);
523 dst.data[i ] = dst_pixel.red;
524 dst.data[i+1] = dst_pixel.green;
525 dst.data[i+2] = dst_pixel.blue;
526 dst.data[i+3] = dst_pixel.alpha;
531 displayContext.putImageData(dst, x, y);
539 * Copy a rectangle of image data from one Layer to this Layer. This
540 * operation will copy exactly the image data that will be drawn once all
541 * operations of the source Layer that were pending at the time this
542 * function was called are complete. This operation will not alter the
543 * size of the source Layer even if its autosize property is set to true.
545 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
546 * @param {Number} srcx The X coordinate of the upper-left corner of the
547 * rectangle within the source Layer's coordinate
548 * space to copy data from.
549 * @param {Number} srcy The Y coordinate of the upper-left corner of the
550 * rectangle within the source Layer's coordinate
551 * space to copy data from.
552 * @param {Number} srcw The width of the rectangle within the source Layer's
553 * coordinate space to copy data from.
554 * @param {Number} srch The height of the rectangle within the source
555 * Layer's coordinate space to copy data from.
556 * @param {Number} x The destination X coordinate.
557 * @param {Number} y The destination Y coordinate.
559 this.copy = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
560 scheduleTaskSynced(srcLayer, function() {
561 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
563 var srcCanvas = srcLayer.getCanvas();
564 if (srcCanvas.width != 0 && srcCanvas.height != 0)
565 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
571 * Add the specified cubic bezier point to the current path.
573 * @param {Number} x The X coordinate of the point to draw.
574 * @param {Number} y The Y coordinate of the point to draw.
575 * @param {Number} cp1x The X coordinate of the first control point.
576 * @param {Number} cp1y The Y coordinate of the first control point.
577 * @param {Number} cp2x The X coordinate of the second control point.
578 * @param {Number} cp2y The Y coordinate of the second control point.
580 this.path = function(x, y, cp1x, cp1y, cp2x, cp2y) {
581 scheduleTask(function() {
583 // Start a new path if current path is closed
585 displayContext.beginPath();
589 if (layer.autosize != 0) fitRect(x, y, 0, 0);
590 displayContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, y);
596 * Add the specified rectangle to the current path.
598 * @param {Number} x The X coordinate of the upper-left corner of the
600 * @param {Number} y The Y coordinate of the upper-left corner of the
602 * @param {Number} w The width of the rectangle to draw.
603 * @param {Number} h The height of the rectangle to draw.
605 this.rect = function(x, y, w, h) {
606 scheduleTask(function() {
608 // Start a new path if current path is closed
610 displayContext.beginPath();
614 if (layer.autosize != 0) fitRect(x, y, w, h);
615 displayContext.rect(x, y, w, h);
621 * Clip all future drawing operations by the current path. The current path
622 * is implicitly closed. The current path can continue to be reused
623 * for other operations (such as fillColor()) but a new path will be started
624 * once a path drawing operation (path() or rect()) is used.
626 this.clip = function() {
627 scheduleTask(function() {
629 // Set new clipping region
630 displayContext.clip();
632 // Path now implicitly closed
639 * Stroke the current path with the specified color. The current path
640 * is implicitly closed. The current path can continue to be reused
641 * for other operations (such as clip()) but a new path will be started
642 * once a path drawing operation (path() or rect()) is used.
644 * @param {String} cap The line cap style. Can be "round", "square",
646 * @param {String} join The line join style. Can be "round", "bevel",
648 * @param {Number} thickness The line thickness in pixels.
649 * @param {Number} r The red component of the color to fill.
650 * @param {Number} g The green component of the color to fill.
651 * @param {Number} b The blue component of the color to fill.
652 * @param {Number} a The alpha component of the color to fill.
654 this.strokeColor = function(cap, join, thickness, r, g, b, a) {
655 scheduleTask(function() {
658 displayContext.lineCap = cap;
659 displayContext.lineJoin = join;
660 displayContext.lineWidth = thickness;
661 displayContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
662 displayContext.stroke();
664 // 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 * Stroke the current path with the image within the specified layer. The
696 * image data will be tiled infinitely within the stroke. The current path
697 * is implicitly closed. The current path can continue to be reused
698 * for other operations (such as clip()) but a new path will be started
699 * once a path drawing operation (path() or rect()) is used.
701 * @param {String} cap The line cap style. Can be "round", "square",
703 * @param {String} join The line join style. Can be "round", "bevel",
705 * @param {Number} thickness The line thickness in pixels.
706 * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
709 this.strokeLayer = function(cap, join, thickness, srcLayer) {
710 scheduleTaskSynced(srcLayer, function() {
712 // Stroke with image data
713 displayContext.lineCap = cap;
714 displayContext.lineJoin = join;
715 displayContext.lineWidth = thickness;
716 displayContext.strokeStyle = displayContext.createPattern(
717 srcLayer.getCanvas(),
720 displayContext.stroke();
722 // Path now implicitly closed
729 * Fills the current path with the image within the specified layer. The
730 * image data will be tiled infinitely within the stroke. The current path
731 * is implicitly closed. The current path can continue to be reused
732 * for other operations (such as clip()) but a new path will be started
733 * once a path drawing operation (path() or rect()) is used.
735 * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
738 this.fillLayer = function(srcLayer) {
739 scheduleTask(function() {
741 // Fill with image data
742 displayContext.fillStyle = displayContext.createPattern(
743 srcLayer.getCanvas(),
746 displayContext.fill();
748 // Path now implicitly closed
755 * Push current layer state onto stack.
757 this.push = function() {
758 scheduleTask(function() {
760 // Save current state onto stack
761 displayContext.save();
768 * Pop layer state off stack.
770 this.pop = function() {
771 scheduleTask(function() {
773 // Restore current state from stack
775 displayContext.restore();
783 * Reset the layer, clearing the stack, the current path, and any transform
786 this.reset = function() {
787 scheduleTask(function() {
790 while (stackSize > 0) {
791 displaycontext.restore();
796 displayContext.setTransform(
803 displayContext.beginPath();
810 * Applies the given affine transform (defined with three values from the
811 * transform's matrix).
813 * @param {Number} a The first value in the affine transform's matrix.
814 * @param {Number} b The second value in the affine transform's matrix.
815 * @param {Number} c The third value in the affine transform's matrix.
816 * @param {Number} d The fourth value in the affine transform's matrix.
817 * @param {Number} e The fifth value in the affine transform's matrix.
818 * @param {Number} f The sixth value in the affine transform's matrix.
820 this.transform = function(a, b, c, d, e, f) {
821 scheduleTask(function() {
824 displayContext.transform(
835 * Sets the channel mask for future operations on this Layer.
837 * The channel mask is a Guacamole-specific compositing operation identifier
838 * with a single bit representing each of four channels (in order): source
839 * image where destination transparent, source where destination opaque,
840 * destination where source transparent, and destination where source
843 * @param {Number} mask The channel mask for future operations on this
846 this.setChannelMask = function(mask) {
847 scheduleTask(function() {
848 displayContext.globalCompositeOperation = compositeOperation[mask];
853 * Sets the miter limit for stroke operations using the miter join. This
854 * limit is the maximum ratio of the size of the miter join to the stroke
855 * width. If this ratio is exceeded, the miter will not be drawn for that
858 * @param {Number} limit The miter limit for stroke operations using the
861 this.setMiterLimit = function(limit) {
862 scheduleTask(function() {
863 displayContext.miterLimit = limit;
867 // Initialize canvas dimensions
868 display.width = width;
869 display.height = height;
874 * Channel mask for the composite operation "rout".
876 Guacamole.Layer.ROUT = 0x2;
879 * Channel mask for the composite operation "atop".
881 Guacamole.Layer.ATOP = 0x6;
884 * Channel mask for the composite operation "xor".
886 Guacamole.Layer.XOR = 0xA;
889 * Channel mask for the composite operation "rover".
891 Guacamole.Layer.ROVER = 0xB;
894 * Channel mask for the composite operation "over".
896 Guacamole.Layer.OVER = 0xE;
899 * Channel mask for the composite operation "plus".
901 Guacamole.Layer.PLUS = 0xF;
904 * Channel mask for the composite operation "rin".
905 * Beware that WebKit-based browsers may leave the contents of the destionation
906 * layer where the source layer is transparent, despite the definition of this
909 Guacamole.Layer.RIN = 0x1;
912 * Channel mask for the composite operation "in".
913 * Beware that WebKit-based browsers may leave the contents of the destionation
914 * layer where the source layer is transparent, despite the definition of this
917 Guacamole.Layer.IN = 0x4;
920 * Channel mask for the composite operation "out".
921 * Beware that WebKit-based browsers may leave the contents of the destionation
922 * layer where the source layer is transparent, despite the definition of this
925 Guacamole.Layer.OUT = 0x8;
928 * Channel mask for the composite operation "ratop".
929 * Beware that WebKit-based browsers may leave the contents of the destionation
930 * layer where the source layer is transparent, despite the definition of this
933 Guacamole.Layer.RATOP = 0x9;
936 * Channel mask for the composite operation "src".
937 * Beware that WebKit-based browsers may leave the contents of the destionation
938 * layer where the source layer is transparent, despite the definition of this
941 Guacamole.Layer.SRC = 0xC;
945 * Represents a single pixel of image data. All components have a minimum value
946 * of 0 and a maximum value of 255.
950 * @param {Number} r The red component of this pixel.
951 * @param {Number} g The green component of this pixel.
952 * @param {Number} b The blue component of this pixel.
953 * @param {Number} a The alpha component of this pixel.
955 Guacamole.Layer.Pixel = function(r, g, b, a) {
958 * The red component of this pixel, where 0 is the minimum value,
959 * and 255 is the maximum.
964 * The green component of this pixel, where 0 is the minimum value,
965 * and 255 is the maximum.
970 * The blue component of this pixel, where 0 is the minimum value,
971 * and 255 is the maximum.
976 * The alpha component of this pixel, where 0 is the minimum value,
977 * and 255 is the maximum.