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.
8 // Namespace object for the utilities.
9 function ImageUtil() {}
14 ImageUtil.trace = (function() {
15 function PerformanceTrace() {
18 this.container_ = null;
21 PerformanceTrace.prototype.bindToDOM = function(container) {
22 this.container_ = container;
25 PerformanceTrace.prototype.report = function(key, value) {
26 if (!(key in this.lines_)) {
27 if (this.container_) {
28 var div = this.lines_[key] = document.createElement('div');
29 this.container_.appendChild(div);
31 this.lines_[key] = {};
34 this.lines_[key].textContent = key + ': ' + value;
35 if (ImageUtil.trace.log) this.dumpLine(key);
38 PerformanceTrace.prototype.resetTimer = function(key) {
39 this.timers_[key] = Date.now();
42 PerformanceTrace.prototype.reportTimer = function(key) {
43 this.report(key, (Date.now() - this.timers_[key]) + 'ms');
46 PerformanceTrace.prototype.dump = function() {
47 for (var key in this.lines_)
51 PerformanceTrace.prototype.dumpLine = function(key) {
52 console.log('trace.' + this.lines_[key].textContent);
55 return new PerformanceTrace();
59 * @param {number} min Minimum value.
60 * @param {number} value Value to adjust.
61 * @param {number} max Maximum value.
62 * @return {number} The closest to the |value| number in span [min, max].
64 ImageUtil.clamp = function(min, value, max) {
65 return Math.max(min, Math.min(max, value));
69 * @param {number} min Minimum value.
70 * @param {number} value Value to check.
71 * @param {number} max Maximum value.
72 * @return {boolean} True if value is between.
74 ImageUtil.between = function(min, value, max) {
75 return (value - min) * (value - max) <= 0;
83 * Rectangle constructor takes 0, 1, 2 or 4 arguments.
84 * Supports following variants:
85 * new Rect(left, top, width, height)
86 * new Rect(width, height)
87 * new Rect(rect) // anything with left, top, width, height properties
88 * new Rect(bounds) // anything with left, top, right, bottom properties
89 * new Rect(canvas|image) // anything with width and height properties.
90 * new Rect() // empty rectangle.
94 switch (arguments.length) {
96 this.left = arguments[0];
97 this.top = arguments[1];
98 this.width = arguments[2];
99 this.height = arguments[3];
105 this.width = arguments[0];
106 this.height = arguments[1];
110 var source = arguments[0];
111 if ('left' in source && 'top' in source) {
112 this.left = source.left;
113 this.top = source.top;
114 if ('right' in source && 'bottom' in source) {
115 this.width = source.right - source.left;
116 this.height = source.bottom - source.top;
123 if ('width' in source && 'height' in source) {
124 this.width = source.width;
125 this.height = source.height;
128 break; // Fall through to the error message.
138 console.error('Invalid Rect constructor arguments:',
139 Array.apply(null, arguments));
143 * @param {number} factor Factor to scale.
144 * @return {Rect} A rectangle with every dimension scaled.
146 Rect.prototype.scale = function(factor) {
151 this.height * factor);
155 * @param {number} dx Difference in X.
156 * @param {number} dy Difference in Y.
157 * @return {Rect} A rectangle shifted by (dx,dy), same size.
159 Rect.prototype.shift = function(dx, dy) {
160 return new Rect(this.left + dx, this.top + dy, this.width, this.height);
164 * @param {number} x Coordinate of the left top corner.
165 * @param {number} y Coordinate of the left top corner.
166 * @return {Rect} A rectangle with left==x and top==y, same size.
168 Rect.prototype.moveTo = function(x, y) {
169 return new Rect(x, y, this.width, this.height);
173 * @param {number} dx Difference in X.
174 * @param {number} dy Difference in Y.
175 * @return {Rect} A rectangle inflated by (dx, dy), same center.
177 Rect.prototype.inflate = function(dx, dy) {
179 this.left - dx, this.top - dy, this.width + 2 * dx, this.height + 2 * dy);
183 * @param {number} x Coordinate of the point.
184 * @param {number} y Coordinate of the point.
185 * @return {boolean} True if the point lies inside the rectangle.
187 Rect.prototype.inside = function(x, y) {
188 return this.left <= x && x < this.left + this.width &&
189 this.top <= y && y < this.top + this.height;
193 * @param {Rect} rect Rectangle to check.
194 * @return {boolean} True if this rectangle intersects with the |rect|.
196 Rect.prototype.intersects = function(rect) {
197 return (this.left + this.width) > rect.left &&
198 (rect.left + rect.width) > this.left &&
199 (this.top + this.height) > rect.top &&
200 (rect.top + rect.height) > this.top;
204 * @param {Rect} rect Rectangle to check.
205 * @return {boolean} True if this rectangle containing the |rect|.
207 Rect.prototype.contains = function(rect) {
208 return (this.left <= rect.left) &&
209 (rect.left + rect.width) <= (this.left + this.width) &&
210 (this.top <= rect.top) &&
211 (rect.top + rect.height) <= (this.top + this.height);
215 * @return {boolean} True if rectangle is empty.
217 Rect.prototype.isEmpty = function() {
218 return this.width === 0 || this.height === 0;
222 * Clamp the rectangle to the bounds by moving it.
223 * Decrease the size only if necessary.
224 * @param {Rect} bounds Bounds.
225 * @return {Rect} Calculated rectangle.
227 Rect.prototype.clamp = function(bounds) {
228 var rect = new Rect(this);
230 if (rect.width > bounds.width) {
231 rect.left = bounds.left;
232 rect.width = bounds.width;
233 } else if (rect.left < bounds.left) {
234 rect.left = bounds.left;
235 } else if (rect.left + rect.width >
236 bounds.left + bounds.width) {
237 rect.left = bounds.left + bounds.width - rect.width;
240 if (rect.height > bounds.height) {
241 rect.top = bounds.top;
242 rect.height = bounds.height;
243 } else if (rect.top < bounds.top) {
244 rect.top = bounds.top;
245 } else if (rect.top + rect.height >
246 bounds.top + bounds.height) {
247 rect.top = bounds.top + bounds.height - rect.height;
254 * @return {string} String representation.
256 Rect.prototype.toString = function() {
257 return '(' + this.left + ',' + this.top + '):' +
258 '(' + (this.left + this.width) + ',' + (this.top + this.height) + ')';
261 * Useful shortcuts for drawing (static functions).
265 * Draw the image in context with appropriate scaling.
266 * @param {CanvasRenderingContext2D} context Context to draw.
267 * @param {Image} image Image to draw.
268 * @param {Rect=} opt_dstRect Rectangle in the canvas (whole canvas by default).
269 * @param {Rect=} opt_srcRect Rectangle in the image (whole image by default).
271 Rect.drawImage = function(context, image, opt_dstRect, opt_srcRect) {
272 opt_dstRect = opt_dstRect || new Rect(context.canvas);
273 opt_srcRect = opt_srcRect || new Rect(image);
274 if (opt_dstRect.isEmpty() || opt_srcRect.isEmpty())
276 context.drawImage(image,
277 opt_srcRect.left, opt_srcRect.top, opt_srcRect.width, opt_srcRect.height,
278 opt_dstRect.left, opt_dstRect.top, opt_dstRect.width, opt_dstRect.height);
282 * Draw a box around the rectangle.
283 * @param {CanvasRenderingContext2D} context Context to draw.
284 * @param {Rect} rect Rectangle.
286 Rect.outline = function(context, rect) {
288 rect.left - 0.5, rect.top - 0.5, rect.width + 1, rect.height + 1);
292 * Fill the rectangle.
293 * @param {CanvasRenderingContext2D} context Context to draw.
294 * @param {Rect} rect Rectangle.
296 Rect.fill = function(context, rect) {
297 context.fillRect(rect.left, rect.top, rect.width, rect.height);
301 * Fills the space between the two rectangles.
302 * @param {CanvasRenderingContext2D} context Context to draw.
303 * @param {Rect} inner Inner rectangle.
304 * @param {Rect} outer Outer rectangle.
306 Rect.fillBetween = function(context, inner, outer) {
307 var innerRight = inner.left + inner.width;
308 var innerBottom = inner.top + inner.height;
309 var outerRight = outer.left + outer.width;
310 var outerBottom = outer.top + outer.height;
311 if (inner.top > outer.top) {
313 outer.left, outer.top, outer.width, inner.top - outer.top);
315 if (inner.left > outer.left) {
317 outer.left, inner.top, inner.left - outer.left, inner.height);
319 if (inner.width < outerRight) {
321 innerRight, inner.top, outerRight - innerRight, inner.height);
323 if (inner.height < outerBottom) {
325 outer.left, innerBottom, outer.width, outerBottom - innerBottom);
331 * @param {number} x X coordinate of circle center.
332 * @param {number} y Y coordinate of circle center.
333 * @param {number} r Radius.
336 function Circle(x, y, r) {
339 this.squaredR = r * r;
343 * Check if the point is inside the circle.
344 * @param {number} x X coordinate of the point.
345 * @param {number} y Y coordinate of the point.
346 * @return {boolean} True if the point is inside.
348 Circle.prototype.inside = function(x, y) {
351 return x * x + y * y <= this.squaredR;
355 * Copy an image applying scaling and rotation.
357 * @param {HTMLCanvasElement} dst Destination.
358 * @param {HTMLCanvasElement|HTMLImageElement} src Source.
359 * @param {number} scaleX Y scale transformation.
360 * @param {number} scaleY X scale transformation.
361 * @param {number} angle (in radians).
363 ImageUtil.drawImageTransformed = function(dst, src, scaleX, scaleY, angle) {
364 var context = dst.getContext('2d');
366 context.translate(context.canvas.width / 2, context.canvas.height / 2);
367 context.rotate(angle);
368 context.scale(scaleX, scaleY);
369 context.drawImage(src, -src.width / 2, -src.height / 2);
374 * Adds or removes an attribute to/from an HTML element.
375 * @param {HTMLElement} element To be applied to.
376 * @param {string} attribute Name of attribute.
377 * @param {boolean} on True if add, false if remove.
379 ImageUtil.setAttribute = function(element, attribute, on) {
381 element.setAttribute(attribute, '');
383 element.removeAttribute(attribute);
387 * Adds or removes CSS class to/from an HTML element.
388 * @param {HTMLElement} element To be applied to.
389 * @param {string} className Name of CSS class.
390 * @param {boolean} on True if add, false if remove.
392 ImageUtil.setClass = function(element, className, on) {
393 var cl = element.classList;
397 cl.remove(className);
401 * ImageLoader loads an image from a given Entry into a canvas in two steps:
402 * 1. Loads the image into an HTMLImageElement.
403 * 2. Copies pixels from HTMLImageElement to HTMLCanvasElement. This is done
404 * stripe-by-stripe to avoid freezing up the UI. The transform is taken into
407 * @param {HTMLDocument} document Owner document.
408 * @param {MetadataCache=} opt_metadataCache Metadata cache. Required for
409 * caching. If not passed, caching will be disabled.
412 ImageUtil.ImageLoader = function(document, opt_metadataCache) {
413 this.document_ = document;
414 this.metadataCache_ = opt_metadataCache || null;
415 this.image_ = new Image();
416 this.generation_ = 0;
421 * TODO(mtomasz): Simplify, or even get rid of this class and merge with the
422 * ThumbnaiLoader class.
424 * @param {FileEntry} entry Image entry to be loaded.
425 * @param {function(function(object))} transformFetcher function to get
426 * the image transform (which we need for the image orientation).
427 * @param {function(HTMLCanvasElement, string=)} callback Callback to be
428 * called when loaded. The second optional argument is an error identifier.
429 * @param {number=} opt_delay Load delay in milliseconds, useful to let the
430 * animations play out before the computation heavy image loading starts.
432 ImageUtil.ImageLoader.prototype.load = function(
433 entry, transformFetcher, callback, opt_delay) {
437 this.callback_ = callback;
439 // The transform fetcher is not cancellable so we need a generation counter.
440 var generation = ++this.generation_;
441 var onTransform = function(image, transform) {
442 if (generation === this.generation_) {
444 image, transform || { scaleX: 1, scaleY: 1, rotate90: 0});
448 var onError = function(opt_error) {
449 this.image_.onerror = null;
450 this.image_.onload = null;
451 var tmpCallback = this.callback_;
452 this.callback_ = null;
453 var emptyCanvas = this.document_.createElement('canvas');
454 emptyCanvas.width = 0;
455 emptyCanvas.height = 0;
456 tmpCallback(emptyCanvas, opt_error);
459 var loadImage = function(opt_metadata) {
460 ImageUtil.metrics.startInterval(ImageUtil.getMetricName('LoadTime'));
461 this.timeout_ = null;
463 this.image_.onload = function(e) {
464 this.image_.onerror = null;
465 this.image_.onload = null;
467 transformFetcher(entry, onTransform.bind(this, e.target));
470 // The error callback has an optional error argument, which in case of a
471 // general error should not be specified
472 this.image_.onerror = onError.bind(this, 'GALLERY_IMAGE_ERROR');
474 // Load the image directly. The query parameter is workaround for
475 // crbug.com/379678, which force to update the contents of the image.
476 this.image_.src = entry.toURL() + "?nocache=" + Date.now();
479 // Loads the image. If already loaded, then forces a reload.
480 var startLoad = this.resetImage_.bind(this, function() {
481 // Fetch metadata to detect last modification time for the caching purpose.
482 if (this.metadataCache_)
483 this.metadataCache_.getOne(entry, 'filesystem', loadImage);
486 }.bind(this), onError);
489 this.timeout_ = setTimeout(startLoad, opt_delay);
496 * Resets the image by forcing the garbage collection and clearing the src
499 * @param {function()} onSuccess Success callback.
500 * @param {function(opt_string)} onError Failure callback with an optional
504 ImageUtil.ImageLoader.prototype.resetImage_ = function(onSuccess, onError) {
505 var clearSrc = function() {
506 this.image_.onload = onSuccess;
507 this.image_.onerror = onSuccess;
508 this.image_.src = '';
511 var emptyImage = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAA' +
512 'AAABAAEAAAICTAEAOw==';
514 if (this.image_.src !== emptyImage) {
515 // Load an empty image, then clear src.
516 this.image_.onload = clearSrc;
517 this.image_.onerror = onError.bind(this, 'GALLERY_IMAGE_ERROR');
518 this.image_.src = emptyImage;
520 // Empty image already loaded, so clear src immediately.
526 * @return {boolean} True if an image is loading.
528 ImageUtil.ImageLoader.prototype.isBusy = function() {
529 return !!this.callback_;
533 * @param {Entry} entry Image entry.
534 * @return {boolean} True if loader loads this image.
536 ImageUtil.ImageLoader.prototype.isLoading = function(entry) {
537 return this.isBusy() && util.isSameEntry(this.entry_, entry);
541 * @param {function} callback To be called when the image loaded.
543 ImageUtil.ImageLoader.prototype.setCallback = function(callback) {
544 this.callback_ = callback;
548 * Stops loading image.
550 ImageUtil.ImageLoader.prototype.cancel = function() {
551 if (!this.callback_) return;
552 this.callback_ = null;
554 clearTimeout(this.timeout_);
555 this.timeout_ = null;
558 this.image_.onload = function() {};
559 this.image_.onerror = function() {};
560 this.image_.src = '';
562 this.generation_++; // Silence the transform fetcher if it is in progress.
566 * @param {HTMLImageElement} image Image to be transformed.
567 * @param {Object} transform transformation description to apply to the image.
570 ImageUtil.ImageLoader.prototype.convertImage_ = function(image, transform) {
571 var canvas = this.document_.createElement('canvas');
573 if (transform.rotate90 & 1) { // Rotated +/-90deg, swap the dimensions.
574 canvas.width = image.height;
575 canvas.height = image.width;
577 canvas.width = image.width;
578 canvas.height = image.height;
581 var context = canvas.getContext('2d');
583 context.translate(canvas.width / 2, canvas.height / 2);
584 context.rotate(transform.rotate90 * Math.PI / 2);
585 context.scale(transform.scaleX, transform.scaleY);
587 var stripCount = Math.ceil(image.width * image.height / (1 << 21));
588 var step = Math.max(16, Math.ceil(image.height / stripCount)) & 0xFFFFF0;
590 this.copyStrip_(context, image, 0, step);
594 * @param {CanvasRenderingContext2D} context Context to draw.
595 * @param {HTMLImageElement} image Image to draw.
596 * @param {number} firstRow Number of the first pixel row to draw.
597 * @param {number} rowCount Count of pixel rows to draw.
600 ImageUtil.ImageLoader.prototype.copyStrip_ = function(
601 context, image, firstRow, rowCount) {
602 var lastRow = Math.min(firstRow + rowCount, image.height);
605 image, 0, firstRow, image.width, lastRow - firstRow,
606 -image.width / 2, firstRow - image.height / 2,
607 image.width, lastRow - firstRow);
609 if (lastRow === image.height) {
611 if (this.entry_.toURL().substr(0, 5) !== 'data:') { // Ignore data urls.
612 ImageUtil.metrics.recordInterval(ImageUtil.getMetricName('LoadTime'));
615 setTimeout(this.callback_, 0, context.canvas);
619 this.callback_ = null;
622 this.timeout_ = setTimeout(
624 self.timeout_ = null;
625 self.copyStrip_(context, image, lastRow, rowCount);
631 * @param {HTMLElement} element To remove children from.
633 ImageUtil.removeChildren = function(element) {
634 element.textContent = '';
638 * @param {string} name File name (with extension).
639 * @return {string} File name without extension.
641 ImageUtil.getDisplayNameFromName = function(name) {
642 var index = name.lastIndexOf('.');
644 return name.substr(0, index);
650 * @param {string} name File name.
651 * @return {string} File extension.
653 ImageUtil.getExtensionFromFullName = function(name) {
654 var index = name.lastIndexOf('.');
656 return name.substring(index);
662 * Metrics (from metrics.js) itnitialized by the File Manager from owner frame.
665 ImageUtil.metrics = null;
668 * @param {string} name Local name.
669 * @return {string} Full name.
671 ImageUtil.getMetricName = function(name) {
672 return 'PhotoEditor.' + name;
676 * Used for metrics reporting, keep in sync with the histogram description.
678 ImageUtil.FILE_TYPES = ['jpg', 'png', 'gif', 'bmp', 'webp'];