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