6885f59e6845d6fe7159a1beec67bbed8a556f04
[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
120         // Only preserve old data if width/height are both non-zero
121         var oldData = null;
122         if (width != 0 && height != 0) {
123
124             // Create canvas and context for holding old data
125             oldData = document.createElement("canvas");
126             oldData.width = width;
127             oldData.height = height;
128
129             var oldDataContext = oldData.getContext("2d");
130
131             // Copy image data from current
132             oldDataContext.drawImage(display,
133                     0, 0, width, height,
134                     0, 0, width, height);
135
136         }
137
138         // Resize canvas
139         display.width = newWidth;
140         display.height = newHeight;
141
142         // Redraw old data, if any
143         if (oldData)
144                 displayContext.drawImage(oldData, 
145                     0, 0, width, height,
146                     0, 0, width, height);
147
148         width = newWidth;
149         height = newHeight;
150     }
151
152     /**
153      * Given the X and Y coordinates of the upper-left corner of a rectangle
154      * and the rectangle's width and height, resize the backing canvas element
155      * as necessary to ensure that the rectangle fits within the canvas
156      * element's coordinate space. This function will only make the canvas
157      * larger. If the rectangle already fits within the canvas element's
158      * coordinate space, the canvas is left unchanged.
159      * 
160      * @private
161      * @param {Number} x The X coordinate of the upper-left corner of the
162      *                   rectangle to fit.
163      * @param {Number} y The Y coordinate of the upper-left corner of the
164      *                   rectangle to fit.
165      * @param {Number} w The width of the the rectangle to fit.
166      * @param {Number} h The height of the the rectangle to fit.
167      */
168     function fitRect(x, y, w, h) {
169         
170         // Calculate bounds
171         var opBoundX = w + x;
172         var opBoundY = h + y;
173         
174         // Determine max width
175         var resizeWidth;
176         if (opBoundX > width)
177             resizeWidth = opBoundX;
178         else
179             resizeWidth = width;
180
181         // Determine max height
182         var resizeHeight;
183         if (opBoundY > height)
184             resizeHeight = opBoundY;
185         else
186             resizeHeight = height;
187
188         // Resize if necessary
189         if (resizeWidth != width || resizeHeight != height)
190             resize(resizeWidth, resizeHeight);
191
192     }
193
194     /**
195      * A container for an task handler. Each operation which must be ordered
196      * is associated with a Task that goes into a task queue. Tasks in this
197      * queue are executed in order once their handlers are set, while Tasks 
198      * without handlers block themselves and any following Tasks from running.
199      *
200      * @constructor
201      * @private
202      * @param {function} taskHandler The function to call when this task 
203      *                               runs, if any.
204      */
205     function Task(taskHandler) {
206         
207         /**
208          * The handler this Task is associated with, if any.
209          * 
210          * @type function
211          */
212         this.handler = taskHandler;
213         
214     }
215
216     /**
217      * If no tasks are pending or running, run the provided handler immediately,
218      * if any. Otherwise, schedule a task to run immediately after all currently
219      * running or pending tasks are complete.
220      * 
221      * @private
222      * @param {function} handler The function to call when possible, if any.
223      * @returns {Task} The Task created and added to the queue for future
224      *                 running, if any, or null if the handler was run
225      *                 immediately and no Task needed to be created.
226      */
227     function scheduleTask(handler) {
228         
229         // If no pending tasks, just call (if available) and exit
230         if (layer.isReady() && handler != null) {
231             handler();
232             return null;
233         }
234
235         // If tasks are pending/executing, schedule a pending task
236         // and return a reference to it.
237         var task = new Task(handler);
238         tasks.push(task);
239         return task;
240         
241     }
242
243     var tasksInProgress = false;
244
245     /**
246      * Run any Tasks which were pending but are now ready to run and are not
247      * blocked by other Tasks.
248      * @private
249      */
250     function handlePendingTasks() {
251
252         if (tasksInProgress)
253             return;
254
255         tasksInProgress = true;
256
257         // Draw all pending tasks.
258         var task;
259         while ((task = tasks[0]) != null && task.handler) {
260             tasks.shift();
261             task.handler();
262         }
263
264         tasksInProgress = false;
265
266     }
267
268     /**
269      * Set to true if this Layer should resize itself to accomodate the
270      * dimensions of any drawing operation, and false (the default) otherwise.
271      * 
272      * Note that setting this property takes effect immediately, and thus may
273      * take effect on operations that were started in the past but have not
274      * yet completed. If you wish the setting of this flag to only modify
275      * future operations, you will need to make the setting of this flag an
276      * operation with sync().
277      * 
278      * @example
279      * // Set autosize to true for all future operations
280      * layer.sync(function() {
281      *     layer.autosize = true;
282      * });
283      * 
284      * @type Boolean
285      * @default false
286      */
287     this.autosize = false;
288
289     /**
290      * Returns the canvas element backing this Layer.
291      * @returns {Element} The canvas element backing this Layer.
292      */
293     this.getCanvas = function() {
294         return display;
295     };
296
297     /**
298      * Returns whether this Layer is ready. A Layer is ready if it has no
299      * pending operations and no operations in-progress.
300      * 
301      * @returns {Boolean} true if this Layer is ready, false otherwise.
302      */
303     this.isReady = function() {
304         return tasks.length == 0;
305     };
306
307     /**
308      * Changes the size of this Layer to the given width and height. Resizing
309      * is only attempted if the new size provided is actually different from
310      * the current size.
311      * 
312      * @param {Number} newWidth The new width to assign to this Layer.
313      * @param {Number} newHeight The new height to assign to this Layer.
314      */
315     this.resize = function(newWidth, newHeight) {
316         scheduleTask(function() {
317             if (newWidth != width || newHeight != height)
318                 resize(newWidth, newHeight);
319         });
320     };
321
322     /**
323      * Draws the specified image at the given coordinates. The image specified
324      * must already be loaded.
325      * 
326      * @param {Number} x The destination X coordinate.
327      * @param {Number} y The destination Y coordinate.
328      * @param {Image} image The image to draw. Note that this is an Image
329      *                      object - not a URL.
330      */
331     this.drawImage = function(x, y, image) {
332         scheduleTask(function() {
333             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
334             displayContext.drawImage(image, x, y);
335         });
336     };
337
338     /**
339      * Draws the image at the specified URL at the given coordinates. The image
340      * will be loaded automatically, and this and any future operations will
341      * wait for the image to finish loading.
342      * 
343      * @param {Number} x The destination X coordinate.
344      * @param {Number} y The destination Y coordinate.
345      * @param {String} url The URL of the image to draw.
346      */
347     this.draw = function(x, y, url) {
348         var task = scheduleTask(null);
349
350         var image = new Image();
351         image.onload = function() {
352
353             task.handler = function() {
354                 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
355                 displayContext.drawImage(image, x, y);
356             };
357
358             // As this task originally had no handler and may have blocked
359             // other tasks, handle any blocked tasks.
360             handlePendingTasks();
361
362         };
363         image.src = url;
364
365     };
366
367     /**
368      * Run an arbitrary function as soon as currently pending operations
369      * are complete.
370      * 
371      * @param {function} handler The function to call once all currently
372      *                           pending operations are complete.
373      */
374     this.sync = function(handler) {
375         return scheduleTask(handler);
376     };
377
378     /**
379      * Copy a rectangle of image data from one Layer to this Layer. This
380      * operation will copy exactly the image data that will be drawn once all
381      * operations of the source Layer that were pending at the time this
382      * function was called are complete. This operation will not alter the
383      * size of the source Layer even if its autosize property is set to true.
384      * 
385      * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
386      * @param {Number} srcx The X coordinate of the upper-left corner of the
387      *                      rectangle within the source Layer's coordinate
388      *                      space to copy data from.
389      * @param {Number} srcy The Y coordinate of the upper-left corner of the
390      *                      rectangle within the source Layer's coordinate
391      *                      space to copy data from.
392      * @param {Number} srcw The width of the rectangle within the source Layer's
393      *                      coordinate space to copy data from.
394      * @param {Number} srch The height of the rectangle within the source
395      *                      Layer's coordinate space to copy data from.
396      * @param {Number} x The destination X coordinate.
397      * @param {Number} y The destination Y coordinate.
398      */
399     this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
400
401         var srcCopied = null;
402
403         function doCopyRect() {
404             if (layer.autosize != 0) fitRect(x, y, srcw, srch);
405
406             var srcCanvas = srcLayer.getCanvas();
407             if (srcCanvas.width != 0 && srcCanvas.height != 0)
408                 displayContext.drawImage(srcCanvas, srcx, srcy, srcw, srch, x, y, srcw, srch);
409
410             // Unblock the copy complete task, if it exists
411             if (srcCopied != null)
412                 srcCopied.handler = function() {};
413         }
414
415         // If we ARE the source layer, no need to sync.
416         // Syncing would result in deadlock.
417         if (layer === srcLayer)
418             scheduleTask(doCopyRect);
419
420         // Otherwise synchronize copy operation with source layer
421         else {
422             
423             // Task which will be unblocked only when the source layer is ready
424             // This task will perform the copy
425             var task = scheduleTask(null);
426
427             // Task which will unblock the drawing task.
428             var srcReady = srcLayer.sync(function() {
429                 
430                 task.handler = doCopyRect;
431
432                 // As this task originally had no handler and may have blocked
433                 // other tasks, handle any blocked tasks.
434                 handlePendingTasks();
435
436             });
437
438             // Task which will be unblocked only after the copy has
439             // occurred (this will only be created if the draw task
440             // was postponed)
441             if (srcReady != null)
442                 srcCopied = srcLayer.sync(null);
443
444         }
445
446     };
447
448     /**
449      * Clear the specified rectangle of image data.
450      * 
451      * @param {Number} x The X coordinate of the upper-left corner of the
452      *                   rectangle to clear.
453      * @param {Number} y The Y coordinate of the upper-left corner of the
454      *                   rectangle to clear.
455      * @param {Number} w The width of the rectangle to clear.
456      * @param {Number} h The height of the rectangle to clear.
457      */
458     this.clearRect = function(x, y, w, h) {
459         scheduleTask(function() {
460             if (layer.autosize != 0) fitRect(x, y, w, h);
461             displayContext.clearRect(x, y, w, h);
462         });
463     };
464
465     /**
466      * Fill the specified rectangle of image data with the specified color.
467      * 
468      * @param {Number} x The X coordinate of the upper-left corner of the
469      *                   rectangle to draw.
470      * @param {Number} y The Y coordinate of the upper-left corner of the
471      *                   rectangle to draw.
472      * @param {Number} w The width of the rectangle to draw.
473      * @param {Number} h The height of the rectangle to draw.
474      * @param {Number} r The red component of the color of the rectangle.
475      * @param {Number} g The green component of the color of the rectangle.
476      * @param {Number} b The blue component of the color of the rectangle.
477      * @param {Number} a The alpha component of the color of the rectangle.
478      */
479     this.drawRect = function(x, y, w, h, r, g, b, a) {
480         scheduleTask(function() {
481             if (layer.autosize != 0) fitRect(x, y, w, h);
482             displayContext.fillStyle = "rgba("
483                         + r + "," + g + "," + b + "," + a / 255 + ")";
484             displayContext.fillRect(x, y, w, h);
485         });
486     };
487
488     /**
489      * Clip all future drawing operations by the specified rectangle.
490      * 
491      * @param {Number} x The X coordinate of the upper-left corner of the
492      *                   rectangle to use for the clipping region.
493      * @param {Number} y The Y coordinate of the upper-left corner of the
494      *                   rectangle to use for the clipping region.
495      * @param {Number} w The width of the rectangle to use for the clipping region.
496      * @param {Number} h The height of the rectangle to use for the clipping region.
497      */
498     this.clipRect = function(x, y, w, h) {
499         scheduleTask(function() {
500
501             // Clear any current clipping region
502             displayContext.restore();
503             displayContext.save();
504
505             if (layer.autosize != 0) fitRect(x, y, w, h);
506
507             // Set new clipping region
508             displayContext.beginPath();
509             displayContext.rect(x, y, w, h);
510             displayContext.clip();
511
512         });
513     };
514
515     /**
516      * Provides the given filtering function with a writable snapshot of
517      * image data and the current width and height of the Layer.
518      * 
519      * @param {function} filter A function which accepts an array of image
520      *                          data (as returned by the canvas element's
521      *                          display context's getImageData() function),
522      *                          the width of the Layer, and the height of the
523      *                          Layer as parameters, in that order. This
524      *                          function must accomplish its filtering by
525      *                          modifying the given image data array directly.
526      */
527     this.filter = function(filter) {
528         scheduleTask(function() {
529             var imageData = displayContext.getImageData(0, 0, width, height);
530             filter(imageData.data, width, height);
531             displayContext.putImageData(imageData, 0, 0);
532         });
533     };
534
535     /**
536      * Sets the channel mask for future operations on this Layer. The channel
537      * mask is a Guacamole-specific compositing operation identifier with a
538      * single bit representing each of four channels (in order): source image
539      * where destination transparent, source where destination opaque,
540      * destination where source transparent, and destination where source
541      * opaque.
542      * 
543      * @param {Number} mask The channel mask for future operations on this
544      *                      Layer.
545      */
546     this.setChannelMask = function(mask) {
547         scheduleTask(function() {
548             displayContext.globalCompositeOperation = compositeOperation[mask];
549         });
550     };
551
552     // Initialize canvas dimensions
553     display.width = width;
554     display.height = height;
555
556 };