Use transfer function within copy, if set.
[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
463                 // Just copy if no transfer function
464                 if (!transferFunction)
465                     displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
466                 
467                 // Otherwise, copy via transfer function
468                 else {
469
470                     // Get image data from src and dst
471                     var src = srcLayer.getCanvas().getContext("2d").getImageData(srcx, srcy, srcw, srch);
472                     var dst = displayContext.getImageData(x , y, srcw, srch);
473
474                     // Apply transfer for each pixel
475                     for (var i=0; i<srcw*srch*4; i+=4) {
476                         dst.data[i  ] = transferFunction(src.data[i  ], dst.data[i  ]);
477                         dst.data[i+1] = transferFunction(src.data[i+1], dst.data[i+1]);
478                         dst.data[i+2] = transferFunction(src.data[i+2], dst.data[i+2]);
479                         dst.data[i+3] = 0xFF; // Assume output opaque
480                     }
481
482                 }
483             }
484
485             // Unblock the source layer now that draw is complete
486             if (srcLock != null) 
487                 srcLock.unblock();
488
489             // Flag operation as done
490             drawComplete = true;
491         }
492
493         // If we ARE the source layer, no need to sync.
494         // Syncing would result in deadlock.
495         if (layer === srcLayer)
496             scheduleTask(doCopyRect);
497
498         // Otherwise synchronize copy operation with source layer
499         else {
500             
501             // Currently blocked draw task
502             var task = scheduleTask(doCopyRect, true);
503
504             // Unblock draw task once source layer is ready
505             srcLayer.sync(task.unblock);
506
507             // Block source layer until draw completes
508             // Note that the draw MAY have already been performed at this point,
509             // in which case creating a lock on the source layer will lead to
510             // deadlock (the draw task has already run and will thus never
511             // clear the lock)
512             if (!drawComplete)
513                 srcLock = srcLayer.sync(null, true);
514
515         }
516
517     };
518
519     /**
520      * Clear the specified rectangle of image data.
521      * 
522      * @param {Number} x The X coordinate of the upper-left corner of the
523      *                   rectangle to clear.
524      * @param {Number} y The Y coordinate of the upper-left corner of the
525      *                   rectangle to clear.
526      * @param {Number} w The width of the rectangle to clear.
527      * @param {Number} h The height of the rectangle to clear.
528      */
529     this.clearRect = function(x, y, w, h) {
530         scheduleTask(function() {
531             if (layer.autosize != 0) fitRect(x, y, w, h);
532             displayContext.clearRect(x, y, w, h);
533         });
534     };
535
536     /**
537      * Fill the specified rectangle of image data with the specified color.
538      * 
539      * @param {Number} x The X coordinate of the upper-left corner of the
540      *                   rectangle to draw.
541      * @param {Number} y The Y coordinate of the upper-left corner of the
542      *                   rectangle to draw.
543      * @param {Number} w The width of the rectangle to draw.
544      * @param {Number} h The height of the rectangle to draw.
545      * @param {Number} r The red component of the color of the rectangle.
546      * @param {Number} g The green component of the color of the rectangle.
547      * @param {Number} b The blue component of the color of the rectangle.
548      * @param {Number} a The alpha component of the color of the rectangle.
549      */
550     this.drawRect = function(x, y, w, h, r, g, b, a) {
551         scheduleTask(function() {
552             if (layer.autosize != 0) fitRect(x, y, w, h);
553             displayContext.fillStyle = "rgba("
554                         + r + "," + g + "," + b + "," + a / 255 + ")";
555             displayContext.fillRect(x, y, w, h);
556         });
557     };
558
559     /**
560      * Clip all future drawing operations by the specified rectangle.
561      * 
562      * @param {Number} x The X coordinate of the upper-left corner of the
563      *                   rectangle to use for the clipping region.
564      * @param {Number} y The Y coordinate of the upper-left corner of the
565      *                   rectangle to use for the clipping region.
566      * @param {Number} w The width of the rectangle to use for the clipping region.
567      * @param {Number} h The height of the rectangle to use for the clipping region.
568      */
569     this.clipRect = function(x, y, w, h) {
570         scheduleTask(function() {
571
572             // Clear any current clipping region
573             displayContext.restore();
574             displayContext.save();
575
576             if (layer.autosize != 0) fitRect(x, y, w, h);
577
578             // Set new clipping region
579             displayContext.beginPath();
580             displayContext.rect(x, y, w, h);
581             displayContext.clip();
582
583         });
584     };
585
586     /**
587      * Provides the given filtering function with a writable snapshot of
588      * image data and the current width and height of the Layer.
589      * 
590      * @param {function} filter A function which accepts an array of image
591      *                          data (as returned by the canvas element's
592      *                          display context's getImageData() function),
593      *                          the width of the Layer, and the height of the
594      *                          Layer as parameters, in that order. This
595      *                          function must accomplish its filtering by
596      *                          modifying the given image data array directly.
597      */
598     this.filter = function(filter) {
599         scheduleTask(function() {
600             var imageData = displayContext.getImageData(0, 0, width, height);
601             filter(imageData.data, width, height);
602             displayContext.putImageData(imageData, 0, 0);
603         });
604     };
605
606     /**
607      * Sets the composite operation for future operations on this Layer. This
608      * operation is either a channel mask, or the ID of a binary raster
609      * operation.
610      * 
611      * The channel mask is a Guacamole-specific compositing operation identifier
612      * with a single bit representing each of four channels (in order): source
613      * image where destination transparent, source where destination opaque,
614      * destination where source transparent, and destination where source
615      * opaque.
616      * 
617      * @param {Number} operation The composite operation (channel mask or binary
618      *                           raster operation) for future operations on this
619      *                           Layer.
620      */
621     this.setCompositeOperation = function(operation) {
622         scheduleTask(function() {
623             
624             // If channel mask, set composite operation only
625             if (operation <= 0xF) {
626                 displayContext.globalCompositeOperation = compositeOperation[operation];
627                 transferFunction = null;
628             }
629
630             // Otherwise, set binary raster operation
631             else {
632                 displayContext.globalCompositeOperation = "source-over";
633                 transferFunction = binaryCompositeTransferFunction[operation];
634             }
635
636         });
637     };
638
639     // Initialize canvas dimensions
640     display.width = width;
641     display.height = height;
642
643 };
644
645 /**
646  * Channel mask for the composite operation "rout".
647  */
648 Guacamole.Layer.ROUT  = 0x2;
649
650 /**
651  * Channel mask for the composite operation "atop".
652  */
653 Guacamole.Layer.ATOP  = 0x6;
654
655 /**
656  * Channel mask for the composite operation "xor".
657  */
658 Guacamole.Layer.XOR   = 0xA;
659
660 /**
661  * Channel mask for the composite operation "rover".
662  */
663 Guacamole.Layer.ROVER = 0xB;
664
665 /**
666  * Channel mask for the composite operation "over".
667  */
668 Guacamole.Layer.OVER  = 0xE;
669
670 /**
671  * Channel mask for the composite operation "plus".
672  */
673 Guacamole.Layer.PLUS  = 0xF;
674
675 /**
676  * Channel mask for the composite operation "rin".
677  * Beware that WebKit-based browsers may leave the contents of the destionation
678  * layer where the source layer is transparent, despite the definition of this
679  * operation.
680  */
681 Guacamole.Layer.RIN   = 0x1;
682
683 /**
684  * Channel mask for the composite operation "in".
685  * Beware that WebKit-based browsers may leave the contents of the destionation
686  * layer where the source layer is transparent, despite the definition of this
687  * operation.
688  */
689 Guacamole.Layer.IN    = 0x4;
690
691 /**
692  * Channel mask for the composite operation "out".
693  * Beware that WebKit-based browsers may leave the contents of the destionation
694  * layer where the source layer is transparent, despite the definition of this
695  * operation.
696  */
697 Guacamole.Layer.OUT   = 0x8;
698
699 /**
700  * Channel mask for the composite operation "ratop".
701  * Beware that WebKit-based browsers may leave the contents of the destionation
702  * layer where the source layer is transparent, despite the definition of this
703  * operation.
704  */
705 Guacamole.Layer.RATOP = 0x9;
706
707 /**
708  * Channel mask for the composite operation "src".
709  * Beware that WebKit-based browsers may leave the contents of the destionation
710  * layer where the source layer is transparent, despite the definition of this
711  * operation.
712  */
713 Guacamole.Layer.SRC   = 0xC;
714