1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 * Command queue is the only way to modify images.
8 * Command execution is asynchronous (callback-based).
10 * @param {Document} document Document to create canvases in.
11 * @param {HTMLCanvasElement} canvas The canvas with the original image.
12 * @param {function(function())} saveFunction Function to save the image.
15 function CommandQueue(document, canvas, saveFunction) {
16 this.document_ = document;
19 this.subscribers_ = [];
20 this.currentImage_ = canvas;
22 // Current image may be null or not-null but with width = height = 0.
23 // Copying an image with zero dimensions causes js errors.
24 if (this.currentImage_) {
25 this.baselineImage_ = document.createElement('canvas');
26 this.baselineImage_.width = this.currentImage_.width;
27 this.baselineImage_.height = this.currentImage_.height;
28 if (this.currentImage_.width > 0 && this.currentImage_.height > 0) {
29 var context = this.baselineImage_.getContext('2d');
30 context.drawImage(this.currentImage_, 0, 0);
33 this.baselineImage_ = null;
36 this.previousImage_ = document.createElement('canvas');
37 this.previousImageAvailable_ = false;
39 this.saveFunction_ = saveFunction;
45 * Attach the UI elements to the command queue.
46 * Once the UI is attached the results of image manipulations are displayed.
48 * @param {ImageView} imageView The ImageView object to display the results.
49 * @param {ImageEditor.Prompt} prompt Prompt to use with this CommandQueue.
50 * @param {function(boolean)} lock Function to enable/disable buttons etc.
52 CommandQueue.prototype.attachUI = function(imageView, prompt, lock) {
61 * Execute the action when the queue is not busy.
62 * @param {function()} callback Callback.
64 CommandQueue.prototype.executeWhenReady = function(callback) {
66 this.subscribers_.push(callback);
68 setTimeout(callback, 0);
72 * @return {boolean} True if the command queue is busy.
74 CommandQueue.prototype.isBusy = function() { return this.busy_ };
77 * Set the queue state to busy. Lock the UI.
80 CommandQueue.prototype.setBusy_ = function() {
82 throw new Error('CommandQueue already busy');
86 if (this.UIContext_.lock)
87 this.UIContext_.lock(true);
89 ImageUtil.trace.resetTimer('command-busy');
93 * Set the queue state to not busy. Unlock the UI and execute pending actions.
96 CommandQueue.prototype.clearBusy_ = function() {
98 throw new Error('Inconsistent CommandQueue already not busy');
102 // Execute the actions requested while the queue was busy.
103 while (this.subscribers_.length)
104 this.subscribers_.shift()();
106 if (this.UIContext_.lock)
107 this.UIContext_.lock(false);
109 ImageUtil.trace.reportTimer('command-busy');
113 * Commit the image change: save and unlock the UI.
114 * @param {number=} opt_delay Delay in ms (to avoid disrupting the animation).
117 CommandQueue.prototype.commit_ = function(opt_delay) {
118 setTimeout(this.saveFunction_.bind(null, this.clearBusy_.bind(this)),
123 * Internal function to execute the command in a given context.
125 * @param {Command} command The command to execute.
126 * @param {Object} uiContext The UI context.
127 * @param {function(number=)} callback Completion callback.
130 CommandQueue.prototype.doExecute_ = function(command, uiContext, callback) {
131 if (!this.currentImage_)
132 throw new Error('Cannot operate on null image');
134 // Remember one previous image so that the first undo is as fast as possible.
135 this.previousImage_.width = this.currentImage_.width;
136 this.previousImage_.height = this.currentImage_.height;
137 this.previousImageAvailable_ = true;
138 var context = this.previousImage_.getContext('2d');
139 context.drawImage(this.currentImage_, 0, 0);
144 function(result, opt_delay) {
145 this.currentImage_ = result;
152 * Executes the command.
154 * @param {Command} command Command to execute.
155 * @param {boolean=} opt_keep_redo True if redo stack should not be cleared.
157 CommandQueue.prototype.execute = function(command, opt_keep_redo) {
163 this.undo_.push(command);
165 this.doExecute_(command, this.UIContext_, this.commit_.bind(this));
169 * @return {boolean} True if Undo is applicable.
171 CommandQueue.prototype.canUndo = function() {
172 return this.undo_.length != 0;
176 * Undo the most recent command.
178 CommandQueue.prototype.undo = function() {
180 throw new Error('Cannot undo');
184 var command = this.undo_.pop();
185 this.redo_.push(command);
189 function complete() {
190 var delay = command.revertView(
191 self.currentImage_, self.UIContext_.imageView);
195 if (this.previousImageAvailable_) {
196 // First undo after an execute call.
197 this.currentImage_.width = this.previousImage_.width;
198 this.currentImage_.height = this.previousImage_.height;
199 var context = this.currentImage_.getContext('2d');
200 context.drawImage(this.previousImage_, 0, 0);
203 this.previousImage_.width = 0;
204 this.previousImage_.height = 0;
205 this.previousImageAvailable_ = false;
208 // TODO(kaznacheev) Consider recalculating previousImage_ right here
209 // by replaying the commands in the background.
211 this.currentImage_.width = this.baselineImage_.width;
212 this.currentImage_.height = this.baselineImage_.height;
213 var context = this.currentImage_.getContext('2d');
214 context.drawImage(this.baselineImage_, 0, 0);
216 var replay = function(index) {
217 if (index < self.undo_.length)
218 self.doExecute_(self.undo_[index], {}, replay.bind(null, index + 1));
229 * @return {boolean} True if Redo is applicable.
231 CommandQueue.prototype.canRedo = function() {
232 return this.redo_.length != 0;
236 * Repeat the command that was recently un-done.
238 CommandQueue.prototype.redo = function() {
240 throw new Error('Cannot redo');
242 this.execute(this.redo_.pop(), true);
246 * Closes internal buffers. Call to ensure, that internal buffers are freed
247 * as soon as possible.
249 CommandQueue.prototype.close = function() {
250 // Free memory used by the undo buffer.
251 this.previousImage_.width = 0;
252 this.previousImage_.height = 0;
253 this.previousImageAvailable_ = false;
255 if (this.baselineImage_) {
256 this.baselineImage_.width = 0;
257 this.baselineImage_.height = 0;
262 * Command object encapsulates an operation on an image and a way to visualize
265 * @param {string} name Command name.
268 function Command(name) {
273 * @return {string} String representation of the command.
275 Command.prototype.toString = function() {
276 return 'Command ' + this.name_;
280 * Execute the command and visualize its results.
282 * The two actions are combined into one method because sometimes it is nice
283 * to be able to show partial results for slower operations.
285 * @param {Document} document Document on which to execute command.
286 * @param {HTMLCanvasElement} srcCanvas Canvas to execute on.
287 * @param {function(HTMLCanvasElement, number)} callback Callback to call on
289 * @param {Object} uiContext Context to work in.
291 Command.prototype.execute = function(document, srcCanvas, callback, uiContext) {
292 console.error('Command.prototype.execute not implemented');
296 * Visualize reversion of the operation.
298 * @param {HTMLCanvasElement} canvas Image data to use.
299 * @param {ImageView} imageView ImageView to revert.
300 * @return {number} Animation duration in ms.
302 Command.prototype.revertView = function(canvas, imageView) {
303 imageView.replace(canvas);
308 * Creates canvas to render on.
310 * @param {Document} document Document to create canvas in.
311 * @param {HTMLCanvasElement} srcCanvas to copy optional dimensions from.
312 * @param {number=} opt_width new canvas width.
313 * @param {number=} opt_height new canvas height.
314 * @return {HTMLCanvasElement} Newly created canvas.
317 Command.prototype.createCanvas_ = function(
318 document, srcCanvas, opt_width, opt_height) {
319 var result = document.createElement('canvas');
320 result.width = opt_width || srcCanvas.width;
321 result.height = opt_height || srcCanvas.height;
328 * @param {number} rotate90 Rotation angle in 90 degree increments (signed).
332 Command.Rotate = function(rotate90) {
333 Command.call(this, 'rotate(' + rotate90 * 90 + 'deg)');
334 this.rotate90_ = rotate90;
337 Command.Rotate.prototype = { __proto__: Command.prototype };
340 Command.Rotate.prototype.execute = function(
341 document, srcCanvas, callback, uiContext) {
342 var result = this.createCanvas_(
345 (this.rotate90_ & 1) ? srcCanvas.height : srcCanvas.width,
346 (this.rotate90_ & 1) ? srcCanvas.width : srcCanvas.height);
347 ImageUtil.drawImageTransformed(
348 result, srcCanvas, 1, 1, this.rotate90_ * Math.PI / 2);
350 if (uiContext.imageView) {
351 delay = uiContext.imageView.replaceAndAnimate(result, null, this.rotate90_);
353 setTimeout(callback, 0, result, delay);
357 Command.Rotate.prototype.revertView = function(canvas, imageView) {
358 return imageView.replaceAndAnimate(canvas, null, -this.rotate90_);
365 * @param {ImageRect} imageRect Crop rectangle in image coordinates.
369 Command.Crop = function(imageRect) {
370 Command.call(this, 'crop' + imageRect.toString());
371 this.imageRect_ = imageRect;
374 Command.Crop.prototype = { __proto__: Command.prototype };
377 Command.Crop.prototype.execute = function(
378 document, srcCanvas, callback, uiContext) {
379 var result = this.createCanvas_(
380 document, srcCanvas, this.imageRect_.width, this.imageRect_.height);
382 result.getContext('2d'), srcCanvas, null, this.imageRect_);
384 if (uiContext.imageView) {
385 delay = uiContext.imageView.replaceAndAnimate(result, this.imageRect_, 0);
387 setTimeout(callback, 0, result, delay);
391 Command.Crop.prototype.revertView = function(canvas, imageView) {
392 return imageView.animateAndReplace(canvas, this.imageRect_);
399 * @param {string} name Command name.
400 * @param {function(ImageData,ImageData,number,number)} filter Filter function.
401 * @param {string} message Message to display when done.
405 Command.Filter = function(name, filter, message) {
406 Command.call(this, name);
407 this.filter_ = filter;
408 this.message_ = message;
411 Command.Filter.prototype = { __proto__: Command.prototype };
414 Command.Filter.prototype.execute = function(
415 document, srcCanvas, callback, uiContext) {
416 var result = this.createCanvas_(document, srcCanvas);
420 function onProgressVisible(updatedRow, rowCount) {
421 if (updatedRow == rowCount) {
422 uiContext.imageView.replace(result);
424 uiContext.prompt.show(self.message_, 2000);
427 var viewport = uiContext.imageView.viewport_;
429 var imageStrip = new ImageRect(viewport.getImageBounds());
430 imageStrip.top = previousRow;
431 imageStrip.height = updatedRow - previousRow;
433 var screenStrip = new ImageRect(viewport.getImageBoundsOnScreen());
434 screenStrip.top = Math.round(viewport.imageToScreenY(previousRow));
436 Math.round(viewport.imageToScreenY(updatedRow)) - screenStrip.top;
438 uiContext.imageView.paintDeviceRect(result, imageStrip);
439 previousRow = updatedRow;
443 function onProgressInvisible(updatedRow, rowCount) {
444 if (updatedRow == rowCount) {
449 filter.applyByStrips(result, srcCanvas, this.filter_,
450 uiContext.imageView ? onProgressVisible : onProgressInvisible);