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