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 * Map of all Guacamole channel masks to HTML5 canvas composite operation
87 * names. Not all channel mask combinations are currently implemented.
90 var compositeOperation = {
91 /* 0x0 NOT IMPLEMENTED */
92 0x1: "destination-in",
93 0x2: "destination-out",
94 /* 0x3 NOT IMPLEMENTED */
96 /* 0x5 NOT IMPLEMENTED */
98 /* 0x7 NOT IMPLEMENTED */
100 0x9: "destination-atop",
102 0xB: "destination-over",
104 /* 0xD NOT IMPLEMENTED */
110 * Resizes the canvas element backing this Layer without testing the
111 * new size. This function should only be used internally.
114 * @param {Number} newWidth The new width to assign to this Layer.
115 * @param {Number} newHeight The new height to assign to this Layer.
117 function resize(newWidth, newHeight) {
119 // Only preserve old data if width/height are both non-zero
121 if (width != 0 && height != 0) {
123 // Create canvas and context for holding old data
124 oldData = document.createElement("canvas");
125 oldData.width = width;
126 oldData.height = height;
128 var oldDataContext = oldData.getContext("2d");
130 // Copy image data from current
131 oldDataContext.drawImage(display,
133 0, 0, width, height);
137 // Preserve composite operation
138 var oldCompositeOperation = displayContext.globalCompositeOperation;
141 display.width = newWidth;
142 display.height = newHeight;
144 // Redraw old data, if any
146 displayContext.drawImage(oldData,
148 0, 0, width, height);
150 // Restore composite operation
151 displayContext.globalCompositeOperation = oldCompositeOperation;
159 * Given the X and Y coordinates of the upper-left corner of a rectangle
160 * and the rectangle's width and height, resize the backing canvas element
161 * as necessary to ensure that the rectangle fits within the canvas
162 * element's coordinate space. This function will only make the canvas
163 * larger. If the rectangle already fits within the canvas element's
164 * coordinate space, the canvas is left unchanged.
167 * @param {Number} x The X coordinate of the upper-left corner of the
169 * @param {Number} y The Y coordinate of the upper-left corner of the
171 * @param {Number} w The width of the the rectangle to fit.
172 * @param {Number} h The height of the the rectangle to fit.
174 function fitRect(x, y, w, h) {
177 var opBoundX = w + x;
178 var opBoundY = h + y;
180 // Determine max width
182 if (opBoundX > width)
183 resizeWidth = opBoundX;
187 // Determine max height
189 if (opBoundY > height)
190 resizeHeight = opBoundY;
192 resizeHeight = height;
194 // Resize if necessary
195 if (resizeWidth != width || resizeHeight != height)
196 resize(resizeWidth, resizeHeight);
201 * A container for an task handler. Each operation which must be ordered
202 * is associated with a Task that goes into a task queue. Tasks in this
203 * queue are executed in order once their handlers are set, while Tasks
204 * without handlers block themselves and any following Tasks from running.
208 * @param {function} taskHandler The function to call when this task
210 * @param {boolean} blocked Whether this task should start blocked.
212 function Task(taskHandler, blocked) {
217 * Whether this Task is blocked.
221 this.blocked = blocked;
224 * The handler this Task is associated with, if any.
228 this.handler = taskHandler;
231 * Unblocks this Task, allowing it to run.
233 this.unblock = function() {
234 task.blocked = false;
235 handlePendingTasks();
241 * If no tasks are pending or running, run the provided handler immediately,
242 * if any. Otherwise, schedule a task to run immediately after all currently
243 * running or pending tasks are complete.
246 * @param {function} handler The function to call when possible, if any.
247 * @param {boolean} blocked Whether the task should start blocked.
248 * @returns {Task} The Task created and added to the queue for future
249 * running, if any, or null if the handler was run
250 * immediately and no Task needed to be created.
252 function scheduleTask(handler, blocked) {
254 // If no pending tasks, just call (if available) and exit
255 if (layer.isReady() && !blocked) {
256 if (handler) handler();
260 // If tasks are pending/executing, schedule a pending task
261 // and return a reference to it.
262 var task = new Task(handler, blocked);
268 var tasksInProgress = false;
271 * Run any Tasks which were pending but are now ready to run and are not
272 * blocked by other Tasks.
275 function handlePendingTasks() {
280 tasksInProgress = true;
282 // Draw all pending tasks.
284 while ((task = tasks[0]) != null && !task.blocked) {
286 if (task.handler) task.handler();
289 tasksInProgress = false;
294 * Set to true if this Layer should resize itself to accomodate the
295 * dimensions of any drawing operation, and false (the default) otherwise.
297 * Note that setting this property takes effect immediately, and thus may
298 * take effect on operations that were started in the past but have not
299 * yet completed. If you wish the setting of this flag to only modify
300 * future operations, you will need to make the setting of this flag an
301 * operation with sync().
304 * // Set autosize to true for all future operations
305 * layer.sync(function() {
306 * layer.autosize = true;
312 this.autosize = false;
315 * Returns the canvas element backing this Layer.
316 * @returns {Element} The canvas element backing this Layer.
318 this.getCanvas = function() {
323 * Returns whether this Layer is ready. A Layer is ready if it has no
324 * pending operations and no operations in-progress.
326 * @returns {Boolean} true if this Layer is ready, false otherwise.
328 this.isReady = function() {
329 return tasks.length == 0;
333 * Changes the size of this Layer to the given width and height. Resizing
334 * is only attempted if the new size provided is actually different from
337 * @param {Number} newWidth The new width to assign to this Layer.
338 * @param {Number} newHeight The new height to assign to this Layer.
340 this.resize = function(newWidth, newHeight) {
341 scheduleTask(function() {
342 if (newWidth != width || newHeight != height)
343 resize(newWidth, newHeight);
348 * Draws the specified image at the given coordinates. The image specified
349 * must already be loaded.
351 * @param {Number} x The destination X coordinate.
352 * @param {Number} y The destination Y coordinate.
353 * @param {Image} image The image to draw. Note that this is an Image
354 * object - not a URL.
356 this.drawImage = function(x, y, image) {
357 scheduleTask(function() {
358 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
359 displayContext.drawImage(image, x, y);
364 * Draws the image at the specified URL at the given coordinates. The image
365 * will be loaded automatically, and this and any future operations will
366 * wait for the image to finish loading.
368 * @param {Number} x The destination X coordinate.
369 * @param {Number} y The destination Y coordinate.
370 * @param {String} url The URL of the image to draw.
372 this.draw = function(x, y, url) {
374 var task = scheduleTask(function() {
375 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
376 displayContext.drawImage(image, x, y);
379 var image = new Image();
380 image.onload = task.unblock;
386 * Run an arbitrary function as soon as currently pending operations
389 * @param {function} handler The function to call once all currently
390 * pending operations are complete.
391 * @param {boolean} blocked Whether the task should start blocked.
393 this.sync = scheduleTask;
396 * Transfer a rectangle of image data from one Layer to this Layer using the
397 * specified transfer function.
399 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
400 * @param {Number} srcx The X coordinate of the upper-left corner of the
401 * rectangle within the source Layer's coordinate
402 * space to copy data from.
403 * @param {Number} srcy The Y coordinate of the upper-left corner of the
404 * rectangle within the source Layer's coordinate
405 * space to copy data from.
406 * @param {Number} srcw The width of the rectangle within the source Layer's
407 * coordinate space to copy data from.
408 * @param {Number} srch The height of the rectangle within the source
409 * Layer's coordinate space to copy data from.
410 * @param {Number} x The destination X coordinate.
411 * @param {Number} y The destination Y coordinate.
412 * @param {Function} transferFunction The transfer function to use to
413 * transfer data from source to
416 this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
418 var drawComplete = false;
421 function doTransfer() {
422 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
424 var srcCanvas = srcLayer.getCanvas();
425 if (srcCanvas.width != 0 && srcCanvas.height != 0) {
427 // Get image data from src and dst
428 var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
429 var dst = displayContext.getImageData(x , y, srcw, srch);
431 // Apply transfer for each pixel
432 for (var i=0; i<srcw*srch*4; i+=4) {
434 // Get source pixel environment
435 var src_pixel = new Guacamole.Layer.Pixel(
442 // Get destination pixel environment
443 var dst_pixel = new Guacamole.Layer.Pixel(
450 // Apply transfer function
451 transferFunction(src_pixel, dst_pixel);
454 dst.data[i ] = dst_pixel.red;
455 dst.data[i+1] = dst_pixel.green;
456 dst.data[i+2] = dst_pixel.blue;
457 dst.data[i+3] = dst_pixel.alpha;
462 displayContext.putImageData(dst, x, y);
466 // Unblock the source layer now that draw is complete
470 // Flag operation as done
474 // If we ARE the source layer, no need to sync.
475 // Syncing would result in deadlock.
476 if (layer === srcLayer)
477 scheduleTask(doTransfer);
479 // Otherwise synchronize copy operation with source layer
482 // Currently blocked draw task
483 var task = scheduleTask(doTransfer, true);
485 // Unblock draw task once source layer is ready
486 srcLayer.sync(task.unblock);
488 // Block source layer until draw completes
489 // Note that the draw MAY have already been performed at this point,
490 // in which case creating a lock on the source layer will lead to
491 // deadlock (the draw task has already run and will thus never
494 srcLock = srcLayer.sync(null, true);
501 * Copy a rectangle of image data from one Layer to this Layer. This
502 * operation will copy exactly the image data that will be drawn once all
503 * operations of the source Layer that were pending at the time this
504 * function was called are complete. This operation will not alter the
505 * size of the source Layer even if its autosize property is set to true.
507 * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
508 * @param {Number} srcx The X coordinate of the upper-left corner of the
509 * rectangle within the source Layer's coordinate
510 * space to copy data from.
511 * @param {Number} srcy The Y coordinate of the upper-left corner of the
512 * rectangle within the source Layer's coordinate
513 * space to copy data from.
514 * @param {Number} srcw The width of the rectangle within the source Layer's
515 * coordinate space to copy data from.
516 * @param {Number} srch The height of the rectangle within the source
517 * Layer's coordinate space to copy data from.
518 * @param {Number} x The destination X coordinate.
519 * @param {Number} y The destination Y coordinate.
521 this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
523 var drawComplete = false;
526 function doCopyRect() {
527 if (layer.autosize != 0) fitRect(x, y, srcw, srch);
529 var srcCanvas = srcLayer.getCanvas();
530 if (srcCanvas.width != 0 && srcCanvas.height != 0)
531 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
533 // Unblock the source layer now that draw is complete
537 // Flag operation as done
541 // If we ARE the source layer, no need to sync.
542 // Syncing would result in deadlock.
543 if (layer === srcLayer)
544 scheduleTask(doCopyRect);
546 // Otherwise synchronize copy operation with source layer
549 // Currently blocked draw task
550 var task = scheduleTask(doCopyRect, true);
552 // Unblock draw task once source layer is ready
553 srcLayer.sync(task.unblock);
555 // Block source layer until draw completes
556 // Note that the draw MAY have already been performed at this point,
557 // in which case creating a lock on the source layer will lead to
558 // deadlock (the draw task has already run and will thus never
561 srcLock = srcLayer.sync(null, true);
568 * Clear the specified rectangle of image data.
570 * @param {Number} x The X coordinate of the upper-left corner of the
571 * rectangle to clear.
572 * @param {Number} y The Y coordinate of the upper-left corner of the
573 * rectangle to clear.
574 * @param {Number} w The width of the rectangle to clear.
575 * @param {Number} h The height of the rectangle to clear.
577 this.clearRect = function(x, y, w, h) {
578 scheduleTask(function() {
579 if (layer.autosize != 0) fitRect(x, y, w, h);
580 displayContext.clearRect(x, y, w, h);
585 * Fill the specified rectangle of image data with the specified color.
587 * @param {Number} x The X coordinate of the upper-left corner of the
589 * @param {Number} y The Y coordinate of the upper-left corner of the
591 * @param {Number} w The width of the rectangle to draw.
592 * @param {Number} h The height of the rectangle to draw.
593 * @param {Number} r The red component of the color of the rectangle.
594 * @param {Number} g The green component of the color of the rectangle.
595 * @param {Number} b The blue component of the color of the rectangle.
596 * @param {Number} a The alpha component of the color of the rectangle.
598 this.drawRect = function(x, y, w, h, r, g, b, a) {
599 scheduleTask(function() {
600 if (layer.autosize != 0) fitRect(x, y, w, h);
601 displayContext.fillStyle = "rgba("
602 + r + "," + g + "," + b + "," + a / 255 + ")";
603 displayContext.fillRect(x, y, w, h);
608 * Clip all future drawing operations by the specified rectangle.
610 * @param {Number} x The X coordinate of the upper-left corner of the
611 * rectangle to use for the clipping region.
612 * @param {Number} y The Y coordinate of the upper-left corner of the
613 * rectangle to use for the clipping region.
614 * @param {Number} w The width of the rectangle to use for the clipping region.
615 * @param {Number} h The height of the rectangle to use for the clipping region.
617 this.clipRect = function(x, y, w, h) {
618 scheduleTask(function() {
620 // Clear any current clipping region
621 displayContext.restore();
622 displayContext.save();
624 if (layer.autosize != 0) fitRect(x, y, w, h);
626 // Set new clipping region
627 displayContext.beginPath();
628 displayContext.rect(x, y, w, h);
629 displayContext.clip();
635 * Provides the given filtering function with a writable snapshot of
636 * image data and the current width and height of the Layer.
638 * @param {function} filter A function which accepts an array of image
639 * data (as returned by the canvas element's
640 * display context's getImageData() function),
641 * the width of the Layer, and the height of the
642 * Layer as parameters, in that order. This
643 * function must accomplish its filtering by
644 * modifying the given image data array directly.
646 this.filter = function(filter) {
647 scheduleTask(function() {
648 var imageData = displayContext.getImageData(0, 0, width, height);
649 filter(imageData.data, width, height);
650 displayContext.putImageData(imageData, 0, 0);
655 * Sets the channel mask for future operations on this Layer.
657 * The channel mask is a Guacamole-specific compositing operation identifier
658 * with a single bit representing each of four channels (in order): source
659 * image where destination transparent, source where destination opaque,
660 * destination where source transparent, and destination where source
663 * @param {Number} mask The channel mask for future operations on this
666 this.setChannelMask = function(mask) {
667 scheduleTask(function() {
668 displayContext.globalCompositeOperation = compositeOperation[mask];
672 // Initialize canvas dimensions
673 display.width = width;
674 display.height = height;
679 * Channel mask for the composite operation "rout".
681 Guacamole.Layer.ROUT = 0x2;
684 * Channel mask for the composite operation "atop".
686 Guacamole.Layer.ATOP = 0x6;
689 * Channel mask for the composite operation "xor".
691 Guacamole.Layer.XOR = 0xA;
694 * Channel mask for the composite operation "rover".
696 Guacamole.Layer.ROVER = 0xB;
699 * Channel mask for the composite operation "over".
701 Guacamole.Layer.OVER = 0xE;
704 * Channel mask for the composite operation "plus".
706 Guacamole.Layer.PLUS = 0xF;
709 * Channel mask for the composite operation "rin".
710 * Beware that WebKit-based browsers may leave the contents of the destionation
711 * layer where the source layer is transparent, despite the definition of this
714 Guacamole.Layer.RIN = 0x1;
717 * Channel mask for the composite operation "in".
718 * Beware that WebKit-based browsers may leave the contents of the destionation
719 * layer where the source layer is transparent, despite the definition of this
722 Guacamole.Layer.IN = 0x4;
725 * Channel mask for the composite operation "out".
726 * Beware that WebKit-based browsers may leave the contents of the destionation
727 * layer where the source layer is transparent, despite the definition of this
730 Guacamole.Layer.OUT = 0x8;
733 * Channel mask for the composite operation "ratop".
734 * Beware that WebKit-based browsers may leave the contents of the destionation
735 * layer where the source layer is transparent, despite the definition of this
738 Guacamole.Layer.RATOP = 0x9;
741 * Channel mask for the composite operation "src".
742 * Beware that WebKit-based browsers may leave the contents of the destionation
743 * layer where the source layer is transparent, despite the definition of this
746 Guacamole.Layer.SRC = 0xC;
750 * Represents a single pixel of image data. All components have a minimum value
751 * of 0 and a maximum value of 255.
755 * @param {Number} r The red component of this pixel.
756 * @param {Number} g The green component of this pixel.
757 * @param {Number} b The blue component of this pixel.
758 * @param {Number} a The alpha component of this pixel.
760 Guacamole.Layer.Pixel = function(r, g, b, a) {
763 * The red component of this pixel, where 0 is the minimum value,
764 * and 255 is the maximum.
769 * The green component of this pixel, where 0 is the minimum value,
770 * and 255 is the maximum.
775 * The blue component of this pixel, where 0 is the minimum value,
776 * and 255 is the maximum.
781 * The alpha component of this pixel, where 0 is the minimum value,
782 * and 255 is the maximum.