Fix reset() to properly reset EVERYTHING.
[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     }
172
173     /**
174      * Given the X and Y coordinates of the upper-left corner of a rectangle
175      * and the rectangle's width and height, resize the backing canvas element
176      * as necessary to ensure that the rectangle fits within the canvas
177      * element's coordinate space. This function will only make the canvas
178      * larger. If the rectangle already fits within the canvas element's
179      * coordinate space, the canvas is left unchanged.
180      * 
181      * @private
182      * @param {Number} x The X coordinate of the upper-left corner of the
183      *                   rectangle to fit.
184      * @param {Number} y The Y coordinate of the upper-left corner of the
185      *                   rectangle to fit.
186      * @param {Number} w The width of the the rectangle to fit.
187      * @param {Number} h The height of the the rectangle to fit.
188      */
189     function fitRect(x, y, w, h) {
190         
191         // Calculate bounds
192         var opBoundX = w + x;
193         var opBoundY = h + y;
194         
195         // Determine max width
196         var resizeWidth;
197         if (opBoundX > width)
198             resizeWidth = opBoundX;
199         else
200             resizeWidth = width;
201
202         // Determine max height
203         var resizeHeight;
204         if (opBoundY > height)
205             resizeHeight = opBoundY;
206         else
207             resizeHeight = height;
208
209         // Resize if necessary
210         if (resizeWidth != width || resizeHeight != height)
211             resize(resizeWidth, resizeHeight);
212
213     }
214
215     /**
216      * A container for an task handler. Each operation which must be ordered
217      * is associated with a Task that goes into a task queue. Tasks in this
218      * queue are executed in order once their handlers are set, while Tasks 
219      * without handlers block themselves and any following Tasks from running.
220      *
221      * @constructor
222      * @private
223      * @param {function} taskHandler The function to call when this task 
224      *                               runs, if any.
225      * @param {boolean} blocked Whether this task should start blocked.
226      */
227     function Task(taskHandler, blocked) {
228        
229         var task = this;
230        
231         /**
232          * Whether this Task is blocked.
233          * 
234          * @type boolean
235          */
236         this.blocked = blocked;
237
238         /**
239          * The handler this Task is associated with, if any.
240          * 
241          * @type function
242          */
243         this.handler = taskHandler;
244        
245         /**
246          * Unblocks this Task, allowing it to run.
247          */
248         this.unblock = function() {
249             task.blocked = false;
250             handlePendingTasks();
251         }
252
253     }
254
255     /**
256      * If no tasks are pending or running, run the provided handler immediately,
257      * if any. Otherwise, schedule a task to run immediately after all currently
258      * running or pending tasks are complete.
259      * 
260      * @private
261      * @param {function} handler The function to call when possible, if any.
262      * @param {boolean} blocked Whether the task should start blocked.
263      * @returns {Task} The Task created and added to the queue for future
264      *                 running, if any, or null if the handler was run
265      *                 immediately and no Task needed to be created.
266      */
267     function scheduleTask(handler, blocked) {
268         
269         // If no pending tasks, just call (if available) and exit
270         if (layer.isReady() && !blocked) {
271             if (handler) handler();
272             return null;
273         }
274
275         // If tasks are pending/executing, schedule a pending task
276         // and return a reference to it.
277         var task = new Task(handler, blocked);
278         tasks.push(task);
279         return task;
280         
281     }
282
283     var tasksInProgress = false;
284
285     /**
286      * Run any Tasks which were pending but are now ready to run and are not
287      * blocked by other Tasks.
288      * @private
289      */
290     function handlePendingTasks() {
291
292         if (tasksInProgress)
293             return;
294
295         tasksInProgress = true;
296
297         // Draw all pending tasks.
298         var task;
299         while ((task = tasks[0]) != null && !task.blocked) {
300             tasks.shift();
301             if (task.handler) task.handler();
302         }
303
304         tasksInProgress = false;
305
306     }
307
308     /**
309      * Schedules a task within the current layer just as scheduleTast() does,
310      * except that another specified layer will be blocked until this task
311      * completes, and this task will not start until the other layer is
312      * ready.
313      * 
314      * Essentially, a task is scheduled in both layers, and the specified task
315      * will only be performed once both layers are ready, and neither layer may
316      * proceed until this task completes.
317      * 
318      * Note that there is no way to specify whether the task starts blocked,
319      * as whether the task is blocked depends completely on whether the
320      * other layer is currently ready.
321      * 
322      * @param {Guacamole.Layer} otherLayer The other layer which must be blocked
323      *                          until this task completes.
324      * @param {function} handler The function to call when possible.
325      */
326     function scheduleTaskSynced(otherLayer, handler) {
327
328         // If we ARE the other layer, no need to sync.
329         // Syncing would result in deadlock.
330         if (layer === otherLayer)
331             scheduleTask(handler);
332
333         // Otherwise synchronize operation with other layer
334         else {
335
336             var drawComplete = false;
337             var layerLock = null;
338
339             function performTask() {
340
341                 // Perform task
342                 handler();
343
344                 // Unblock the other layer now that draw is complete
345                 if (layerLock != null) 
346                     layerLock.unblock();
347
348                 // Flag operation as done
349                 drawComplete = true;
350
351             }
352
353             // Currently blocked draw task
354             var task = scheduleTask(performTask, true);
355
356             // Unblock draw task once source layer is ready
357             otherLayer.sync(task.unblock);
358
359             // Block other layer until draw completes
360             // Note that the draw MAY have already been performed at this point,
361             // in which case creating a lock on the other layer will lead to
362             // deadlock (the draw task has already run and will thus never
363             // clear the lock)
364             if (!drawComplete)
365                 layerLock = otherLayer.sync(null, true);
366
367         }
368     }
369
370     /**
371      * Set to true if this Layer should resize itself to accomodate the
372      * dimensions of any drawing operation, and false (the default) otherwise.
373      * 
374      * Note that setting this property takes effect immediately, and thus may
375      * take effect on operations that were started in the past but have not
376      * yet completed. If you wish the setting of this flag to only modify
377      * future operations, you will need to make the setting of this flag an
378      * operation with sync().
379      * 
380      * @example
381      * // Set autosize to true for all future operations
382      * layer.sync(function() {
383      *     layer.autosize = true;
384      * });
385      * 
386      * @type Boolean
387      * @default false
388      */
389     this.autosize = false;
390
391     /**
392      * Returns the canvas element backing this Layer.
393      * @returns {Element} The canvas element backing this Layer.
394      */
395     this.getCanvas = function() {
396         return display;
397     };
398
399     /**
400      * Returns whether this Layer is ready. A Layer is ready if it has no
401      * pending operations and no operations in-progress.
402      * 
403      * @returns {Boolean} true if this Layer is ready, false otherwise.
404      */
405     this.isReady = function() {
406         return tasks.length == 0;
407     };
408
409     /**
410      * Changes the size of this Layer to the given width and height. Resizing
411      * is only attempted if the new size provided is actually different from
412      * the current size.
413      * 
414      * @param {Number} newWidth The new width to assign to this Layer.
415      * @param {Number} newHeight The new height to assign to this Layer.
416      */
417     this.resize = function(newWidth, newHeight) {
418         scheduleTask(function() {
419             if (newWidth != width || newHeight != height)
420                 resize(newWidth, newHeight);
421         });
422     };
423
424     /**
425      * Draws the specified image at the given coordinates. The image specified
426      * must already be loaded.
427      * 
428      * @param {Number} x The destination X coordinate.
429      * @param {Number} y The destination Y coordinate.
430      * @param {Image} image The image to draw. Note that this is an Image
431      *                      object - not a URL.
432      */
433     this.drawImage = function(x, y, image) {
434         scheduleTask(function() {
435             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
436             displayContext.drawImage(image, x, y);
437         });
438     };
439
440     /**
441      * Draws the image at the specified URL at the given coordinates. The image
442      * will be loaded automatically, and this and any future operations will
443      * wait for the image to finish loading.
444      * 
445      * @param {Number} x The destination X coordinate.
446      * @param {Number} y The destination Y coordinate.
447      * @param {String} url The URL of the image to draw.
448      */
449     this.draw = function(x, y, url) {
450
451         var task = scheduleTask(function() {
452             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
453             displayContext.drawImage(image, x, y);
454         }, true);
455
456         var image = new Image();
457         image.onload = task.unblock;
458         image.src = url;
459
460     };
461
462     /**
463      * Run an arbitrary function as soon as currently pending operations
464      * are complete.
465      * 
466      * @param {function} handler The function to call once all currently
467      *                           pending operations are complete.
468      * @param {boolean} blocked Whether the task should start blocked.
469      */
470     this.sync = scheduleTask;
471
472     /**
473      * Transfer a rectangle of image data from one Layer to this Layer using the
474      * specified transfer function.
475      * 
476      * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
477      * @param {Number} srcx The X coordinate of the upper-left corner of the
478      *                      rectangle within the source Layer's coordinate
479      *                      space to copy data from.
480      * @param {Number} srcy The Y coordinate of the upper-left corner of the
481      *                      rectangle within the source Layer's coordinate
482      *                      space to copy data from.
483      * @param {Number} srcw The width of the rectangle within the source Layer's
484      *                      coordinate space to copy data from.
485      * @param {Number} srch The height of the rectangle within the source
486      *                      Layer's coordinate space to copy data from.
487      * @param {Number} x The destination X coordinate.
488      * @param {Number} y The destination Y coordinate.
489      * @param {Function} transferFunction The transfer function to use to
490      *                                    transfer data from source to
491      *                                    destination.
492      */
493     this.transfer = function(srcLayer, srcx, srcy, srcw, srch, x, y, transferFunction) {
494         scheduleTaskSynced(srcLayer, function() {
495
496             if (layer.autosize != 0) fitRect(x, y, srcw, srch);
497
498             var srcCanvas = srcLayer.getCanvas();
499             if (srcCanvas.width != 0 && srcCanvas.height != 0) {
500
501                 // Get image data from src and dst
502                 var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
503                 var dst = displayContext.getImageData(x , y, srcw, srch);
504
505                 // Apply transfer for each pixel
506                 for (var i=0; i<srcw*srch*4; i+=4) {
507
508                     // Get source pixel environment
509                     var src_pixel = new Guacamole.Layer.Pixel(
510                         src.data[i],
511                         src.data[i+1],
512                         src.data[i+2],
513                         src.data[i+3]
514                     );
515                         
516                     // Get destination pixel environment
517                     var dst_pixel = new Guacamole.Layer.Pixel(
518                         dst.data[i],
519                         dst.data[i+1],
520                         dst.data[i+2],
521                         dst.data[i+3]
522                     );
523
524                     // Apply transfer function
525                     transferFunction(src_pixel, dst_pixel);
526
527                     // Save pixel data
528                     dst.data[i  ] = dst_pixel.red;
529                     dst.data[i+1] = dst_pixel.green;
530                     dst.data[i+2] = dst_pixel.blue;
531                     dst.data[i+3] = dst_pixel.alpha;
532
533                 }
534
535                 // Draw image data
536                 displayContext.putImageData(dst, x, y);
537
538             }
539
540         });
541     };
542
543     /**
544      * Copy a rectangle of image data from one Layer to this Layer. This
545      * operation will copy exactly the image data that will be drawn once all
546      * operations of the source Layer that were pending at the time this
547      * function was called are complete. This operation will not alter the
548      * size of the source Layer even if its autosize property is set to true.
549      * 
550      * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
551      * @param {Number} srcx The X coordinate of the upper-left corner of the
552      *                      rectangle within the source Layer's coordinate
553      *                      space to copy data from.
554      * @param {Number} srcy The Y coordinate of the upper-left corner of the
555      *                      rectangle within the source Layer's coordinate
556      *                      space to copy data from.
557      * @param {Number} srcw The width of the rectangle within the source Layer's
558      *                      coordinate space to copy data from.
559      * @param {Number} srch The height of the rectangle within the source
560      *                      Layer's coordinate space to copy data from.
561      * @param {Number} x The destination X coordinate.
562      * @param {Number} y The destination Y coordinate.
563      */
564     this.copy = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
565         scheduleTaskSynced(srcLayer, function() {
566             if (layer.autosize != 0) fitRect(x, y, srcw, srch);
567
568             var srcCanvas = srcLayer.getCanvas();
569             if (srcCanvas.width != 0 && srcCanvas.height != 0)
570                 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
571
572         });
573     };
574
575     /**
576      * Add the specified cubic bezier point to the current path.
577      * 
578      * @param {Number} x The X coordinate of the point to draw.
579      * @param {Number} y The Y coordinate of the point to draw.
580      * @param {Number} cp1x The X coordinate of the first control point.
581      * @param {Number} cp1y The Y coordinate of the first control point.
582      * @param {Number} cp2x The X coordinate of the second control point.
583      * @param {Number} cp2y The Y coordinate of the second control point.
584      */
585     this.path = function(x, y, cp1x, cp1y, cp2x, cp2y) {
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.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, y);
596             
597         });
598     };
599
600     /**
601      * Add the specified rectangle to the current path.
602      * 
603      * @param {Number} x The X coordinate of the upper-left corner of the
604      *                   rectangle to draw.
605      * @param {Number} y The Y coordinate of the upper-left corner of the
606      *                   rectangle to draw.
607      * @param {Number} w The width of the rectangle to draw.
608      * @param {Number} h The height of the rectangle to draw.
609      */
610     this.rect = function(x, y, w, h) {
611         scheduleTask(function() {
612             
613             // Start a new path if current path is closed
614             if (pathClosed) {
615                 displayContext.beginPath();
616                 pathClosed = false;
617             }
618             
619             if (layer.autosize != 0) fitRect(x, y, w, h);
620             displayContext.rect(x, y, w, h);
621             
622         });
623     };
624
625     /**
626      * Clip all future drawing operations by the current path. The current path
627      * is implicitly closed. The current path can continue to be reused
628      * for other operations (such as fillColor()) but a new path will be started
629      * once a path drawing operation (path() or rect()) is used.
630      */
631     this.clip = function() {
632         scheduleTask(function() {
633
634             // Set new clipping region
635             displayContext.clip();
636
637             // Path now implicitly closed
638             pathClosed = true;
639
640         });
641     };
642
643     /**
644      * Stroke the current path with the specified color. The current path
645      * is implicitly closed. The current path can continue to be reused
646      * for other operations (such as clip()) but a new path will be started
647      * once a path drawing operation (path() or rect()) is used.
648      * 
649      * @param {String} cap The line cap style. Can be "round", "square",
650      *                     or "butt".
651      * @param {String} join The line join style. Can be "round", "bevel",
652      *                      or "miter".
653      * @param {Number} thickness The line thickness in pixels.
654      * @param {Number} r The red component of the color to fill.
655      * @param {Number} g The green component of the color to fill.
656      * @param {Number} b The blue component of the color to fill.
657      * @param {Number} a The alpha component of the color to fill.
658      */
659     this.strokeColor = function(cap, join, thickness, r, g, b, a) {
660         scheduleTask(function() {
661
662             // Stroke with color
663             displayContext.lineCap = cap;
664             displayContext.lineJoin = join;
665             displayContext.lineWidth = thickness;
666             displayContext.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
667             displayContext.stroke();
668
669             // Path now implicitly closed
670             pathClosed = true;
671
672         });
673     };
674
675     /**
676      * Fills the current path with the specified color. The current path
677      * is implicitly closed. The current path can continue to be reused
678      * for other operations (such as clip()) but a new path will be started
679      * once a path drawing operation (path() or rect()) is used.
680      * 
681      * @param {Number} r The red component of the color to fill.
682      * @param {Number} g The green component of the color to fill.
683      * @param {Number} b The blue component of the color to fill.
684      * @param {Number} a The alpha component of the color to fill.
685      */
686     this.fillColor = function(r, g, b, a) {
687         scheduleTask(function() {
688
689             // Fill with color
690             displayContext.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a/255.0 + ")";
691             displayContext.fill();
692
693             // Path now implicitly closed
694             pathClosed = true;
695
696         });
697     };
698
699     /**
700      * Stroke the current path with the image within the specified layer. The
701      * image data will be tiled infinitely within the stroke. The current path
702      * is implicitly closed. The current path can continue to be reused
703      * for other operations (such as clip()) but a new path will be started
704      * once a path drawing operation (path() or rect()) is used.
705      * 
706      * @param {String} cap The line cap style. Can be "round", "square",
707      *                     or "butt".
708      * @param {String} join The line join style. Can be "round", "bevel",
709      *                      or "miter".
710      * @param {Number} thickness The line thickness in pixels.
711      * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
712      *                                   within the stroke.
713      */
714     this.strokeLayer = function(cap, join, thickness, srcLayer) {
715         scheduleTaskSynced(srcLayer, function() {
716
717             // Stroke with image data
718             displayContext.lineCap = cap;
719             displayContext.lineJoin = join;
720             displayContext.lineWidth = thickness;
721             displayContext.strokeStyle = displayContext.createPattern(
722                 srcLayer.getCanvas(),
723                 "repeat"
724             );
725             displayContext.stroke();
726
727             // Path now implicitly closed
728             pathClosed = true;
729
730         });
731     };
732
733     /**
734      * Fills the current path with the image within the specified layer. The
735      * image data will be tiled infinitely within the stroke. The current path
736      * is implicitly closed. The current path can continue to be reused
737      * for other operations (such as clip()) but a new path will be started
738      * once a path drawing operation (path() or rect()) is used.
739      * 
740      * @param {Guacamole.Layer} srcLayer The layer to use as a repeating pattern
741      *                                   within the fill.
742      */
743     this.fillLayer = function(srcLayer) {
744         scheduleTask(function() {
745
746             // Fill with image data 
747             displayContext.fillStyle = displayContext.createPattern(
748                 srcLayer.getCanvas(),
749                 "repeat"
750             );
751             displayContext.fill();
752
753             // Path now implicitly closed
754             pathClosed = true;
755
756         });
757     };
758
759     /**
760      * Push current layer state onto stack.
761      */
762     this.push = function() {
763         scheduleTask(function() {
764
765             // Save current state onto stack
766             displayContext.save();
767             stackSize++;
768
769         });
770     };
771
772     /**
773      * Pop layer state off stack.
774      */
775     this.pop = function() {
776         scheduleTask(function() {
777
778             // Restore current state from stack
779             if (stackSize > 0) {
780                 displayContext.restore();
781                 stackSize--;
782             }
783
784         });
785     };
786
787     /**
788      * Reset the layer, clearing the stack, the current path, and any transform
789      * matrix.
790      */
791     this.reset = function() {
792         scheduleTask(function() {
793
794             // Clear stack
795             while (stackSize > 0) {
796                 displayContext.restore();
797                 stackSize--;
798             }
799
800             // Restore to initial state
801             displayContext.restore();
802             displayContext.save();
803
804             // Clear path
805             displayContext.beginPath();
806             pathClosed = false;
807
808         });
809     };
810
811     /**
812      * Applies the given affine transform (defined with three values from the
813      * transform's matrix).
814      * 
815      * @param {Number} a The first value in the affine transform's matrix.
816      * @param {Number} b The second value in the affine transform's matrix.
817      * @param {Number} c The third value in the affine transform's matrix.
818      * @param {Number} d The fourth value in the affine transform's matrix.
819      * @param {Number} e The fifth value in the affine transform's matrix.
820      * @param {Number} f The sixth value in the affine transform's matrix.
821      */
822     this.transform = function(a, b, c, d, e, f) {
823         scheduleTask(function() {
824
825             // Clear transform
826             displayContext.transform(
827                 a, b, c,
828                 d, e, f
829               /*0, 0, 1*/
830             );
831
832         });
833     };
834
835
836     /**
837      * Sets the channel mask for future operations on this Layer.
838      * 
839      * The channel mask is a Guacamole-specific compositing operation identifier
840      * with a single bit representing each of four channels (in order): source
841      * image where destination transparent, source where destination opaque,
842      * destination where source transparent, and destination where source
843      * opaque.
844      * 
845      * @param {Number} mask The channel mask for future operations on this
846      *                      Layer.
847      */
848     this.setChannelMask = function(mask) {
849         scheduleTask(function() {
850             displayContext.globalCompositeOperation = compositeOperation[mask];
851         });
852     };
853
854     /**
855      * Sets the miter limit for stroke operations using the miter join. This
856      * limit is the maximum ratio of the size of the miter join to the stroke
857      * width. If this ratio is exceeded, the miter will not be drawn for that
858      * joint of the path.
859      * 
860      * @param {Number} limit The miter limit for stroke operations using the
861      *                       miter join.
862      */
863     this.setMiterLimit = function(limit) {
864         scheduleTask(function() {
865             displayContext.miterLimit = limit;
866         });
867     };
868
869     // Initialize canvas dimensions
870     display.width = width;
871     display.height = height;
872
873 };
874
875 /**
876  * Channel mask for the composite operation "rout".
877  */
878 Guacamole.Layer.ROUT  = 0x2;
879
880 /**
881  * Channel mask for the composite operation "atop".
882  */
883 Guacamole.Layer.ATOP  = 0x6;
884
885 /**
886  * Channel mask for the composite operation "xor".
887  */
888 Guacamole.Layer.XOR   = 0xA;
889
890 /**
891  * Channel mask for the composite operation "rover".
892  */
893 Guacamole.Layer.ROVER = 0xB;
894
895 /**
896  * Channel mask for the composite operation "over".
897  */
898 Guacamole.Layer.OVER  = 0xE;
899
900 /**
901  * Channel mask for the composite operation "plus".
902  */
903 Guacamole.Layer.PLUS  = 0xF;
904
905 /**
906  * Channel mask for the composite operation "rin".
907  * Beware that WebKit-based browsers may leave the contents of the destionation
908  * layer where the source layer is transparent, despite the definition of this
909  * operation.
910  */
911 Guacamole.Layer.RIN   = 0x1;
912
913 /**
914  * Channel mask for the composite operation "in".
915  * Beware that WebKit-based browsers may leave the contents of the destionation
916  * layer where the source layer is transparent, despite the definition of this
917  * operation.
918  */
919 Guacamole.Layer.IN    = 0x4;
920
921 /**
922  * Channel mask for the composite operation "out".
923  * Beware that WebKit-based browsers may leave the contents of the destionation
924  * layer where the source layer is transparent, despite the definition of this
925  * operation.
926  */
927 Guacamole.Layer.OUT   = 0x8;
928
929 /**
930  * Channel mask for the composite operation "ratop".
931  * Beware that WebKit-based browsers may leave the contents of the destionation
932  * layer where the source layer is transparent, despite the definition of this
933  * operation.
934  */
935 Guacamole.Layer.RATOP = 0x9;
936
937 /**
938  * Channel mask for the composite operation "src".
939  * Beware that WebKit-based browsers may leave the contents of the destionation
940  * layer where the source layer is transparent, despite the definition of this
941  * operation.
942  */
943 Guacamole.Layer.SRC   = 0xC;
944
945
946 /**
947  * Represents a single pixel of image data. All components have a minimum value
948  * of 0 and a maximum value of 255.
949  * 
950  * @constructor
951  * 
952  * @param {Number} r The red component of this pixel.
953  * @param {Number} g The green component of this pixel.
954  * @param {Number} b The blue component of this pixel.
955  * @param {Number} a The alpha component of this pixel.
956  */
957 Guacamole.Layer.Pixel = function(r, g, b, a) {
958
959     /**
960      * The red component of this pixel, where 0 is the minimum value,
961      * and 255 is the maximum.
962      */
963     this.red   = r;
964
965     /**
966      * The green component of this pixel, where 0 is the minimum value,
967      * and 255 is the maximum.
968      */
969     this.green = g;
970
971     /**
972      * The blue component of this pixel, where 0 is the minimum value,
973      * and 255 is the maximum.
974      */
975     this.blue  = b;
976
977     /**
978      * The alpha component of this pixel, where 0 is the minimum value,
979      * and 255 is the maximum.
980      */
981     this.alpha = a;
982
983 };