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 * Whether a new path should be started with the next path drawing
89 var pathClosed = true;
92 * The number of states on the state stack.
94 * Note that there will ALWAYS be one element on the stack, but that
95 * element is not exposed. It is only used to reset the layer to its
101 * Map of all Guacamole channel masks to HTML5 canvas composite operation
102 * names. Not all channel mask combinations are currently implemented.
105 var compositeOperation = {
106 /* 0x0 NOT IMPLEMENTED */
107 0x1: "destination-in",
108 0x2: "destination-out",
109 /* 0x3 NOT IMPLEMENTED */
111 /* 0x5 NOT IMPLEMENTED */
113 /* 0x7 NOT IMPLEMENTED */
115 0x9: "destination-atop",
117 0xB: "destination-over",
119 /* 0xD NOT IMPLEMENTED */
125 * Resizes the canvas element backing this Layer without testing the
126 * new size. This function should only be used internally.
129 * @param {Number} newWidth The new width to assign to this Layer.
130 * @param {Number} newHeight The new height to assign to this Layer.
132 function resize(newWidth, newHeight) {
134 // Only preserve old data if width/height are both non-zero
136 if (width != 0 && height != 0) {
138 // Create canvas and context for holding old data
139 oldData = document.createElement("canvas");
140 oldData.width = width;
141 oldData.height = height;
143 var oldDataContext = oldData.getContext("2d");
145 // Copy image data from current
146 oldDataContext.drawImage(display,
148 0, 0, width, height);
152 // Preserve composite operation
153 var oldCompositeOperation = displayContext.globalCompositeOperation;
156 display.width = newWidth;
157 display.height = newHeight;
159 // Redraw old data, if any
161 displayContext.drawImage(oldData,
163 0, 0, width, height);
165 // Restore composite operation
166 displayContext.globalCompositeOperation = oldCompositeOperation;
171 // Acknowledge reset of stack (happens on resize of canvas)
173 displayContext.save();
178 * Given the X and Y coordinates of the upper-left corner of a rectangle
179 * and the rectangle's width and height, resize the backing canvas element
180 * as necessary to ensure that the rectangle fits within the canvas
181 * element's coordinate space. This function will only make the canvas
182 * larger. If the rectangle already fits within the canvas element's
183 * coordinate space, the canvas is left unchanged.
186 * @param {Number} x The X coordinate of the upper-left corner of the
188 * @param {Number} y The Y coordinate of the upper-left corner of the
190 * @param {Number} w The width of the the rectangle to fit.
191 * @param {Number} h The height of the the rectangle to fit.
193 function fitRect(x, y, w, h) {
196 var opBoundX = w + x;
197 var opBoundY = h + y;
199 // Determine max width
201 if (opBoundX > width)
202 resizeWidth = opBoundX;
206 // Determine max height
208 if (opBoundY > height)
209 resizeHeight = opBoundY;
211 resizeHeight = height;
213 // Resize if necessary
214 if (resizeWidth != width || resizeHeight != height)
215 resize(resizeWidth, resizeHeight);
220 * A container for an task handler. Each operation which must be ordered
221 * is associated with a Task that goes into a task queue. Tasks in this
222 * queue are executed in order once their handlers are set, while Tasks
223 * without handlers block themselves and any following Tasks from running.
227 * @param {function} taskHandler The function to call when this task
229 * @param {boolean} blocked Whether this task should start blocked.
231 function Task(taskHandler, blocked) {
236 * Whether this Task is blocked.
240 this.blocked = blocked;
243 * The handler this Task is associated with, if any.
247 this.handler = taskHandler;
250 * Unblocks this Task, allowing it to run.
252 this.unblock = function() {
253 task.blocked = false;
254 handlePendingTasks();
260 * If no tasks are pending or running, run the provided handler immediately,
261 * if any. Otherwise, schedule a task to run immediately after all currently
262 * running or pending tasks are complete.
265 * @param {function} handler The function to call when possible, if any.
266 * @param {boolean} blocked Whether the task should start blocked.
267 * @returns {Task} The Task created and added to the queue for future
268 * running, if any, or null if the handler was run
269 * immediately and no Task needed to be created.
271 function scheduleTask(handler, blocked) {
273 // If no pending tasks, just call (if available) and exit
274 if (layer.isReady() && !blocked) {
275 if (handler) handler();
279 // If tasks are pending/executing, schedule a pending task
280 // and return a reference to it.
281 var task = new Task(handler, blocked);
287 var tasksInProgress = false;
290 * Run any Tasks which were pending but are now ready to run and are not
291 * blocked by other Tasks.
294 function handlePendingTasks() {
299 tasksInProgress = true;
301 // Draw all pending tasks.
303 while ((task = tasks[0]) != null && !task.blocked) {
305 if (task.handler) task.handler();
308 tasksInProgress = false;
313 * Schedules a task within the current layer just as scheduleTast() does,
314 * except that another specified layer will be blocked until this task
315 * completes, and this task will not start until the other layer is
318 * Essentially, a task is scheduled in both layers, and the specified task
319 * will only be performed once both layers are ready, and neither layer may
320 * proceed until this task completes.
322 * Note that there is no way to specify whether the task starts blocked,
323 * as whether the task is blocked depends completely on whether the
324 * other layer is currently ready.
326 * @param {Guacamole.Layer} otherLayer The other layer which must be blocked
327 * until this task completes.
328 * @param {function} handler The function to call when possible.
330 function scheduleTaskSynced(otherLayer, handler) {
332 // If we ARE the other layer, no need to sync.
333 // Syncing would result in deadlock.
334 if (layer === otherLayer)
335 scheduleTask(handler);
337 // Otherwise synchronize operation with other layer
340 var drawComplete = false;
341 var layerLock = null;
343 function performTask() {
348 // Unblock the other layer now that draw is complete
349 if (layerLock != null)
352 // Flag operation as done
357 // Currently blocked draw task
358 var task = scheduleTask(performTask, true);
360 // Unblock draw task once source layer is ready
361 otherLayer.sync(task.unblock);
363 // Block other layer until draw completes
364 // Note that the draw MAY have already been performed at this point,
365 // in which case creating a lock on the other layer will lead to
366 // deadlock (the draw task has already run and will thus never
369 layerLock = otherLayer.sync(null, true);
375 * Set to true if this Layer should resize itself to accomodate the
376 * dimensions of any drawing operation, and false (the default) otherwise.
378 * Note that setting this property takes effect immediately, and thus may
379 * take effect on operations that were started in the past but have not
380 * yet completed. If you wish the setting of this flag to only modify
381 * future operations, you will need to make the setting of this flag an
382 * operation with sync().
385 * // Set autosize to true for all future operations
386 * layer.sync(function() {
387 * layer.autosize = true;
393 this.autosize = false;
396 * Returns the canvas element backing this Layer.
397 * @returns {Element} The canvas element backing this Layer.
399 this.getCanvas = function() {
404 * Returns whether this Layer is ready. A Layer is ready if it has no
405 * pending operations and no operations in-progress.
407 * @returns {Boolean} true if this Layer is ready, false otherwise.
409 this.isReady = function() {
410 return tasks.length == 0;
414 * Changes the size of this Layer to the given width and height. Resizing
415 * is only attempted if the new size provided is actually different from
418 * @param {Number} newWidth The new width to assign to this Layer.
419 * @param {Number} newHeight The new height to assign to this Layer.
421 this.resize = function(newWidth, newHeight) {
422 scheduleTask(function() {
423 if (newWidth != width || newHeight != height)
424 resize(newWidth, newHeight);
429 * Draws the specified image at the given coordinates. The image specified
430 * must already be loaded.
432 * @param {Number} x The destination X coordinate.
433 * @param {Number} y The destination Y coordinate.
434 * @param {Image} image The image to draw. Note that this is an Image
435 * object - not a URL.
437 this.drawImage = function(x, y, image) {
438 scheduleTask(function() {
439 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
440 displayContext.drawImage(image, x, y);
445 * Draws the image at the specified URL at the given coordinates. The image
446 * will be loaded automatically, and this and any future operations will
447 * wait for the image to finish loading.
449 * @param {Number} x The destination X coordinate.
450 * @param {Number} y The destination Y coordinate.
451 * @param {String} url The URL of the image to draw.
453 this.draw = function(x, y, url) {
455 var task = scheduleTask(function() {
456 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
457 displayContext.drawImage(image, x, y);
460 var image = new Image();
461 image.onload = task.unblock;
467 * Run an arbitrary function as soon as currently pending operations
470 * @param {function} handler The function to call once all currently
471 * pending operations are complete.
472 * @param {boolean} blocked Whether the task should start blocked.
474 this.sync = scheduleTask;
477 * Transfer a rectangle of image data from one Layer to this Layer using the
478 * specified transfer function.
480 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
481 * @param {Number} srcx The X coordinate of the upper-left corner of the
482 * rectangle within the source Layer's coordinate
483 * space to copy data from.
484 * @param {Number} srcy The Y coordinate of the upper-left corner of the
485 * rectangle within the source Layer's coordinate
486 * space to copy data from.
487 * @param {Number} srcw The width of the rectangle within the source Layer's
488 * coordinate space to copy data from.
489 * @param {Number} srch The height of the rectangle within the source
490 * Layer's coordinate space to copy data from.
491 * @param {Number} x The destination X coordinate.
492 * @param {Number} y The destination Y coordinate.
493 * @param {Function} transferFunction The transfer function to use to
494 * transfer data from source to
497 this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
498 scheduleTaskSynced(srcLayer, function() {
500 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
502 var srcCanvas = srcLayer.getCanvas();
503 if (srcCanvas.width != 0 && srcCanvas.height != 0) {
505 // Get image data from src and dst
506 var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
507 var dst = displayContext.getImageData(x , y, srcw, srch);
509 // Apply transfer for each pixel
510 for (var i=0; i<srcw*srch*4; i+=4) {
512 // Get source pixel environment
513 var src_pixel = new Guacamole.Layer.Pixel(
520 // Get destination pixel environment
521 var dst_pixel = new Guacamole.Layer.Pixel(
528 // Apply transfer function
529 transferFunction(src_pixel, dst_pixel);
532 dst.data[i ] = dst_pixel.red;
533 dst.data[i+1] = dst_pixel.green;
534 dst.data[i+2] = dst_pixel.blue;
535 dst.data[i+3] = dst_pixel.alpha;
540 displayContext.putImageData(dst, x, y);
548 * Copy a rectangle of image data from one Layer to this Layer. This
549 * operation will copy exactly the image data that will be drawn once all
550 * operations of the source Layer that were pending at the time this
551 * function was called are complete. This operation will not alter the
552 * size of the source Layer even if its autosize property is set to true.
554 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
555 * @param {Number} srcx The X coordinate of the upper-left corner of the
556 * rectangle within the source Layer's coordinate
557 * space to copy data from.
558 * @param {Number} srcy The Y coordinate of the upper-left corner of the
559 * rectangle within the source Layer's coordinate
560 * space to copy data from.
561 * @param {Number} srcw The width of the rectangle within the source Layer's
562 * coordinate space to copy data from.
563 * @param {Number} srch The height of the rectangle within the source
564 * Layer's coordinate space to copy data from.
565 * @param {Number} x The destination X coordinate.
566 * @param {Number} y The destination Y coordinate.
568 this.copy = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
569 scheduleTaskSynced(srcLayer, function() {
570 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
572 var srcCanvas = srcLayer.getCanvas();
573 if (srcCanvas.width != 0 && srcCanvas.height != 0)
574 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
580 * Add the specified cubic bezier point to the current path.
582 * @param {Number} x The X coordinate of the point to draw.
583 * @param {Number} y The Y coordinate of the point to draw.
584 * @param {Number} cp1x The X coordinate of the first control point.
585 * @param {Number} cp1y The Y coordinate of the first control point.
586 * @param {Number} cp2x The X coordinate of the second control point.
587 * @param {Number} cp2y The Y coordinate of the second control point.
589 this.path = function(x, y, cp1x, cp1y, cp2x, cp2y) {
590 scheduleTask(function() {
592 // Start a new path if current path is closed
594 displayContext.beginPath();
598 if (layer.autosize != 0) fitRect(x, y, 0, 0);
599 displayContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, y);
605 * Add the specified rectangle to the current path.
607 * @param {Number} x The X coordinate of the upper-left corner of the
609 * @param {Number} y The Y coordinate of the upper-left corner of the
611 * @param {Number} w The width of the rectangle to draw.
612 * @param {Number} h The height of the rectangle to draw.
614 this.rect = function(x, y, w, h) {
615 scheduleTask(function() {
617 // Start a new path if current path is closed
619 displayContext.beginPath();
623 if (layer.autosize != 0) fitRect(x, y, w, h);
624 displayContext.rect(x, y, w, h);
630 * Clip all future drawing operations by the current path. The current path
631 * is implicitly closed. The current path can continue to be reused
632 * for other operations (such as fillColor()) but a new path will be started
633 * once a path drawing operation (path() or rect()) is used.
635 this.clip = function() {
636 scheduleTask(function() {
638 // Set new clipping region
639 displayContext.clip();
641 // Path now implicitly closed
648 * Stroke the current path with the specified color. The current path
649 * is implicitly closed. The current path can continue to be reused
650 * for other operations (such as clip()) but a new path will be started
651 * once a path drawing operation (path() or rect()) is used.
653 * @param {String} cap The line cap style. Can be "round", "square",
655 * @param {String} join The line join style. Can be "round", "bevel",
657 * @param {Number} thickness The line thickness in pixels.
658 * @param {Number} r The red component of the color to fill.
659 * @param {Number} g The green component of the color to fill.
660 * @param {Number} b The blue component of the color to fill.
661 * @param {Number} a The alpha component of the color to fill.
663 this.strokeColor = function(cap, join, thickness, r, g, b, a) {
664 scheduleTask(function() {
667 displayContext.lineCap = cap;
668 displayContext.lineJoin = join;
669 displayContext.lineWidth = thickness;
670 displayContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
671 displayContext.stroke();
673 // Path now implicitly closed
680 * Fills the current path with the specified color. The current path
681 * is implicitly closed. The current path can continue to be reused
682 * for other operations (such as clip()) but a new path will be started
683 * once a path drawing operation (path() or rect()) is used.
685 * @param {Number} r The red component of the color to fill.
686 * @param {Number} g The green component of the color to fill.
687 * @param {Number} b The blue component of the color to fill.
688 * @param {Number} a The alpha component of the color to fill.
690 this.fillColor = function(r, g, b, a) {
691 scheduleTask(function() {
694 displayContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
695 displayContext.fill();
697 // Path now implicitly closed
704 * Stroke the current path with the image within the specified layer. The
705 * image data will be tiled infinitely within the stroke. The current path
706 * is implicitly closed. The current path can continue to be reused
707 * for other operations (such as clip()) but a new path will be started
708 * once a path drawing operation (path() or rect()) is used.
710 * @param {String} cap The line cap style. Can be "round", "square",
712 * @param {String} join The line join style. Can be "round", "bevel",
714 * @param {Number} thickness The line thickness in pixels.
715 * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
718 this.strokeLayer = function(cap, join, thickness, srcLayer) {
719 scheduleTaskSynced(srcLayer, function() {
721 // Stroke with image data
722 displayContext.lineCap = cap;
723 displayContext.lineJoin = join;
724 displayContext.lineWidth = thickness;
725 displayContext.strokeStyle = displayContext.createPattern(
726 srcLayer.getCanvas(),
729 displayContext.stroke();
731 // Path now implicitly closed
738 * Fills the current path with the image within the specified layer. The
739 * image data will be tiled infinitely within the stroke. The current path
740 * is implicitly closed. The current path can continue to be reused
741 * for other operations (such as clip()) but a new path will be started
742 * once a path drawing operation (path() or rect()) is used.
744 * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
747 this.fillLayer = function(srcLayer) {
748 scheduleTask(function() {
750 // Fill with image data
751 displayContext.fillStyle = displayContext.createPattern(
752 srcLayer.getCanvas(),
755 displayContext.fill();
757 // Path now implicitly closed
764 * Push current layer state onto stack.
766 this.push = function() {
767 scheduleTask(function() {
769 // Save current state onto stack
770 displayContext.save();
777 * Pop layer state off stack.
779 this.pop = function() {
780 scheduleTask(function() {
782 // Restore current state from stack
784 displayContext.restore();
792 * Reset the layer, clearing the stack, the current path, and any transform
795 this.reset = function() {
796 scheduleTask(function() {
799 while (stackSize > 0) {
800 displayContext.restore();
804 // Restore to initial state
805 displayContext.restore();
806 displayContext.save();
809 displayContext.beginPath();
816 * Applies the given affine transform (defined with three values from the
817 * transform's matrix).
819 * @param {Number} a The first value in the affine transform's matrix.
820 * @param {Number} b The second value in the affine transform's matrix.
821 * @param {Number} c The third value in the affine transform's matrix.
822 * @param {Number} d The fourth value in the affine transform's matrix.
823 * @param {Number} e The fifth value in the affine transform's matrix.
824 * @param {Number} f The sixth value in the affine transform's matrix.
826 this.transform = function(a, b, c, d, e, f) {
827 scheduleTask(function() {
830 displayContext.transform(
841 * Sets the channel mask for future operations on this Layer.
843 * The channel mask is a Guacamole-specific compositing operation identifier
844 * with a single bit representing each of four channels (in order): source
845 * image where destination transparent, source where destination opaque,
846 * destination where source transparent, and destination where source
849 * @param {Number} mask The channel mask for future operations on this
852 this.setChannelMask = function(mask) {
853 scheduleTask(function() {
854 displayContext.globalCompositeOperation = compositeOperation[mask];
859 * Sets the miter limit for stroke operations using the miter join. This
860 * limit is the maximum ratio of the size of the miter join to the stroke
861 * width. If this ratio is exceeded, the miter will not be drawn for that
864 * @param {Number} limit The miter limit for stroke operations using the
867 this.setMiterLimit = function(limit) {
868 scheduleTask(function() {
869 displayContext.miterLimit = limit;
873 // Initialize canvas dimensions
874 display.width = width;
875 display.height = height;
880 * Channel mask for the composite operation "rout".
882 Guacamole.Layer.ROUT = 0x2;
885 * Channel mask for the composite operation "atop".
887 Guacamole.Layer.ATOP = 0x6;
890 * Channel mask for the composite operation "xor".
892 Guacamole.Layer.XOR = 0xA;
895 * Channel mask for the composite operation "rover".
897 Guacamole.Layer.ROVER = 0xB;
900 * Channel mask for the composite operation "over".
902 Guacamole.Layer.OVER = 0xE;
905 * Channel mask for the composite operation "plus".
907 Guacamole.Layer.PLUS = 0xF;
910 * Channel mask for the composite operation "rin".
911 * Beware that WebKit-based browsers may leave the contents of the destionation
912 * layer where the source layer is transparent, despite the definition of this
915 Guacamole.Layer.RIN = 0x1;
918 * Channel mask for the composite operation "in".
919 * Beware that WebKit-based browsers may leave the contents of the destionation
920 * layer where the source layer is transparent, despite the definition of this
923 Guacamole.Layer.IN = 0x4;
926 * Channel mask for the composite operation "out".
927 * Beware that WebKit-based browsers may leave the contents of the destionation
928 * layer where the source layer is transparent, despite the definition of this
931 Guacamole.Layer.OUT = 0x8;
934 * Channel mask for the composite operation "ratop".
935 * Beware that WebKit-based browsers may leave the contents of the destionation
936 * layer where the source layer is transparent, despite the definition of this
939 Guacamole.Layer.RATOP = 0x9;
942 * Channel mask for the composite operation "src".
943 * Beware that WebKit-based browsers may leave the contents of the destionation
944 * layer where the source layer is transparent, despite the definition of this
947 Guacamole.Layer.SRC = 0xC;
951 * Represents a single pixel of image data. All components have a minimum value
952 * of 0 and a maximum value of 255.
956 * @param {Number} r The red component of this pixel.
957 * @param {Number} g The green component of this pixel.
958 * @param {Number} b The blue component of this pixel.
959 * @param {Number} a The alpha component of this pixel.
961 Guacamole.Layer.Pixel = function(r, g, b, a) {
964 * The red component of this pixel, where 0 is the minimum value,
965 * and 255 is the maximum.
970 * The green component of this pixel, where 0 is the minimum value,
971 * and 255 is the maximum.
976 * The blue component of this pixel, where 0 is the minimum value,
977 * and 255 is the maximum.
982 * The alpha component of this pixel, where 0 is the minimum value,
983 * and 255 is the maximum.