Fixed autosize -> layer.autosize.
[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     display.style.position = "absolute";
52     display.style.left = "0px";
53     display.style.top = "0px";
54
55     /**
56      * The 2D display context of the canvas element backing this Layer.
57      * @private
58      */
59     var displayContext = display.getContext("2d");
60
61     /**
62      * The queue of all pending Tasks. Tasks will be run in order, with new
63      * tasks added at the end of the queue and old tasks removed from the
64      * front of the queue (FIFO).
65      * @private
66      */
67     var tasks = new Array();
68
69     /**
70      * Map of all Guacamole channel masks to HTML5 canvas composite operation
71      * names. Not all channel mask combinations are currently implemented.
72      * @private
73      */
74     var compositeOperation = {
75      /* 0x0 NOT IMPLEMENTED */
76         0x1: "destination-in",
77         0x2: "destination-out",
78      /* 0x3 NOT IMPLEMENTED */
79         0x4: "source-in",
80      /* 0x5 NOT IMPLEMENTED */
81         0x6: "source-atop",
82      /* 0x7 NOT IMPLEMENTED */
83         0x8: "source-out",
84         0x9: "destination-atop",
85         0xA: "xor",
86         0xB: "destination-over",
87         0xC: "copy",
88      /* 0xD NOT IMPLEMENTED */
89         0xE: "source-over",
90         0xF: "lighter"
91     };
92
93     /**
94      * Resizes the canvas element backing this Layer without testing the
95      * new size. This function should only be used internally.
96      * 
97      * @private
98      * @param {Number} newWidth The new width to assign to this Layer.
99      * @param {Number} newHeight The new height to assign to this Layer.
100      */
101     function resize(newWidth, newHeight) {
102         display.width = newWidth;
103         display.height = newHeight;
104
105         width = newWidth;
106         height = newHeight;
107     }
108
109     /**
110      * Given the X and Y coordinates of the upper-left corner of a rectangle
111      * and the rectangle's width and height, resize the backing canvas element
112      * as necessary to ensure that the rectangle fits within the canvas
113      * element's coordinate space. This function will only make the canvas
114      * larger. If the rectangle already fits within the canvas element's
115      * coordinate space, the canvas is left unchanged.
116      * 
117      * @private
118      * @param {Number} x The X coordinate of the upper-left corner of the
119      *                   rectangle to fit.
120      * @param {Number} y The Y coordinate of the upper-left corner of the
121      *                   rectangle to fit.
122      * @param {Number} w The width of the the rectangle to fit.
123      * @param {Number} h The height of the the rectangle to fit.
124      */
125     function fitRect(x, y, w, h) {
126         
127         // Calculate bounds
128         var opBoundX = w + x;
129         var opBoundY = h + y;
130         
131         // Determine max width
132         var resizeWidth;
133         if (opBoundX > width)
134             resizeWidth = opBoundX;
135         else
136             resizeWidth = width;
137
138         // Determine max height
139         var resizeHeight;
140         if (opBoundY > height)
141             resizeHeight = opBoundY;
142         else
143             resizeHeight = height;
144
145         // Resize if necessary
146         if (resizeWidth != width || resizeHeight != height)
147             resize(resizeWidth, resizeHeight);
148
149     }
150
151     /**
152      * A container for an task handler. Each operation which must be ordered
153      * is associated with a Task that goes into a task queue. Tasks in this
154      * queue are executed in order once their handlers are set, while Tasks 
155      * without handlers block themselves and any following Tasks from running.
156      *
157      * @constructor
158      * @private
159      * @param {function} taskHandler The function to call when this task 
160      *                               runs, if any.
161      */
162     function Task(taskHandler) {
163         
164         /**
165          * The handler this Task is associated with, if any.
166          * 
167          * @type function
168          */
169         this.handler = taskHandler;
170         
171     }
172
173     /**
174      * If no tasks are pending or running, run the provided handler immediately,
175      * if any. Otherwise, schedule a task to run immediately after all currently
176      * running or pending tasks are complete.
177      * 
178      * @private
179      * @param {function} handler The function to call when possible, if any.
180      * @returns {Task} The Task created and added to the queue for future
181      *                 running, if any, or null if the handler was run
182      *                 immediately and no Task needed to be created.
183      */
184     function scheduleTask(handler) {
185         
186         // If no pending tasks, just call (if available) and exit
187         if (layer.isReady() && handler != null) {
188             handler();
189             return null;
190         }
191
192         // If tasks are pending/executing, schedule a pending task
193         // and return a reference to it.
194         var task = new Task(handler);
195         tasks.push(task);
196         return task;
197         
198     }
199
200     /**
201      * Run any Tasks which were pending but are now ready to run and are not
202      * blocked by other Tasks.
203      * @private
204      */
205     function handlePendingTasks() {
206
207         // Draw all pending tasks.
208         var task;
209         while ((task = tasks[0]) != null && task.handler) {
210             task.handler();
211             tasks.shift();
212         }
213
214     }
215
216     /**
217      * Set to true if this Layer should resize itself to accomodate the
218      * dimensions of any drawing operation, and false (the default) otherwise.
219      * 
220      * Note that setting this property takes effect immediately, and thus may
221      * take effect on operations that were started in the past but have not
222      * yet completed. If you wish the setting of this flag to only modify
223      * future operations, you will need to make the setting of this flag an
224      * operation with sync().
225      * 
226      * @example
227      * // Set autosize to true for all future operations
228      * layer.sync(function() {
229      *     layer.autosize = true;
230      * });
231      * 
232      * @type Boolean
233      * @default false
234      */
235     this.autosize = false;
236
237     /**
238      * Returns the canvas element backing this Layer.
239      * @returns {Element} The canvas element backing this Layer.
240      */
241     this.getCanvas = function() {
242         return display;
243     };
244
245     /**
246      * Returns whether this Layer is ready. A Layer is ready if it has no
247      * pending operations and no operations in-progress.
248      * 
249      * @returns {Boolean} true if this Layer is ready, false otherwise.
250      */
251     this.isReady = function() {
252         return tasks.length == 0;
253     };
254
255     /**
256      * Changes the size of this Layer to the given width and height. Resizing
257      * is only attempted if the new size provided is actually different from
258      * the current size.
259      * 
260      * @param {Number} newWidth The new width to assign to this Layer.
261      * @param {Number} newHeight The new height to assign to this Layer.
262      */
263     this.resize = function(newWidth, newHeight) {
264         scheduleTask(function() {
265             if (newWidth != width || newHeight != height)
266                 resize(newWidth, newHeight);
267         });
268     };
269
270     /**
271      * Draws the specified image at the given coordinates. The image specified
272      * must already be loaded.
273      * 
274      * @param {Number} x The destination X coordinate.
275      * @param {Number} y The destination Y coordinate.
276      * @param {Image} image The image to draw. Note that this is an Image
277      *                      object - not a URL.
278      */
279     this.drawImage = function(x, y, image) {
280         scheduleTask(function() {
281             if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
282             displayContext.drawImage(image, x, y);
283         });
284     };
285
286     /**
287      * Draws the image at the specified URL at the given coordinates. The image
288      * will be loaded automatically, and this and any future operations will
289      * wait for the image to finish loading.
290      * 
291      * @param {Number} x The destination X coordinate.
292      * @param {Number} y The destination Y coordinate.
293      * @param {String} url The URL of the image to draw.
294      */
295     this.draw = function(x, y, url) {
296         var task = scheduleTask(null);
297
298         var image = new Image();
299         image.onload = function() {
300
301             task.handler = function() {
302                 if (layer.autosize != 0) fitRect(x, y, image.width, image.height);
303                 displayContext.drawImage(image, x, y);
304             };
305
306             // As this task originally had no handler and may have blocked
307             // other tasks, handle any blocked tasks.
308             handlePendingTasks();
309
310         };
311         image.src = url;
312
313     };
314
315     /**
316      * Run an arbitrary function as soon as currently pending operations
317      * are complete.
318      * 
319      * @param {function} handler The function to call once all currently
320      *                           pending operations are complete.
321      */
322     this.sync = function(handler) {
323         scheduleTask(handler);
324     };
325
326     /**
327      * Copy a rectangle of image data from one Layer to this Layer. This
328      * operation will copy exactly the image data that will be drawn once all
329      * operations of the source Layer that were pending at the time this
330      * function was called are complete. This operation will not alter the
331      * size of the source Layer even if its autosize property is set to true.
332      * 
333      * @param {Guacamole.Layer} srcLayer The Layer to copy image data from.
334      * @param {Number} srcx The X coordinate of the upper-left corner of the
335      *                      rectangle within the source Layer's coordinate
336      *                      space to copy data from.
337      * @param {Number} srcy The Y coordinate of the upper-left corner of the
338      *                      rectangle within the source Layer's coordinate
339      *                      space to copy data from.
340      * @param {Number} srcw The width of the rectangle within the source Layer's
341      *                      coordinate space to copy data from.
342      * @param {Number} srch The height of the rectangle within the source
343      *                      Layer's coordinate space to copy data from.
344      * @param {Number} x The destination X coordinate.
345      * @param {Number} y The destination Y coordinate.
346      */
347     this.copyRect = function(srcLayer, srcx, srcy, srcw, srch, x, y) {
348
349         function doCopyRect() {
350             if (layer.autosize != 0) fitRect(x, y, srcw, srch);
351             displayContext.drawImage(srcLayer, srcx, srcy, srcw, srch, x, y, srcw, srch);
352         }
353
354         // If we ARE the source layer, no need to sync.
355         // Syncing would result in deadlock.
356         if (layer === srcLayer)
357             scheduleTask(doCopyRect);
358
359         // Otherwise synchronize copy operation with source layer
360         else {
361             var task = scheduleTask(null);
362             srcLayer.sync(function() {
363                 
364                 task.handler = doCopyRect;
365
366                 // As this task originally had no handler and may have blocked
367                 // other tasks, handle any blocked tasks.
368                 handlePendingTasks();
369
370             });
371         }
372
373     };
374
375     /**
376      * Clear the specified rectangle of image data.
377      * 
378      * @param {Number} x The X coordinate of the upper-left corner of the
379      *                   rectangle to clear.
380      * @param {Number} y The Y coordinate of the upper-left corner of the
381      *                   rectangle to clear.
382      * @param {Number} w The width of the rectangle to clear.
383      * @param {Number} h The height of the rectangle to clear.
384      */
385     this.clearRect = function(x, y, w, h) {
386         scheduleTask(function() {
387             if (layer.autosize != 0) fitRect(x, y, w, h);
388             displayContext.clearRect(x, y, w, h);
389         });
390     };
391
392     /**
393      * Provides the given filtering function with a writable snapshot of
394      * image data and the current width and height of the Layer.
395      * 
396      * @param {function} filter A function which accepts an array of image
397      *                          data (as returned by the canvas element's
398      *                          display context's getImageData() function),
399      *                          the width of the Layer, and the height of the
400      *                          Layer as parameters, in that order. This
401      *                          function must accomplish its filtering by
402      *                          modifying the given image data array directly.
403      */
404     this.filter = function(filter) {
405         scheduleTask(function() {
406             var imageData = displayContext.getImageData(0, 0, width, height);
407             filter(imageData.data, width, height);
408             displayContext.putImageData(imageData, 0, 0);
409         });
410     };
411
412     /**
413      * Sets the channel mask for future operations on this Layer. The channel
414      * mask is a Guacamole-specific compositing operation identifier with a
415      * single bit representing each of four channels (in order): source image
416      * where destination transparent, source where destination opaque,
417      * destination where source transparent, and destination where source
418      * opaque.
419      * 
420      * @param {Number} mask The channel mask for future operations on this
421      *                      Layer.
422      */
423     this.setChannelMask = function(mask) {
424         scheduleTask(function() {
425             displayContext.globalCompositeOperation = compositeOperation[mask];
426         });
427     };
428
429     // Initialize canvas dimensions
430     resize(width, height);
431
432 }
433