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;
174 * Given the X and Y coordinates of the upper-left corner of a rectangle
175 * and the rectangle's width and height, resize the backing canvas element
176 * as necessary to ensure that the rectangle fits within the canvas
177 * element's coordinate space. This function will only make the canvas
178 * larger. If the rectangle already fits within the canvas element's
179 * coordinate space, the canvas is left unchanged.
182 * @param {Number} x The X coordinate of the upper-left corner of the
184 * @param {Number} y The Y coordinate of the upper-left corner of the
186 * @param {Number} w The width of the the rectangle to fit.
187 * @param {Number} h The height of the the rectangle to fit.
189 function fitRect(x, y, w, h) {
192 var opBoundX = w + x;
193 var opBoundY = h + y;
195 // Determine max width
197 if (opBoundX > width)
198 resizeWidth = opBoundX;
202 // Determine max height
204 if (opBoundY > height)
205 resizeHeight = opBoundY;
207 resizeHeight = height;
209 // Resize if necessary
210 if (resizeWidth != width || resizeHeight != height)
211 resize(resizeWidth, resizeHeight);
216 * A container for an task handler. Each operation which must be ordered
217 * is associated with a Task that goes into a task queue. Tasks in this
218 * queue are executed in order once their handlers are set, while Tasks
219 * without handlers block themselves and any following Tasks from running.
223 * @param {function} taskHandler The function to call when this task
225 * @param {boolean} blocked Whether this task should start blocked.
227 function Task(taskHandler, blocked) {
232 * Whether this Task is blocked.
236 this.blocked = blocked;
239 * The handler this Task is associated with, if any.
243 this.handler = taskHandler;
246 * Unblocks this Task, allowing it to run.
248 this.unblock = function() {
249 task.blocked = false;
250 handlePendingTasks();
256 * If no tasks are pending or running, run the provided handler immediately,
257 * if any. Otherwise, schedule a task to run immediately after all currently
258 * running or pending tasks are complete.
261 * @param {function} handler The function to call when possible, if any.
262 * @param {boolean} blocked Whether the task should start blocked.
263 * @returns {Task} The Task created and added to the queue for future
264 * running, if any, or null if the handler was run
265 * immediately and no Task needed to be created.
267 function scheduleTask(handler, blocked) {
269 // If no pending tasks, just call (if available) and exit
270 if (layer.isReady() && !blocked) {
271 if (handler) handler();
275 // If tasks are pending/executing, schedule a pending task
276 // and return a reference to it.
277 var task = new Task(handler, blocked);
283 var tasksInProgress = false;
286 * Run any Tasks which were pending but are now ready to run and are not
287 * blocked by other Tasks.
290 function handlePendingTasks() {
295 tasksInProgress = true;
297 // Draw all pending tasks.
299 while ((task = tasks[0]) != null && !task.blocked) {
301 if (task.handler) task.handler();
304 tasksInProgress = false;
309 * Schedules a task within the current layer just as scheduleTast() does,
310 * except that another specified layer will be blocked until this task
311 * completes, and this task will not start until the other layer is
314 * Essentially, a task is scheduled in both layers, and the specified task
315 * will only be performed once both layers are ready, and neither layer may
316 * proceed until this task completes.
318 * Note that there is no way to specify whether the task starts blocked,
319 * as whether the task is blocked depends completely on whether the
320 * other layer is currently ready.
322 * @param {Guacamole.Layer} otherLayer The other layer which must be blocked
323 * until this task completes.
324 * @param {function} handler The function to call when possible.
326 function scheduleTaskSynced(otherLayer, handler) {
328 // If we ARE the other layer, no need to sync.
329 // Syncing would result in deadlock.
330 if (layer === otherLayer)
331 scheduleTask(handler);
333 // Otherwise synchronize operation with other layer
336 var drawComplete = false;
337 var layerLock = null;
339 function performTask() {
344 // Unblock the other layer now that draw is complete
345 if (layerLock != null)
348 // Flag operation as done
353 // Currently blocked draw task
354 var task = scheduleTask(performTask, true);
356 // Unblock draw task once source layer is ready
357 otherLayer.sync(task.unblock);
359 // Block other layer until draw completes
360 // Note that the draw MAY have already been performed at this point,
361 // in which case creating a lock on the other layer will lead to
362 // deadlock (the draw task has already run and will thus never
365 layerLock = otherLayer.sync(null, true);
371 * Set to true if this Layer should resize itself to accomodate the
372 * dimensions of any drawing operation, and false (the default) otherwise.
374 * Note that setting this property takes effect immediately, and thus may
375 * take effect on operations that were started in the past but have not
376 * yet completed. If you wish the setting of this flag to only modify
377 * future operations, you will need to make the setting of this flag an
378 * operation with sync().
381 * // Set autosize to true for all future operations
382 * layer.sync(function() {
383 * layer.autosize = true;
389 this.autosize = false;
392 * Returns the canvas element backing this Layer.
393 * @returns {Element} The canvas element backing this Layer.
395 this.getCanvas = function() {
400 * Returns whether this Layer is ready. A Layer is ready if it has no
401 * pending operations and no operations in-progress.
403 * @returns {Boolean} true if this Layer is ready, false otherwise.
405 this.isReady = function() {
406 return tasks.length == 0;
410 * Changes the size of this Layer to the given width and height. Resizing
411 * is only attempted if the new size provided is actually different from
414 * @param {Number} newWidth The new width to assign to this Layer.
415 * @param {Number} newHeight The new height to assign to this Layer.
417 this.resize = function(newWidth, newHeight) {
418 scheduleTask(function() {
419 if (newWidth != width || newHeight != height)
420 resize(newWidth, newHeight);
425 * Draws the specified image at the given coordinates. The image specified
426 * must already be loaded.
428 * @param {Number} x The destination X coordinate.
429 * @param {Number} y The destination Y coordinate.
430 * @param {Image} image The image to draw. Note that this is an Image
431 * object - not a URL.
433 this.drawImage = function(x, y, image) {
434 scheduleTask(function() {
435 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
436 displayContext.drawImage(image, x, y);
441 * Draws the image at the specified URL at the given coordinates. The image
442 * will be loaded automatically, and this and any future operations will
443 * wait for the image to finish loading.
445 * @param {Number} x The destination X coordinate.
446 * @param {Number} y The destination Y coordinate.
447 * @param {String} url The URL of the image to draw.
449 this.draw = function(x, y, url) {
451 var task = scheduleTask(function() {
452 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
453 displayContext.drawImage(image, x, y);
456 var image = new Image();
457 image.onload = task.unblock;
463 * Run an arbitrary function as soon as currently pending operations
466 * @param {function} handler The function to call once all currently
467 * pending operations are complete.
468 * @param {boolean} blocked Whether the task should start blocked.
470 this.sync = scheduleTask;
473 * Transfer a rectangle of image data from one Layer to this Layer using the
474 * specified transfer function.
476 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
477 * @param {Number} srcx The X coordinate of the upper-left corner of the
478 * rectangle within the source Layer's coordinate
479 * space to copy data from.
480 * @param {Number} srcy The Y coordinate of the upper-left corner of the
481 * rectangle within the source Layer's coordinate
482 * space to copy data from.
483 * @param {Number} srcw The width of the rectangle within the source Layer's
484 * coordinate space to copy data from.
485 * @param {Number} srch The height of the rectangle within the source
486 * Layer's coordinate space to copy data from.
487 * @param {Number} x The destination X coordinate.
488 * @param {Number} y The destination Y coordinate.
489 * @param {Function} transferFunction The transfer function to use to
490 * transfer data from source to
493 this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
494 scheduleTaskSynced(srcLayer, function() {
496 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
498 var srcCanvas = srcLayer.getCanvas();
499 if (srcCanvas.width != 0 && srcCanvas.height != 0) {
501 // Get image data from src and dst
502 var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
503 var dst = displayContext.getImageData(x , y, srcw, srch);
505 // Apply transfer for each pixel
506 for (var i=0; i<srcw*srch*4; i+=4) {
508 // Get source pixel environment
509 var src_pixel = new Guacamole.Layer.Pixel(
516 // Get destination pixel environment
517 var dst_pixel = new Guacamole.Layer.Pixel(
524 // Apply transfer function
525 transferFunction(src_pixel, dst_pixel);
528 dst.data[i ] = dst_pixel.red;
529 dst.data[i+1] = dst_pixel.green;
530 dst.data[i+2] = dst_pixel.blue;
531 dst.data[i+3] = dst_pixel.alpha;
536 displayContext.putImageData(dst, x, y);
544 * Copy a rectangle of image data from one Layer to this Layer. This
545 * operation will copy exactly the image data that will be drawn once all
546 * operations of the source Layer that were pending at the time this
547 * function was called are complete. This operation will not alter the
548 * size of the source Layer even if its autosize property is set to true.
550 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
551 * @param {Number} srcx The X coordinate of the upper-left corner of the
552 * rectangle within the source Layer's coordinate
553 * space to copy data from.
554 * @param {Number} srcy The Y coordinate of the upper-left corner of the
555 * rectangle within the source Layer's coordinate
556 * space to copy data from.
557 * @param {Number} srcw The width of the rectangle within the source Layer's
558 * coordinate space to copy data from.
559 * @param {Number} srch The height of the rectangle within the source
560 * Layer's coordinate space to copy data from.
561 * @param {Number} x The destination X coordinate.
562 * @param {Number} y The destination Y coordinate.
564 this.copy = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
565 scheduleTaskSynced(srcLayer, function() {
566 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
568 var srcCanvas = srcLayer.getCanvas();
569 if (srcCanvas.width != 0 && srcCanvas.height != 0)
570 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
576 * Add the specified cubic bezier point to the current path.
578 * @param {Number} x The X coordinate of the point to draw.
579 * @param {Number} y The Y coordinate of the point to draw.
580 * @param {Number} cp1x The X coordinate of the first control point.
581 * @param {Number} cp1y The Y coordinate of the first control point.
582 * @param {Number} cp2x The X coordinate of the second control point.
583 * @param {Number} cp2y The Y coordinate of the second control point.
585 this.path = function(x, y, cp1x, cp1y, cp2x, cp2y) {
586 scheduleTask(function() {
588 // Start a new path if current path is closed
590 displayContext.beginPath();
594 if (layer.autosize != 0) fitRect(x, y, 0, 0);
595 displayContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, y);
601 * Add the specified rectangle to the current path.
603 * @param {Number} x The X coordinate of the upper-left corner of the
605 * @param {Number} y The Y coordinate of the upper-left corner of the
607 * @param {Number} w The width of the rectangle to draw.
608 * @param {Number} h The height of the rectangle to draw.
610 this.rect = function(x, y, w, h) {
611 scheduleTask(function() {
613 // Start a new path if current path is closed
615 displayContext.beginPath();
619 if (layer.autosize != 0) fitRect(x, y, w, h);
620 displayContext.rect(x, y, w, h);
626 * Clip all future drawing operations by the current path. The current path
627 * is implicitly closed. The current path can continue to be reused
628 * for other operations (such as fillColor()) but a new path will be started
629 * once a path drawing operation (path() or rect()) is used.
631 this.clip = function() {
632 scheduleTask(function() {
634 // Set new clipping region
635 displayContext.clip();
637 // Path now implicitly closed
644 * Stroke the current path with the specified color. The current path
645 * is implicitly closed. The current path can continue to be reused
646 * for other operations (such as clip()) but a new path will be started
647 * once a path drawing operation (path() or rect()) is used.
649 * @param {String} cap The line cap style. Can be "round", "square",
651 * @param {String} join The line join style. Can be "round", "bevel",
653 * @param {Number} thickness The line thickness in pixels.
654 * @param {Number} r The red component of the color to fill.
655 * @param {Number} g The green component of the color to fill.
656 * @param {Number} b The blue component of the color to fill.
657 * @param {Number} a The alpha component of the color to fill.
659 this.strokeColor = function(cap, join, thickness, r, g, b, a) {
660 scheduleTask(function() {
663 displayContext.lineCap = cap;
664 displayContext.lineJoin = join;
665 displayContext.lineWidth = thickness;
666 displayContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
667 displayContext.stroke();
669 // Path now implicitly closed
676 * Fills the current path with the specified color. The current path
677 * is implicitly closed. The current path can continue to be reused
678 * for other operations (such as clip()) but a new path will be started
679 * once a path drawing operation (path() or rect()) is used.
681 * @param {Number} r The red component of the color to fill.
682 * @param {Number} g The green component of the color to fill.
683 * @param {Number} b The blue component of the color to fill.
684 * @param {Number} a The alpha component of the color to fill.
686 this.fillColor = function(r, g, b, a) {
687 scheduleTask(function() {
690 displayContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
691 displayContext.fill();
693 // Path now implicitly closed
700 * Stroke the current path with the image within the specified layer. The
701 * image data will be tiled infinitely within the stroke. The current path
702 * is implicitly closed. The current path can continue to be reused
703 * for other operations (such as clip()) but a new path will be started
704 * once a path drawing operation (path() or rect()) is used.
706 * @param {String} cap The line cap style. Can be "round", "square",
708 * @param {String} join The line join style. Can be "round", "bevel",
710 * @param {Number} thickness The line thickness in pixels.
711 * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
714 this.strokeLayer = function(cap, join, thickness, srcLayer) {
715 scheduleTaskSynced(srcLayer, function() {
717 // Stroke with image data
718 displayContext.lineCap = cap;
719 displayContext.lineJoin = join;
720 displayContext.lineWidth = thickness;
721 displayContext.strokeStyle = displayContext.createPattern(
722 srcLayer.getCanvas(),
725 displayContext.stroke();
727 // Path now implicitly closed
734 * Fills the current path with the image within the specified layer. The
735 * image data will be tiled infinitely within the stroke. The current path
736 * is implicitly closed. The current path can continue to be reused
737 * for other operations (such as clip()) but a new path will be started
738 * once a path drawing operation (path() or rect()) is used.
740 * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
743 this.fillLayer = function(srcLayer) {
744 scheduleTask(function() {
746 // Fill with image data
747 displayContext.fillStyle = displayContext.createPattern(
748 srcLayer.getCanvas(),
751 displayContext.fill();
753 // Path now implicitly closed
760 * Push current layer state onto stack.
762 this.push = function() {
763 scheduleTask(function() {
765 // Save current state onto stack
766 displayContext.save();
773 * Pop layer state off stack.
775 this.pop = function() {
776 scheduleTask(function() {
778 // Restore current state from stack
780 displayContext.restore();
788 * Reset the layer, clearing the stack, the current path, and any transform
791 this.reset = function() {
792 scheduleTask(function() {
795 while (stackSize > 0) {
796 displayContext.restore();
800 // Restore to initial state
801 displayContext.restore();
802 displayContext.save();
805 displayContext.beginPath();
812 * Applies the given affine transform (defined with three values from the
813 * transform's matrix).
815 * @param {Number} a The first value in the affine transform's matrix.
816 * @param {Number} b The second value in the affine transform's matrix.
817 * @param {Number} c The third value in the affine transform's matrix.
818 * @param {Number} d The fourth value in the affine transform's matrix.
819 * @param {Number} e The fifth value in the affine transform's matrix.
820 * @param {Number} f The sixth value in the affine transform's matrix.
822 this.transform = function(a, b, c, d, e, f) {
823 scheduleTask(function() {
826 displayContext.transform(
837 * Sets the channel mask for future operations on this Layer.
839 * The channel mask is a Guacamole-specific compositing operation identifier
840 * with a single bit representing each of four channels (in order): source
841 * image where destination transparent, source where destination opaque,
842 * destination where source transparent, and destination where source
845 * @param {Number} mask The channel mask for future operations on this
848 this.setChannelMask = function(mask) {
849 scheduleTask(function() {
850 displayContext.globalCompositeOperation = compositeOperation[mask];
855 * Sets the miter limit for stroke operations using the miter join. This
856 * limit is the maximum ratio of the size of the miter join to the stroke
857 * width. If this ratio is exceeded, the miter will not be drawn for that
860 * @param {Number} limit The miter limit for stroke operations using the
863 this.setMiterLimit = function(limit) {
864 scheduleTask(function() {
865 displayContext.miterLimit = limit;
869 // Initialize canvas dimensions
870 display.width = width;
871 display.height = height;
876 * Channel mask for the composite operation "rout".
878 Guacamole.Layer.ROUT = 0x2;
881 * Channel mask for the composite operation "atop".
883 Guacamole.Layer.ATOP = 0x6;
886 * Channel mask for the composite operation "xor".
888 Guacamole.Layer.XOR = 0xA;
891 * Channel mask for the composite operation "rover".
893 Guacamole.Layer.ROVER = 0xB;
896 * Channel mask for the composite operation "over".
898 Guacamole.Layer.OVER = 0xE;
901 * Channel mask for the composite operation "plus".
903 Guacamole.Layer.PLUS = 0xF;
906 * Channel mask for the composite operation "rin".
907 * Beware that WebKit-based browsers may leave the contents of the destionation
908 * layer where the source layer is transparent, despite the definition of this
911 Guacamole.Layer.RIN = 0x1;
914 * Channel mask for the composite operation "in".
915 * Beware that WebKit-based browsers may leave the contents of the destionation
916 * layer where the source layer is transparent, despite the definition of this
919 Guacamole.Layer.IN = 0x4;
922 * Channel mask for the composite operation "out".
923 * Beware that WebKit-based browsers may leave the contents of the destionation
924 * layer where the source layer is transparent, despite the definition of this
927 Guacamole.Layer.OUT = 0x8;
930 * Channel mask for the composite operation "ratop".
931 * Beware that WebKit-based browsers may leave the contents of the destionation
932 * layer where the source layer is transparent, despite the definition of this
935 Guacamole.Layer.RATOP = 0x9;
938 * Channel mask for the composite operation "src".
939 * Beware that WebKit-based browsers may leave the contents of the destionation
940 * layer where the source layer is transparent, despite the definition of this
943 Guacamole.Layer.SRC = 0xC;
947 * Represents a single pixel of image data. All components have a minimum value
948 * of 0 and a maximum value of 255.
952 * @param {Number} r The red component of this pixel.
953 * @param {Number} g The green component of this pixel.
954 * @param {Number} b The blue component of this pixel.
955 * @param {Number} a The alpha component of this pixel.
957 Guacamole.Layer.Pixel = function(r, g, b, a) {
960 * The red component of this pixel, where 0 is the minimum value,
961 * and 255 is the maximum.
966 * The green component of this pixel, where 0 is the minimum value,
967 * and 255 is the maximum.
972 * The blue component of this pixel, where 0 is the minimum value,
973 * and 255 is the maximum.
978 * The alpha component of this pixel, where 0 is the minimum value,
979 * and 255 is the maximum.