CB-12985 : setup eslint and removed jshint

This commit is contained in:
Audrey So 2017-06-09 14:51:30 -07:00
parent 55d419a36e
commit 80342b0ddd
13 changed files with 287 additions and 299 deletions

10
.eslintrc.yml Normal file
View File

@ -0,0 +1,10 @@
root: true
extends: semistandard
rules:
indent:
- error
- 4
camelcase: off
padded-blocks: off
operator-linebreak: off
no-throw-literal: off

View File

@ -1,16 +0,0 @@
{
"browser": true
, "devel": true
, "bitwise": true
, "undef": true
, "trailing": true
, "quotmark": false
, "indent": 4
, "unused": "vars"
, "latedef": "nofunc"
, "globals": {
"module": false,
"exports": false,
"require": false
}
}

View File

@ -45,8 +45,8 @@
"scripts": { "scripts": {
"precommit": "npm run gen-docs && git add README.md", "precommit": "npm run gen-docs && git add README.md",
"gen-docs": "jsdoc2md --template \"jsdoc2md/TEMPLATE.md\" \"www/**/*.js\" --plugin \"dmd-plugin-cordova-plugin\" > README.md", "gen-docs": "jsdoc2md --template \"jsdoc2md/TEMPLATE.md\" \"www/**/*.js\" --plugin \"dmd-plugin-cordova-plugin\" > README.md",
"test": "npm run jshint", "test": "npm run eslint",
"jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests" "eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests"
}, },
"author": "Apache Software Foundation", "author": "Apache Software Foundation",
"license": "Apache-2.0", "license": "Apache-2.0",
@ -59,8 +59,14 @@
}, },
"devDependencies": { "devDependencies": {
"dmd-plugin-cordova-plugin": "^0.1.0", "dmd-plugin-cordova-plugin": "^0.1.0",
"eslint": "^4.2.0",
"eslint-config-semistandard": "^11.0.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.3.0",
"eslint-plugin-node": "^5.0.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1",
"husky": "^0.10.1", "husky": "^0.10.1",
"jsdoc-to-markdown": "^1.2.0", "jsdoc-to-markdown": "^1.2.0"
"jshint": "^2.6.0"
} }
} }

View File

