1 // Copyright (c) 2012 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 * Loads a thumbnail using provided url. In CANVAS mode, loaded images
9 * are attached as <canvas> element, while in IMAGE mode as <img>.
10 * <canvas> renders faster than <img>, however has bigger memory overhead.
12 * @param {FileEntry} entry File entry.
13 * @param {ThumbnailLoader.LoaderType=} opt_loaderType Canvas or Image loader,
15 * @param {Object=} opt_metadata Metadata object.
16 * @param {string=} opt_mediaType Media type.
17 * @param {ThumbnailLoader.UseEmbedded=} opt_useEmbedded If to use embedded
18 * jpeg thumbnail if available. Default: USE_EMBEDDED.
19 * @param {number=} opt_priority Priority, the highest is 0. default: 2.
22 function ThumbnailLoader(entry, opt_loaderType, opt_metadata, opt_mediaType,
23 opt_useEmbedded, opt_priority) {
24 opt_useEmbedded = opt_useEmbedded || ThumbnailLoader.UseEmbedded.USE_EMBEDDED;
26 this.mediaType_ = opt_mediaType || FileType.getMediaType(entry);
27 this.loaderType_ = opt_loaderType || ThumbnailLoader.LoaderType.IMAGE;
28 this.metadata_ = opt_metadata;
29 this.priority_ = (opt_priority !== undefined) ? opt_priority : 2;
30 this.transform_ = null;
33 this.thumbnailUrl_ = entry.toURL(); // Use the URL directly.
37 this.fallbackUrl_ = null;
38 this.thumbnailUrl_ = null;
39 if (opt_metadata.drive && opt_metadata.drive.customIconUrl)
40 this.fallbackUrl_ = opt_metadata.drive.customIconUrl;
42 // Fetch the rotation from the Drive metadata (if available).
44 if (opt_metadata.drive && opt_metadata.drive.imageRotation !== undefined) {
48 rotate90: opt_metadata.drive.imageRotation / 90
52 if (opt_metadata.thumbnail && opt_metadata.thumbnail.url &&
53 opt_useEmbedded === ThumbnailLoader.UseEmbedded.USE_EMBEDDED) {
54 this.thumbnailUrl_ = opt_metadata.thumbnail.url;
55 this.transform_ = driveTransform !== undefined ? driveTransform :
56 opt_metadata.thumbnail.transform;
57 } else if (FileType.isImage(entry)) {
58 this.thumbnailUrl_ = entry.toURL();
59 this.transform_ = driveTransform !== undefined ? driveTransform :
60 opt_metadata.media && opt_metadata.media.imageTransform;
61 } else if (this.fallbackUrl_) {
62 // Use fallback as the primary thumbnail.
63 this.thumbnailUrl_ = this.fallbackUrl_;
64 this.fallbackUrl_ = null;
65 } // else the generic thumbnail based on the media type will be used.
69 * In percents (0.0 - 1.0), how much area can be cropped to fill an image
70 * in a container, when loading a thumbnail in FillMode.AUTO mode.
71 * The specified 30% value allows to fill 16:9, 3:2 pictures in 4:3 element.
74 ThumbnailLoader.AUTO_FILL_THRESHOLD = 0.3;
77 * Type of displaying a thumbnail within a box.
80 ThumbnailLoader.FillMode = {
81 FILL: 0, // Fill whole box. Image may be cropped.
82 FIT: 1, // Keep aspect ratio, do not crop.
83 OVER_FILL: 2, // Fill whole box with possible stretching.
84 AUTO: 3 // Try to fill, but if incompatible aspect ratio, then fit.
88 * Optimization mode for downloading thumbnails.
91 ThumbnailLoader.OptimizationMode = {
92 NEVER_DISCARD: 0, // Never discards downloading. No optimization.
93 DISCARD_DETACHED: 1 // Canceled if the container is not attached anymore.
97 * Type of element to store the image.
100 ThumbnailLoader.LoaderType = {
106 * Whether to use the embedded thumbnail, or not. The embedded thumbnail may
110 ThumbnailLoader.UseEmbedded = {
116 * Maximum thumbnail's width when generating from the full resolution image.
120 ThumbnailLoader.THUMBNAIL_MAX_WIDTH = 500;
123 * Maximum thumbnail's height when generating from the full resolution image.
127 ThumbnailLoader.THUMBNAIL_MAX_HEIGHT = 500;
130 * Loads and attaches an image.
132 * @param {HTMLElement} box Container element.
133 * @param {ThumbnailLoader.FillMode} fillMode Fill mode.
134 * @param {ThumbnailLoader.OptimizationMode=} opt_optimizationMode Optimization
135 * for downloading thumbnails. By default optimizations are disabled.
136 * @param {function(Image, Object)} opt_onSuccess Success callback,
137 * accepts the image and the transform.
138 * @param {function} opt_onError Error callback.
139 * @param {function} opt_onGeneric Callback for generic image used.
141 ThumbnailLoader.prototype.load = function(box, fillMode, opt_optimizationMode,
142 opt_onSuccess, opt_onError, opt_onGeneric) {
143 opt_optimizationMode = opt_optimizationMode ||
144 ThumbnailLoader.OptimizationMode.NEVER_DISCARD;
146 if (!this.thumbnailUrl_) {
147 // Relevant CSS rules are in file_types.css.
148 box.setAttribute('generic-thumbnail', this.mediaType_);
149 if (opt_onGeneric) opt_onGeneric();
154 this.canvasUpToDate_ = false;
155 this.image_ = new Image();
156 this.image_.onload = function() {
157 this.attachImage(box, fillMode);
159 opt_onSuccess(this.image_, this.transform_);
161 this.image_.onerror = function() {
164 if (this.fallbackUrl_) {
165 this.thumbnailUrl_ = this.fallbackUrl_;
166 this.fallbackUrl_ = null;
167 this.load(box, fillMode, opt_optimizationMode, opt_onSuccess);
169 box.setAttribute('generic-thumbnail', this.mediaType_);
173 if (this.image_.src) {
174 console.warn('Thumbnail already loaded: ' + this.thumbnailUrl_);
178 // TODO(mtomasz): Smarter calculation of the requested size.
179 var wasAttached = box.ownerDocument.contains(box);
180 var modificationTime = this.metadata_ &&
181 this.metadata_.filesystem &&
182 this.metadata_.filesystem.modificationTime &&
183 this.metadata_.filesystem.modificationTime.getTime();
184 this.taskId_ = util.loadImage(
187 { maxWidth: ThumbnailLoader.THUMBNAIL_MAX_WIDTH,
188 maxHeight: ThumbnailLoader.THUMBNAIL_MAX_HEIGHT,
190 priority: this.priority_,
191 timestamp: modificationTime },
193 if (opt_optimizationMode ==
194 ThumbnailLoader.OptimizationMode.DISCARD_DETACHED &&
195 !box.ownerDocument.contains(box)) {
196 // If the container is not attached, then invalidate the download.
204 * Cancels loading the current image.
206 ThumbnailLoader.prototype.cancel = function() {
208 this.image_.onload = function() {};
209 this.image_.onerror = function() {};
210 util.cancelLoadImage(this.taskId_);
216 * @return {boolean} True if a valid image is loaded.
218 ThumbnailLoader.prototype.hasValidImage = function() {
219 return !!(this.image_ && this.image_.width && this.image_.height);
223 * @return {boolean} True if the image is rotated 90 degrees left or right.
226 ThumbnailLoader.prototype.isRotated_ = function() {
227 return this.transform_ && (this.transform_.rotate90 % 2 === 1);
231 * @return {number} Image width (corrected for rotation).
233 ThumbnailLoader.prototype.getWidth = function() {
234 return this.isRotated_() ? this.image_.height : this.image_.width;
238 * @return {number} Image height (corrected for rotation).
240 ThumbnailLoader.prototype.getHeight = function() {
241 return this.isRotated_() ? this.image_.width : this.image_.height;
245 * Load an image but do not attach it.
247 * @param {function(boolean)} callback Callback, parameter is true if the image
248 * has loaded successfully or a stock icon has been used.
250 ThumbnailLoader.prototype.loadDetachedImage = function(callback) {
251 if (!this.thumbnailUrl_) {
257 this.canvasUpToDate_ = false;
258 this.image_ = new Image();
259 this.image_.onload = callback.bind(null, true);
260 this.image_.onerror = callback.bind(null, false);
262 // TODO(mtomasz): Smarter calculation of the requested size.
263 var modificationTime = this.metadata_ &&
264 this.metadata_.filesystem &&
265 this.metadata_.filesystem.modificationTime &&
266 this.metadata_.filesystem.modificationTime.getTime();
267 this.taskId_ = util.loadImage(
270 { maxWidth: ThumbnailLoader.THUMBNAIL_MAX_WIDTH,
271 maxHeight: ThumbnailLoader.THUMBNAIL_MAX_HEIGHT,
273 priority: this.priority_,
274 timestamp: modificationTime });
278 * Renders the thumbnail into either canvas or an image element.
281 ThumbnailLoader.prototype.renderMedia_ = function() {
282 if (this.loaderType_ !== ThumbnailLoader.LoaderType.CANVAS)
286 this.canvas_ = document.createElement('canvas');
288 // Copy the image to a canvas if the canvas is outdated.
289 if (!this.canvasUpToDate_) {
290 this.canvas_.width = this.image_.width;
291 this.canvas_.height = this.image_.height;
292 var context = this.canvas_.getContext('2d');
293 context.drawImage(this.image_, 0, 0);
294 this.canvasUpToDate_ = true;
299 * Attach the image to a given element.
300 * @param {Element} container Parent element.
301 * @param {ThumbnailLoader.FillMode} fillMode Fill mode.
303 ThumbnailLoader.prototype.attachImage = function(container, fillMode) {
304 if (!this.hasValidImage()) {
305 container.setAttribute('generic-thumbnail', this.mediaType_);
310 util.applyTransform(container, this.transform_);
311 var attachableMedia = this.loaderType_ === ThumbnailLoader.LoaderType.CANVAS ?
312 this.canvas_ : this.image_;
314 ThumbnailLoader.centerImage_(
315 container, attachableMedia, fillMode, this.isRotated_());
317 if (attachableMedia.parentNode !== container) {
318 container.textContent = '';
319 container.appendChild(attachableMedia);
323 attachableMedia.classList.add('cached');
327 * Gets the loaded image.
328 * TODO(mtomasz): Apply transformations.
330 * @return {Image|HTMLCanvasElement} Either image or a canvas object.
332 ThumbnailLoader.prototype.getImage = function() {
334 return this.loaderType_ === ThumbnailLoader.LoaderType.CANVAS ? this.canvas_ :
339 * Update the image style to fit/fill the container.
341 * Using webkit center packing does not align the image properly, so we need
342 * to wait until the image loads and its dimensions are known, then manually
343 * position it at the center.
345 * @param {HTMLElement} box Containing element.
346 * @param {Image|HTMLCanvasElement} img Element containing an image.
347 * @param {ThumbnailLoader.FillMode} fillMode Fill mode.
348 * @param {boolean} rotate True if the image should be rotated 90 degrees.
351 ThumbnailLoader.centerImage_ = function(box, img, fillMode, rotate) {
352 var imageWidth = img.width;
353 var imageHeight = img.height;
358 var boxWidth = box.clientWidth;
359 var boxHeight = box.clientHeight;
363 case ThumbnailLoader.FillMode.FILL:
364 case ThumbnailLoader.FillMode.OVER_FILL:
367 case ThumbnailLoader.FillMode.FIT:
370 case ThumbnailLoader.FillMode.AUTO:
371 var imageRatio = imageWidth / imageHeight;
373 if (boxWidth && boxHeight)
374 boxRatio = boxWidth / boxHeight;
375 // Cropped area in percents.
376 var ratioFactor = boxRatio / imageRatio;
377 fill = (ratioFactor >= 1.0 - ThumbnailLoader.AUTO_FILL_THRESHOLD) &&
378 (ratioFactor <= 1.0 + ThumbnailLoader.AUTO_FILL_THRESHOLD);
382 if (boxWidth && boxHeight) {
383 // When we know the box size we can position the image correctly even
384 // in a non-square box.
385 var fitScaleX = (rotate ? boxHeight : boxWidth) / imageWidth;
386 var fitScaleY = (rotate ? boxWidth : boxHeight) / imageHeight;
389 Math.max(fitScaleX, fitScaleY) :
390 Math.min(fitScaleX, fitScaleY);
392 if (fillMode !== ThumbnailLoader.FillMode.OVER_FILL)
393 scale = Math.min(scale, 1); // Never overscale.
395 fractionX = imageWidth * scale / boxWidth;
396 fractionY = imageHeight * scale / boxHeight;
398 // We do not know the box size so we assume it is square.
399 // Compute the image position based only on the image dimensions.
400 // First try vertical fit or horizontal fill.
401 fractionX = imageWidth / imageHeight;
403 if ((fractionX < 1) === !!fill) { // Vertical fill or horizontal fit.
404 fractionY = 1 / fractionX;
409 function percent(fraction) {
410 return (fraction * 100).toFixed(2) + '%';
413 img.style.width = percent(fractionX);
414 img.style.height = percent(fractionY);
415 img.style.left = percent((1 - fractionX) / 2);
416 img.style.top = percent((1 - fractionY) / 2);