Commit 1428ae59 authored by Naoki Fukino's avatar Naoki Fukino Committed by Commit Bot

Use const/let in image loader.

ImageLoader still has many vars in its scripts.
It will make presubmit linter unhappy even when we modify an line in
a file in the future.
Let me eliminate all vars beforehand.

Bug: 778674
Test: Confirm that thumbnails of image files (incl. raw files) are correct.
Change-Id: I6960d6c37f9791f4d3ad52be0cbf607af3bd8337
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1991056
Commit-Queue: Naoki Fukino <fukino@chromium.org>
Reviewed-by: default avatarNoel Gordon <noel@chromium.org>
Cr-Commit-Position: refs/heads/master@{#729645}
parent 19c76086
...@@ -54,8 +54,8 @@ ImageCache.prototype.initialize = function(callback) { ...@@ -54,8 +54,8 @@ ImageCache.prototype.initialize = function(callback) {
// Establish a connection to the database or (re)create it if not available // Establish a connection to the database or (re)create it if not available
// or not up to date. After changing the database's schema, increment // or not up to date. After changing the database's schema, increment
// ImageCache.DB_VERSION to force database recreating. // ImageCache.DB_VERSION to force database recreating.
var openRequest = window.indexedDB.open( const openRequest =
ImageCache.DB_NAME, ImageCache.DB_VERSION); window.indexedDB.open(ImageCache.DB_NAME, ImageCache.DB_VERSION);
openRequest.onsuccess = function(e) { openRequest.onsuccess = function(e) {
this.db_ = e.target.result; this.db_ = e.target.result;
...@@ -66,7 +66,7 @@ ImageCache.prototype.initialize = function(callback) { ...@@ -66,7 +66,7 @@ ImageCache.prototype.initialize = function(callback) {
openRequest.onupgradeneeded = function(e) { openRequest.onupgradeneeded = function(e) {
console.info('Cache database creating or upgrading.'); console.info('Cache database creating or upgrading.');
var db = e.target.result; const db = e.target.result;
if (db.objectStoreNames.contains('metadata')) { if (db.objectStoreNames.contains('metadata')) {
db.deleteObjectStore('metadata'); db.deleteObjectStore('metadata');
} }
...@@ -91,9 +91,9 @@ ImageCache.prototype.initialize = function(callback) { ...@@ -91,9 +91,9 @@ ImageCache.prototype.initialize = function(callback) {
* @private * @private
*/ */
ImageCache.prototype.setCacheSize_ = function(size, opt_transaction) { ImageCache.prototype.setCacheSize_ = function(size, opt_transaction) {
var transaction = opt_transaction || const transaction =
this.db_.transaction(['settings'], 'readwrite'); opt_transaction || this.db_.transaction(['settings'], 'readwrite');
var settingsStore = transaction.objectStore('settings'); const settingsStore = transaction.objectStore('settings');
settingsStore.put({key: 'size', value: size}); // Update asynchronously. settingsStore.put({key: 'size', value: size}); // Update asynchronously.
}; };
...@@ -109,10 +109,10 @@ ImageCache.prototype.setCacheSize_ = function(size, opt_transaction) { ...@@ -109,10 +109,10 @@ ImageCache.prototype.setCacheSize_ = function(size, opt_transaction) {
*/ */
ImageCache.prototype.fetchCacheSize_ = function( ImageCache.prototype.fetchCacheSize_ = function(
onSuccess, onFailure, opt_transaction) { onSuccess, onFailure, opt_transaction) {
var transaction = opt_transaction || const transaction = opt_transaction ||
this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite'); this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite');
var settingsStore = transaction.objectStore('settings'); const settingsStore = transaction.objectStore('settings');
var sizeRequest = settingsStore.get('size'); const sizeRequest = settingsStore.get('size');
sizeRequest.onsuccess = function(e) { sizeRequest.onsuccess = function(e) {
if (e.target.result) { if (e.target.result) {
...@@ -141,7 +141,7 @@ ImageCache.prototype.fetchCacheSize_ = function( ...@@ -141,7 +141,7 @@ ImageCache.prototype.fetchCacheSize_ = function(
*/ */
ImageCache.prototype.evictCache_ = function( ImageCache.prototype.evictCache_ = function(
size, onSuccess, onFailure, opt_transaction) { size, onSuccess, onFailure, opt_transaction) {
var transaction = opt_transaction || const transaction = opt_transaction ||
this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite'); this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite');
// Check if the requested size is smaller than the cache size. // Check if the requested size is smaller than the cache size.
...@@ -150,7 +150,7 @@ ImageCache.prototype.evictCache_ = function( ...@@ -150,7 +150,7 @@ ImageCache.prototype.evictCache_ = function(
return; return;
} }
var onCacheSize = function(cacheSize) { const onCacheSize = function(cacheSize) {
if (size < ImageCache.MEMORY_LIMIT - cacheSize) { if (size < ImageCache.MEMORY_LIMIT - cacheSize) {
// Enough space, no need to evict. // Enough space, no need to evict.
this.setCacheSize_(cacheSize + size, transaction); this.setCacheSize_(cacheSize + size, transaction);
...@@ -158,21 +158,21 @@ ImageCache.prototype.evictCache_ = function( ...@@ -158,21 +158,21 @@ ImageCache.prototype.evictCache_ = function(
return; return;
} }
var bytesToEvict = Math.max(size, ImageCache.EVICTION_CHUNK_SIZE); let bytesToEvict = Math.max(size, ImageCache.EVICTION_CHUNK_SIZE);
// Fetch all metadata. // Fetch all metadata.
var metadataEntries = []; const metadataEntries = [];
var metadataStore = transaction.objectStore('metadata'); const metadataStore = transaction.objectStore('metadata');
var dataStore = transaction.objectStore('data'); const dataStore = transaction.objectStore('data');
var onEntriesFetched = function() { const onEntriesFetched = function() {
metadataEntries.sort(function(a, b) { metadataEntries.sort(function(a, b) {
return b.lastLoadTimestamp - a.lastLoadTimestamp; return b.lastLoadTimestamp - a.lastLoadTimestamp;
}); });
var totalEvicted = 0; let totalEvicted = 0;
while (bytesToEvict > 0) { while (bytesToEvict > 0) {
var entry = metadataEntries.pop(); const entry = metadataEntries.pop();
totalEvicted += entry.size; totalEvicted += entry.size;
bytesToEvict -= entry.size; bytesToEvict -= entry.size;
metadataStore.delete(entry.key); // Remove asynchronously. metadataStore.delete(entry.key); // Remove asynchronously.
...@@ -183,7 +183,7 @@ ImageCache.prototype.evictCache_ = function( ...@@ -183,7 +183,7 @@ ImageCache.prototype.evictCache_ = function(
}.bind(this); }.bind(this);
metadataStore.openCursor().onsuccess = function(e) { metadataStore.openCursor().onsuccess = function(e) {
var cursor = e.target.result; const cursor = e.target.result;
if (cursor) { if (cursor) {
metadataEntries.push(cursor.value); metadataEntries.push(cursor.value);
cursor.continue(); cursor.continue();
...@@ -214,8 +214,8 @@ ImageCache.prototype.saveImage = function( ...@@ -214,8 +214,8 @@ ImageCache.prototype.saveImage = function(
return; return;
} }
var onNotFoundInCache = function() { const onNotFoundInCache = function() {
var metadataEntry = { const metadataEntry = {
key: key, key: key,
timestamp: timestamp, timestamp: timestamp,
width: width, width: width,
...@@ -225,14 +225,14 @@ ImageCache.prototype.saveImage = function( ...@@ -225,14 +225,14 @@ ImageCache.prototype.saveImage = function(
lastLoadTimestamp: Date.now(), lastLoadTimestamp: Date.now(),
}; };
var dataEntry = {key: key, data: data}; const dataEntry = {key: key, data: data};
var transaction = this.db_.transaction(['settings', 'metadata', 'data'], const transaction =
'readwrite'); this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite');
var metadataStore = transaction.objectStore('metadata'); const metadataStore = transaction.objectStore('metadata');
var dataStore = transaction.objectStore('data'); const dataStore = transaction.objectStore('data');
var onCacheEvicted = function() { const onCacheEvicted = function() {
metadataStore.put(metadataEntry); // Add asynchronously. metadataStore.put(metadataEntry); // Add asynchronously.
dataStore.put(dataEntry); // Add asynchronously. dataStore.put(dataEntry); // Add asynchronously.
}; };
...@@ -263,19 +263,19 @@ ImageCache.prototype.loadImage = function( ...@@ -263,19 +263,19 @@ ImageCache.prototype.loadImage = function(
return; return;
} }
var transaction = this.db_.transaction(['settings', 'metadata', 'data'], const transaction =
'readwrite'); this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite');
var metadataStore = transaction.objectStore('metadata'); const metadataStore = transaction.objectStore('metadata');
var dataStore = transaction.objectStore('data'); const dataStore = transaction.objectStore('data');
var metadataRequest = metadataStore.get(key); const metadataRequest = metadataStore.get(key);
var dataRequest = dataStore.get(key); const dataRequest = dataStore.get(key);
var metadataEntry = null; let metadataEntry = null;
var metadataReceived = false; let metadataReceived = false;
var dataEntry = null; let dataEntry = null;
var dataReceived = false; let dataReceived = false;
var onPartialSuccess = function() { const onPartialSuccess = function() {
// Check if all sub-requests have finished. // Check if all sub-requests have finished.
if (!metadataReceived || !dataReceived) { if (!metadataReceived || !dataReceived) {
return; return;
...@@ -352,17 +352,17 @@ ImageCache.prototype.removeImage = function( ...@@ -352,17 +352,17 @@ ImageCache.prototype.removeImage = function(
return; return;
} }
var transaction = opt_transaction || const transaction = opt_transaction ||
this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite'); this.db_.transaction(['settings', 'metadata', 'data'], 'readwrite');
var metadataStore = transaction.objectStore('metadata'); const metadataStore = transaction.objectStore('metadata');
var dataStore = transaction.objectStore('data'); const dataStore = transaction.objectStore('data');
var cacheSize = null; let cacheSize = null;
var cacheSizeReceived = false; let cacheSizeReceived = false;
var metadataEntry = null; let metadataEntry = null;
var metadataReceived = false; let metadataReceived = false;
var onPartialSuccess = function() { const onPartialSuccess = function() {
if (!cacheSizeReceived || !metadataReceived) { if (!cacheSizeReceived || !metadataReceived) {
return; return;
} }
...@@ -385,11 +385,11 @@ ImageCache.prototype.removeImage = function( ...@@ -385,11 +385,11 @@ ImageCache.prototype.removeImage = function(
dataStore.delete(key); // Delete asynchronously. dataStore.delete(key); // Delete asynchronously.
}.bind(this); }.bind(this);
var onCacheSizeFailure = function() { const onCacheSizeFailure = function() {
cacheSizeReceived = true; cacheSizeReceived = true;
}; };
var onCacheSizeSuccess = function(result) { const onCacheSizeSuccess = function(result) {
cacheSize = result; cacheSize = result;
cacheSizeReceived = true; cacheSizeReceived = true;
onPartialSuccess(); onPartialSuccess();
...@@ -399,7 +399,7 @@ ImageCache.prototype.removeImage = function( ...@@ -399,7 +399,7 @@ ImageCache.prototype.removeImage = function(
this.fetchCacheSize_(onCacheSizeSuccess, onCacheSizeFailure, transaction); this.fetchCacheSize_(onCacheSizeSuccess, onCacheSizeFailure, transaction);
// Receive image's metadata. // Receive image's metadata.
var metadataRequest = metadataStore.get(key); const metadataRequest = metadataStore.get(key);
metadataRequest.onsuccess = function(e) { metadataRequest.onsuccess = function(e) {
if (e.target.result) { if (e.target.result) {
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
'use strict'; 'use strict';
function testCreateCacheKey() { function testCreateCacheKey() {
let key = LoadImageRequest.cacheKey({url: 'http://example.com/image.jpg'}); const key = LoadImageRequest.cacheKey({url: 'http://example.com/image.jpg'});
assertTrue(!!key); assertTrue(!!key);
} }
......
...@@ -38,8 +38,8 @@ function ImageLoader() { ...@@ -38,8 +38,8 @@ function ImageLoader() {
{volumeId: event.volumeMetadata.volumeId}, function() {}); {volumeId: event.volumeMetadata.volumeId}, function() {});
} }
}); });
var initPromises = volumeMetadataList.map(function(volumeMetadata) { const initPromises = volumeMetadataList.map(function(volumeMetadata) {
var requestPromise = new Promise(function(callback) { const requestPromise = new Promise(function(callback) {
chrome.fileSystem.requestFileSystem( chrome.fileSystem.requestFileSystem(
{volumeId: volumeMetadata.volumeId}, {volumeId: volumeMetadata.volumeId},
/** @type {function(FileSystem=)} */(callback)); /** @type {function(FileSystem=)} */(callback));
...@@ -87,11 +87,11 @@ ImageLoader.prototype.onIncomingRequest_ = function( ...@@ -87,11 +87,11 @@ ImageLoader.prototype.onIncomingRequest_ = function(
return; return;
} }
var request = /** @type {!LoadImageRequest} */ (request_data); const request = /** @type {!LoadImageRequest} */ (request_data);
// Sending a response may fail if the receiver already went offline. // Sending a response may fail if the receiver already went offline.
// This is not an error, but a normal and quite common situation. // This is not an error, but a normal and quite common situation.
let failSafeSendResponse = function(response) { const failSafeSendResponse = function(response) {
try { try {
sendResponse(response); sendResponse(response);
} catch (e) { } catch (e) {
...@@ -124,14 +124,14 @@ ImageLoader.prototype.onIncomingRequest_ = function( ...@@ -124,14 +124,14 @@ ImageLoader.prototype.onIncomingRequest_ = function(
* @private * @private
*/ */
ImageLoader.prototype.onMessage_ = function(senderId, request, callback) { ImageLoader.prototype.onMessage_ = function(senderId, request, callback) {
var requestId = senderId + ':' + request.taskId; const requestId = senderId + ':' + request.taskId;
if (request.cancel) { if (request.cancel) {
// Cancel a task. // Cancel a task.
this.scheduler_.remove(requestId); this.scheduler_.remove(requestId);
return false; // No callback calls. return false; // No callback calls.
} else { } else {
// Create a request task and add it to the scheduler (queue). // Create a request task and add it to the scheduler (queue).
var requestTask = new ImageRequest( const requestTask = new ImageRequest(
requestId, this.cache_, this.piexLoader_, request, callback); requestId, this.cache_, this.piexLoader_, request, callback);
this.scheduler_.add(requestTask); this.scheduler_.add(requestTask);
return true; // Request will call the callback. return true; // Request will call the callback.
......
...@@ -189,7 +189,7 @@ ImageLoaderClient.CACHE_MEMORY_LIMIT = 20 * 1024 * 1024; // 20 MB. ...@@ -189,7 +189,7 @@ ImageLoaderClient.CACHE_MEMORY_LIMIT = 20 * 1024 * 1024; // 20 MB.
* @return {?number} Remote task id or null if loaded from cache. * @return {?number} Remote task id or null if loaded from cache.
*/ */
ImageLoaderClient.loadToImage = function(request, image, onSuccess, onError) { ImageLoaderClient.loadToImage = function(request, image, onSuccess, onError) {
var callback = function(result) { const callback = function(result) {
if (result.status == LoadImageResponseStatus.ERROR) { if (result.status == LoadImageResponseStatus.ERROR) {
onError(); onError();
return; return;
......
...@@ -40,7 +40,7 @@ function loadAndCheckCacheUsed(client, url, cache) { ...@@ -40,7 +40,7 @@ function loadAndCheckCacheUsed(client, url, cache) {
} }
}; };
let request = LoadImageRequest.createForUrl(url); const request = LoadImageRequest.createForUrl(url);
request.cache = cache; request.cache = cache;
return new Promise(function(fulfill) { return new Promise(function(fulfill) {
...@@ -51,7 +51,7 @@ function loadAndCheckCacheUsed(client, url, cache) { ...@@ -51,7 +51,7 @@ function loadAndCheckCacheUsed(client, url, cache) {
} }
function testCache(callback) { function testCache(callback) {
var client = new ImageLoaderClient(); const client = new ImageLoaderClient();
reportPromise( reportPromise(
loadAndCheckCacheUsed(client, 'http://example.com/image.jpg', true) loadAndCheckCacheUsed(client, 'http://example.com/image.jpg', true)
.then(function(cacheUsed) { .then(function(cacheUsed) {
...@@ -66,7 +66,7 @@ function testCache(callback) { ...@@ -66,7 +66,7 @@ function testCache(callback) {
} }
function testNoCache(callback) { function testNoCache(callback) {
var client = new ImageLoaderClient(); const client = new ImageLoaderClient();
reportPromise( reportPromise(
loadAndCheckCacheUsed(client, 'http://example.com/image.jpg', false) loadAndCheckCacheUsed(client, 'http://example.com/image.jpg', false)
.then(function(cacheUsed) { .then(function(cacheUsed) {
...@@ -81,7 +81,7 @@ function testNoCache(callback) { ...@@ -81,7 +81,7 @@ function testNoCache(callback) {
} }
function testDataURLCache(callback) { function testDataURLCache(callback) {
var client = new ImageLoaderClient(); const client = new ImageLoaderClient();
reportPromise( reportPromise(
loadAndCheckCacheUsed(client, 'data:URI', true) loadAndCheckCacheUsed(client, 'data:URI', true)
.then(function(cacheUsed) { .then(function(cacheUsed) {
......
...@@ -20,15 +20,15 @@ function calculateCopyParametersFromOptions(source, options) { ...@@ -20,15 +20,15 @@ function calculateCopyParametersFromOptions(source, options) {
* - Target: max size is 100x100 * - Target: max size is 100x100
*/ */
function testNormalImage() { function testNormalImage() {
var source = new Image(); const source = new Image();
source.width = 200; source.width = 200;
source.height = 50; source.height = 50;
var options = { const options = {
maxWidth: 100, maxWidth: 100,
maxHeight: 100, maxHeight: 100,
orientation: ImageOrientation.fromClockwiseRotation(0) orientation: ImageOrientation.fromClockwiseRotation(0)
}; };
var result = calculateCopyParametersFromOptions(source, options); const result = calculateCopyParametersFromOptions(source, options);
assertEquals(0, result.source.x); assertEquals(0, result.source.x);
assertEquals(0, result.source.y); assertEquals(0, result.source.y);
assertEquals(200, result.source.width); assertEquals(200, result.source.width);
...@@ -47,15 +47,15 @@ function testNormalImage() { ...@@ -47,15 +47,15 @@ function testNormalImage() {
* - Target: max size is 100x100 * - Target: max size is 100x100
*/ */
function testRotatedImage() { function testRotatedImage() {
var source = new Image(); const source = new Image();
source.width = 50; source.width = 50;
source.height = 200; source.height = 200;
var options = { const options = {
maxWidth: 100, maxWidth: 100,
maxHeight: 100, maxHeight: 100,
orientation: ImageOrientation.fromClockwiseRotation(1) orientation: ImageOrientation.fromClockwiseRotation(1)
}; };
var result = calculateCopyParametersFromOptions(source, options); const result = calculateCopyParametersFromOptions(source, options);
assertEquals(0, result.source.x); assertEquals(0, result.source.x);
assertEquals(0, result.source.y); assertEquals(0, result.source.y);
assertEquals(50, result.source.width); assertEquals(50, result.source.width);
...@@ -74,16 +74,16 @@ function testRotatedImage() { ...@@ -74,16 +74,16 @@ function testRotatedImage() {
* - Target: 50x50 cropped image. * - Target: 50x50 cropped image.
*/ */
function testCroppedImage() { function testCroppedImage() {
var source = new Image(); const source = new Image();
source.width = 800; source.width = 800;
source.height = 100; source.height = 100;
var options = { const options = {
width: 50, width: 50,
height: 50, height: 50,
crop: true, crop: true,
orientation: ImageOrientation.fromClockwiseRotation(0) orientation: ImageOrientation.fromClockwiseRotation(0)
}; };
var result = calculateCopyParametersFromOptions(source, options); const result = calculateCopyParametersFromOptions(source, options);
assertEquals(350, result.source.x); assertEquals(350, result.source.x);
assertEquals(0, result.source.y); assertEquals(0, result.source.y);
assertEquals(100, result.source.width); assertEquals(100, result.source.width);
...@@ -102,16 +102,16 @@ function testCroppedImage() { ...@@ -102,16 +102,16 @@ function testCroppedImage() {
* - Target: 50x50 cropped image. * - Target: 50x50 cropped image.
*/ */
function testCroppedImageWithResize() { function testCroppedImageWithResize() {
var source = new Image(); const source = new Image();
source.width = 200; source.width = 200;
source.height = 25; source.height = 25;
var options = { const options = {
width: 50, width: 50,
height: 50, height: 50,
crop: true, crop: true,
orientation: ImageOrientation.fromClockwiseRotation(0) orientation: ImageOrientation.fromClockwiseRotation(0)
}; };
var result = calculateCopyParametersFromOptions(source, options); const result = calculateCopyParametersFromOptions(source, options);
assertEquals(87, result.source.x); assertEquals(87, result.source.x);
assertEquals(0, result.source.y); assertEquals(0, result.source.y);
assertEquals(25, result.source.width); assertEquals(25, result.source.width);
...@@ -130,16 +130,16 @@ function testCroppedImageWithResize() { ...@@ -130,16 +130,16 @@ function testCroppedImageWithResize() {
* - Target: 50x50 cropped image. * - Target: 50x50 cropped image.
*/ */
function testCroppedTinyImage() { function testCroppedTinyImage() {
var source = new Image(); const source = new Image();
source.width = 20; source.width = 20;
source.height = 10; source.height = 10;
var options = { const options = {
width: 50, width: 50,
height: 50, height: 50,
crop: true, crop: true,
orientation: ImageOrientation.fromClockwiseRotation(0) orientation: ImageOrientation.fromClockwiseRotation(0)
}; };
var result = calculateCopyParametersFromOptions(source, options); const result = calculateCopyParametersFromOptions(source, options);
assertEquals(5, result.source.x); assertEquals(5, result.source.x);
assertEquals(0, result.source.y); assertEquals(0, result.source.y);
assertEquals(10, result.source.width); assertEquals(10, result.source.width);
...@@ -158,16 +158,16 @@ function testCroppedTinyImage() { ...@@ -158,16 +158,16 @@ function testCroppedTinyImage() {
* - Target: 50x50 cropped image * - Target: 50x50 cropped image
*/ */
function testCroppedRotatedImage() { function testCroppedRotatedImage() {
var source = new Image(); const source = new Image();
source.width = 100; source.width = 100;
source.height = 400; source.height = 400;
var options = { const options = {
width: 50, width: 50,
height: 50, height: 50,
crop: true, crop: true,
orientation: ImageOrientation.fromClockwiseRotation(1) orientation: ImageOrientation.fromClockwiseRotation(1)
}; };
var result = calculateCopyParametersFromOptions(source, options); const result = calculateCopyParametersFromOptions(source, options);
assertEquals(0, result.source.x); assertEquals(0, result.source.x);
assertEquals(150, result.source.y); assertEquals(150, result.source.y);
assertEquals(100, result.source.width); assertEquals(100, result.source.width);
......
...@@ -95,7 +95,7 @@ ImageLoaderUtil.resizeAndCrop = function(source, target, request) { ...@@ -95,7 +95,7 @@ ImageLoaderUtil.resizeAndCrop = function(source, target, request) {
target.height = copyParameters.canvas.height; target.height = copyParameters.canvas.height;
// Apply. // Apply.
let targetContext = const targetContext =
/** @type {CanvasRenderingContext2D} */ (target.getContext('2d')); /** @type {CanvasRenderingContext2D} */ (target.getContext('2d'));
targetContext.save(); targetContext.save();
request.orientation.cancelImageOrientation( request.orientation.cancelImageOrientation(
...@@ -208,10 +208,10 @@ ImageLoaderUtil.convertColorSpace = function(target, colorSpace) { ...@@ -208,10 +208,10 @@ ImageLoaderUtil.convertColorSpace = function(target, colorSpace) {
} }
if (colorSpace === ColorSpace.ADOBE_RGB) { if (colorSpace === ColorSpace.ADOBE_RGB) {
const matrix = ImageLoaderUtil.MATRIX_FROM_ADOBE_TO_STANDARD; const matrix = ImageLoaderUtil.MATRIX_FROM_ADOBE_TO_STANDARD;
let context = const context =
assertInstanceof(target.getContext('2d'), CanvasRenderingContext2D); assertInstanceof(target.getContext('2d'), CanvasRenderingContext2D);
let imageData = context.getImageData(0, 0, target.width, target.height); const imageData = context.getImageData(0, 0, target.width, target.height);
let data = imageData.data; const data = imageData.data;
for (let i = 0; i < data.length; i += 4) { for (let i = 0; i < data.length; i += 4) {
// Scale to [0, 1]. // Scale to [0, 1].
let adobeR = data[i] / 255; let adobeR = data[i] / 255;
......
...@@ -47,7 +47,7 @@ const puppeteer = require('puppeteer'); ...@@ -47,7 +47,7 @@ const puppeteer = require('puppeteer');
headless: !program.debug headless: !program.debug
}); });
let page = await browser.newPage(); const page = await browser.newPage();
await page.setViewport({ await page.setViewport({
width: 1200, height: 800 width: 1200, height: 800
......
...@@ -16,13 +16,13 @@ console.log('[PiexLoader] wasm mode loaded'); ...@@ -16,13 +16,13 @@ console.log('[PiexLoader] wasm mode loaded');
* image: function(number, number):PiexWasmImageResult * image: function(number, number):PiexWasmImageResult
* }} * }}
*/ */
var PiexWasmModule; let PiexWasmModule;
/** /**
* |window| var Module defined in page <script src='piex/piex.js.wasm'>. * |window| var Module defined in page <script src='piex/piex.js.wasm'>.
* @type {PiexWasmModule} * @type {PiexWasmModule}
*/ */
var Module = window['Module'] || {}; const PiexModule = window['Module'] || {};
/** /**
* Set true only if the wasm Module.onAbort() handler is called. * Set true only if the wasm Module.onAbort() handler is called.
...@@ -35,7 +35,7 @@ let wasmFailed = false; ...@@ -35,7 +35,7 @@ let wasmFailed = false;
* the Module has failed and re-throws the error. * the Module has failed and re-throws the error.
* @throws {!Error|string} * @throws {!Error|string}
*/ */
Module.onAbort = (error) => { PiexModule.onAbort = (error) => {
wasmFailed = true; wasmFailed = true;
throw error; throw error;
}; };
...@@ -49,7 +49,7 @@ Module.onAbort = (error) => { ...@@ -49,7 +49,7 @@ Module.onAbort = (error) => {
* broken Module state. * broken Module state.
*/ */
function wasmModuleFailed() { function wasmModuleFailed() {
if (wasmFailed || !Module.calledRun) { if (wasmFailed || !PiexModule.calledRun) {
console.error('[PiexLoader] wasmModuleFailed'); console.error('[PiexLoader] wasmModuleFailed');
setTimeout(chrome.runtime.reload, 0); setTimeout(chrome.runtime.reload, 0);
return true; return true;
...@@ -178,7 +178,7 @@ function readFromFileSystem(url) { ...@@ -178,7 +178,7 @@ function readFromFileSystem(url) {
* length:number * length:number
* }} * }}
*/ */
var PiexWasmPreviewImageMetadata; let PiexWasmPreviewImageMetadata;
/** /**
* The piex wasm Module.image(<raw image source>,...) API returns |error|, or * The piex wasm Module.image(<raw image source>,...) API returns |error|, or
...@@ -196,7 +196,7 @@ var PiexWasmPreviewImageMetadata; ...@@ -196,7 +196,7 @@ var PiexWasmPreviewImageMetadata;
* details:?Object * details:?Object
* }} * }}
*/ */
var PiexWasmImageResult; let PiexWasmImageResult;
/** /**
* Piex wasm raw image preview image extractor. * Piex wasm raw image preview image extractor.
...@@ -242,13 +242,13 @@ class ImageBuffer { ...@@ -242,13 +242,13 @@ class ImageBuffer {
* @throws {!Error} * @throws {!Error}
*/ */
process() { process() {
this.memory = Module._malloc(this.length); this.memory = PiexModule._malloc(this.length);
if (!this.memory) { if (!this.memory) {
throw new Error('Image malloc failed: ' + this.length + ' bytes'); throw new Error('Image malloc failed: ' + this.length + ' bytes');
} }
Module.HEAP8.set(this.source, this.memory); PiexModule.HEAP8.set(this.source, this.memory);
const result = Module.image(this.memory, this.length); const result = PiexModule.image(this.memory, this.length);
if (result.error) { if (result.error) {
throw new Error(result.error); throw new Error(result.error);
} }
...@@ -310,7 +310,7 @@ class ImageBuffer { ...@@ -310,7 +310,7 @@ class ImageBuffer {
return null; return null;
} }
let format = {}; const format = {};
for (const [key, value] of Object.entries(details)) { for (const [key, value] of Object.entries(details)) {
if (typeof value === 'string') { if (typeof value === 'string') {
format[key] = value.replace(/\0+$/, '').trim(); format[key] = value.replace(/\0+$/, '').trim();
...@@ -330,7 +330,7 @@ class ImageBuffer { ...@@ -330,7 +330,7 @@ class ImageBuffer {
* Release resources. * Release resources.
*/ */
close() { close() {
Module._free(this.memory); PiexModule._free(this.memory);
} }
} }
......
...@@ -273,13 +273,13 @@ ImageRequest.prototype.downloadOriginal_ = function(onSuccess, onFailure) { ...@@ -273,13 +273,13 @@ ImageRequest.prototype.downloadOriginal_ = function(onSuccess, onFailure) {
}.bind(this); }.bind(this);
// Download data urls directly since they are not supported by XmlHttpRequest. // Download data urls directly since they are not supported by XmlHttpRequest.
var dataUrlMatches = this.request_.url.match(/^data:([^,;]*)[,;]/); const dataUrlMatches = this.request_.url.match(/^data:([^,;]*)[,;]/);
if (dataUrlMatches) { if (dataUrlMatches) {
this.image_.src = this.request_.url; this.image_.src = this.request_.url;
this.contentType_ = dataUrlMatches[1]; this.contentType_ = dataUrlMatches[1];
return; return;
} }
var drivefsUrlMatches = this.request_.url.match(/^drivefs:(.*)/); const drivefsUrlMatches = this.request_.url.match(/^drivefs:(.*)/);
if (drivefsUrlMatches) { if (drivefsUrlMatches) {
window.webkitResolveLocalFileSystemURL( window.webkitResolveLocalFileSystemURL(
drivefsUrlMatches[1], drivefsUrlMatches[1],
...@@ -300,21 +300,24 @@ ImageRequest.prototype.downloadOriginal_ = function(onSuccess, onFailure) { ...@@ -300,21 +300,24 @@ ImageRequest.prototype.downloadOriginal_ = function(onSuccess, onFailure) {
return; return;
} }
var fileType = FileType.getTypeForName(this.request_.url); const fileType = FileType.getTypeForName(this.request_.url);
// Load RAW images by using Piex loader instead of XHR. // Load RAW images by using Piex loader instead of XHR.
if (fileType.type === 'raw') { if (fileType.type === 'raw') {
this.piexLoader_.load(this.request_.url).then(function(data) { this.piexLoader_.load(this.request_.url)
var blob = new Blob([data.thumbnail], {type: 'image/jpeg'}); .then(
var url = URL.createObjectURL(blob); function(data) {
this.image_.src = url; const blob = new Blob([data.thumbnail], {type: 'image/jpeg'});
this.request_.orientation = data.orientation; const url = URL.createObjectURL(blob);
this.request_.colorSpace = data.colorSpace; this.image_.src = url;
this.ifd_ = data.ifd; this.request_.orientation = data.orientation;
}.bind(this), function() { this.request_.colorSpace = data.colorSpace;
// The error has already been logged in PiexLoader. this.ifd_ = data.ifd;
onFailure(); }.bind(this),
}); function() {
// The error has already been logged in PiexLoader.
onFailure();
});
return; return;
} }
...@@ -330,7 +333,7 @@ ImageRequest.prototype.downloadOriginal_ = function(onSuccess, onFailure) { ...@@ -330,7 +333,7 @@ ImageRequest.prototype.downloadOriginal_ = function(onSuccess, onFailure) {
} }
// Fetch the image via XHR and parse it. // Fetch the image via XHR and parse it.
var parseImage = function(contentType, blob) { const parseImage = function(contentType, blob) {
if (contentType) { if (contentType) {
this.contentType_ = contentType; this.contentType_ = contentType;
} }
...@@ -396,8 +399,8 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) { ...@@ -396,8 +399,8 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) {
this.aborted_ = false; this.aborted_ = false;
// Do not call any callbacks when aborting. // Do not call any callbacks when aborting.
var onMaybeSuccess = /** @type {function(string, Blob)} */ ( const onMaybeSuccess =
function(contentType, response) { /** @type {function(string, Blob)} */ (function(contentType, response) {
// When content type is not available, try to estimate it from url. // When content type is not available, try to estimate it from url.
if (!contentType) { if (!contentType) {
contentType = contentType =
...@@ -409,7 +412,7 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) { ...@@ -409,7 +412,7 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) {
} }
}.bind(this)); }.bind(this));
var onMaybeFailure = /** @type {function(number=)} */ (function(opt_code) { const onMaybeFailure = /** @type {function(number=)} */ (function(opt_code) {
if (!this.aborted_) { if (!this.aborted_) {
onFailure(); onFailure();
} }
...@@ -417,7 +420,7 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) { ...@@ -417,7 +420,7 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) {
// The query parameter is workaround for crbug.com/379678, which forces the // The query parameter is workaround for crbug.com/379678, which forces the
// browser to obtain the latest contents of the image. // browser to obtain the latest contents of the image.
var noCacheUrl = url + '?nocache=' + Date.now(); const noCacheUrl = url + '?nocache=' + Date.now();
this.xhr_ = ImageRequest.load_(noCacheUrl, onMaybeSuccess, onMaybeFailure); this.xhr_ = ImageRequest.load_(noCacheUrl, onMaybeSuccess, onMaybeFailure);
}; };
...@@ -427,7 +430,7 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) { ...@@ -427,7 +430,7 @@ ImageRequest.prototype.load = function(url, onSuccess, onFailure) {
* @return {string} Extracted extension, e.g. png. * @return {string} Extracted extension, e.g. png.
*/ */
ImageRequest.prototype.extractExtension_ = function(url) { ImageRequest.prototype.extractExtension_ = function(url) {
var result = (/\.([a-zA-Z]+)$/i).exec(url); const result = (/\.([a-zA-Z]+)$/i).exec(url);
return result ? result[1] : ''; return result ? result[1] : '';
}; };
...@@ -443,7 +446,7 @@ ImageRequest.prototype.extractExtension_ = function(url) { ...@@ -443,7 +446,7 @@ ImageRequest.prototype.extractExtension_ = function(url) {
* @private * @private
*/ */
ImageRequest.load_ = function(url, onSuccess, onFailure) { ImageRequest.load_ = function(url, onSuccess, onFailure) {
let xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; xhr.responseType = 'blob';
xhr.onreadystatechange = function() { xhr.onreadystatechange = function() {
...@@ -454,8 +457,8 @@ ImageRequest.load_ = function(url, onSuccess, onFailure) { ...@@ -454,8 +457,8 @@ ImageRequest.load_ = function(url, onSuccess, onFailure) {
onFailure(xhr.status); onFailure(xhr.status);
return; return;
} }
let response = /** @type {Blob} */ (xhr.response); const response = /** @type {Blob} */ (xhr.response);
let contentType = xhr.getResponseHeader('Content-Type') || response.type; const contentType = xhr.getResponseHeader('Content-Type') || response.type;
onSuccess(contentType, response); onSuccess(contentType, response);
}.bind(this); }.bind(this);
......
...@@ -82,17 +82,17 @@ Scheduler.prototype.add = function(request) { ...@@ -82,17 +82,17 @@ Scheduler.prototype.add = function(request) {
* @param {string} requestId Unique ID of the request. * @param {string} requestId Unique ID of the request.
*/ */
Scheduler.prototype.remove = function(requestId) { Scheduler.prototype.remove = function(requestId) {
var request = this.requests_[requestId]; const request = this.requests_[requestId];
if (!request) { if (!request) {
return; return;
} }
// Remove from the internal queues with pending tasks. // Remove from the internal queues with pending tasks.
var newIndex = this.pendingRequests_.indexOf(request); const newIndex = this.pendingRequests_.indexOf(request);
if (newIndex != -1) { if (newIndex != -1) {
this.newRequests_.splice(newIndex, 1); this.newRequests_.splice(newIndex, 1);
} }
var pendingIndex = this.pendingRequests_.indexOf(request); const pendingIndex = this.pendingRequests_.indexOf(request);
if (pendingIndex != -1) { if (pendingIndex != -1) {
this.pendingRequests_.splice(pendingIndex, 1); this.pendingRequests_.splice(pendingIndex, 1);
} }
...@@ -137,7 +137,7 @@ Scheduler.prototype.continue_ = function() { ...@@ -137,7 +137,7 @@ Scheduler.prototype.continue_ = function() {
// Run only up to MAXIMUM_IN_PARALLEL in the same time. // Run only up to MAXIMUM_IN_PARALLEL in the same time.
while (this.pendingRequests_.length && while (this.pendingRequests_.length &&
this.activeRequests_.length < Scheduler.MAXIMUM_IN_PARALLEL) { this.activeRequests_.length < Scheduler.MAXIMUM_IN_PARALLEL) {
var request = this.pendingRequests_.shift(); const request = this.pendingRequests_.shift();
this.activeRequests_.push(request); this.activeRequests_.push(request);
// Try to load from cache. If doesn't exist, then download. // Try to load from cache. If doesn't exist, then download.
...@@ -157,7 +157,7 @@ Scheduler.prototype.continue_ = function() { ...@@ -157,7 +157,7 @@ Scheduler.prototype.continue_ = function() {
* @private * @private
*/ */
Scheduler.prototype.finish_ = function(request) { Scheduler.prototype.finish_ = function(request) {
var index = this.activeRequests_.indexOf(request); const index = this.activeRequests_.indexOf(request);
if (index < 0) { if (index < 0) {
console.warn('Request not found.'); console.warn('Request not found.');
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment