Fixed layer resize(), avoid multiple handlePengingTasks() calls
[guacamole-common-js.git] / src / main / resources / layer.js
1
2 /*
3  *  Guacamole - Clientless Remote Desktop
4  *  Copyright (C) 2010  Michael Jumper
5  *
6  *  This program is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU Affero General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU Affero General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Affero General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 // Guacamole namespace
21 var Guacamole = Guacamole || {};
22
23 /**
24  * Abstract ordered drawing surface. Each Layer contains a canvas element and
25  * provides simple drawing instructions for drawing to that canvas element,
26  * however unlike the canvas element itself, drawing operations on a Layer are
27  * guaranteed to run in order, even if such an operation must wait for an image
28  * to load before completing.
29  * 
30  * @constructor
31  * 
32  * @param {Number} width The width of the Layer, in pixels. The canvas element
33  *                       backing this Layer will be given this width.
34  *                       
35  * @param {Number} height The height of the Layer, in pixels. The canvas element
36  *                        backing this Layer will be given this height.
37  */
38 Guacamole.Layer = function(width, height) {
39
40     /**
41      * Reference to this Layer.
42      * @private
43      */
44     var layer = this;
45
46     /**
47      * The canvas element backing this Layer.
48      * @private
49      */
50     var display = document.createElement("canvas");
51
52     /**
53      * The 2D display context of the canvas element backing this Layer.
54      * @private
55      */
56     var displayContext = display.getContext("2d");
57     displayContext.save();
58
59     /**
60      * The queue of all pending Tasks. Tasks will be run in order, with new
61      * tasks added at the end of the queue and old tasks removed from the
62      * front of the queue (FIFO).
63      * @private
64      */
65     var tasks = new Array();
66
67     /**
68      * Map of all Guacamole channel masks to HTML5 canvas composite operation
69      * names. Not all channel mask combinations are currently implemented.
70      * @private
71      */
72     var compositeOperation = {
73      /* 0x0 NOT IMPLEMENTED */
74         0x1: "destination-in",
75         0x2: "destination-out",
76      /* 0x3 NOT IMPLEMENTED */
77         0x4: "source-in",
78      /* 0x5 NOT IMPLEMENTED */
79         0x6: "source-atop",
80      /* 0x7 NOT IMPLEMENTED */
81         0x8: "source-out",
82         0x9: "destination-atop",
83         0xA: "xor",
84         0xB: "destination-over",
85         0xC: "copy",
86      /* 0xD NOT IMPLEMENTED */
87         0xE: "source-over",
88         0xF: "lighter"
89     };
90
91     /**
92      * Resizes the canvas element backing this Layer without testing the
93      * new size. This function should only be used internally.
94      * 
95      * @private
96      * @param {Number} newWidth The new width to assign to this Layer.
97      * @param {Number} newHeight The new height to assign to this Layer.
98      */
99     function resize(newWidth, newHeight) {
100
101
102         // Only preserve old data if width/height are both non-zero
103         var oldData = null;
104         if (width != 0 && height != 0) {
105
106             // Create canvas and context for holding old data
107             oldData = document.createElement("canvas");
108             oldData.width = width;
109             oldData.height = height;
110
111             var oldDataContext = oldData.getContext("2d");
112
113             // Copy image data from current
114             oldDataContext.drawImage(display,
115                     0, 0, width, height,
116                     0, 0, width, height);
117
118         }
119
120         // Resize canvas
121         display.width = newWidth;
122         display.height = newHeight;
123
124         // Redraw old data, if any
125         if (oldData)
126             displayContext.drawImage(oldData, 
127                     0, 0, width, height,
128                     0, 0, width, height);
129
130         width = newWidth;
131         height = newHeight;
132     }
133
134     /**
135      * Given the X and Y coordinates of the upper-left corner of a rectangle
136      * and the rectangle's width and height, resize the backing canvas element
137      * as necessary to ensure that the rectangle fits within the canvas
138      * element's coordinate space. This function will only make the canvas
139      * larger. If the rectangle already fits within the canvas element's
140      * coordinate space, the canvas is left unchanged.
141      * 
142      * @private
143      * @param {Number} x The X coordinate of the upper-left corner of the
144      *                   rectangle to fit.
145      * @param {Number} y The Y coordinate of the upper-left corner of the
146      *                   rectangle to fit.
147      * @param {Number} w The width of the the rectangle to fit.
148      * @param {Number} h The height of the the rectangle to fit.
149      */
150     function fitRect(x, y, w, h) {
151         
152         // Calculate bounds
153         var opBoundX = w + x;
154         var opBoundY = h + y;
155         
156         // Determine max width
157         var resizeWidth;
158         if (opBoundX > width)
159             resizeWidth = opBoundX;
160         else
161             resizeWidth = width;
162
163         // Determine max height
164         var resizeHeight;
165         if (opBoundY > height)
166             resizeHeight = opBoundY;
167         else
168             resizeHeight = height;
169
170         // Resize if necessary
171         if (resizeWidth != width || resizeHeight != height)
172             resize(resizeWidth, resizeHeight);
173
174     }
175
176     /**
177      * A container for an task handler. Each operation which must be ordered
178      * is associated with a Task that goes into a task queue. Tasks in this
179      * queue are executed in order once their handlers are set, while Tasks 
180      * without handlers block themselves and any following Tasks from running.
181      *
182      * @constructor
183      * @private
184      * @param {function} taskHandler The function to call when this task 
185      *                               runs, if any.
186      */
187     function Task(taskHandler) {
188         
189         /**
190          * The handler this Task is associated with, if any.
191          * 
192          * @type function
193          */
194         this.handler = taskHandler;
195         
196     }
197
198     /**
199      * If no tasks are pending or running, run the provided handler immediately,
200      * if any. Otherwise, schedule a task to run immediately after all currently
201      * running or pending tasks are complete.
202      * 
203      * @private
204      * @param {function} handler The function to call when possible, if any.
205      * @returns {Task} The Task created and added to the queue for future
206      *                 running, if any, or null if the handler was run
207      *                 immediately and no Task needed to be created.
208      */
209     function scheduleTask(handler) {
210         
211         // If no pending tasks, just call (if available) and exit
212         if (layer.isReady() && handler != null) {
213             handler();
214             return null;
215         }
216
217         // If tasks are pending/executing, schedule a pending task
218         // and return a reference to it.
219         var task = new Task(handler);
220         tasks.push(task);
221         return task;
222         
223     }
224
225     var tasksInProgress = false;
226
227     /**
228      * Run any Tasks which were pending but are now ready to run and are not
229      * blocked by other Tasks.
230      * @private
231      */
232     function handlePendingTasks() {
233
234         if (tasksInProgress)
235             return;
236
237         tasksInProgress = true;
238
239         // Draw all pending tasks.
240         var task;
241         while ((task = tasks[0]) != null && task.handler) {
242             tasks.shift();
243             task.handler();
244         }
245
246         tasksInProgress = false;
247
248     }
249
250     /**
251      * Set to true if this Layer should resize itself to accomodate the
252      * dimensions of any drawing operation, and false (the default) otherwise.
253      * 
254      * Note that setting this property takes effect immediately, and thus may
255      * take effect on operations that were started in the past but have not
256      * yet completed. If you wish the setting of this flag to only modify
257      * future operations, you will need to make the setting of this flag an
258      * operation with sync().
259      * 
260      * @example
261      * // Set autosize to true for all future operations
262      * layer.sync(function() {
263      *     layer.autosize = true;
264      * });
265      * 
266      * @type Boolean
267      * @default false
268      */
269     this.autosize = false;
270
271     /**
272      * Returns the canvas element backing this Layer.
273      * @returns {Element} The canvas element backing this Layer.
274      */
275     this.getCanvas = function() {
276         return display;
277     };
278
279     /**
280      * Returns whether this Layer is ready. A Layer is ready if it has no
281      * pending operations and no operations in-progress.
282      * 
283      * @returns {Boolean} true if this Layer is ready, false otherwise.
284      */
285     this.isReady = function() {
286         return tasks.length == 0;
287     };
288
289     /**
290      * Changes the size of this Layer to the given width and height. Resizing
291      * is only attempted if the new size provided is actually different from
292      * the current size.
293      * 
294      * @param {Number} newWidth The new width to assign to this Layer.
295      * @param {Number} newHeight The new height to assign to this Layer.
296      */
297     this.resize = function(newWidth, newHeight) {
298         scheduleTask(function() {
299             if (newWidth != width || newHeight != height)
300                 resize(newWidth, newHeight);
301         });
302     };
303
304     /**
305      * Draws the specified image at the given coordinates. The image specified
306      * must already be loaded.
307      * 
308      * @param {Number} x The destination X coordinate.
309      * @param {Number} y The destination Y coordinate.
310      * @param {Image} image The image to draw. Note that this is an Image
311      *                      object - not a URL.
312      */
313     this.drawImage = function(x, y, image) {
314         scheduleTask(function() {
315             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
316             displayContext.drawImage(image, x, y);
317         });
318     };
319
320     /**
321      * Draws the image at the specified URL at the given coordinates. The image
322      * will be loaded automatically, and this and any future operations will
323      * wait for the image to finish loading.
324      * 
325      * @param {Number} x The destination X coordinate.
326      * @param {Number} y The destination Y coordinate.
327      * @param {String} url The URL of the image to draw.
328      */
329     this.draw = function(x, y, url) {
330         var task = scheduleTask(null);
331
332         var image = new Image();
333         image.onload = function() {
334
335             task.handler = function() {
336                 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
337                 displayContext.drawImage(image, x, y);
338             };
339
340             // As this task originally had no handler and may have blocked
341             // other tasks, handle any blocked tasks.
342             handlePendingTasks();
343
344         };
345         image.src = url;
346
347     };
348
349     /**
350      * Run an arbitrary function as soon as currently pending operations
351      * are complete.
352      * 
353      * @param {function} handler The function to call once all currently
354      *                           pending operations are complete.
355      */
356     this.sync = function(handler) {
357         scheduleTask(handler);
358     };
359
360     /**
361      * Copy a rectangle of image data from one Layer to this Layer. This
362      * operation will copy exactly the image data that will be drawn once all
363      * operations of the source Layer that were pending at the time this
364      * function was called are complete. This operation will not alter the
365      * size of the source Layer even if its autosize property is set to true.
366      * 
367      * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
368      * @param {Number} srcx The X coordinate of the upper-left corner of the
369      *                      rectangle within the source Layer's coordinate
370      *                      space to copy data from.
371      * @param {Number} srcy The Y coordinate of the upper-left corner of the
372      *                      rectangle within the source Layer's coordinate
373      *                      space to copy data from.
374      * @param {Number} srcw The width of the rectangle within the source Layer's
375      *                      coordinate space to copy data from.
376      * @param {Number} srch The height of the rectangle within the source
377      *                      Layer's coordinate space to copy data from.
378      * @param {Number} x The destination X coordinate.
379      * @param {Number} y The destination Y coordinate.
380      */
381     this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
382
383         function doCopyRect() {
384             if (layer.autosize != 0) fitRect(x, y, srcw, srch);
385             displayContext.drawImage(srcLayer.getCanvas(), srcx, srcy, srcw, srch, x, y, srcw, srch);
386         }
387
388         // If we ARE the source layer, no need to sync.
389         // Syncing would result in deadlock.
390         if (layer === srcLayer)
391             scheduleTask(doCopyRect);
392
393         // Otherwise synchronize copy operation with source layer
394         else {
395             var task = scheduleTask(null);
396             srcLayer.sync(function() {
397                 
398                 task.handler = doCopyRect;
399
400                 // As this task originally had no handler and may have blocked
401                 // other tasks, handle any blocked tasks.
402                 handlePendingTasks();
403
404             });
405         }
406
407     };
408
409     /**
410      * Clear the specified rectangle of image data.
411      * 
412      * @param {Number} x The X coordinate of the upper-left corner of the
413      *                   rectangle to clear.
414      * @param {Number} y The Y coordinate of the upper-left corner of the
415      *                   rectangle to clear.
416      * @param {Number} w The width of the rectangle to clear.
417      * @param {Number} h The height of the rectangle to clear.
418      */
419     this.clearRect = function(x, y, w, h) {
420         scheduleTask(function() {
421             if (layer.autosize != 0) fitRect(x, y, w, h);
422             displayContext.clearRect(x, y, w, h);
423         });
424     };
425
426     /**
427      * Fill the specified rectangle of image data with the specified color.
428      * 
429      * @param {Number} x The X coordinate of the upper-left corner of the
430      *                   rectangle to draw.
431      * @param {Number} y The Y coordinate of the upper-left corner of the
432      *                   rectangle to draw.
433      * @param {Number} w The width of the rectangle to draw.
434      * @param {Number} h The height of the rectangle to draw.
435      * @param {Number} r The red component of the color of the rectangle.
436      * @param {Number} g The green component of the color of the rectangle.
437      * @param {Number} b The blue component of the color of the rectangle.
438      * @param {Number} a The alpha component of the color of the rectangle.
439      */
440     this.drawRect = function(x, y, w, h, r, g, b, a) {
441         scheduleTask(function() {
442             if (layer.autosize != 0) fitRect(x, y, w, h);
443             displayContext.fillStyle = "rgba("
444                         + r + "," + g + "," + b + "," + a / 255 + ")";
445             displayContext.fillRect(x, y, w, h);
446         });
447     };
448
449     /**
450      * Clip all future drawing operations by the specified rectangle.
451      * 
452      * @param {Number} x The X coordinate of the upper-left corner of the
453      *                   rectangle to use for the clipping region.
454      * @param {Number} y The Y coordinate of the upper-left corner of the
455      *                   rectangle to use for the clipping region.
456      * @param {Number} w The width of the rectangle to use for the clipping region.
457      * @param {Number} h The height of the rectangle to use for the clipping region.
458      */
459     this.clipRect = function(x, y, w, h) {
460         scheduleTask(function() {
461
462             // Clear any current clipping region
463             displayContext.restore();
464             displayContext.save();
465
466             if (layer.autosize != 0) fitRect(x, y, w, h);
467
468             // Set new clipping region
469             displayContext.beginPath();
470             displayContext.rect(x, y, w, h);
471             displayContext.clip();
472
473         });
474     };
475
476     /**
477      * Provides the given filtering function with a writable snapshot of
478      * image data and the current width and height of the Layer.
479      * 
480      * @param {function} filter A function which accepts an array of image
481      *                          data (as returned by the canvas element's
482      *                          display context's getImageData() function),
483      *                          the width of the Layer, and the height of the
484      *                          Layer as parameters, in that order. This
485      *                          function must accomplish its filtering by
486      *                          modifying the given image data array directly.
487      */
488     this.filter = function(filter) {
489         scheduleTask(function() {
490             var imageData = displayContext.getImageData(0, 0, width, height);
491             filter(imageData.data, width, height);
492             displayContext.putImageData(imageData, 0, 0);
493         });
494     };
495
496     /**
497      * Sets the channel mask for future operations on this Layer. The channel
498      * mask is a Guacamole-specific compositing operation identifier with a
499      * single bit representing each of four channels (in order): source image
500      * where destination transparent, source where destination opaque,
501      * destination where source transparent, and destination where source
502      * opaque.
503      * 
504      * @param {Number} mask The channel mask for future operations on this
505      *                      Layer.
506      */
507     this.setChannelMask = function(mask) {
508         scheduleTask(function() {
509             displayContext.globalCompositeOperation = compositeOperation[mask];
510         });
511     };
512
513     // Initialize canvas dimensions
514     display.width = width;
515     display.height = height;
516
517 };