Added pre-defined channel mask constants. Setting cursor layer to Guacamole.Layer...
[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  * Channel mask for the composite operation "rout".
43  */
44 Guacamole.Layer.ROUT  = 0x2;
45
46 /**
47  * Channel mask for the composite operation "atop".
48  */
49 Guacamole.Layer.ATOP  = 0x6;
50
51 /**
52  * Channel mask for the composite operation "xor".
53  */
54 Guacamole.Layer.XOR   = 0xA;
55
56 /**
57  * Channel mask for the composite operation "rover".
58  */
59 Guacamole.Layer.ROVER = 0xB;
60
61 /**
62  * Channel mask for the composite operation "over".
63  */
64 Guacamole.Layer.OVER  = 0xE;
65
66 /**
67  * Channel mask for the composite operation "plus".
68  */
69 Guacamole.Layer.PLUS  = 0xF;
70
71 /**
72  * Channel mask for the composite operation "rin".
73  * Beware that WebKit-based browsers may leave the contents of the destionation
74  * layer where the source layer is transparent, despite the definition of this
75  * operation.
76  */
77 Guacamole.Layer.RIN   = 0x1;
78
79 /**
80  * Channel mask for the composite operation "in".
81  * Beware that WebKit-based browsers may leave the contents of the destionation
82  * layer where the source layer is transparent, despite the definition of this
83  * operation.
84  */
85 Guacamole.Layer.IN    = 0x4;
86
87 /**
88  * Channel mask for the composite operation "out".
89  * Beware that WebKit-based browsers may leave the contents of the destionation
90  * layer where the source layer is transparent, despite the definition of this
91  * operation.
92  */
93 Guacamole.Layer.OUT   = 0x8;
94
95 /**
96  * Channel mask for the composite operation "ratop".
97  * Beware that WebKit-based browsers may leave the contents of the destionation
98  * layer where the source layer is transparent, despite the definition of this
99  * operation.
100  */
101 Guacamole.Layer.RATOP = 0x9;
102
103 /**
104  * Channel mask for the composite operation "src".
105  * Beware that WebKit-based browsers may leave the contents of the destionation
106  * layer where the source layer is transparent, despite the definition of this
107  * operation.
108  */
109 Guacamole.Layer.SRC   = 0xC;
110
111 /**
112  * Abstract ordered drawing surface. Each Layer contains a canvas element and
113  * provides simple drawing instructions for drawing to that canvas element,
114  * however unlike the canvas element itself, drawing operations on a Layer are
115  * guaranteed to run in order, even if such an operation must wait for an image
116  * to load before completing.
117  * 
118  * @constructor
119  * 
120  * @param {Number} width The width of the Layer, in pixels. The canvas element
121  *                       backing this Layer will be given this width.
122  *                       
123  * @param {Number} height The height of the Layer, in pixels. The canvas element
124  *                        backing this Layer will be given this height.
125  */
126 Guacamole.Layer = function(width, height) {
127
128     /**
129      * Reference to this Layer.
130      * @private
131      */
132     var layer = this;
133
134     /**
135      * The canvas element backing this Layer.
136      * @private
137      */
138     var display = document.createElement("canvas");
139
140     /**
141      * The 2D display context of the canvas element backing this Layer.
142      * @private
143      */
144     var displayContext = display.getContext("2d");
145     displayContext.save();
146
147     /**
148      * The queue of all pending Tasks. Tasks will be run in order, with new
149      * tasks added at the end of the queue and old tasks removed from the
150      * front of the queue (FIFO).
151      * @private
152      */
153     var tasks = new Array();
154
155     /**
156      * Map of all Guacamole channel masks to HTML5 canvas composite operation
157      * names. Not all channel mask combinations are currently implemented.
158      * @private
159      */
160     var compositeOperation = {
161      /* 0x0 NOT IMPLEMENTED */
162         0x1: "destination-in",
163         0x2: "destination-out",
164      /* 0x3 NOT IMPLEMENTED */
165         0x4: "source-in",
166      /* 0x5 NOT IMPLEMENTED */
167         0x6: "source-atop",
168      /* 0x7 NOT IMPLEMENTED */
169         0x8: "source-out",
170         0x9: "destination-atop",
171         0xA: "xor",
172         0xB: "destination-over",
173         0xC: "copy",
174      /* 0xD NOT IMPLEMENTED */
175         0xE: "source-over",
176         0xF: "lighter"
177     };
178
179     /**
180      * Resizes the canvas element backing this Layer without testing the
181      * new size. This function should only be used internally.
182      * 
183      * @private
184      * @param {Number} newWidth The new width to assign to this Layer.
185      * @param {Number} newHeight The new height to assign to this Layer.
186      */
187     function resize(newWidth, newHeight) {
188
189
190         // Only preserve old data if width/height are both non-zero
191         var oldData = null;
192         if (width != 0 && height != 0) {
193
194             // Create canvas and context for holding old data
195             oldData = document.createElement("canvas");
196             oldData.width = width;
197             oldData.height = height;
198
199             var oldDataContext = oldData.getContext("2d");
200
201             // Copy image data from current
202             oldDataContext.drawImage(display,
203                     0, 0, width, height,
204                     0, 0, width, height);
205
206         }
207
208         // Resize canvas
209         display.width = newWidth;
210         display.height = newHeight;
211
212         // Redraw old data, if any
213         if (oldData)
214                 displayContext.drawImage(oldData, 
215                     0, 0, width, height,
216                     0, 0, width, height);
217
218         width = newWidth;
219         height = newHeight;
220     }
221
222     /**
223      * Given the X and Y coordinates of the upper-left corner of a rectangle
224      * and the rectangle's width and height, resize the backing canvas element
225      * as necessary to ensure that the rectangle fits within the canvas
226      * element's coordinate space. This function will only make the canvas
227      * larger. If the rectangle already fits within the canvas element's
228      * coordinate space, the canvas is left unchanged.
229      * 
230      * @private
231      * @param {Number} x The X coordinate of the upper-left corner of the
232      *                   rectangle to fit.
233      * @param {Number} y The Y coordinate of the upper-left corner of the
234      *                   rectangle to fit.
235      * @param {Number} w The width of the the rectangle to fit.
236      * @param {Number} h The height of the the rectangle to fit.
237      */
238     function fitRect(x, y, w, h) {
239         
240         // Calculate bounds
241         var opBoundX = w + x;
242         var opBoundY = h + y;
243         
244         // Determine max width
245         var resizeWidth;
246         if (opBoundX > width)
247             resizeWidth = opBoundX;
248         else
249             resizeWidth = width;
250
251         // Determine max height
252         var resizeHeight;
253         if (opBoundY > height)
254             resizeHeight = opBoundY;
255         else
256             resizeHeight = height;
257
258         // Resize if necessary
259         if (resizeWidth != width || resizeHeight != height)
260             resize(resizeWidth, resizeHeight);
261
262     }
263
264     /**
265      * A container for an task handler. Each operation which must be ordered
266      * is associated with a Task that goes into a task queue. Tasks in this
267      * queue are executed in order once their handlers are set, while Tasks 
268      * without handlers block themselves and any following Tasks from running.
269      *
270      * @constructor
271      * @private
272      * @param {function} taskHandler The function to call when this task 
273      *                               runs, if any.
274      * @param {boolean} blocked Whether this task should start blocked.
275      */
276     function Task(taskHandler, blocked) {
277        
278         var task = this;
279        
280         /**
281          * Whether this Task is blocked.
282          * 
283          * @type boolean
284          */
285         this.blocked = blocked;
286
287         /**
288          * The handler this Task is associated with, if any.
289          * 
290          * @type function
291          */
292         this.handler = taskHandler;
293        
294         /**
295          * Unblocks this Task, allowing it to run.
296          */
297         this.unblock = function() {
298             task.blocked = false;
299             handlePendingTasks();
300         }
301
302     }
303
304     /**
305      * If no tasks are pending or running, run the provided handler immediately,
306      * if any. Otherwise, schedule a task to run immediately after all currently
307      * running or pending tasks are complete.
308      * 
309      * @private
310      * @param {function} handler The function to call when possible, if any.
311      * @param {boolean} blocked Whether the task should start blocked.
312      * @returns {Task} The Task created and added to the queue for future
313      *                 running, if any, or null if the handler was run
314      *                 immediately and no Task needed to be created.
315      */
316     function scheduleTask(handler, blocked) {
317         
318         // If no pending tasks, just call (if available) and exit
319         if (layer.isReady() && !blocked) {
320             if (handler) handler();
321             return null;
322         }
323
324         // If tasks are pending/executing, schedule a pending task
325         // and return a reference to it.
326         var task = new Task(handler, blocked);
327         tasks.push(task);
328         return task;
329         
330     }
331
332     var tasksInProgress = false;
333
334     /**
335      * Run any Tasks which were pending but are now ready to run and are not
336      * blocked by other Tasks.
337      * @private
338      */
339     function handlePendingTasks() {
340
341         if (tasksInProgress)
342             return;
343
344         tasksInProgress = true;
345
346         // Draw all pending tasks.
347         var task;
348         while ((task = tasks[0]) != null && !task.blocked) {
349             tasks.shift();
350             if (task.handler) task.handler();
351         }
352
353         tasksInProgress = false;
354
355     }
356
357     /**
358      * Set to true if this Layer should resize itself to accomodate the
359      * dimensions of any drawing operation, and false (the default) otherwise.
360      * 
361      * Note that setting this property takes effect immediately, and thus may
362      * take effect on operations that were started in the past but have not
363      * yet completed. If you wish the setting of this flag to only modify
364      * future operations, you will need to make the setting of this flag an
365      * operation with sync().
366      * 
367      * @example
368      * // Set autosize to true for all future operations
369      * layer.sync(function() {
370      *     layer.autosize = true;
371      * });
372      * 
373      * @type Boolean
374      * @default false
375      */
376     this.autosize = false;
377
378     /**
379      * Returns the canvas element backing this Layer.
380      * @returns {Element} The canvas element backing this Layer.
381      */
382     this.getCanvas = function() {
383         return display;
384     };
385
386     /**
387      * Returns whether this Layer is ready. A Layer is ready if it has no
388      * pending operations and no operations in-progress.
389      * 
390      * @returns {Boolean} true if this Layer is ready, false otherwise.
391      */
392     this.isReady = function() {
393         return tasks.length == 0;
394     };
395
396     /**
397      * Changes the size of this Layer to the given width and height. Resizing
398      * is only attempted if the new size provided is actually different from
399      * the current size.
400      * 
401      * @param {Number} newWidth The new width to assign to this Layer.
402      * @param {Number} newHeight The new height to assign to this Layer.
403      */
404     this.resize = function(newWidth, newHeight) {
405         scheduleTask(function() {
406             if (newWidth != width || newHeight != height)
407                 resize(newWidth, newHeight);
408         });
409     };
410
411     /**
412      * Draws the specified image at the given coordinates. The image specified
413      * must already be loaded.
414      * 
415      * @param {Number} x The destination X coordinate.
416      * @param {Number} y The destination Y coordinate.
417      * @param {Image} image The image to draw. Note that this is an Image
418      *                      object - not a URL.
419      */
420     this.drawImage = function(x, y, image) {
421         scheduleTask(function() {
422             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
423             displayContext.drawImage(image, x, y);
424         });
425     };
426
427     /**
428      * Draws the image at the specified URL at the given coordinates. The image
429      * will be loaded automatically, and this and any future operations will
430      * wait for the image to finish loading.
431      * 
432      * @param {Number} x The destination X coordinate.
433      * @param {Number} y The destination Y coordinate.
434      * @param {String} url The URL of the image to draw.
435      */
436     this.draw = function(x, y, url) {
437
438         var task = scheduleTask(function() {
439             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
440             displayContext.drawImage(image, x, y);
441         }, true);
442
443         var image = new Image();
444         image.onload = task.unblock;
445         image.src = url;
446
447     };
448
449     /**
450      * Run an arbitrary function as soon as currently pending operations
451      * are complete.
452      * 
453      * @param {function} handler The function to call once all currently
454      *                           pending operations are complete.
455      * @param {boolean} blocked Whether the task should start blocked.
456      */
457     this.sync = scheduleTask;
458
459     /**
460      * Copy a rectangle of image data from one Layer to this Layer. This
461      * operation will copy exactly the image data that will be drawn once all
462      * operations of the source Layer that were pending at the time this
463      * function was called are complete. This operation will not alter the
464      * size of the source Layer even if its autosize property is set to true.
465      * 
466      * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
467      * @param {Number} srcx The X coordinate of the upper-left corner of the
468      *                      rectangle within the source Layer's coordinate
469      *                      space to copy data from.
470      * @param {Number} srcy The Y coordinate of the upper-left corner of the
471      *                      rectangle within the source Layer's coordinate
472      *                      space to copy data from.
473      * @param {Number} srcw The width of the rectangle within the source Layer's
474      *                      coordinate space to copy data from.
475      * @param {Number} srch The height of the rectangle within the source
476      *                      Layer's coordinate space to copy data from.
477      * @param {Number} x The destination X coordinate.
478      * @param {Number} y The destination Y coordinate.
479      */
480     this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
481
482         var drawComplete = false;
483         var srcLock = null;
484
485         function doCopyRect() {
486             if (layer.autosize != 0) fitRect(x, y, srcw, srch);
487
488             var srcCanvas = srcLayer.getCanvas();
489             if (srcCanvas.width != 0 && srcCanvas.height != 0)
490                 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
491
492             // Unblock the source layer now that draw is complete
493             if (srcLock != null) 
494                 srcLock.unblock();
495
496             // Flag operation as done
497             drawComplete = true;
498         }
499
500         // If we ARE the source layer, no need to sync.
501         // Syncing would result in deadlock.
502         if (layer === srcLayer)
503             scheduleTask(doCopyRect);
504
505         // Otherwise synchronize copy operation with source layer
506         else {
507             
508             // Currently blocked draw task
509             var task = scheduleTask(doCopyRect, true);
510
511             // Unblock draw task once source layer is ready
512             srcLayer.sync(task.unblock);
513
514             // Block source layer until draw completes
515             // Note that the draw MAY have already been performed at this point,
516             // in which case creating a lock on the source layer will lead to
517             // deadlock (the draw task has already run and will thus never
518             // clear the lock)
519             if (!drawComplete)
520                 srcLock = srcLayer.sync(null, true);
521
522         }
523
524     };
525
526     /**
527      * Clear the specified rectangle of image data.
528      * 
529      * @param {Number} x The X coordinate of the upper-left corner of the
530      *                   rectangle to clear.
531      * @param {Number} y The Y coordinate of the upper-left corner of the
532      *                   rectangle to clear.
533      * @param {Number} w The width of the rectangle to clear.
534      * @param {Number} h The height of the rectangle to clear.
535      */
536     this.clearRect = function(x, y, w, h) {
537         scheduleTask(function() {
538             if (layer.autosize != 0) fitRect(x, y, w, h);
539             displayContext.clearRect(x, y, w, h);
540         });
541     };
542
543     /**
544      * Fill the specified rectangle of image data with the specified color.
545      * 
546      * @param {Number} x The X coordinate of the upper-left corner of the
547      *                   rectangle to draw.
548      * @param {Number} y The Y coordinate of the upper-left corner of the
549      *                   rectangle to draw.
550      * @param {Number} w The width of the rectangle to draw.
551      * @param {Number} h The height of the rectangle to draw.
552      * @param {Number} r The red component of the color of the rectangle.
553      * @param {Number} g The green component of the color of the rectangle.
554      * @param {Number} b The blue component of the color of the rectangle.
555      * @param {Number} a The alpha component of the color of the rectangle.
556      */
557     this.drawRect = function(x, y, w, h, r, g, b, a) {
558         scheduleTask(function() {
559             if (layer.autosize != 0) fitRect(x, y, w, h);
560             displayContext.fillStyle = "rgba("
561                         + r + "," + g + "," + b + "," + a / 255 + ")";
562             displayContext.fillRect(x, y, w, h);
563         });
564     };
565
566     /**
567      * Clip all future drawing operations by the specified rectangle.
568      * 
569      * @param {Number} x The X coordinate of the upper-left corner of the
570      *                   rectangle to use for the clipping region.
571      * @param {Number} y The Y coordinate of the upper-left corner of the
572      *                   rectangle to use for the clipping region.
573      * @param {Number} w The width of the rectangle to use for the clipping region.
574      * @param {Number} h The height of the rectangle to use for the clipping region.
575      */
576     this.clipRect = function(x, y, w, h) {
577         scheduleTask(function() {
578
579             // Clear any current clipping region
580             displayContext.restore();
581             displayContext.save();
582
583             if (layer.autosize != 0) fitRect(x, y, w, h);
584
585             // Set new clipping region
586             displayContext.beginPath();
587             displayContext.rect(x, y, w, h);
588             displayContext.clip();
589
590         });
591     };
592
593     /**
594      * Provides the given filtering function with a writable snapshot of
595      * image data and the current width and height of the Layer.
596      * 
597      * @param {function} filter A function which accepts an array of image
598      *                          data (as returned by the canvas element's
599      *                          display context's getImageData() function),
600      *                          the width of the Layer, and the height of the
601      *                          Layer as parameters, in that order. This
602      *                          function must accomplish its filtering by
603      *                          modifying the given image data array directly.
604      */
605     this.filter = function(filter) {
606         scheduleTask(function() {
607             var imageData = displayContext.getImageData(0, 0, width, height);
608             filter(imageData.data, width, height);
609             displayContext.putImageData(imageData, 0, 0);
610         });
611     };
612
613     /**
614      * Sets the channel mask for future operations on this Layer. The channel
615      * mask is a Guacamole-specific compositing operation identifier with a
616      * single bit representing each of four channels (in order): source image
617      * where destination transparent, source where destination opaque,
618      * destination where source transparent, and destination where source
619      * opaque.
620      * 
621      * @param {Number} mask The channel mask for future operations on this
622      *                      Layer.
623      */
624     this.setChannelMask = function(mask) {
625         scheduleTask(function() {
626             displayContext.globalCompositeOperation = compositeOperation[mask];
627         });
628     };
629
630     // Initialize canvas dimensions
631     display.width = width;
632     display.height = height;
633
634 };