Reset internal stack state when stack automatically reset from resize.
[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      * Add the specified cubic bezier point to the current path.
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      * @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.
588      */
589     this.path = function(x, y, cp1x, cp1y, cp2x, cp2y) {
590         scheduleTask(function() {
591             
592             // Start a new path if current path is closed
593             if (pathClosed) {
594                 displayContext.beginPath();
595                 pathClosed = false;
596             }
597             
598             if (layer.autosize != 0) fitRect(x, y, 0, 0);
599             displayContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, y);
600             
601         });
602     };
603
604     /**
605      * Add the specified rectangle to the current path.
606      * 
607      * @param {Number} x The X coordinate of the upper-left corner of the
608      *                   rectangle to draw.
609      * @param {Number} y The Y coordinate of the upper-left corner of the
610      *                   rectangle to draw.
611      * @param {Number} w The width of the rectangle to draw.
612      * @param {Number} h The height of the rectangle to draw.
613      */
614     this.rect = function(x, y, w, h) {
615         scheduleTask(function() {
616             
617             // Start a new path if current path is closed
618             if (pathClosed) {
619                 displayContext.beginPath();
620                 pathClosed = false;
621             }
622             
623             if (layer.autosize != 0) fitRect(x, y, w, h);
624             displayContext.rect(x, y, w, h);
625             
626         });
627     };
628
629     /**
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.
634      */
635     this.clip = function() {
636         scheduleTask(function() {
637
638             // Set new clipping region
639             displayContext.clip();
640
641             // Path now implicitly closed
642             pathClosed = true;
643
644         });
645     };
646
647     /**
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.
652      * 
653      * @param {String} cap The line cap style. Can be "round", "square",
654      *                     or "butt".
655      * @param {String} join The line join style. Can be "round", "bevel",
656      *                      or "miter".
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.
662      */
663     this.strokeColor = function(cap, join, thickness, r, g, b, a) {
664         scheduleTask(function() {
665
666             // Stroke with color
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();
672
673             // Path now implicitly closed
674             pathClosed = true;
675
676         });
677     };
678
679     /**
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.
684      * 
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.
689      */
690     this.fillColor = function(r, g, b, a) {
691         scheduleTask(function() {
692
693             // Fill with color
694             displayContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
695             displayContext.fill();
696
697             // Path now implicitly closed
698             pathClosed = true;
699
700         });
701     };
702
703     /**
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.
709      * 
710      * @param {String} cap The line cap style. Can be "round", "square",
711      *                     or "butt".
712      * @param {String} join The line join style. Can be "round", "bevel",
713      *                      or "miter".
714      * @param {Number} thickness The line thickness in pixels.
715      * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
716      *                                   within the stroke.
717      */
718     this.strokeLayer = function(cap, join, thickness, srcLayer) {
719         scheduleTaskSynced(srcLayer, function() {
720
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(),
727                 "repeat"
728             );
729             displayContext.stroke();
730
731             // Path now implicitly closed
732             pathClosed = true;
733
734         });
735     };
736
737     /**
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.
743      * 
744      * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
745      *                                   within the fill.
746      */
747     this.fillLayer = function(srcLayer) {
748         scheduleTask(function() {
749
750             // Fill with image data 
751             displayContext.fillStyle = displayContext.createPattern(
752                 srcLayer.getCanvas(),
753                 "repeat"
754             );
755             displayContext.fill();
756
757             // Path now implicitly closed
758             pathClosed = true;
759
760         });
761     };
762
763     /**
764      * Push current layer state onto stack.
765      */
766     this.push = function() {
767         scheduleTask(function() {
768
769             // Save current state onto stack
770             displayContext.save();
771             stackSize++;
772
773         });
774     };
775
776     /**
777      * Pop layer state off stack.
778      */
779     this.pop = function() {
780         scheduleTask(function() {
781
782             // Restore current state from stack
783             if (stackSize > 0) {
784                 displayContext.restore();
785                 stackSize--;
786             }
787
788         });
789     };
790
791     /**
792      * Reset the layer, clearing the stack, the current path, and any transform
793      * matrix.
794      */
795     this.reset = function() {
796         scheduleTask(function() {
797
798             // Clear stack
799             while (stackSize > 0) {
800                 displayContext.restore();
801                 stackSize--;
802             }
803
804             // Restore to initial state
805             displayContext.restore();
806             displayContext.save();
807
808             // Clear path
809             displayContext.beginPath();
810             pathClosed = false;
811
812         });
813     };
814
815     /**
816      * Applies the given affine transform (defined with three values from the
817      * transform's matrix).
818      * 
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.
825      */
826     this.transform = function(a, b, c, d, e, f) {
827         scheduleTask(function() {
828
829             // Clear transform
830             displayContext.transform(
831                 a, b, c,
832                 d, e, f
833               /*0, 0, 1*/
834             );
835
836         });
837     };
838
839
840     /**
841      * Sets the channel mask for future operations on this Layer.
842      * 
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
847      * opaque.
848      * 
849      * @param {Number} mask The channel mask for future operations on this
850      *                      Layer.
851      */
852     this.setChannelMask = function(mask) {
853         scheduleTask(function() {
854             displayContext.globalCompositeOperation = compositeOperation[mask];
855         });
856     };
857
858     /**
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
862      * joint of the path.
863      * 
864      * @param {Number} limit The miter limit for stroke operations using the
865      *                       miter join.
866      */
867     this.setMiterLimit = function(limit) {
868         scheduleTask(function() {
869             displayContext.miterLimit = limit;
870         });
871     };
872
873     // Initialize canvas dimensions
874     display.width = width;
875     display.height = height;
876
877 };
878
879 /**
880  * Channel mask for the composite operation "rout".
881  */
882 Guacamole.Layer.ROUT  = 0x2;
883
884 /**
885  * Channel mask for the composite operation "atop".
886  */
887 Guacamole.Layer.ATOP  = 0x6;
888
889 /**
890  * Channel mask for the composite operation "xor".
891  */
892 Guacamole.Layer.XOR   = 0xA;
893
894 /**
895  * Channel mask for the composite operation "rover".
896  */
897 Guacamole.Layer.ROVER = 0xB;
898
899 /**
900  * Channel mask for the composite operation "over".
901  */
902 Guacamole.Layer.OVER  = 0xE;
903
904 /**
905  * Channel mask for the composite operation "plus".
906  */
907 Guacamole.Layer.PLUS  = 0xF;
908
909 /**
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
913  * operation.
914  */
915 Guacamole.Layer.RIN   = 0x1;
916
917 /**
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
921  * operation.
922  */
923 Guacamole.Layer.IN    = 0x4;
924
925 /**
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
929  * operation.
930  */
931 Guacamole.Layer.OUT   = 0x8;
932
933 /**
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
937  * operation.
938  */
939 Guacamole.Layer.RATOP = 0x9;
940
941 /**
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
945  * operation.
946  */
947 Guacamole.Layer.SRC   = 0xC;
948
949
950 /**
951  * Represents a single pixel of image data. All components have a minimum value
952  * of 0 and a maximum value of 255.
953  * 
954  * @constructor
955  * 
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.
960  */
961 Guacamole.Layer.Pixel = function(r, g, b, a) {
962
963     /**
964      * The red component of this pixel, where 0 is the minimum value,
965      * and 255 is the maximum.
966      */
967     this.red   = r;
968
969     /**
970      * The green component of this pixel, where 0 is the minimum value,
971      * and 255 is the maximum.
972      */
973     this.green = g;
974
975     /**
976      * The blue component of this pixel, where 0 is the minimum value,
977      * and 255 is the maximum.
978      */
979     this.blue  = b;
980
981     /**
982      * The alpha component of this pixel, where 0 is the minimum value,
983      * and 255 is the maximum.
984      */
985     this.alpha = a;
986
987 };