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