Refactored to more reasonable path operations.
[guacamole-common-js.git] / src / main / resources / layer.js
1
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
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/
9  *
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
13  * License.
14  *
15  * The Original Code is guacamole-common-js.
16  *
17  * The Initial Developer of the Original Code is
18  * Michael Jumper.
19  * Portions created by the Initial Developer are Copyright (C) 2010
20  * the Initial Developer. All Rights Reserved.
21  *
22  * Contributor(s):
23  *
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.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 // Guacamole namespace
39 var Guacamole = Guacamole || {};
40
41 /**
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.
47  * 
48  * @constructor
49  * 
50  * @param {Number} width The width of the Layer, in pixels. The canvas element
51  *                       backing this Layer will be given this width.
52  *                       
53  * @param {Number} height The height of the Layer, in pixels. The canvas element
54  *                        backing this Layer will be given this height.
55  */
56 Guacamole.Layer = function(width, height) {
57
58     /**
59      * Reference to this Layer.
60      * @private
61      */
62     var layer = this;
63
64     /**
65      * The canvas element backing this Layer.
66      * @private
67      */
68     var display = document.createElement("canvas");
69
70     /**
71      * The 2D display context of the canvas element backing this Layer.
72      * @private
73      */
74     var displayContext = display.getContext("2d");
75     displayContext.save();
76
77     /**
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).
81      * @private
82      */
83     var tasks = new Array();
84
85     /**
86      * Whether a new path should be started with the next path drawing
87      * operations.
88      */
89     var pathClosed = true;
90
91     /**
92      * The number of states on the state stack.
93      * 
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
96      * initial state.
97      */
98     var stackSize = 0;
99
100     /**
101      * Map of all Guacamole channel masks to HTML5 canvas composite operation
102      * names. Not all channel mask combinations are currently implemented.
103      * @private
104      */
105     var compositeOperation = {
106      /* 0x0 NOT IMPLEMENTED */
107         0x1: "destination-in",
108         0x2: "destination-out",
109      /* 0x3 NOT IMPLEMENTED */
110         0x4: "source-in",
111      /* 0x5 NOT IMPLEMENTED */
112         0x6: "source-atop",
113      /* 0x7 NOT IMPLEMENTED */
114         0x8: "source-out",
115         0x9: "destination-atop",
116         0xA: "xor",
117         0xB: "destination-over",
118         0xC: "copy",
119      /* 0xD NOT IMPLEMENTED */
120         0xE: "source-over",
121         0xF: "lighter"
122     };
123
124     /**
125      * Resizes the canvas element backing this Layer without testing the
126      * new size. This function should only be used internally.
127      * 
128      * @private
129      * @param {Number} newWidth The new width to assign to this Layer.
130      * @param {Number} newHeight The new height to assign to this Layer.
131      */
132     function resize(newWidth, newHeight) {
133
134         // Only preserve old data if width/height are both non-zero
135         var oldData = null;
136         if (width != 0 && height != 0) {
137
138             // Create canvas and context for holding old data
139             oldData = document.createElement("canvas");
140             oldData.width = width;
141             oldData.height = height;
142
143             var oldDataContext = oldData.getContext("2d");
144
145             // Copy image data from current
146             oldDataContext.drawImage(display,
147                     0, 0, width, height,
148                     0, 0, width, height);
149
150         }
151
152         // Preserve composite operation
153         var oldCompositeOperation = displayContext.globalCompositeOperation;
154
155         // Resize canvas
156         display.width = newWidth;
157         display.height = newHeight;
158
159         // Redraw old data, if any
160         if (oldData)
161                 displayContext.drawImage(oldData, 
162                     0, 0, width, height,
163                     0, 0, width, height);
164
165         // Restore composite operation
166         displayContext.globalCompositeOperation = oldCompositeOperation;
167
168         width = newWidth;
169         height = newHeight;
170
171         // Acknowledge reset of stack (happens on resize of canvas)
172         stackSize = 0;
173         displayContext.save();
174
175     }
176
177     /**
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.
184      * 
185      * @private
186      * @param {Number} x The X coordinate of the upper-left corner of the
187      *                   rectangle to fit.
188      * @param {Number} y The Y coordinate of the upper-left corner of the
189      *                   rectangle to fit.
190      * @param {Number} w The width of the the rectangle to fit.
191      * @param {Number} h The height of the the rectangle to fit.
192      */
193     function fitRect(x, y, w, h) {
194         
195         // Calculate bounds
196         var opBoundX = w + x;
197         var opBoundY = h + y;
198         
199         // Determine max width
200         var resizeWidth;
201         if (opBoundX > width)
202             resizeWidth = opBoundX;
203         else
204             resizeWidth = width;
205
206         // Determine max height
207         var resizeHeight;
208         if (opBoundY > height)
209             resizeHeight = opBoundY;
210         else
211             resizeHeight = height;
212
213         // Resize if necessary
214         if (resizeWidth != width || resizeHeight != height)
215             resize(resizeWidth, resizeHeight);
216
217     }
218
219     /**
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.
224      *
225      * @constructor
226      * @private
227      * @param {function} taskHandler The function to call when this task 
228      *                               runs, if any.
229      * @param {boolean} blocked Whether this task should start blocked.
230      */
231     function Task(taskHandler, blocked) {
232        
233         var task = this;
234        
235         /**
236          * Whether this Task is blocked.
237          * 
238          * @type boolean
239          */
240         this.blocked = blocked;
241
242         /**
243          * The handler this Task is associated with, if any.
244          * 
245          * @type function
246          */
247         this.handler = taskHandler;
248        
249         /**
250          * Unblocks this Task, allowing it to run.
251          */
252         this.unblock = function() {
253             task.blocked = false;
254             handlePendingTasks();
255         }
256
257     }
258
259     /**
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.
263      * 
264      * @private
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.
270      */
271     function scheduleTask(handler, blocked) {
272         
273         // If no pending tasks, just call (if available) and exit
274         if (layer.isReady() && !blocked) {
275             if (handler) handler();
276             return null;
277         }
278
279         // If tasks are pending/executing, schedule a pending task
280         // and return a reference to it.
281         var task = new Task(handler, blocked);
282         tasks.push(task);
283         return task;
284         
285     }
286
287     var tasksInProgress = false;
288
289     /**
290      * Run any Tasks which were pending but are now ready to run and are not
291      * blocked by other Tasks.
292      * @private
293      */
294     function handlePendingTasks() {
295
296         if (tasksInProgress)
297             return;
298
299         tasksInProgress = true;
300
301         // Draw all pending tasks.
302         var task;
303         while ((task = tasks[0]) != null && !task.blocked) {
304             tasks.shift();
305             if (task.handler) task.handler();
306         }
307
308         tasksInProgress = false;
309
310     }
311
312     /**
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
316      * ready.
317      * 
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.
321      * 
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.
325      * 
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.
329      */
330     function scheduleTaskSynced(otherLayer, handler) {
331
332         // If we ARE the other layer, no need to sync.
333         // Syncing would result in deadlock.
334         if (layer === otherLayer)
335             scheduleTask(handler);
336
337         // Otherwise synchronize operation with other layer
338         else {
339
340             var drawComplete = false;
341             var layerLock = null;
342
343             function performTask() {
344
345                 // Perform task
346                 handler();
347
348                 // Unblock the other layer now that draw is complete
349                 if (layerLock != null) 
350                     layerLock.unblock();
351
352                 // Flag operation as done
353                 drawComplete = true;
354
355             }
356
357             // Currently blocked draw task
358             var task = scheduleTask(performTask, true);
359
360             // Unblock draw task once source layer is ready
361             otherLayer.sync(task.unblock);
362
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
367             // clear the lock)
368             if (!drawComplete)
369                 layerLock = otherLayer.sync(null, true);
370
371         }
372     }
373
374     /**
375      * Set to true if this Layer should resize itself to accomodate the
376      * dimensions of any drawing operation, and false (the default) otherwise.
377      * 
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().
383      * 
384      * @example
385      * // Set autosize to true for all future operations
386      * layer.sync(function() {
387      *     layer.autosize = true;
388      * });
389      * 
390      * @type Boolean
391      * @default false
392      */
393     this.autosize = false;
394
395     /**
396      * Returns the canvas element backing this Layer.
397      * @returns {Element} The canvas element backing this Layer.
398      */
399     this.getCanvas = function() {
400         return display;
401     };
402
403     /**
404      * Returns whether this Layer is ready. A Layer is ready if it has no
405      * pending operations and no operations in-progress.
406      * 
407      * @returns {Boolean} true if this Layer is ready, false otherwise.
408      */
409     this.isReady = function() {
410         return tasks.length == 0;
411     };
412
413     /**
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
416      * the current size.
417      * 
418      * @param {Number} newWidth The new width to assign to this Layer.
419      * @param {Number} newHeight The new height to assign to this Layer.
420      */
421     this.resize = function(newWidth, newHeight) {
422         scheduleTask(function() {
423             if (newWidth != width || newHeight != height)
424                 resize(newWidth, newHeight);
425         });
426     };
427
428     /**
429      * Draws the specified image at the given coordinates. The image specified
430      * must already be loaded.
431      * 
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.
436      */
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);
441         });
442     };
443
444     /**
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.
448      * 
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.
452      */
453     this.draw = function(x, y, url) {
454
455         var task = scheduleTask(function() {
456             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
457             displayContext.drawImage(image, x, y);
458         }, true);
459
460         var image = new Image();
461         image.onload = task.unblock;
462         image.src = url;
463
464     };
465
466     /**
467      * Run an arbitrary function as soon as currently pending operations
468      * are complete.
469      * 
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.
473      */
474     this.sync = scheduleTask;
475
476     /**
477      * Transfer a rectangle of image data from one Layer to this Layer using the
478      * specified transfer function.
479      * 
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
495      *                                    destination.
496      */
497     this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
498         scheduleTaskSynced(srcLayer, function() {
499
500             if (layer.autosize != 0) fitRect(x, y, srcw, srch);
501
502             var srcCanvas = srcLayer.getCanvas();
503             if (srcCanvas.width != 0 && srcCanvas.height != 0) {
504
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);
508
509                 // Apply transfer for each pixel
510                 for (var i=0; i<srcw*srch*4; i+=4) {
511
512                     // Get source pixel environment
513                     var src_pixel = new Guacamole.Layer.Pixel(
514                         src.data[i],
515                         src.data[i+1],
516                         src.data[i+2],
517                         src.data[i+3]
518                     );
519                         
520                     // Get destination pixel environment
521                     var dst_pixel = new Guacamole.Layer.Pixel(
522                         dst.data[i],
523                         dst.data[i+1],
524                         dst.data[i+2],
525                         dst.data[i+3]
526                     );
527
528                     // Apply transfer function
529                     transferFunction(src_pixel, dst_pixel);
530
531                     // Save pixel data
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;
536
537                 }
538
539                 // Draw image data
540                 displayContext.putImageData(dst, x, y);
541
542             }
543
544         });
545     };
546
547     /**
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.
553      * 
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.
567      */
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);
571
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);
575
576         });
577     };
578
579     /**
580      * Starts a new path at the specified point.
581      * 
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      */
585     this.moveTo = function(x, y) {
586         scheduleTask(function() {
587             
588             // Start a new path if current path is closed
589             if (pathClosed) {
590                 displayContext.beginPath();
591                 pathClosed = false;
592             }
593             
594             if (layer.autosize != 0) fitRect(x, y, 0, 0);
595             displayContext.moveTo(x, y);
596             
597         });
598     };
599
600     /**
601      * Add the specified line to the current path.
602      * 
603      * @param {Number} x The X coordinate of the endpoint of the line to draw.
604      * @param {Number} y The Y coordinate of the endpoint of the line to draw.
605      */
606     this.lineTo = function(x, y) {
607         scheduleTask(function() {
608             
609             // Start a new path if current path is closed
610             if (pathClosed) {
611                 displayContext.beginPath();
612                 pathClosed = false;
613             }
614             
615             if (layer.autosize != 0) fitRect(x, y, 0, 0);
616             displayContext.lineTo(x, y);
617             
618         });
619     };
620
621     /**
622      * Add the specified arc to the current path. Drawing direction is
623      * determined by the start and end angles. To draw clockwise, ensure
624      * the end angle is greater than the start angle. To draw counterclockwise,
625      * ensure the end angle is less than the start angle.
626      * 
627      * @param {Number} x The X coordinate of the center of the circle which
628      *                   will contain the arc.
629      * @param {Number} y The Y coordinate of the center of the circle which
630      *                   will contain the arc.
631      * @param {Number} radius The radius of the circle.
632      * @param {Number} startAngle The starting angle of the arc, in radians.
633      * @param {Number} endAngle The ending angle of the arc, in radians.
634      */
635     this.arc = function(x, y, radius, startAngle, endAngle) {
636         scheduleTask(function() {
637             
638             // Start a new path if current path is closed
639             if (pathClosed) {
640                 displayContext.beginPath();
641                 pathClosed = false;
642             }
643             
644             if (layer.autosize != 0) fitRect(x, y, 0, 0);
645             displayContext.arc(x, y, radius, startAngle, endAngle, endAngle < startAngle);
646             
647         });
648     };
649
650     /**
651      * Starts a new path at the specified point.
652      * 
653      * @param {Number} cp1x The X coordinate of the first control point.
654      * @param {Number} cp1y The Y coordinate of the first control point.
655      * @param {Number} cp2x The X coordinate of the second control point.
656      * @param {Number} cp2y The Y coordinate of the second control point.
657      * @param {Number} x The X coordinate of the endpoint of the curve.
658      * @param {Number} y The Y coordinate of the endpoint of the curve.
659      */
660     this.curveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
661         scheduleTask(function() {
662             
663             // Start a new path if current path is closed
664             if (pathClosed) {
665                 displayContext.beginPath();
666                 pathClosed = false;
667             }
668             
669             if (layer.autosize != 0) fitRect(x, y, 0, 0);
670             displayContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
671             
672         });
673     };
674
675     /**
676      * Closes the current path by connecting the end point with the start
677      * point (if any) with a straight line.
678      */
679     this.close = function() {
680         scheduleTask(function() {
681             
682             // Close path
683             displayContext.closePath();
684             pathClosed = true;
685             
686         });
687     };
688
689     /**
690      * Add the specified rectangle to the current path.
691      * 
692      * @param {Number} x The X coordinate of the upper-left corner of the
693      *                   rectangle to draw.
694      * @param {Number} y The Y coordinate of the upper-left corner of the
695      *                   rectangle to draw.
696      * @param {Number} w The width of the rectangle to draw.
697      * @param {Number} h The height of the rectangle to draw.
698      */
699     this.rect = function(x, y, w, h) {
700         scheduleTask(function() {
701             
702             // Start a new path if current path is closed
703             if (pathClosed) {
704                 displayContext.beginPath();
705                 pathClosed = false;
706             }
707             
708             if (layer.autosize != 0) fitRect(x, y, w, h);
709             displayContext.rect(x, y, w, h);
710             
711         });
712     };
713
714     /**
715      * Clip all future drawing operations by the current path. The current path
716      * is implicitly closed. The current path can continue to be reused
717      * for other operations (such as fillColor()) but a new path will be started
718      * once a path drawing operation (path() or rect()) is used.
719      */
720     this.clip = function() {
721         scheduleTask(function() {
722
723             // Set new clipping region
724             displayContext.clip();
725
726             // Path now implicitly closed
727             pathClosed = true;
728
729         });
730     };
731
732     /**
733      * Stroke the current path with the specified color. The current path
734      * is implicitly closed. The current path can continue to be reused
735      * for other operations (such as clip()) but a new path will be started
736      * once a path drawing operation (path() or rect()) is used.
737      * 
738      * @param {String} cap The line cap style. Can be "round", "square",
739      *                     or "butt".
740      * @param {String} join The line join style. Can be "round", "bevel",
741      *                      or "miter".
742      * @param {Number} thickness The line thickness in pixels.
743      * @param {Number} r The red component of the color to fill.
744      * @param {Number} g The green component of the color to fill.
745      * @param {Number} b The blue component of the color to fill.
746      * @param {Number} a The alpha component of the color to fill.
747      */
748     this.strokeColor = function(cap, join, thickness, r, g, b, a) {
749         scheduleTask(function() {
750
751             // Stroke with color
752             displayContext.lineCap = cap;
753             displayContext.lineJoin = join;
754             displayContext.lineWidth = thickness;
755             displayContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
756             displayContext.stroke();
757
758             // Path now implicitly closed
759             pathClosed = true;
760
761         });
762     };
763
764     /**
765      * Fills the current path with the specified color. The current path
766      * is implicitly closed. The current path can continue to be reused
767      * for other operations (such as clip()) but a new path will be started
768      * once a path drawing operation (path() or rect()) is used.
769      * 
770      * @param {Number} r The red component of the color to fill.
771      * @param {Number} g The green component of the color to fill.
772      * @param {Number} b The blue component of the color to fill.
773      * @param {Number} a The alpha component of the color to fill.
774      */
775     this.fillColor = function(r, g, b, a) {
776         scheduleTask(function() {
777
778             // Fill with color
779             displayContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
780             displayContext.fill();
781
782             // Path now implicitly closed
783             pathClosed = true;
784
785         });
786     };
787
788     /**
789      * Stroke the current path with the image within the specified layer. The
790      * image data will be tiled infinitely within the stroke. The current path
791      * is implicitly closed. The current path can continue to be reused
792      * for other operations (such as clip()) but a new path will be started
793      * once a path drawing operation (path() or rect()) is used.
794      * 
795      * @param {String} cap The line cap style. Can be "round", "square",
796      *                     or "butt".
797      * @param {String} join The line join style. Can be "round", "bevel",
798      *                      or "miter".
799      * @param {Number} thickness The line thickness in pixels.
800      * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
801      *                                   within the stroke.
802      */
803     this.strokeLayer = function(cap, join, thickness, srcLayer) {
804         scheduleTaskSynced(srcLayer, function() {
805
806             // Stroke with image data
807             displayContext.lineCap = cap;
808             displayContext.lineJoin = join;
809             displayContext.lineWidth = thickness;
810             displayContext.strokeStyle = displayContext.createPattern(
811                 srcLayer.getCanvas(),
812                 "repeat"
813             );
814             displayContext.stroke();
815
816             // Path now implicitly closed
817             pathClosed = true;
818
819         });
820     };
821
822     /**
823      * Fills the current path with the image within the specified layer. The
824      * image data will be tiled infinitely within the stroke. The current path
825      * is implicitly closed. The current path can continue to be reused
826      * for other operations (such as clip()) but a new path will be started
827      * once a path drawing operation (path() or rect()) is used.
828      * 
829      * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
830      *                                   within the fill.
831      */
832     this.fillLayer = function(srcLayer) {
833         scheduleTask(function() {
834
835             // Fill with image data 
836             displayContext.fillStyle = displayContext.createPattern(
837                 srcLayer.getCanvas(),
838                 "repeat"
839             );
840             displayContext.fill();
841
842             // Path now implicitly closed
843             pathClosed = true;
844
845         });
846     };
847
848     /**
849      * Push current layer state onto stack.
850      */
851     this.push = function() {
852         scheduleTask(function() {
853
854             // Save current state onto stack
855             displayContext.save();
856             stackSize++;
857
858         });
859     };
860
861     /**
862      * Pop layer state off stack.
863      */
864     this.pop = function() {
865         scheduleTask(function() {
866
867             // Restore current state from stack
868             if (stackSize > 0) {
869                 displayContext.restore();
870                 stackSize--;
871             }
872
873         });
874     };
875
876     /**
877      * Reset the layer, clearing the stack, the current path, and any transform
878      * matrix.
879      */
880     this.reset = function() {
881         scheduleTask(function() {
882
883             // Clear stack
884             while (stackSize > 0) {
885                 displayContext.restore();
886                 stackSize--;
887             }
888
889             // Restore to initial state
890             displayContext.restore();
891             displayContext.save();
892
893             // Clear path
894             displayContext.beginPath();
895             pathClosed = false;
896
897         });
898     };
899
900     /**
901      * Sets the given affine transform (defined with six values from the
902      * transform's matrix).
903      * 
904      * @param {Number} a The first value in the affine transform's matrix.
905      * @param {Number} b The second value in the affine transform's matrix.
906      * @param {Number} c The third value in the affine transform's matrix.
907      * @param {Number} d The fourth value in the affine transform's matrix.
908      * @param {Number} e The fifth value in the affine transform's matrix.
909      * @param {Number} f The sixth value in the affine transform's matrix.
910      */
911     this.setTransform = function(a, b, c, d, e, f) {
912         scheduleTask(function() {
913
914             // Set transform
915             displayContext.setTransform(
916                 a, b, c,
917                 d, e, f
918               /*0, 0, 1*/
919             );
920
921         });
922     };
923
924
925     /**
926      * Applies the given affine transform (defined with six values from the
927      * transform's matrix).
928      * 
929      * @param {Number} a The first value in the affine transform's matrix.
930      * @param {Number} b The second value in the affine transform's matrix.
931      * @param {Number} c The third value in the affine transform's matrix.
932      * @param {Number} d The fourth value in the affine transform's matrix.
933      * @param {Number} e The fifth value in the affine transform's matrix.
934      * @param {Number} f The sixth value in the affine transform's matrix.
935      */
936     this.transform = function(a, b, c, d, e, f) {
937         scheduleTask(function() {
938
939             // Apply transform
940             displayContext.transform(
941                 a, b, c,
942                 d, e, f
943               /*0, 0, 1*/
944             );
945
946         });
947     };
948
949
950     /**
951      * Sets the channel mask for future operations on this Layer.
952      * 
953      * The channel mask is a Guacamole-specific compositing operation identifier
954      * with a single bit representing each of four channels (in order): source
955      * image where destination transparent, source where destination opaque,
956      * destination where source transparent, and destination where source
957      * opaque.
958      * 
959      * @param {Number} mask The channel mask for future operations on this
960      *                      Layer.
961      */
962     this.setChannelMask = function(mask) {
963         scheduleTask(function() {
964             displayContext.globalCompositeOperation = compositeOperation[mask];
965         });
966     };
967
968     /**
969      * Sets the miter limit for stroke operations using the miter join. This
970      * limit is the maximum ratio of the size of the miter join to the stroke
971      * width. If this ratio is exceeded, the miter will not be drawn for that
972      * joint of the path.
973      * 
974      * @param {Number} limit The miter limit for stroke operations using the
975      *                       miter join.
976      */
977     this.setMiterLimit = function(limit) {
978         scheduleTask(function() {
979             displayContext.miterLimit = limit;
980         });
981     };
982
983     // Initialize canvas dimensions
984     display.width = width;
985     display.height = height;
986
987 };
988
989 /**
990  * Channel mask for the composite operation "rout".
991  */
992 Guacamole.Layer.ROUT  = 0x2;
993
994 /**
995  * Channel mask for the composite operation "atop".
996  */
997 Guacamole.Layer.ATOP  = 0x6;
998
999 /**
1000  * Channel mask for the composite operation "xor".
1001  */
1002 Guacamole.Layer.XOR   = 0xA;
1003
1004 /**
1005  * Channel mask for the composite operation "rover".
1006  */
1007 Guacamole.Layer.ROVER = 0xB;
1008
1009 /**
1010  * Channel mask for the composite operation "over".
1011  */
1012 Guacamole.Layer.OVER  = 0xE;
1013
1014 /**
1015  * Channel mask for the composite operation "plus".
1016  */
1017 Guacamole.Layer.PLUS  = 0xF;
1018
1019 /**
1020  * Channel mask for the composite operation "rin".
1021  * Beware that WebKit-based browsers may leave the contents of the destionation
1022  * layer where the source layer is transparent, despite the definition of this
1023  * operation.
1024  */
1025 Guacamole.Layer.RIN   = 0x1;
1026
1027 /**
1028  * Channel mask for the composite operation "in".
1029  * Beware that WebKit-based browsers may leave the contents of the destionation
1030  * layer where the source layer is transparent, despite the definition of this
1031  * operation.
1032  */
1033 Guacamole.Layer.IN    = 0x4;
1034
1035 /**
1036  * Channel mask for the composite operation "out".
1037  * Beware that WebKit-based browsers may leave the contents of the destionation
1038  * layer where the source layer is transparent, despite the definition of this
1039  * operation.
1040  */
1041 Guacamole.Layer.OUT   = 0x8;
1042
1043 /**
1044  * Channel mask for the composite operation "ratop".
1045  * Beware that WebKit-based browsers may leave the contents of the destionation
1046  * layer where the source layer is transparent, despite the definition of this
1047  * operation.
1048  */
1049 Guacamole.Layer.RATOP = 0x9;
1050
1051 /**
1052  * Channel mask for the composite operation "src".
1053  * Beware that WebKit-based browsers may leave the contents of the destionation
1054  * layer where the source layer is transparent, despite the definition of this
1055  * operation.
1056  */
1057 Guacamole.Layer.SRC   = 0xC;
1058
1059
1060 /**
1061  * Represents a single pixel of image data. All components have a minimum value
1062  * of 0 and a maximum value of 255.
1063  * 
1064  * @constructor
1065  * 
1066  * @param {Number} r The red component of this pixel.
1067  * @param {Number} g The green component of this pixel.
1068  * @param {Number} b The blue component of this pixel.
1069  * @param {Number} a The alpha component of this pixel.
1070  */
1071 Guacamole.Layer.Pixel = function(r, g, b, a) {
1072
1073     /**
1074      * The red component of this pixel, where 0 is the minimum value,
1075      * and 255 is the maximum.
1076      */
1077     this.red   = r;
1078
1079     /**
1080      * The green component of this pixel, where 0 is the minimum value,
1081      * and 255 is the maximum.
1082      */
1083     this.green = g;
1084
1085     /**
1086      * The blue component of this pixel, where 0 is the minimum value,
1087      * and 255 is the maximum.
1088      */
1089     this.blue  = b;
1090
1091     /**
1092      * The alpha component of this pixel, where 0 is the minimum value,
1093      * and 255 is the maximum.
1094      */
1095     this.alpha = a;
1096
1097 };