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