@ -22,19 +22,19 @@
/* globals qnx, FileError, PluginResult */ /* globals qnx, FileError, PluginResult */
var PictureSourceType = { var PictureSourceType = {
PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android) PHOTOLIBRARY: 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
CAMERA : 1, // Take picture from camera CAMERA: 1, // Take picture from camera
SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android) SAVEDPHOTOALBUM: 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
}, },
DestinationType = { DestinationType = {
DATA_URL: 0, // Return base64 encoded string DATA_URL: 0, // Return base64 encoded string
FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android) FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS) NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
}, },
savePath = window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', '') + '/shared/camera/', savePath = window.qnx.webplatform.getApplication().getEnv('HOME').replace('/data', '') + '/shared/camera/',
invokeAvailable = true; invokeAvailable = true;
//check for camera card - it isn't currently availble in work perimeter // check for camera card - it isn't currently availble in work perimeter
window.qnx.webplatform.getApplication().invocation.queryTargets( window.qnx.webplatform.getApplication().invocation.queryTargets(
{ {
type: 'image/jpeg', type: 'image/jpeg',
@ -47,7 +47,7 @@ window.qnx.webplatform.getApplication().invocation.queryTargets(
} }
); );
//open a webview with getUserMedia camera card implementation when camera card not available // open a webview with getUserMedia camera card implementation when camera card not available
function showCameraDialog (done, cancel, fail) { function showCameraDialog (done, cancel, fail) {
var wv = qnx.webplatform.createWebView(function () { var wv = qnx.webplatform.createWebView(function () {
wv.url = 'local:///chrome/camera.html'; wv.url = 'local:///chrome/camera.html';
@ -85,16 +85,16 @@ function showCameraDialog (done, cancel, fail) {
}); });
} }
//create unique name for saved file (same pattern as BB10 camera app) // create unique name for saved file (same pattern as BB10 camera app)
function imgName() { function imgName () {
var date = new Date(), var date = new Date(),
pad = function (n) { return n < 10 ? '0' + n : n; }; pad = function (n) { return n < 10 ? '0' + n : n; };
return 'IMG_' + date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate()) + '_' + return 'IMG_' + date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate()) + '_' +
pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds()) + '.png'; pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds()) + '.png';
} }
//convert dataURI to Blob // convert dataURI to Blob
function dataURItoBlob(dataURI) { function dataURItoBlob (dataURI) {
var byteString = atob(dataURI.split(',')[1]), var byteString = atob(dataURI.split(',')[1]),
mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0], mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0],
arrayBuffer = new ArrayBuffer(byteString.length), arrayBuffer = new ArrayBuffer(byteString.length),
@ -106,8 +106,8 @@ function dataURItoBlob(dataURI) {
return new Blob([new DataView(arrayBuffer)], { type: mimeString }); return new Blob([new DataView(arrayBuffer)], { type: mimeString });
} }
//save dataURI to file system and call success with path // save dataURI to file system and call success with path
function saveImage(data, success, fail) { function saveImage (data, success, fail) {
var name = savePath + imgName(); var name = savePath + imgName();
require('lib/webview').setSandbox(false); require('lib/webview').setSandbox(false);
window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) { window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) {
@ -123,30 +123,30 @@ function saveImage(data, success, fail) {
}, fail); }, fail);
} }
function encodeBase64(filePath, callback) { function encodeBase64 (filePath, callback) {
var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox, // save original sandbox value var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox, // save original sandbox value
errorHandler = function (err) { errorHandler = function (err) {
var msg = "An error occured: "; var msg = 'An error occured: ';
switch (err.code) { switch (err.code) {
case FileError.NOT_FOUND_ERR: case FileError.NOT_FOUND_ERR:
msg += "File or directory not found"; msg += 'File or directory not found';
break; break;
case FileError.NOT_READABLE_ERR: case FileError.NOT_READABLE_ERR:
msg += "File or directory not readable"; msg += 'File or directory not readable';
break; break;
case FileError.PATH_EXISTS_ERR: case FileError.PATH_EXISTS_ERR:
msg += "File or directory already exists"; msg += 'File or directory already exists';
break; break;
case FileError.TYPE_MISMATCH_ERR: case FileError.TYPE_MISMATCH_ERR:
msg += "Invalid file type"; msg += 'Invalid file type';
break; break;
default: default:
msg += "Unknown Error"; msg += 'Unknown Error';
break; break;
} }
@ -182,12 +182,12 @@ module.exports = {
result = new PluginResult(args, env), result = new PluginResult(args, env),
done = function (data) { done = function (data) {
if (destinationType === DestinationType.FILE_URI) { if (destinationType === DestinationType.FILE_URI) {
data = "file://" + data; data = 'file://' + data;
result.callbackOk(data, false); result.callbackOk(data, false);
} else { } else {
encodeBase64(data, function (data) { encodeBase64(data, function (data) {
if (/^data:/.test(data)) { if (/^data:/.test(data)) {
data = data.slice(data.indexOf(",") + 1); data = data.slice(data.indexOf(',') + 1);
result.callbackOk(data, false); result.callbackOk(data, false);
} else { } else {
result.callbackError(data, false); result.callbackError(data, false);
@ -204,10 +204,10 @@ module.exports = {
} }
}; };
switch(sourceType) { switch (sourceType) {
case PictureSourceType.CAMERA: case PictureSourceType.CAMERA:
if (invokeAvailable) { if (invokeAvailable) {
window.qnx.webplatform.getApplication().cards.camera.open("photo", done, cancel, invoked); window.qnx.webplatform.getApplication().cards.camera.open('photo', done, cancel, invoked);
} else { } else {
showCameraDialog(done, cancel, fail); showCameraDialog(done, cancel, fail);
} }
@ -216,8 +216,8 @@ module.exports = {
case PictureSourceType.PHOTOLIBRARY: case PictureSourceType.PHOTOLIBRARY:
case PictureSourceType.SAVEDPHOTOALBUM: case PictureSourceType.SAVEDPHOTOALBUM:
window.qnx.webplatform.getApplication().cards.filePicker.open({ window.qnx.webplatform.getApplication().cards.filePicker.open({
mode: "Picker", mode: 'Picker',
type: ["picture"] type: ['picture']
}, done, cancel, invoked); }, done, cancel, invoked);
break; break;
} }

View File

@ -21,7 +21,7 @@
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647; var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
function takePicture(success, error, opts) { function takePicture (success, error, opts) {
if (opts && opts[2] === 1) { if (opts && opts[2] === 1) {
capture(success, error, opts); capture(success, error, opts);
} else { } else {
@ -32,9 +32,9 @@ function takePicture(success, error, opts) {
input.type = 'file'; input.type = 'file';
input.name = 'files[]'; input.name = 'files[]';
input.onchange = function(inputEvent) { input.onchange = function (inputEvent) {
var reader = new FileReader(); var reader = new FileReader();
reader.onload = function(readerEvent) { reader.onload = function (readerEvent) {
input.parentNode.removeChild(input); input.parentNode.removeChild(input);
var imageData = readerEvent.target.result; var imageData = readerEvent.target.result;
@ -49,13 +49,13 @@ function takePicture(success, error, opts) {
} }
} }
function capture(success, errorCallback, opts) { function capture (success, errorCallback, opts) {
var localMediaStream; var localMediaStream;
var targetWidth = opts[3]; var targetWidth = opts[3];
var targetHeight = opts[4]; var targetHeight = opts[4];
targetWidth = targetWidth == -1?320:targetWidth; targetWidth = targetWidth == -1 ? 320 : targetWidth;
targetHeight = targetHeight == -1?240:targetHeight; targetHeight = targetHeight == -1 ? 240 : targetHeight;
var video = document.createElement('video'); var video = document.createElement('video');
var button = document.createElement('button'); var button = document.createElement('button');
@ -70,7 +70,7 @@ function capture(success, errorCallback, opts) {
video.height = targetHeight; video.height = targetHeight;
button.innerHTML = 'Capture!'; button.innerHTML = 'Capture!';
button.onclick = function() { button.onclick = function () {
// create a canvas and capture a frame from video stream // create a canvas and capture a frame from video stream
var canvas = document.createElement('canvas'); var canvas = document.createElement('canvas');
canvas.width = targetWidth; canvas.width = targetWidth;
@ -100,7 +100,7 @@ function capture(success, errorCallback, opts) {
navigator.mozGetUserMedia || navigator.mozGetUserMedia ||
navigator.msGetUserMedia; navigator.msGetUserMedia;
var successCallback = function(stream) { var successCallback = function (stream) {
localMediaStream = stream; localMediaStream = stream;
video.src = window.URL.createObjectURL(localMediaStream); video.src = window.URL.createObjectURL(localMediaStream);
video.play(); video.play();
@ -117,7 +117,7 @@ function capture(success, errorCallback, opts) {
module.exports = { module.exports = {
takePicture: takePicture, takePicture: takePicture,
cleanup: function(){} cleanup: function () {}
}; };
require("cordova/exec/proxy").add("Camera",module.exports); require('cordova/exec/proxy').add('Camera', module.exports);

View File

@ -21,17 +21,17 @@
/* globals MozActivity */ /* globals MozActivity */
function takePicture(success, error, opts) { function takePicture (success, error, opts) {
var pick = new MozActivity({ var pick = new MozActivity({
name: "pick", name: 'pick',
data: { data: {
type: ["image/*"] type: ['image/*']
} }
}); });
pick.onerror = error || function() {}; pick.onerror = error || function () {};
pick.onsuccess = function() { pick.onsuccess = function () {
// image is returned as Blob in this.result.blob // image is returned as Blob in this.result.blob
// we need to call success with url or base64 encoded image // we need to call success with url or base64 encoded image
if (opts && opts.destinationType === 0) { if (opts && opts.destinationType === 0) {
@ -47,7 +47,7 @@ function takePicture(success, error, opts) {
module.exports = { module.exports = {
takePicture: takePicture, takePicture: takePicture,
cleanup: function(){} cleanup: function () {}
}; };
require("cordova/exec/proxy").add("Camera", module.exports); require('cordova/exec/proxy').add('Camera', module.exports);

View File

@ -19,13 +19,11 @@
* *
*/ */
/*jshint unused:true, undef:true, browser:true */ /* jshint unused:true, undef:true, browser:true */
/*global Windows:true, URL:true, module:true, require:true, WinJS:true */ /* global Windows:true, URL:true, module:true, require:true, WinJS:true */
var Camera = require('./Camera'); var Camera = require('./Camera');
var getAppData = function () { var getAppData = function () {
return Windows.Storage.ApplicationData.current; return Windows.Storage.ApplicationData.current;
}; };
@ -67,8 +65,8 @@ module.exports = {
}; };
// https://msdn.microsoft.com/en-us/library/windows/apps/ff462087(v=vs.105).aspx // https://msdn.microsoft.com/en-us/library/windows/apps/ff462087(v=vs.105).aspx
var windowsVideoContainers = [".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"]; var windowsVideoContainers = ['.avi', '.flv', '.asx', '.asf', '.mov', '.mp4', '.mpg', '.rm', '.srt', '.swf', '.wmv', '.vob'];
var windowsPhoneVideoContainers = [".avi", ".3gp", ".3g2", ".wmv", ".3gp", ".3g2", ".mp4", ".m4v"]; var windowsPhoneVideoContainers = ['.avi', '.3gp', '.3g2', '.wmv', '.3gp', '.3g2', '.mp4', '.m4v'];
// Default aspect ratio 1.78 (16:9 hd video standard) // Default aspect ratio 1.78 (16:9 hd video standard)
var DEFAULT_ASPECT_RATIO = '1.8'; var DEFAULT_ASPECT_RATIO = '1.8';
@ -77,16 +75,16 @@ var DEFAULT_ASPECT_RATIO = '1.8';
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647; var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
// Resize method // Resize method
function resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) { function resizeImage (successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) {
var tempPhotoFileName = ""; var tempPhotoFileName = '';
var targetContentType = ""; var targetContentType = '';
if (encodingType == Camera.EncodingType.PNG) { if (encodingType == Camera.EncodingType.PNG) {
tempPhotoFileName = "camera_cordova_temp_return.png"; tempPhotoFileName = 'camera_cordova_temp_return.png';
targetContentType = "image/png"; targetContentType = 'image/png';
} else { } else {
tempPhotoFileName = "camera_cordova_temp_return.jpg"; tempPhotoFileName = 'camera_cordova_temp_return.jpg';
targetContentType = "image/jpeg"; targetContentType = 'image/jpeg';
} }
var storageFolder = getAppData().localFolder; var storageFolder = getAppData().localFolder;
@ -94,12 +92,12 @@ function resizeImage(successCallback, errorCallback, file, targetWidth, targetHe
.then(function (storageFile) { .then(function (storageFile) {
return fileIO.readBufferAsync(storageFile); return fileIO.readBufferAsync(storageFile);
}) })
.then(function(buffer) { .then(function (buffer) {
var strBase64 = encodeToBase64String(buffer); var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64; var imageData = 'data:' + file.contentType + ';base64,' + strBase64;
var image = new Image(); var image = new Image();
image.src = imageData; image.src = imageData;
image.onload = function() { image.onload = function () {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height); var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width; var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height; var imageHeight = ratio * this.height;
@ -110,7 +108,7 @@ function resizeImage(successCallback, errorCallback, file, targetWidth, targetHe
canvas.width = imageWidth; canvas.width = imageWidth;
canvas.height = imageHeight; canvas.height = imageHeight;
canvas.getContext("2d").drawImage(this, 0, 0, imageWidth, imageHeight); canvas.getContext('2d').drawImage(this, 0, 0, imageWidth, imageHeight);
var fileContent = canvas.toDataURL(targetContentType).split(',')[1]; var fileContent = canvas.toDataURL(targetContentType).split(',')[1];
@ -123,26 +121,26 @@ function resizeImage(successCallback, errorCallback, file, targetWidth, targetHe
return fileIO.writeBufferAsync(storagefile, content); return fileIO.writeBufferAsync(storagefile, content);
}) })
.done(function () { .done(function () {
successCallback("ms-appdata:///local/" + storageFileName); successCallback('ms-appdata:///local/' + storageFileName);
}, errorCallback); }, errorCallback);
}; };
}) })
.done(null, function(err) { .done(null, function (err) {
errorCallback(err); errorCallback(err);
} }
); );
} }
// Because of asynchronous method, so let the successCallback be called in it. // Because of asynchronous method, so let the successCallback be called in it.
function resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight) { function resizeImageBase64 (successCallback, errorCallback, file, targetWidth, targetHeight) {
fileIO.readBufferAsync(file).done( function(buffer) { fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 = encodeToBase64String(buffer); var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64; var imageData = 'data:' + file.contentType + ';base64,' + strBase64;
var image = new Image(); var image = new Image();
image.src = imageData; image.src = imageData;
image.onload = function() { image.onload = function () {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height); var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width; var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height; var imageHeight = ratio * this.height;
@ -151,21 +149,21 @@ function resizeImageBase64(successCallback, errorCallback, file, targetWidth, ta
canvas.width = imageWidth; canvas.width = imageWidth;
canvas.height = imageHeight; canvas.height = imageHeight;
var ctx = canvas.getContext("2d"); var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, imageWidth, imageHeight); ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload // The resized file ready for upload
var finalFile = canvas.toDataURL(file.contentType); var finalFile = canvas.toDataURL(file.contentType);
// Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API. // Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API.
var arr = finalFile.split(","); var arr = finalFile.split(',');
var newStr = finalFile.substr(arr[0].length + 1); var newStr = finalFile.substr(arr[0].length + 1);
successCallback(newStr); successCallback(newStr);
}; };
}, function(err) { errorCallback(err); }); }, function (err) { errorCallback(err); });
} }
function takePictureFromFile(successCallback, errorCallback, args) { function takePictureFromFile (successCallback, errorCallback, args) {
// Detect Windows Phone // Detect Windows Phone
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) { if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
takePictureFromFileWP(successCallback, errorCallback, args); takePictureFromFileWP(successCallback, errorCallback, args);
@ -174,7 +172,7 @@ function takePictureFromFile(successCallback, errorCallback, args) {
} }
} }
function takePictureFromFileWP(successCallback, errorCallback, args) { function takePictureFromFileWP (successCallback, errorCallback, args) {
var mediaType = args[6], var mediaType = args[6],
destinationType = args[1], destinationType = args[1],
targetWidth = args[3], targetWidth = args[3],
@ -186,65 +184,60 @@ function takePictureFromFileWP(successCallback, errorCallback, args) {
Using FileOpenPicker will suspend the app and it's required to catch the PickSingleFileAndContinue Using FileOpenPicker will suspend the app and it's required to catch the PickSingleFileAndContinue
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/ */
var filePickerActivationHandler = function(eventArgs) { var filePickerActivationHandler = function (eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) { if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) {
var file = eventArgs.files[0]; var file = eventArgs.files[0];
if (!file) { if (!file) {
errorCallback("User didn't choose a file."); errorCallback("User didn't choose a file.");
webUIApp.removeEventListener("activated", filePickerActivationHandler); webUIApp.removeEventListener('activated', filePickerActivationHandler);
return; return;
} }
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) { if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) { if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType); resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
} } else {
else {
var storageFolder = getAppData().localFolder; var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) { file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) { if (destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name); successCallback('ms-appdata:///local/' + storageFile.name);
} } else {
else {
successCallback(URL.createObjectURL(storageFile)); successCallback(URL.createObjectURL(storageFile));
} }
}, function () { }, function () {
errorCallback("Can't access localStorage folder."); errorCallback("Can't access localStorage folder.");
}); });
} }
} } else {
else {
if (targetHeight > 0 && targetWidth > 0) { if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight); resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else { } else {
fileIO.readBufferAsync(file).done(function (buffer) { fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer); var strBase64 = encodeToBase64String(buffer);
successCallback(strBase64); successCallback(strBase64);
}, errorCallback); }, errorCallback);
} }
} }
webUIApp.removeEventListener("activated", filePickerActivationHandler); webUIApp.removeEventListener('activated', filePickerActivationHandler);
} }
}; };
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker(); var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) { if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]); fileOpenPicker.fileTypeFilter.replaceAll(['.png', '.jpg', '.jpeg']);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary; fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
} } else if (mediaType == Camera.MediaType.VIDEO) {
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsPhoneVideoContainers); fileOpenPicker.fileTypeFilter.replaceAll(windowsPhoneVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary; fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
} } else {
else { fileOpenPicker.fileTypeFilter.replaceAll(['*']);
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary; fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
} }
webUIApp.addEventListener("activated", filePickerActivationHandler); webUIApp.addEventListener('activated', filePickerActivationHandler);
fileOpenPicker.pickSingleFileAndContinue(); fileOpenPicker.pickSingleFileAndContinue();
} }
function takePictureFromFileWindows(successCallback, errorCallback, args) { function takePictureFromFileWindows (successCallback, errorCallback, args) {
var mediaType = args[6], var mediaType = args[6],
destinationType = args[1], destinationType = args[1],
targetWidth = args[3], targetWidth = args[3],
@ -253,15 +246,13 @@ function takePictureFromFileWindows(successCallback, errorCallback, args) {
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker(); var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) { if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]); fileOpenPicker.fileTypeFilter.replaceAll(['.png', '.jpg', '.jpeg']);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary; fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
} } else if (mediaType == Camera.MediaType.VIDEO) {
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsVideoContainers); fileOpenPicker.fileTypeFilter.replaceAll(windowsVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary; fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
} } else {
else { fileOpenPicker.fileTypeFilter.replaceAll(['*']);
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary; fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
} }
@ -273,27 +264,24 @@ function takePictureFromFileWindows(successCallback, errorCallback, args) {
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) { if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) { if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType); resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
} } else {
else {
var storageFolder = getAppData().localFolder; var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) { file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) { if (destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name); successCallback('ms-appdata:///local/' + storageFile.name);
} } else {
else { successCallback(URL.createObjectURL(storageFile));
successCallback(URL.createObjectURL(storageFile)); }
}
}, function () { }, function () {
errorCallback("Can't access localStorage folder."); errorCallback("Can't access localStorage folder.");
}); });
} }
} } else {
else {
if (targetHeight > 0 && targetWidth > 0) { if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight); resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else { } else {
fileIO.readBufferAsync(file).done(function (buffer) { fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer); var strBase64 = encodeToBase64String(buffer);
successCallback(strBase64); successCallback(strBase64);
}, errorCallback); }, errorCallback);
} }
@ -303,7 +291,7 @@ function takePictureFromFileWindows(successCallback, errorCallback, args) {
}); });
} }
function takePictureFromCamera(successCallback, errorCallback, args) { function takePictureFromCamera (successCallback, errorCallback, args) {
// Check if necessary API available // Check if necessary API available
if (!Windows.Media.Capture.CameraCaptureUI) { if (!Windows.Media.Capture.CameraCaptureUI) {
takePictureFromCameraWP(successCallback, errorCallback, args); takePictureFromCameraWP(successCallback, errorCallback, args);
@ -312,7 +300,7 @@ function takePictureFromCamera(successCallback, errorCallback, args) {
} }
} }
function takePictureFromCameraWP(successCallback, errorCallback, args) { function takePictureFromCameraWP (successCallback, errorCallback, args) {
// We are running on WP8.1 which lacks CameraCaptureUI class // We are running on WP8.1 which lacks CameraCaptureUI class
// so we need to use MediaCapture class instead and implement custom UI for camera // so we need to use MediaCapture class instead and implement custom UI for camera
var destinationType = args[1], var destinationType = args[1],
@ -329,25 +317,25 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
CaptureNS = Windows.Media.Capture, CaptureNS = Windows.Media.Capture,
sensor = null; sensor = null;
function createCameraUI() { function createCameraUI () {
// create style for take and cancel buttons // create style for take and cancel buttons
var buttonStyle = "width:45%;padding: 10px 16px;font-size: 18px;line-height: 1.3333333;color: #333;background-color: #fff;border-color: #ccc; border: 1px solid transparent;border-radius: 6px; display: block; margin: 20px; z-index: 1000;border-color: #adadad;"; var buttonStyle = 'width:45%;padding: 10px 16px;font-size: 18px;line-height: 1.3333333;color: #333;background-color: #fff;border-color: #ccc; border: 1px solid transparent;border-radius: 6px; display: block; margin: 20px; z-index: 1000;border-color: #adadad;';
// Create fullscreen preview // Create fullscreen preview
// z-order style element for capturePreview and cameraCancelButton elts // z-order style element for capturePreview and cameraCancelButton elts
// is necessary to avoid overriding by another page elements, -1 sometimes is not enough // is necessary to avoid overriding by another page elements, -1 sometimes is not enough
capturePreview = document.createElement("video"); capturePreview = document.createElement('video');
capturePreview.style.cssText = "position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: " + (HIGHEST_POSSIBLE_Z_INDEX - 1) + ";"; capturePreview.style.cssText = 'position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: ' + (HIGHEST_POSSIBLE_Z_INDEX - 1) + ';';
// Create capture button // Create capture button
cameraCaptureButton = document.createElement("button"); cameraCaptureButton = document.createElement('button');
cameraCaptureButton.innerText = "Take"; cameraCaptureButton.innerText = 'Take';
cameraCaptureButton.style.cssText = buttonStyle + "position: fixed; left: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";"; cameraCaptureButton.style.cssText = buttonStyle + 'position: fixed; left: 0; bottom: 0; margin: 20px; z-index: ' + HIGHEST_POSSIBLE_Z_INDEX + ';';
// Create cancel button // Create cancel button
cameraCancelButton = document.createElement("button"); cameraCancelButton = document.createElement('button');
cameraCancelButton.innerText = "Cancel"; cameraCancelButton.innerText = 'Cancel';
cameraCancelButton.style.cssText = buttonStyle + "position: fixed; right: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";"; cameraCancelButton.style.cssText = buttonStyle + 'position: fixed; right: 0; bottom: 0; margin: 20px; z-index: ' + HIGHEST_POSSIBLE_Z_INDEX + ';';
capture = new CaptureNS.MediaCapture(); capture = new CaptureNS.MediaCapture();
@ -355,21 +343,21 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video; captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video;
} }
function continueVideoOnFocus() { function continueVideoOnFocus () {
// if preview is defined it would be stuck, play it // if preview is defined it would be stuck, play it
if (capturePreview) { if (capturePreview) {
capturePreview.play(); capturePreview.play();
} }
} }
function startCameraPreview() { function startCameraPreview () {
// Search for available camera devices // Search for available camera devices
// This is necessary to detect which camera (front or back) we should use // This is necessary to detect which camera (front or back) we should use
var DeviceEnum = Windows.Devices.Enumeration; var DeviceEnum = Windows.Devices.Enumeration;
var expectedPanel = cameraDirection === 1 ? DeviceEnum.Panel.front : DeviceEnum.Panel.back; var expectedPanel = cameraDirection === 1 ? DeviceEnum.Panel.front : DeviceEnum.Panel.back;
// Add focus event handler to capture the event when user suspends the app and comes back while the preview is on // Add focus event handler to capture the event when user suspends the app and comes back while the preview is on
window.addEventListener("focus", continueVideoOnFocus); window.addEventListener('focus', continueVideoOnFocus);
DeviceEnum.DeviceInformation.findAllAsync(DeviceEnum.DeviceClass.videoCapture).then(function (devices) { DeviceEnum.DeviceInformation.findAllAsync(DeviceEnum.DeviceClass.videoCapture).then(function (devices) {
if (devices.length <= 0) { if (devices.length <= 0) {
@ -378,7 +366,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
return; return;
} }
devices.forEach(function(currDev) { devices.forEach(function (currDev) {
if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) { if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
captureSettings.videoDeviceId = currDev.id; captureSettings.videoDeviceId = currDev.id;
} }
@ -418,7 +406,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
// Bind events to controls // Bind events to controls
sensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault(); sensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault();
if (sensor !== null) { if (sensor !== null) {
sensor.addEventListener("orientationchanged", onOrientationChange); sensor.addEventListener('orientationchanged', onOrientationChange);
} }
// add click events to capture and cancel buttons // add click events to capture and cancel buttons
@ -459,7 +447,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
}); });
} }
function destroyCameraPreview() { function destroyCameraPreview () {
// If sensor is available, remove event listener // If sensor is available, remove event listener
if (sensor !== null) { if (sensor !== null) {
sensor.removeEventListener('orientationchanged', onOrientationChange); sensor.removeEventListener('orientationchanged', onOrientationChange);
@ -474,7 +462,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
cameraCancelButton.removeEventListener('click', onCameraCancelButtonClick); cameraCancelButton.removeEventListener('click', onCameraCancelButtonClick);
// Remove the focus event handler // Remove the focus event handler
window.removeEventListener("focus", continueVideoOnFocus); window.removeEventListener('focus', continueVideoOnFocus);
// Remove elements // Remove elements
[capturePreview, cameraCaptureButton, cameraCancelButton].forEach(function (elem) { [capturePreview, cameraCaptureButton, cameraCancelButton].forEach(function (elem) {
@ -490,7 +478,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
} }
} }
function captureAction() { function captureAction () {
var encodingProperties, var encodingProperties,
fileName, fileName,
@ -505,41 +493,41 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
} }
tempFolder.createFileAsync(fileName, OptUnique) tempFolder.createFileAsync(fileName, OptUnique)
.then(function(tempCapturedFile) { .then(function (tempCapturedFile) {
return new WinJS.Promise(function (complete) { return new WinJS.Promise(function (complete) {
var photoStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var photoStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
var finalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var finalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
capture.capturePhotoToStreamAsync(encodingProperties, photoStream) capture.capturePhotoToStreamAsync(encodingProperties, photoStream)
.then(function() { .then(function () {
return Windows.Graphics.Imaging.BitmapDecoder.createAsync(photoStream); return Windows.Graphics.Imaging.BitmapDecoder.createAsync(photoStream);
}) })
.then(function(dec) { .then(function (dec) {
finalStream.size = 0; // BitmapEncoder requires the output stream to be empty finalStream.size = 0; // BitmapEncoder requires the output stream to be empty
return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(finalStream, dec); return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(finalStream, dec);
}) })
.then(function(enc) { .then(function (enc) {
// We need to rotate the photo wrt sensor orientation // We need to rotate the photo wrt sensor orientation
enc.bitmapTransform.rotation = orientationToRotation(sensor.getCurrentOrientation()); enc.bitmapTransform.rotation = orientationToRotation(sensor.getCurrentOrientation());
return enc.flushAsync(); return enc.flushAsync();
}) })
.then(function() { .then(function () {
return tempCapturedFile.openAsync(Windows.Storage.FileAccessMode.readWrite); return tempCapturedFile.openAsync(Windows.Storage.FileAccessMode.readWrite);
}) })
.then(function(fileStream) { .then(function (fileStream) {
return Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(finalStream, fileStream); return Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(finalStream, fileStream);
}) })
.done(function() { .done(function () {
photoStream.close(); photoStream.close();
finalStream.close(); finalStream.close();
complete(tempCapturedFile); complete(tempCapturedFile);
}, function() { }, function () {
photoStream.close(); photoStream.close();
finalStream.close(); finalStream.close();
throw new Error("An error has occured while capturing the photo."); throw new Error('An error has occured while capturing the photo.');
}); });
}); });
}) })
.done(function(capturedFile) { .done(function (capturedFile) {
destroyCameraPreview(); destroyCameraPreview();
savePhoto(capturedFile, { savePhoto(capturedFile, {
destinationType: destinationType, destinationType: destinationType,
@ -548,13 +536,13 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
encodingType: encodingType, encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback); }, successCallback, errorCallback);
}, function(err) { }, function (err) {
destroyCameraPreview(); destroyCameraPreview();
errorCallback(err); errorCallback(err);
}); });
} }
function getAspectRatios(capture) { function getAspectRatios (capture) {
var videoDeviceController = capture.videoDeviceController; var videoDeviceController = capture.videoDeviceController;
var photoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo).map(function (element) { var photoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo).map(function (element) {
return (element.width / element.height).toFixed(1); return (element.width / element.height).toFixed(1);
@ -583,7 +571,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
}); });
} }
function setAspectRatio(capture, aspect) { function setAspectRatio (capture, aspect) {
// Max photo resolution with desired aspect ratio // Max photo resolution with desired aspect ratio
var videoDeviceController = capture.videoDeviceController; var videoDeviceController = capture.videoDeviceController;
var photoResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo) var photoResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo)
@ -624,7 +612,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
/** /**
* When Capture button is clicked, try to capture a picture and return * When Capture button is clicked, try to capture a picture and return
*/ */
function onCameraCaptureButtonClick() { function onCameraCaptureButtonClick () {
// Make sure user can't click more than once // Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') { if (this.getAttribute('clicked') === '1') {
return false; return false;
@ -637,7 +625,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
/** /**
* When Cancel button is clicked, destroy camera preview and return with error callback * When Cancel button is clicked, destroy camera preview and return with error callback
*/ */
function onCameraCancelButtonClick() { function onCameraCancelButtonClick () {
// Make sure user can't click more than once // Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') { if (this.getAttribute('clicked') === '1') {
return false; return false;
@ -652,7 +640,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
* When the phone orientation change, get the event and change camera preview rotation * When the phone orientation change, get the event and change camera preview rotation
* @param {Object} e - SimpleOrientationSensorOrientationChangedEventArgs * @param {Object} e - SimpleOrientationSensorOrientationChangedEventArgs
*/ */
function onOrientationChange(e) { function onOrientationChange (e) {
setPreviewRotation(e.orientation); setPreviewRotation(e.orientation);
} }
@ -662,29 +650,29 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation * @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
* @return {number} - Windows.Media.Capture.VideoRotation * @return {number} - Windows.Media.Capture.VideoRotation
*/ */
function orientationToRotation(orientation) { function orientationToRotation (orientation) {
// VideoRotation enumerable and BitmapRotation enumerable have the same values // VideoRotation enumerable and BitmapRotation enumerable have the same values
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx // https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmaprotation.aspx // https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmaprotation.aspx
switch (orientation) { switch (orientation) {
// portrait // portrait
case Windows.Devices.Sensors.SimpleOrientation.notRotated: case Windows.Devices.Sensors.SimpleOrientation.notRotated:
return Windows.Media.Capture.VideoRotation.clockwise90Degrees; return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape // landscape
case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise: case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.none; return Windows.Media.Capture.VideoRotation.none;
// portrait-flipped (not supported by WinPhone Apps) // portrait-flipped (not supported by WinPhone Apps)
case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise: case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise:
// Falling back to portrait default // Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees; return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape-flipped // landscape-flipped
case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise: case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.clockwise180Degrees; return Windows.Media.Capture.VideoRotation.clockwise180Degrees;
// faceup & facedown // faceup & facedown
default: default:
// Falling back to portrait default // Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees; return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
} }
} }
@ -692,7 +680,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
* Rotates the current MediaCapture's video * Rotates the current MediaCapture's video
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation * @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
*/ */
function setPreviewRotation(orientation) { function setPreviewRotation (orientation) {
capture.setPreviewRotation(orientationToRotation(orientation)); capture.setPreviewRotation(orientationToRotation(orientation));
} }
@ -704,7 +692,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
} }
} }
function takePictureFromCameraWindows(successCallback, errorCallback, args) { function takePictureFromCameraWindows (successCallback, errorCallback, args) {
var destinationType = args[1], var destinationType = args[1],
targetWidth = args[3], targetWidth = args[3],
targetHeight = args[4], targetHeight = args[4],
@ -731,9 +719,9 @@ function takePictureFromCameraWindows(successCallback, errorCallback, args) {
maxRes = UIMaxRes.highestAvailable; maxRes = UIMaxRes.highestAvailable;
} }
// Temp fix for CB-10539 // Temp fix for CB-10539
/*else if (totalPixels <= 320 * 240) { /* else if (totalPixels <= 320 * 240) {
maxRes = UIMaxRes.verySmallQvga; maxRes = UIMaxRes.verySmallQvga;
}*/ } */
else if (totalPixels <= 640 * 480) { else if (totalPixels <= 640 * 480) {
maxRes = UIMaxRes.smallVga; maxRes = UIMaxRes.smallVga;
} else if (totalPixels <= 1024 * 768) { } else if (totalPixels <= 1024 * 768) {
@ -752,7 +740,7 @@ function takePictureFromCameraWindows(successCallback, errorCallback, args) {
// define focus handler for windows phone 10.0 // define focus handler for windows phone 10.0
var savePhotoOnFocus = function () { var savePhotoOnFocus = function () {
window.removeEventListener("focus", savePhotoOnFocus); window.removeEventListener('focus', savePhotoOnFocus);
// call only when the app is in focus again // call only when the app is in focus again
savePhoto(cameraPicture, { savePhoto(cameraPicture, {
destinationType: destinationType, destinationType: destinationType,
@ -765,14 +753,14 @@ function takePictureFromCameraWindows(successCallback, errorCallback, args) {
// if windows phone 10, add and delete focus eventHandler to capture the focus back from cameraUI to app // if windows phone 10, add and delete focus eventHandler to capture the focus back from cameraUI to app
if (navigator.appVersion.indexOf('Windows Phone 10.0') >= 0) { if (navigator.appVersion.indexOf('Windows Phone 10.0') >= 0) {
window.addEventListener("focus", savePhotoOnFocus); window.addEventListener('focus', savePhotoOnFocus);
} }
cameraCaptureUI.captureFileAsync(WMCapture.CameraCaptureUIMode.photo).done(function (picture) { cameraCaptureUI.captureFileAsync(WMCapture.CameraCaptureUIMode.photo).done(function (picture) {
if (!picture) { if (!picture) {
errorCallback("User didn't capture a photo."); errorCallback("User didn't capture a photo.");
// Remove the focus handler if present // Remove the focus handler if present
window.removeEventListener("focus", savePhotoOnFocus); window.removeEventListener('focus', savePhotoOnFocus);
return; return;
} }
cameraPicture = picture; cameraPicture = picture;
@ -788,31 +776,31 @@ function takePictureFromCameraWindows(successCallback, errorCallback, args) {
}, successCallback, errorCallback); }, successCallback, errorCallback);
} }
}, function () { }, function () {
errorCallback("Fail to capture a photo."); errorCallback('Fail to capture a photo.');
window.removeEventListener("focus", savePhotoOnFocus); window.removeEventListener('focus', savePhotoOnFocus);
}); });
} }
function savePhoto(picture, options, successCallback, errorCallback) { function savePhoto (picture, options, successCallback, errorCallback) {
// success callback for capture operation // success callback for capture operation
var success = function(picture) { var success = function (picture) {
if (options.destinationType == Camera.DestinationType.FILE_URI || options.destinationType == Camera.DestinationType.NATIVE_URI) { if (options.destinationType == Camera.DestinationType.FILE_URI || options.destinationType == Camera.DestinationType.NATIVE_URI) {
if (options.targetHeight > 0 && options.targetWidth > 0) { if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType); resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType);
} else { } else {
picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) { picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) {
successCallback("ms-appdata:///local/" + copiedFile.name); successCallback('ms-appdata:///local/' + copiedFile.name);
},errorCallback); }, errorCallback);
} }
} else { } else {
if (options.targetHeight > 0 && options.targetWidth > 0) { if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight); resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight);
} else { } else {
fileIO.readBufferAsync(picture).done(function(buffer) { fileIO.readBufferAsync(picture).done(function (buffer) {
var strBase64 = encodeToBase64String(buffer); var strBase64 = encodeToBase64String(buffer);
picture.deleteAsync().done(function() { picture.deleteAsync().done(function () {
successCallback(strBase64); successCallback(strBase64);
}, function(err) { }, function (err) {
errorCallback(err); errorCallback(err);
}); });
}, errorCallback); }, errorCallback);
@ -822,38 +810,38 @@ function savePhoto(picture, options, successCallback, errorCallback) {
if (!options.saveToPhotoAlbum) { if (!options.saveToPhotoAlbum) {
success(picture); success(picture);
return;
} else { } else {
var savePicker = new Windows.Storage.Pickers.FileSavePicker(); var savePicker = new Windows.Storage.Pickers.FileSavePicker();
var saveFile = function(file) { var saveFile = function (file) {
if (file) { if (file) {
// Prevent updates to the remote version of the file until we're done // Prevent updates to the remote version of the file until we're done
Windows.Storage.CachedFileManager.deferUpdates(file); Windows.Storage.CachedFileManager.deferUpdates(file);
picture.moveAndReplaceAsync(file) picture.moveAndReplaceAsync(file)
.then(function() { .then(function () {
// Let Windows know that we're finished changing the file so // Let Windows know that we're finished changing the file so
// the other app can update the remote version of the file. // the other app can update the remote version of the file.
return Windows.Storage.CachedFileManager.completeUpdatesAsync(file); return Windows.Storage.CachedFileManager.completeUpdatesAsync(file);
}) })
.done(function(updateStatus) { .done(function (updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) { if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
success(picture); success(picture);
} else { } else {
errorCallback("File update status is not complete."); errorCallback('File update status is not complete.');
} }
}, errorCallback); }, errorCallback);
} else { } else {
errorCallback("Failed to select a file."); errorCallback('Failed to select a file.');
} }
}; };
savePicker.suggestedStartLocation = pickerLocId.picturesLibrary; savePicker.suggestedStartLocation = pickerLocId.picturesLibrary;
if (options.encodingType === Camera.EncodingType.PNG) { if (options.encodingType === Camera.EncodingType.PNG) {
savePicker.fileTypeChoices.insert("PNG", [".png"]); savePicker.fileTypeChoices.insert('PNG', ['.png']);
savePicker.suggestedFileName = "photo.png"; savePicker.suggestedFileName = 'photo.png';
} else { } else {
savePicker.fileTypeChoices.insert("JPEG", [".jpg"]); savePicker.fileTypeChoices.insert('JPEG', ['.jpg']);
savePicker.suggestedFileName = "photo.jpg"; savePicker.suggestedFileName = 'photo.jpg';
} }
// If Windows Phone 8.1 use pickSaveFileAndContinue() // If Windows Phone 8.1 use pickSaveFileAndContinue()
@ -863,14 +851,14 @@ function savePhoto(picture, options, successCallback, errorCallback) {
Using FileSavePicker will suspend the app and it's required to catch the pickSaveFileContinuation Using FileSavePicker will suspend the app and it's required to catch the pickSaveFileContinuation
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/ */
var fileSaveHandler = function(eventArgs) { var fileSaveHandler = function (eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) { if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
var file = eventArgs.file; var file = eventArgs.file;
saveFile(file); saveFile(file);
webUIApp.removeEventListener("activated", fileSaveHandler); webUIApp.removeEventListener('activated', fileSaveHandler);
} }
}; };
webUIApp.addEventListener("activated", fileSaveHandler); webUIApp.addEventListener('activated', fileSaveHandler);
savePicker.pickSaveFileAndContinue(); savePicker.pickSaveFileAndContinue();
} else { } else {
savePicker.pickSaveFileAsync() savePicker.pickSaveFileAsync()
@ -879,4 +867,4 @@ function savePhoto(picture, options, successCallback, errorCallback) {
} }
} }
require("cordova/exec/proxy").add("Camera",module.exports); require('cordova/exec/proxy').add('Camera', module.exports);

View File

@ -19,11 +19,11 @@
* *
*/ */
var argscheck = require('cordova/argscheck'), var argscheck = require('cordova/argscheck');
exec = require('cordova/exec'), var exec = require('cordova/exec');
Camera = require('./Camera'); var Camera = require('./Camera');
// XXX: commented out // XXX: commented out
//CameraPopoverHandle = require('./CameraPopoverHandle'); // CameraPopoverHandle = require('./CameraPopoverHandle');
/** /**
* @namespace navigator * @namespace navigator
@ -131,7 +131,7 @@ for (var key in Camera) {
* @param {module:camera.onError} errorCallback * @param {module:camera.onError} errorCallback
* @param {module:camera.CameraOptions} options CameraOptions * @param {module:camera.CameraOptions} options CameraOptions
*/ */
cameraExport.getPicture = function(successCallback, errorCallback, options) { cameraExport.getPicture = function (successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'Camera.getPicture', arguments); argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
options = options || {}; options = options || {};
var getValue = argscheck.getValue; var getValue = argscheck.getValue;
@ -150,11 +150,11 @@ cameraExport.getPicture = function(successCallback, errorCallback, options) {
var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK); var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType, var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection]; mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
exec(successCallback, errorCallback, "Camera", "takePicture", args); exec(successCallback, errorCallback, 'Camera', 'takePicture', args);
// XXX: commented out // XXX: commented out
//return new CameraPopoverHandle(); // return new CameraPopoverHandle();
}; };
/** /**
@ -178,8 +178,8 @@ cameraExport.getPicture = function(successCallback, errorCallback, options) {
* alert('Failed because: ' + message); * alert('Failed because: ' + message);
* } * }
*/ */
cameraExport.cleanup = function(successCallback, errorCallback) { cameraExport.cleanup = function (successCallback, errorCallback) {
exec(successCallback, errorCallback, "Camera", "cleanup", []); exec(successCallback, errorCallback, 'Camera', 'cleanup', []);
}; };
module.exports = cameraExport; module.exports = cameraExport;

View File

@ -23,79 +23,79 @@
* @module Camera * @module Camera
*/ */
module.exports = { module.exports = {
/** /**
* @description * @description
* Defines the output format of `Camera.getPicture` call. * Defines the output format of `Camera.getPicture` call.
* _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with * _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
* `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will * `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
* disable any image modifications (resize, quality change, cropping, etc.) due * disable any image modifications (resize, quality change, cropping, etc.) due
* to implementation specific. * to implementation specific.
* *
* @enum {number} * @enum {number}
*/ */
DestinationType:{ DestinationType: {
/** Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible */ /** Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible */
DATA_URL: 0, DATA_URL: 0,
/** Return file uri (content://media/external/images/media/2 for Android) */ /** Return file uri (content://media/external/images/media/2 for Android) */
FILE_URI: 1, FILE_URI: 1,
/** Return native uri (eg. asset-library://... for iOS) */ /** Return native uri (eg. asset-library://... for iOS) */
NATIVE_URI: 2 NATIVE_URI: 2
}, },
/** /**
* @enum {number} * @enum {number}
*/ */
EncodingType:{ EncodingType: {
/** Return JPEG encoded image */ /** Return JPEG encoded image */
JPEG: 0, JPEG: 0,
/** Return PNG encoded image */ /** Return PNG encoded image */
PNG: 1 PNG: 1
}, },
/** /**
* @enum {number} * @enum {number}
*/ */
MediaType:{ MediaType: {
/** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */ /** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */
PICTURE: 0, PICTURE: 0,
/** Allow selection of video only, ONLY RETURNS URL */ /** Allow selection of video only, ONLY RETURNS URL */
VIDEO: 1, VIDEO: 1,
/** Allow selection from all media types */ /** Allow selection from all media types */
ALLMEDIA : 2 ALLMEDIA: 2
}, },
/** /**
* @description * @description
* Defines the output format of `Camera.getPicture` call. * Defines the output format of `Camera.getPicture` call.
* _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` * _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
* along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality * along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
* change, cropping, etc.) due to implementation specific. * change, cropping, etc.) due to implementation specific.
* *
* @enum {number} * @enum {number}
*/ */
PictureSourceType:{ PictureSourceType: {
/** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */ /** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */
PHOTOLIBRARY : 0, PHOTOLIBRARY: 0,
/** Take picture from camera */ /** Take picture from camera */
CAMERA : 1, CAMERA: 1,
/** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */ /** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */
SAVEDPHOTOALBUM : 2 SAVEDPHOTOALBUM: 2
}, },
/** /**
* Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover. * Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
* @enum {number} * @enum {number}
*/ */
PopoverArrowDirection:{ PopoverArrowDirection: {
ARROW_UP : 1, ARROW_UP: 1,
ARROW_DOWN : 2, ARROW_DOWN: 2,
ARROW_LEFT : 4, ARROW_LEFT: 4,
ARROW_RIGHT : 8, ARROW_RIGHT: 8,
ARROW_ANY : 15 ARROW_ANY: 15
}, },
/** /**
* @enum {number} * @enum {number}
*/ */
Direction:{ Direction: {
/** Use the back-facing camera */ /** Use the back-facing camera */
BACK: 0, BACK: 0,
/** Use the front-facing camera */ /** Use the front-facing camera */
FRONT: 1 FRONT: 1
} }
}; };

View File

@ -23,8 +23,8 @@
* @ignore in favour of iOS' one * @ignore in favour of iOS' one
* A handle to an image picker popover. * A handle to an image picker popover.
*/ */
var CameraPopoverHandle = function() { var CameraPopoverHandle = function () {
this.setPosition = function(popoverOptions) { this.setPosition = function (popoverOptions) {
console.log('CameraPopoverHandle.setPosition is only supported on iOS.'); console.log('CameraPopoverHandle.setPosition is only supported on iOS.');
}; };
}; };

View File

@ -21,7 +21,7 @@
var Camera = require('./Camera'); var Camera = require('./Camera');
/** /**
* @namespace navigator * @namespace navigator
*/ */

View File

@ -25,9 +25,9 @@ document.addEventListener('DOMContentLoaded', function () {
window.navigator.webkitGetUserMedia( window.navigator.webkitGetUserMedia(
{ video: true }, { video: true },
function (stream) { function (stream) {
var video = document.getElementById('v'), var video = document.getElementById('v');
canvas = document.getElementById('c'), var canvas = document.getElementById('c');
camera = document.getElementById('camera'); var camera = document.getElementById('camera');
video.autoplay = true; video.autoplay = true;
video.width = window.innerWidth; video.width = window.innerWidth;
video.height = window.innerHeight - 100; video.height = window.innerHeight - 100;

View File

@ -48,7 +48,7 @@ var exec = require('cordova/exec');
* } * }
* @module CameraPopoverHandle * @module CameraPopoverHandle
*/ */
var CameraPopoverHandle = function() { var CameraPopoverHandle = function () {
/** /**
* Can be used to reposition the image selection dialog, * Can be used to reposition the image selection dialog,
* for example, when the device orientation changes. * for example, when the device orientation changes.
@ -57,9 +57,9 @@ var CameraPopoverHandle = function() {
* @method setPosition * @method setPosition
* @param {module:CameraPopoverOptions} popoverOptions * @param {module:CameraPopoverOptions} popoverOptions
*/ */
this.setPosition = function(popoverOptions) { this.setPosition = function (popoverOptions) {
var args = [ popoverOptions ]; var args = [ popoverOptions ];
exec(null, null, "Camera", "repositionPopover", args); exec(null, null, 'Camera', 'repositionPopover', args);
}; };
}; };