mirror of
https://github.com/apache/cordova-plugin-camera.git
synced 2026-02-03 00:06:46 +08:00
Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d456eeb711 | ||
|
|
f761934814 | ||
|
|
43b3a911c2 | ||
|
|
8f033f53db | ||
|
|
51d665a7a1 | ||
|
|
9f480b10cb | ||
|
|
a6706aef5f | ||
|
|
fb213b2b38 | ||
|
|
3e24b15934 | ||
|
|
2acda2d2f9 | ||
|
|
97d2014d62 | ||
|
|
b2107e0818 | ||
|
|
16c4325fef | ||
|
|
80342b0ddd | ||
|
|
55d419a36e | ||
|
|
5574490bc3 | ||
|
|
f1b0ccec56 | ||
|
|
e69240f251 | ||
|
|
5b3a99a6db | ||
|
|
3b8f64e330 | ||
|
|
f667ba6179 | ||
|
|
77539558e6 | ||
|
|
cba99940a7 | ||
|
|
7155b636d5 | ||
|
|
160ed2d03f | ||
|
|
c3d7e55ad4 | ||
|
|
1b218cd8a0 | ||
|
|
51e5c02dcb | ||
|
|
26d13b0245 | ||
|
|
ef617cc943 | ||
|
|
1422b0a4f2 | ||
|
|
ba9a803b69 | ||
|
|
9615620843 | ||
|
|
a33c35152e | ||
|
|
eb98015e8a | ||
|
|
3c48ea9c9c | ||
|
|
2286bb3bb2 | ||
|
|
9badea4c95 | ||
|
|
180f7b5510 | ||
|
|
d0b381aad8 | ||
|
|
926fbf0e8c | ||
|
|
e4ff41c07c |
28
.appveyor.yml
Normal file
28
.appveyor.yml
Normal file
@@ -0,0 +1,28 @@
|
||||
# appveyor file
|
||||
# http://www.appveyor.com/docs/appveyor-yml
|
||||
|
||||
max_jobs: 1
|
||||
|
||||
shallow_clone: true
|
||||
|
||||
init:
|
||||
- git config --global core.autocrlf true
|
||||
|
||||
image:
|
||||
- Visual Studio 2017
|
||||
|
||||
environment:
|
||||
nodejs_version: "4"
|
||||
matrix:
|
||||
- PLATFORM: windows-10-store
|
||||
JUST_BUILD: --justBuild
|
||||
install:
|
||||
- npm cache clean -f
|
||||
- node --version
|
||||
- npm install -g cordova-paramedic@https://github.com/apache/cordova-paramedic.git
|
||||
- npm install -g cordova
|
||||
|
||||
build: off
|
||||
|
||||
test_script:
|
||||
- cordova-paramedic --config pr\%PLATFORM% --plugin . %JUST_BUILD%
|
||||
10
.eslintrc.yml
Normal file
10
.eslintrc.yml
Normal 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
|
||||
16
.jshintrc
16
.jshintrc
@@ -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
|
||||
}
|
||||
}
|
||||
96
.travis.yml
96
.travis.yml
@@ -1,8 +1,92 @@
|
||||
language: objective-c
|
||||
sudo: false
|
||||
node_js:
|
||||
- "4.2"
|
||||
addons:
|
||||
jwt:
|
||||
secure: QivPLlqTVvOo3TJeHxuBOfxU6lho1I0IxQ3b68yntkEQQJko6kzleXHfgjf0a8aw8m38E3+fxaBWF1bGyucGwOLDWY8Ddt2P2xg44zdXH5EXHd9oIqAgngIdzLvUtH3Db2TbQEtIGOkrnNR2STovjqB7vHGLASQrgs4oL7r32/s=
|
||||
env:
|
||||
- TEST_DIR=.
|
||||
- TEST_DIR=./tests/ios
|
||||
script: cd $TEST_DIR && npm install && npm test
|
||||
global:
|
||||
- SAUCE_USERNAME=snay
|
||||
- TRAVIS_NODE_VERSION="4.2"
|
||||
matrix:
|
||||
include:
|
||||
- env: TEST_DIR=.
|
||||
language: objective-c
|
||||
- env: TEST_DIR=./tests/ios
|
||||
language: objective-c
|
||||
- env: PLATFORM=browser-chrome
|
||||
os: linux
|
||||
language: node_js
|
||||
node_js: '4.2'
|
||||
- env: PLATFORM=browser-firefox
|
||||
os: linux
|
||||
language: node_js
|
||||
node_js: '4.2'
|
||||
- env: PLATFORM=browser-safari
|
||||
os: linux
|
||||
language: node_js
|
||||
node_js: '4.2'
|
||||
- env: PLATFORM=browser-edge
|
||||
os: linux
|
||||
language: node_js
|
||||
node_js: '4.2'
|
||||
- env: PLATFORM=ios-9.3
|
||||
os: osx
|
||||
osx_image: xcode7.3
|
||||
language: node_js
|
||||
node_js: "4.2"
|
||||
- env: PLATFORM=ios-10.0
|
||||
os: osx
|
||||
osx_image: xcode7.3
|
||||
language: node_js
|
||||
node_js: "4.2"
|
||||
- env: PLATFORM=android-4.4
|
||||
os: linux
|
||||
language: android
|
||||
jdk: oraclejdk8
|
||||
android:
|
||||
components:
|
||||
- tools
|
||||
- extra-android-m2repository
|
||||
- env: PLATFORM=android-5.1
|
||||
os: linux
|
||||
language: android
|
||||
jdk: oraclejdk8
|
||||
android:
|
||||
components:
|
||||
- tools
|
||||
- extra-android-m2repository
|
||||
- env: PLATFORM=android-6.0
|
||||
os: linux
|
||||
language: android
|
||||
jdk: oraclejdk8
|
||||
android:
|
||||
components:
|
||||
- tools
|
||||
- extra-android-m2repository
|
||||
- env: PLATFORM=android-7.0
|
||||
os: linux
|
||||
language: android
|
||||
jdk: oraclejdk8
|
||||
android:
|
||||
components:
|
||||
- tools
|
||||
- extra-android-m2repository
|
||||
before_install:
|
||||
- rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION
|
||||
- node --version
|
||||
- if [[ "$PLATFORM" =~ android ]]; then gradle --version; fi
|
||||
- if [[ "$PLATFORM" =~ ios ]]; then npm install -g ios-deploy; fi
|
||||
- if [[ "$PLATFORM" =~ android ]]; then echo y | android update sdk -u --filter android-22,android-23,android-24,android-25,android-26;
|
||||
fi
|
||||
- git clone https://github.com/apache/cordova-paramedic /tmp/paramedic && pushd /tmp/paramedic
|
||||
&& npm install && popd
|
||||
- npm install -g cordova
|
||||
install:
|
||||
- npm install
|
||||
script:
|
||||
- if [[ "$TEST_DIR" != "" ]];
|
||||
then cd $TEST_DIR && npm install && npm test;
|
||||
else
|
||||
node /tmp/paramedic/main.js --config pr/$PLATFORM --plugin $(pwd) --shouldUseSauce
|
||||
--buildName travis-plugin-camera-$TRAVIS_JOB_NUMBER;
|
||||
fi
|
||||
|
||||
|
||||
47
README.md
47
README.md
@@ -21,9 +21,9 @@ description: Take pictures with the device camera.
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
|Android|iOS| Windows 8.1 Store | Windows 8.1 Phone | Windows 10 Store | Travis CI |
|
||||
|:-:|:-:|:-:|:-:|:-:|:-:|
|
||||
|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera/)|[](https://travis-ci.org/apache/cordova-plugin-camera)
|
||||
|AppVeyor|Travis CI|
|
||||
|:-:|:-:|
|
||||
|[](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-camera)|[](https://travis-ci.org/apache/cordova-plugin-camera)|
|
||||
|
||||
# cordova-plugin-camera
|
||||
|
||||
@@ -53,11 +53,11 @@ It is also possible to install via repo url directly ( unstable )
|
||||
|
||||
## How to Contribute
|
||||
|
||||
Contributors are welcome! And we need your contributions to keep the project moving forward. You can [report bugs](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC), improve the documentation, or [contribute code](https://github.com/apache/cordova-plugin-camera/pulls).
|
||||
Contributors are welcome! And we need your contributions to keep the project moving forward. You can [report bugs](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22cordova-plugin-camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC), improve the documentation, or [contribute code](https://github.com/apache/cordova-plugin-camera/pulls).
|
||||
|
||||
There is a specific [contributor workflow](http://wiki.apache.org/cordova/ContributorWorkflow) we recommend. Start reading there. More information is available on [our wiki](http://wiki.apache.org/cordova).
|
||||
|
||||
:warning: **Found an issue?** File it on [JIRA issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC).
|
||||
:warning: **Found an issue?** File it on [JIRA issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22cordova-plugin-camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC).
|
||||
|
||||
**Have a solution?** Send a [Pull Request](https://github.com/apache/cordova-plugin-camera/pulls).
|
||||
|
||||
@@ -76,23 +76,40 @@ Documentation consists of template and API docs produced from the plugin JS code
|
||||
|
||||
### iOS Quirks
|
||||
|
||||
Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist.
|
||||
Since iOS 10 it's mandatory to provide an usage description in the `info.plist` if trying to access privacy-sensitive data. When the system prompts the user to allow access, this usage description string will displayed as part of the permission dialog box, but if you didn't provide the usage description, the app will crash before showing the dialog. Also, Apple will reject apps that access private data but don't provide an usage description.
|
||||
|
||||
- `NSCameraUsageDescription` describes the reason that the app accesses the user’s camera.
|
||||
- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library.
|
||||
This plugins requires the following usage descriptions:
|
||||
|
||||
When the system prompts the user to allow access, this string is displayed as part of the dialog box.
|
||||
- `NSCameraUsageDescription` specifies the reason for your app to access the device's camera.
|
||||
- `NSPhotoLibraryUsageDescription` specifies the reason for your app to access the user's photo library.
|
||||
- `NSLocationWhenInUseUsageDescription` specifies the reason for your app to access the user's location information while your app is in use. (Set it if you have `CameraUsesGeolocation` preference set to `true`)
|
||||
- `NSPhotoLibraryAddUsageDescription` specifies the reason for your app to get write-only access to the user's photo library
|
||||
|
||||
To add this entry you can pass the following variables on plugin install.
|
||||
To add these entries into the `info.plist`, you can use the `edit-config` tag in the `config.xml` like this:
|
||||
|
||||
- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription`
|
||||
- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription`
|
||||
```
|
||||
<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need camera access to take pictures</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
Example:
|
||||
```
|
||||
<edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need to photo library access to get pictures from there</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
|
||||
```
|
||||
<edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need location access to find things nearby</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
If you don't pass the variable, the plugin will add an empty string as value.
|
||||
```
|
||||
<edit-config target="NSPhotoLibraryAddUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need to photo library access to save pictures there</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -20,6 +20,33 @@
|
||||
-->
|
||||
# Release Notes
|
||||
|
||||
### 3.0.0 (Nov 06, 2017)
|
||||
* Added `cordova-OSX` support
|
||||
* [CB-13515](https://issues.apache.org/jira/browse/CB-13515) (all): Add 'protective' entry to `cordovaDependencies`
|
||||
* [CB-13332](https://issues.apache.org/jira/browse/CB-13332) (iOS): document `NSPhotoLibraryAddUsageDescription`
|
||||
* [CB-13264](https://issues.apache.org/jira/browse/CB-13264) (iOS): Remove **iOS** usage descriptions
|
||||
* [CB-13473](https://issues.apache.org/jira/browse/CB-13473) (CI) Removed **Browser** builds from AppVeyor
|
||||
* [CB-13446](https://issues.apache.org/jira/browse/CB-13446) Sync template with previous doc changes
|
||||
* [CB-13294](https://issues.apache.org/jira/browse/CB-13294) Removed `cordova-plugin-compat`
|
||||
* [CB-13299](https://issues.apache.org/jira/browse/CB-13299) (CI) Fix **Android** builds
|
||||
* [CB-12985](https://issues.apache.org/jira/browse/CB-12985) setup `eslint` and removed `jshint`
|
||||
* [CB-13028](https://issues.apache.org/jira/browse/CB-13028) (CI) **Browser** builds on Travis and AppVeyor
|
||||
* [CB-13002](https://issues.apache.org/jira/browse/CB-13002) (Android, **iOS**) Fix occasional Appium tests failures
|
||||
* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds
|
||||
* [CB-12991](https://issues.apache.org/jira/browse/CB-12991) (CI) Updated CI badges
|
||||
* [CB-12964](https://issues.apache.org/jira/browse/CB-12964) (android) Fix of bug when Pictures folder did not exist.
|
||||
* [CB-12982](https://issues.apache.org/jira/browse/CB-12982) (Android, **iOS**) Appium tests: try to create a session harder
|
||||
* [CB-12682](https://issues.apache.org/jira/browse/CB-12682) (ios, **Android**): changes cancel error message to be consistent for **iOS** **Android**
|
||||
* [CB-12764](https://issues.apache.org/jira/browse/CB-12764) (android) Adapt Appium tests for **Android** 7
|
||||
* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`.
|
||||
|
||||
### 2.4.1 (Apr 27, 2017)
|
||||
* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Updated build badges in `README`
|
||||
* [CB-12650](https://issues.apache.org/jira/browse/CB-12650) Fix manual test for uploading image
|
||||
* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder
|
||||
* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) (android) Appium tests: Bust **Android** 6 and 7 permission dialogs
|
||||
* [CB-12618](https://issues.apache.org/jira/browse/CB-12618) (android) Appium tests: Handle native cling
|
||||
|
||||
### 2.4.0 (Feb 28, 2017)
|
||||
* [CB-12501](https://issues.apache.org/jira/browse/CB-12501) **Android**: Appium tests don't use `XPath` selectors anymore
|
||||
* [CB-12469](https://issues.apache.org/jira/browse/CB-12469) Appium tests can now run on **iOS 10**
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
/*jshint node: true, jasmine: true */
|
||||
|
||||
/*
|
||||
*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
@@ -63,6 +61,17 @@ describe('Camera tests Android.', function () {
|
||||
var isResolutionBad = true;
|
||||
// a path to the image we add to the gallery before test run
|
||||
var fillerImagePath;
|
||||
var isAndroid7 = getIsAndroid7();
|
||||
|
||||
function getIsAndroid7() {
|
||||
if (global.USE_SAUCE) {
|
||||
return global.SAUCE_CAPS && (parseFloat(global.SAUCE_CAPS.platformVersion) >= 7);
|
||||
} else {
|
||||
// this is most likely null, meaning we cannot determine if it is Android 7 or not
|
||||
// paramedic needs to be modified to receive and pass the platform version when testing locally
|
||||
return global.PLATFORM_VERSION && (parseFloat(global.PLATFORM_VERSION) >= 7);
|
||||
}
|
||||
}
|
||||
|
||||
function getNextPromiseId() {
|
||||
promiseCount += 1;
|
||||
@@ -104,6 +113,16 @@ describe('Camera tests Android.', function () {
|
||||
if (!options) {
|
||||
options = {};
|
||||
}
|
||||
// assign default values
|
||||
if (!options.hasOwnProperty('allowEdit')) {
|
||||
options.allowEdit = true;
|
||||
}
|
||||
if (!options.hasOwnProperty('destinationType')) {
|
||||
options.destinationType = cameraConstants.DestinationType.FILE_URI;
|
||||
}
|
||||
if (!options.hasOwnProperty('sourceType')) {
|
||||
options.destinationType = cameraConstants.PictureSourceType.CAMERA;
|
||||
}
|
||||
|
||||
return driver
|
||||
.context(webviewContext)
|
||||
@@ -155,15 +174,34 @@ describe('Camera tests Android.', function () {
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*shutter.*")', MINUTE / 2)
|
||||
.click()
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*done.*")', MINUTE / 2)
|
||||
.click();
|
||||
.click()
|
||||
.then(function () {
|
||||
if (isAndroid7 && options.allowEdit) {
|
||||
return driver
|
||||
.elementByAndroidUIAutomator('new UiSelector().text("Crop picture");', 20000)
|
||||
.click()
|
||||
.fail(function () {
|
||||
// don't freak out just yet...
|
||||
return driver;
|
||||
})
|
||||
.elementByAndroidUIAutomator('new UiSelector().text("JUST ONCE");', 20000)
|
||||
.click()
|
||||
.fail(function () {
|
||||
// maybe someone's hit that "ALWAYS" button?
|
||||
return driver;
|
||||
});
|
||||
}
|
||||
return driver;
|
||||
});
|
||||
})
|
||||
.then(function () {
|
||||
if (skipUiInteractions) {
|
||||
return;
|
||||
}
|
||||
if (options.allowEdit) {
|
||||
var saveText = isAndroid7 ? 'SAVE' : 'Save';
|
||||
return driver
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().text("Save")', MINUTE)
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().text("' + saveText + '")', MINUTE)
|
||||
.click();
|
||||
}
|
||||
})
|
||||
@@ -181,7 +219,7 @@ describe('Camera tests Android.', function () {
|
||||
return driver
|
||||
.context(webviewContext)
|
||||
.setAsyncScriptTimeout(MINUTE / 2)
|
||||
.executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options])
|
||||
.executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options, isAndroid7])
|
||||
.then(function (result) {
|
||||
if (shouldLoad) {
|
||||
if (result !== 'OK') {
|
||||
@@ -225,6 +263,40 @@ describe('Camera tests Android.', function () {
|
||||
})
|
||||
.waitForDeviceReady()
|
||||
.injectLibraries()
|
||||
.then(function () {
|
||||
var options = {
|
||||
quality: 50,
|
||||
allowEdit: false,
|
||||
sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM,
|
||||
saveToPhotoAlbum: false,
|
||||
targetWidth: 210,
|
||||
targetHeight: 210
|
||||
};
|
||||
return driver
|
||||
.then(function () { return getPicture(options, true); })
|
||||
.context(CONTEXT_NATIVE_APP)
|
||||
// case insensitive select, will be handy with Android 7 support
|
||||
.elementByXPath('//android.widget.Button[translate(@text, "alow", "ALOW")="ALLOW"]')
|
||||
.click()
|
||||
.fail(function noAlert() { })
|
||||
.deviceKeyEvent(BACK_BUTTON)
|
||||
.sleep(2000)
|
||||
.elementById('action_bar_title')
|
||||
.then(function () {
|
||||
// success means we're still in native app
|
||||
return driver
|
||||
.deviceKeyEvent(BACK_BUTTON);
|
||||
}, function () {
|
||||
// error means we're already in webview
|
||||
return driver;
|
||||
});
|
||||
})
|
||||
.then(function () {
|
||||
// doing it inside a function because otherwise
|
||||
// it would not hook up to the webviewContext var change
|
||||
// in the first methods of this chain
|
||||
return driver.context(webviewContext);
|
||||
})
|
||||
.deleteFillerImage(fillerImagePath)
|
||||
.then(function () {
|
||||
fillerImagePath = null;
|
||||
@@ -286,11 +358,17 @@ describe('Camera tests Android.', function () {
|
||||
}
|
||||
}
|
||||
|
||||
function checkCamera(pending) {
|
||||
function checkCamera(options, pending) {
|
||||
if (!cameraAvailable) {
|
||||
pending('This test requires a functioning camera on the Android device/emulator, and this test suite\'s functional camera test failed on your target environment.');
|
||||
pending('Skipping because this test requires a functioning camera on the Android device/emulator, and this test suite\'s functional camera test failed on your target environment.');
|
||||
} else if (isAndroid7 && options.allowEdit) {
|
||||
// TODO: Check if it is fixed some day
|
||||
pending('Skipping because can\'t test with allowEdit=true on Android 7: getting unexpected "Camera cancelled" message.');
|
||||
} else if (isAndroid7 && (options.sourceType !== cameraConstants.PictureSourceType.CAMERA)) {
|
||||
pending('Skipping because can\'t click on the gallery tile on Android 7.');
|
||||
}
|
||||
}
|
||||
|
||||
afterAll(function (done) {
|
||||
checkSession(done);
|
||||
driver
|
||||
@@ -299,12 +377,20 @@ describe('Camera tests Android.', function () {
|
||||
}, MINUTE);
|
||||
|
||||
it('camera.ui.util configuring driver and starting a session', function (done) {
|
||||
// retry up to 3 times
|
||||
getDriver()
|
||||
.fail(function () {
|
||||
return getDriver()
|
||||
.fail(function () {
|
||||
return getDriver()
|
||||
.fail(fail);
|
||||
});
|
||||
})
|
||||
.then(function () {
|
||||
appiumSessionStarted = true;
|
||||
}, fail)
|
||||
})
|
||||
.done(done);
|
||||
}, 10 * MINUTE);
|
||||
}, 30 * MINUTE);
|
||||
|
||||
it('camera.ui.util determine screen dimensions', function (done) {
|
||||
checkSession(done, /*skipResolutionCheck?*/ true); // skip the resolution check here since we are about to find out in this spec!
|
||||
@@ -346,15 +432,16 @@ describe('Camera tests Android.', function () {
|
||||
describe('Specs.', function () {
|
||||
// getPicture() with saveToPhotoLibrary = true
|
||||
it('camera.ui.spec.1 Saving a picture to the photo library', function (done) {
|
||||
checkSession(done);
|
||||
checkCamera(pending);
|
||||
var spec = generateSpec({
|
||||
var opts = {
|
||||
quality: 50,
|
||||
allowEdit: false,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
saveToPhotoAlbum: true
|
||||
});
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(opts, pending);
|
||||
|
||||
var spec = generateSpec(opts);
|
||||
tryRunSpec(spec)
|
||||
.then(function () {
|
||||
isTestPictureSaved = true;
|
||||
@@ -386,11 +473,12 @@ describe('Camera tests Android.', function () {
|
||||
})
|
||||
.then(function () {
|
||||
// if the gallery is opened on the videos page,
|
||||
// there should be a "Choose video" caption
|
||||
// there should be a "Choose video" or "Select video" caption
|
||||
var videoSelector = isAndroid7 ? 'new UiSelector().text("Select video")' : 'new UiSelector().text("Choose video")';
|
||||
return driver
|
||||
.elementByAndroidUIAutomator('new UiSelector().text("Choose video")')
|
||||
.elementByAndroidUIAutomator(videoSelector)
|
||||
.fail(function () {
|
||||
throw 'Couldn\'t find "Choose video" element.';
|
||||
throw 'Couldn\'t find a "Choose/select video" element.';
|
||||
});
|
||||
})
|
||||
.deviceKeyEvent(BACK_BUTTON)
|
||||
@@ -428,15 +516,15 @@ describe('Camera tests Android.', function () {
|
||||
// getPicture(), then dismiss
|
||||
// wait for the error callback to be called
|
||||
it('camera.ui.spec.3 Dismissing the camera', function (done) {
|
||||
var options = {
|
||||
quality: 50,
|
||||
allowEdit: true,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
destinationType: cameraConstants.DestinationType.FILE_URI
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(pending);
|
||||
checkCamera(options, pending);
|
||||
var spec = function () {
|
||||
var options = {
|
||||
quality: 50,
|
||||
allowEdit: true,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
destinationType: cameraConstants.DestinationType.FILE_URI
|
||||
};
|
||||
return driver
|
||||
.then(function () {
|
||||
return getPicture(options, true);
|
||||
@@ -455,15 +543,15 @@ describe('Camera tests Android.', function () {
|
||||
// getPicture(), then take picture but dismiss the edit
|
||||
// wait for the error callback to be called
|
||||
it('camera.ui.spec.4 Dismissing the edit', function (done) {
|
||||
var options = {
|
||||
quality: 50,
|
||||
allowEdit: true,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
destinationType: cameraConstants.DestinationType.FILE_URI
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(pending);
|
||||
checkCamera(options, pending);
|
||||
var spec = function () {
|
||||
var options = {
|
||||
quality: 50,
|
||||
allowEdit: true,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
destinationType: cameraConstants.DestinationType.FILE_URI
|
||||
};
|
||||
return driver
|
||||
.then(function () {
|
||||
return getPicture(options, true);
|
||||
@@ -472,8 +560,19 @@ describe('Camera tests Android.', function () {
|
||||
.click()
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*done.*")', MINUTE / 2)
|
||||
.click()
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*discard.*")', MINUTE / 2)
|
||||
.click()
|
||||
.then(function () {
|
||||
if (isAndroid7 && options.allowEdit) {
|
||||
return driver
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().text("Crop picture");', 20000)
|
||||
.click()
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().text("JUST ONCE");', 20000)
|
||||
.click()
|
||||
.deviceKeyEvent(BACK_BUTTON);
|
||||
}
|
||||
return driver
|
||||
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*discard.*")', MINUTE / 2)
|
||||
.click();
|
||||
})
|
||||
.then(function () {
|
||||
return checkPicture(false);
|
||||
});
|
||||
@@ -483,53 +582,56 @@ describe('Camera tests Android.', function () {
|
||||
}, 10 * MINUTE);
|
||||
|
||||
it('camera.ui.spec.5 Verifying target image size, sourceType=CAMERA', function (done) {
|
||||
checkSession(done);
|
||||
checkCamera(pending);
|
||||
var spec = generateSpec({
|
||||
var opts = {
|
||||
quality: 50,
|
||||
allowEdit: false,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
saveToPhotoAlbum: false,
|
||||
targetWidth: 210,
|
||||
targetHeight: 210
|
||||
});
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(opts, pending);
|
||||
var spec = generateSpec(opts);
|
||||
|
||||
tryRunSpec(spec).done(done);
|
||||
}, 10 * MINUTE);
|
||||
|
||||
it('camera.ui.spec.6 Verifying target image size, sourceType=PHOTOLIBRARY', function (done) {
|
||||
checkSession(done);
|
||||
var spec = generateSpec({
|
||||
var opts = {
|
||||
quality: 50,
|
||||
allowEdit: false,
|
||||
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
|
||||
saveToPhotoAlbum: false,
|
||||
targetWidth: 210,
|
||||
targetHeight: 210
|
||||
});
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(opts, pending);
|
||||
var spec = generateSpec(opts);
|
||||
|
||||
tryRunSpec(spec).done(done);
|
||||
}, 10 * MINUTE);
|
||||
|
||||
it('camera.ui.spec.7 Verifying target image size, sourceType=CAMERA, DestinationType=NATIVE_URI', function (done) {
|
||||
checkSession(done);
|
||||
checkCamera(pending);
|
||||
var spec = generateSpec({
|
||||
var opts = {
|
||||
quality: 50,
|
||||
allowEdit: false,
|
||||
allowEdit: true,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
destinationType: cameraConstants.DestinationType.NATIVE_URI,
|
||||
saveToPhotoAlbum: false,
|
||||
targetWidth: 210,
|
||||
targetHeight: 210
|
||||
});
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(opts, pending);
|
||||
var spec = generateSpec(opts);
|
||||
|
||||
tryRunSpec(spec).done(done);
|
||||
}, 10 * MINUTE);
|
||||
|
||||
it('camera.ui.spec.8 Verifying target image size, sourceType=PHOTOLIBRARY, DestinationType=NATIVE_URI', function (done) {
|
||||
checkSession(done);
|
||||
var spec = generateSpec({
|
||||
var opts = {
|
||||
quality: 50,
|
||||
allowEdit: false,
|
||||
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
|
||||
@@ -537,30 +639,33 @@ describe('Camera tests Android.', function () {
|
||||
saveToPhotoAlbum: false,
|
||||
targetWidth: 210,
|
||||
targetHeight: 210
|
||||
});
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(opts, pending);
|
||||
|
||||
var spec = generateSpec(opts);
|
||||
tryRunSpec(spec).done(done);
|
||||
}, 10 * MINUTE);
|
||||
|
||||
it('camera.ui.spec.9 Verifying target image size, sourceType=CAMERA, DestinationType=NATIVE_URI, quality=100', function (done) {
|
||||
checkSession(done);
|
||||
checkCamera(pending);
|
||||
var spec = generateSpec({
|
||||
quality: 100,
|
||||
var opts = {
|
||||
quality: 50,
|
||||
allowEdit: true,
|
||||
sourceType: cameraConstants.PictureSourceType.CAMERA,
|
||||
destinationType: cameraConstants.DestinationType.NATIVE_URI,
|
||||
saveToPhotoAlbum: false,
|
||||
targetWidth: 305,
|
||||
targetHeight: 305
|
||||
});
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(opts, pending);
|
||||
var spec = generateSpec(opts);
|
||||
|
||||
tryRunSpec(spec).done(done);
|
||||
}, 10 * MINUTE);
|
||||
|
||||
it('camera.ui.spec.10 Verifying target image size, sourceType=PHOTOLIBRARY, DestinationType=NATIVE_URI, quality=100', function (done) {
|
||||
checkSession(done);
|
||||
var spec = generateSpec({
|
||||
var opts = {
|
||||
quality: 100,
|
||||
allowEdit: true,
|
||||
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
|
||||
@@ -568,7 +673,10 @@ describe('Camera tests Android.', function () {
|
||||
saveToPhotoAlbum: false,
|
||||
targetWidth: 305,
|
||||
targetHeight: 305
|
||||
});
|
||||
};
|
||||
checkSession(done);
|
||||
checkCamera(opts, pending);
|
||||
var spec = generateSpec(opts);
|
||||
|
||||
tryRunSpec(spec).done(done);
|
||||
}, 10 * MINUTE);
|
||||
@@ -577,15 +685,17 @@ describe('Camera tests Android.', function () {
|
||||
generateOptions().forEach(function (spec) {
|
||||
it('camera.ui.spec.11.' + spec.id + ' Combining options. ' + spec.description, function (done) {
|
||||
checkSession(done);
|
||||
if (spec.options.sourceType == cameraConstants.PictureSourceType.CAMERA) {
|
||||
checkCamera(pending);
|
||||
}
|
||||
checkCamera(spec.options, pending);
|
||||
|
||||
var s = generateSpec(spec.options);
|
||||
tryRunSpec(s).done(done);
|
||||
}, 10 * MINUTE);
|
||||
});
|
||||
|
||||
it('camera.ui.util Delete filler picture from device library', function (done) {
|
||||
if (isAndroid7 || global.USE_SAUCE) {
|
||||
pending();
|
||||
}
|
||||
driver
|
||||
.context(webviewContext)
|
||||
.deleteFillerImage(fillerImagePath)
|
||||
@@ -593,6 +703,9 @@ describe('Camera tests Android.', function () {
|
||||
}, MINUTE);
|
||||
|
||||
it('camera.ui.util Delete taken picture from device library', function (done) {
|
||||
if (isAndroid7 || global.USE_SAUCE) {
|
||||
pending();
|
||||
}
|
||||
checkSession(done);
|
||||
if (!isTestPictureSaved) {
|
||||
// couldn't save test picture earlier, so nothing to delete here
|
||||
@@ -610,6 +723,15 @@ describe('Camera tests Android.', function () {
|
||||
.deviceKeyEvent(BACK_BUTTON)
|
||||
.elementById('Apps')
|
||||
.click()
|
||||
.then(function () {
|
||||
return driver
|
||||
.elementByXPath('//android.widget.Button[@text="OK"]')
|
||||
.click()
|
||||
.fail(function () {
|
||||
// no cling is all right
|
||||
// it is not a brand new emulator, then
|
||||
});
|
||||
})
|
||||
.elementByAndroidUIAutomator('new UiSelector().text("Gallery")')
|
||||
.click()
|
||||
.elementByAndroidUIAutomator('new UiSelector().textContains("Pictures")')
|
||||
@@ -626,3 +748,4 @@ describe('Camera tests Android.', function () {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/*jshint node: true */
|
||||
/* global Q, resolveLocalFileSystemURL, Camera, cordova */
|
||||
/*
|
||||
*
|
||||
@@ -114,7 +113,7 @@ module.exports.getPicture = function (opts, pid) {
|
||||
// calls a callback with 'ERROR: <error message>' if something is wrong
|
||||
// note that this function is executed in the context of tested app
|
||||
// and not in the context of tests
|
||||
module.exports.checkPicture = function (pid, options, cb) {
|
||||
module.exports.checkPicture = function (pid, options, skipContentCheck, cb) {
|
||||
var isIos = cordova.platformId === "ios";
|
||||
var isAndroid = cordova.platformId === "android";
|
||||
// skip image type check if it's unmodified on Android:
|
||||
@@ -169,6 +168,7 @@ module.exports.checkPicture = function (pid, options, cb) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (result.indexOf('file:') === 0 ||
|
||||
result.indexOf('content:') === 0 ||
|
||||
@@ -178,12 +178,18 @@ module.exports.checkPicture = function (pid, options, cb) {
|
||||
errorCallback('Cannot read file. Please install cordova-plugin-file to fix this.');
|
||||
return;
|
||||
}
|
||||
if (skipContentCheck) {
|
||||
cb('OK');
|
||||
return;
|
||||
}
|
||||
resolveLocalFileSystemURL(result, function (entry) {
|
||||
if (skipFileTypeCheck) {
|
||||
displayFile(entry);
|
||||
} else {
|
||||
verifyFile(entry);
|
||||
}
|
||||
}, function (err) {
|
||||
errorCallback(err);
|
||||
});
|
||||
} else {
|
||||
displayImage(result);
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
/*jshint node: true, jasmine: true */
|
||||
|
||||
/*
|
||||
*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
@@ -81,18 +79,18 @@ describe('Camera tests iOS.', function () {
|
||||
return cameraHelper.generateSpecs(sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions);
|
||||
}
|
||||
|
||||
function usePicture() {
|
||||
function usePicture(allowEdit) {
|
||||
return driver
|
||||
.elementByXPath('//*[@label="Use"]')
|
||||
.click()
|
||||
.fail(function () {
|
||||
.sleep(10)
|
||||
.then(function () {
|
||||
if (isXCUI) {
|
||||
return driver
|
||||
.waitForElementByAccessibilityId('Choose', MINUTE / 3)
|
||||
.click();
|
||||
return driver.waitForElementByAccessibilityId('Choose', MINUTE / 3).click();
|
||||
} else {
|
||||
if (allowEdit) {
|
||||
return wdHelper.tapElementByXPath('//UIAButton[@label="Choose"]', driver);
|
||||
}
|
||||
return driver.elementByXPath('//*[@label="Use"]').click();
|
||||
}
|
||||
// For some reason "Choose" element is not clickable by standard Appium methods on iOS <= 9
|
||||
return wdHelper.tapElementByXPath('//UIAButton[@label="Choose"]', driver);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -128,6 +126,16 @@ describe('Camera tests iOS.', function () {
|
||||
if (!options) {
|
||||
options = {};
|
||||
}
|
||||
// assign defaults
|
||||
if (!options.hasOwnProperty('allowEdit')) {
|
||||
options.allowEdit = true;
|
||||
}
|
||||
if (!options.hasOwnProperty('destinationType')) {
|
||||
options.destinationType = cameraConstants.DestinationType.FILE_URI;
|
||||
}
|
||||
if (!options.hasOwnProperty('sourceType')) {
|
||||
options.destinationType = cameraConstants.PictureSourceType.CAMERA;
|
||||
}
|
||||
|
||||
return driver
|
||||
.context(webviewContext)
|
||||
@@ -148,7 +156,7 @@ describe('Camera tests iOS.', function () {
|
||||
if (!options.allowEdit) {
|
||||
return driver;
|
||||
}
|
||||
return usePicture();
|
||||
return usePicture(options.allowEdit);
|
||||
});
|
||||
}
|
||||
if (options.hasOwnProperty('sourceType') && options.sourceType === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM) {
|
||||
@@ -157,7 +165,7 @@ describe('Camera tests iOS.', function () {
|
||||
if (!options.allowEdit) {
|
||||
return driver;
|
||||
}
|
||||
return usePicture();
|
||||
return usePicture(options.allowEdit);
|
||||
});
|
||||
}
|
||||
if (cancelCamera) {
|
||||
@@ -183,7 +191,7 @@ describe('Camera tests iOS.', function () {
|
||||
return driver
|
||||
.context(webviewContext)
|
||||
.setAsyncScriptTimeout(MINUTE / 2)
|
||||
.executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options])
|
||||
.executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options, false])
|
||||
.then(function (result) {
|
||||
if (shouldLoad) {
|
||||
if (result !== 'OK') {
|
||||
@@ -273,14 +281,22 @@ describe('Camera tests iOS.', function () {
|
||||
}
|
||||
|
||||
it('camera.ui.util configure driver and start a session', function (done) {
|
||||
// retry up to 3 times
|
||||
getDriver()
|
||||
.fail(function () {
|
||||
return getDriver()
|
||||
.fail(function () {
|
||||
return getDriver()
|
||||
.fail(fail);
|
||||
});
|
||||
})
|
||||
.fail(fail)
|
||||
.done(done);
|
||||
}, 15 * MINUTE);
|
||||
}, 30 * MINUTE);
|
||||
|
||||
describe('Specs.', function () {
|
||||
afterEach(function (done) {
|
||||
if (specsRun >= 15) {
|
||||
if (specsRun >= 19) {
|
||||
specsRun = 0;
|
||||
// we need to restart the session regularly because for some reason
|
||||
// when running against iOS 10 simulator on SauceLabs,
|
||||
@@ -291,13 +307,20 @@ describe('Camera tests iOS.', function () {
|
||||
return driver
|
||||
.quit()
|
||||
.then(function () {
|
||||
return getDriver();
|
||||
return getDriver()
|
||||
.fail(function () {
|
||||
return getDriver()
|
||||
.fail(function () {
|
||||
return getDriver()
|
||||
.fail(fail);
|
||||
});
|
||||
});
|
||||
})
|
||||
.done(done);
|
||||
} else {
|
||||
done();
|
||||
}
|
||||
}, 15 * MINUTE);
|
||||
}, 30 * MINUTE);
|
||||
|
||||
// getPicture() with mediaType: VIDEO, sourceType: PHOTOLIBRARY
|
||||
it('camera.ui.spec.1 Selecting only videos', function (done) {
|
||||
|
||||
@@ -4,37 +4,54 @@ description: Take pictures with the device camera.
|
||||
---
|
||||
{{>cdv-license~}}
|
||||
|
||||
|Android|iOS| Windows 8.1 Store | Windows 8.1 Phone | Windows 10 Store | Travis CI |
|
||||
|:-:|:-:|:-:|:-:|:-:|:-:|
|
||||
|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera/)|[](https://travis-ci.org/apache/cordova-plugin-camera)
|
||||
|AppVeyor|Travis CI|
|
||||
|:-:|:-:|
|
||||
|[](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-camera)|[](https://travis-ci.org/apache/cordova-plugin-camera)|
|
||||
|
||||
# cordova-plugin-camera
|
||||
|
||||
This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from
|
||||
the system's image library.
|
||||
|
||||
{{>cdv-header device-ready-warning-obj='navigator.camera' npmName='cordova-plugin-camera' cprName='org.apache.cordova.camera' pluginName='Plugin Camera' repoUrl='https://github.com/apache/cordova-plugin-camera' }}
|
||||
{{>cdv-header device-ready-warning-obj='navigator.camera' npmName='cordova-plugin-camera' cprName='org.apache.cordova.camera' pluginName='cordova-plugin-camera' repoUrl='https://github.com/apache/cordova-plugin-camera' }}
|
||||
|
||||
|
||||
### iOS Quirks
|
||||
|
||||
Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist.
|
||||
Since iOS 10 it's mandatory to provide an usage description in the `info.plist` if trying to access privacy-sensitive data. When the system prompts the user to allow access, this usage description string will displayed as part of the permission dialog box, but if you didn't provide the usage description, the app will crash before showing the dialog. Also, Apple will reject apps that access private data but don't provide an usage description.
|
||||
|
||||
- `NSCameraUsageDescription` describes the reason that the app accesses the user’s camera.
|
||||
- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library.
|
||||
This plugins requires the following usage descriptions:
|
||||
|
||||
When the system prompts the user to allow access, this string is displayed as part of the dialog box.
|
||||
- `NSCameraUsageDescription` specifies the reason for your app to access the device's camera.
|
||||
- `NSPhotoLibraryUsageDescription` specifies the reason for your app to access the user's photo library.
|
||||
- `NSLocationWhenInUseUsageDescription` specifies the reason for your app to access the user's location information while your app is in use. (Set it if you have `CameraUsesGeolocation` preference set to `true`)
|
||||
- `NSPhotoLibraryAddUsageDescription` specifies the reason for your app to get write-only access to the user's photo library
|
||||
|
||||
To add this entry you can pass the following variables on plugin install.
|
||||
To add these entries into the `info.plist`, you can use the `edit-config` tag in the `config.xml` like this:
|
||||
|
||||
- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription`
|
||||
- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription`
|
||||
```
|
||||
<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need camera access to take pictures</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
Example:
|
||||
```
|
||||
<edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need to photo library access to get pictures from there</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
|
||||
```
|
||||
<edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need location access to find things nearby</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
If you don't pass the variable, the plugin will add an empty string as value.
|
||||
```
|
||||
<edit-config target="NSPhotoLibraryAddUsageDescription" file="*-Info.plist" mode="merge">
|
||||
<string>need to photo library access to save pictures there</string>
|
||||
</edit-config>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
28
package.json
28
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cordova-plugin-camera",
|
||||
"version": "2.4.0",
|
||||
"version": "3.0.0",
|
||||
"description": "Cordova Camera Plugin",
|
||||
"types": "./types/index.d.ts",
|
||||
"cordova": {
|
||||
@@ -16,13 +16,17 @@
|
||||
"wp8",
|
||||
"windows8",
|
||||
"browser",
|
||||
"windows"
|
||||
"windows",
|
||||
"osx"
|
||||
]
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/apache/cordova-plugin-camera"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://issues.apache.org/jira/browse/CB"
|
||||
},
|
||||
"keywords": [
|
||||
"cordova",
|
||||
"camera",
|
||||
@@ -37,27 +41,37 @@
|
||||
"cordova-wp8",
|
||||
"cordova-windows8",
|
||||
"cordova-browser",
|
||||
"cordova-windows"
|
||||
"cordova-windows",
|
||||
"cordova-osx"
|
||||
],
|
||||
"scripts": {
|
||||
"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",
|
||||
"test": "npm run jshint",
|
||||
"jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests"
|
||||
"test": "npm run eslint",
|
||||
"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",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"cordovaDependencies": {
|
||||
"3.0.0": {
|
||||
"cordova-android": ">=6.3.0"
|
||||
},
|
||||
"4.0.0": {
|
||||
"cordova": ">100"
|
||||
}
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"dmd-plugin-cordova-plugin": "^0.1.0",
|
||||
"eslint": "^4.3.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",
|
||||
"jsdoc-to-markdown": "^1.2.0",
|
||||
"jshint": "^2.6.0"
|
||||
"jsdoc-to-markdown": "^1.2.0"
|
||||
}
|
||||
}
|
||||
|
||||
39
plugin.xml
39
plugin.xml
@@ -22,7 +22,7 @@
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:rim="http://www.blackberry.com/ns/widgets"
|
||||
id="cordova-plugin-camera"
|
||||
version="2.4.0">
|
||||
version="3.0.0">
|
||||
<name>Camera</name>
|
||||
<description>Cordova Camera Plugin</description>
|
||||
<license>Apache 2.0</license>
|
||||
@@ -30,7 +30,9 @@
|
||||
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git</repo>
|
||||
<issue>https://issues.apache.org/jira/browse/CB/component/12320645</issue>
|
||||
|
||||
<dependency id="cordova-plugin-compat" version="^1.1.0" />
|
||||
<engines>
|
||||
<engine name="cordova-android" version=">=6.3.0" />
|
||||
</engines>
|
||||
|
||||
<js-module src="www/CameraConstants.js" name="Camera">
|
||||
<clobbers target="Camera" />
|
||||
@@ -165,20 +167,6 @@
|
||||
<framework src="CoreGraphics.framework" />
|
||||
<framework src="AVFoundation.framework" />
|
||||
|
||||
<preference name="CAMERA_USAGE_DESCRIPTION" default=" " />
|
||||
<config-file target="*-Info.plist" parent="NSCameraUsageDescription">
|
||||
<string>$CAMERA_USAGE_DESCRIPTION</string>
|
||||
</config-file>
|
||||
|
||||
<preference name="PHOTOLIBRARY_USAGE_DESCRIPTION" default=" " />
|
||||
<config-file target="*-Info.plist" parent="NSPhotoLibraryUsageDescription">
|
||||
<string>$PHOTOLIBRARY_USAGE_DESCRIPTION</string>
|
||||
</config-file>
|
||||
|
||||
<config-file target="*-Info.plist" parent="NSLocationWhenInUseUsageDescription">
|
||||
<string></string>
|
||||
</config-file>
|
||||
|
||||
</platform>
|
||||
|
||||
<!-- blackberry10 -->
|
||||
@@ -280,4 +268,23 @@
|
||||
</js-module>
|
||||
</platform>
|
||||
|
||||
<!-- osx -->
|
||||
<platform name="osx">
|
||||
<config-file target="config.xml" parent="/*">
|
||||
<feature name="Camera">
|
||||
<param name="osx-package" value="CDVCamera"/>
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
|
||||
<clobbers target="CameraPopoverHandle" />
|
||||
</js-module>
|
||||
|
||||
<header-file src="src/osx/CDVCamera.h" />
|
||||
<source-file src="src/osx/CDVCamera.m" />
|
||||
|
||||
<framework src="Quartz.framework" />
|
||||
<framework src="AppKit.framework" />
|
||||
</platform>
|
||||
|
||||
</plugin>
|
||||
|
||||
@@ -601,6 +601,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
|
||||
String imageFileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? ".jpg" : ".png");
|
||||
File storageDir = Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_PICTURES);
|
||||
storageDir.mkdirs();
|
||||
String galleryPath = storageDir.getAbsolutePath() + "/" + imageFileName;
|
||||
return galleryPath;
|
||||
}
|
||||
@@ -783,7 +784,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
|
||||
|
||||
}// If cancelled
|
||||
else if (resultCode == Activity.RESULT_CANCELED) {
|
||||
this.failPicture("Camera cancelled.");
|
||||
this.failPicture("No Image Selected");
|
||||
}
|
||||
|
||||
// If something else
|
||||
@@ -812,7 +813,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
|
||||
|
||||
// If cancelled
|
||||
else if (resultCode == Activity.RESULT_CANCELED) {
|
||||
this.failPicture("Camera cancelled.");
|
||||
this.failPicture("No Image Selected");
|
||||
}
|
||||
|
||||
// If something else
|
||||
@@ -831,7 +832,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
|
||||
}
|
||||
});
|
||||
} else if (resultCode == Activity.RESULT_CANCELED) {
|
||||
this.failPicture("Selection cancelled.");
|
||||
this.failPicture("No Image Selected");
|
||||
} else {
|
||||
this.failPicture("Selection did not complete!");
|
||||
}
|
||||
@@ -849,7 +850,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Write an inputstream to local disk
|
||||
*
|
||||
|
||||
@@ -22,19 +22,19 @@
|
||||
/* globals qnx, FileError, PluginResult */
|
||||
|
||||
var PictureSourceType = {
|
||||
PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
|
||||
CAMERA : 1, // Take picture from camera
|
||||
SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
|
||||
},
|
||||
DestinationType = {
|
||||
DATA_URL: 0, // Return base64 encoded string
|
||||
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)
|
||||
},
|
||||
savePath = window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', '') + '/shared/camera/',
|
||||
invokeAvailable = true;
|
||||
PHOTOLIBRARY: 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
|
||||
CAMERA: 1, // Take picture from camera
|
||||
SAVEDPHOTOALBUM: 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
|
||||
};
|
||||
var DestinationType = {
|
||||
DATA_URL: 0, // Return base64 encoded string
|
||||
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)
|
||||
};
|
||||
var savePath = window.qnx.webplatform.getApplication().getEnv('HOME').replace('/data', '') + '/shared/camera/';
|
||||
var 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(
|
||||
{
|
||||
type: 'image/jpeg',
|
||||
@@ -47,14 +47,14 @@ 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) {
|
||||
var wv = qnx.webplatform.createWebView(function () {
|
||||
wv.url = 'local:///chrome/camera.html';
|
||||
wv.allowQnxObject = true;
|
||||
wv.allowRpc = true;
|
||||
wv.zOrder = 1;
|
||||
wv.setGeometry(0, 0, screen.width, screen.height);
|
||||
wv.setGeometry(0, 0, screen.width, screen.height); /* eslint no-undef : 0 */
|
||||
wv.backgroundColor = 0x00000000;
|
||||
wv.active = true;
|
||||
wv.visible = true;
|
||||
@@ -71,7 +71,7 @@ function showCameraDialog (done, cancel, fail) {
|
||||
} else {
|
||||
saveImage(args[1], done, fail);
|
||||
}
|
||||
wv.un('JavaScriptCallback', arguments.callee);
|
||||
wv.un('JavaScriptCallback', arguments.callee); /* eslint no-caller : 0 */
|
||||
wv.visible = false;
|
||||
wv.destroy();
|
||||
qnx.webplatform.getApplication().unlockRotation();
|
||||
@@ -85,29 +85,29 @@ function showCameraDialog (done, cancel, fail) {
|
||||
});
|
||||
}
|
||||
|
||||
//create unique name for saved file (same pattern as BB10 camera app)
|
||||
function imgName() {
|
||||
var date = new Date(),
|
||||
pad = function (n) { return n < 10 ? '0' + n : n; };
|
||||
// create unique name for saved file (same pattern as BB10 camera app)
|
||||
function imgName () {
|
||||
var date = new Date();
|
||||
var pad = function (n) { return n < 10 ? '0' + n : n; };
|
||||
return 'IMG_' + date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate()) + '_' +
|
||||
pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds()) + '.png';
|
||||
}
|
||||
|
||||
//convert dataURI to Blob
|
||||
function dataURItoBlob(dataURI) {
|
||||
var byteString = atob(dataURI.split(',')[1]),
|
||||
mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0],
|
||||
arrayBuffer = new ArrayBuffer(byteString.length),
|
||||
ia = new Uint8Array(arrayBuffer),
|
||||
i;
|
||||
// convert dataURI to Blob
|
||||
function dataURItoBlob (dataURI) {
|
||||
var byteString = atob(dataURI.split(',')[1]);
|
||||
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
|
||||
var arrayBuffer = new ArrayBuffer(byteString.length);
|
||||
var ia = new Uint8Array(arrayBuffer);
|
||||
var i;
|
||||
for (i = 0; i < byteString.length; i++) {
|
||||
ia[i] = byteString.charCodeAt(i);
|
||||
}
|
||||
return new Blob([new DataView(arrayBuffer)], { type: mimeString });
|
||||
}
|
||||
|
||||
//save dataURI to file system and call success with path
|
||||
function saveImage(data, success, fail) {
|
||||
// save dataURI to file system and call success with path
|
||||
function saveImage (data, success, fail) {
|
||||
var name = savePath + imgName();
|
||||
require('lib/webview').setSandbox(false);
|
||||
window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) {
|
||||
@@ -123,91 +123,91 @@ function saveImage(data, success, fail) {
|
||||
}, fail);
|
||||
}
|
||||
|
||||
function encodeBase64(filePath, callback) {
|
||||
var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox, // save original sandbox value
|
||||
errorHandler = function (err) {
|
||||
var msg = "An error occured: ";
|
||||
function encodeBase64 (filePath, callback) {
|
||||
var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox; // save original sandbox value
|
||||
var errorHandler = function (err) {
|
||||
var msg = 'An error occured: ';
|
||||
|
||||
switch (err.code) {
|
||||
case FileError.NOT_FOUND_ERR:
|
||||
msg += "File or directory not found";
|
||||
break;
|
||||
switch (err.code) {
|
||||
case FileError.NOT_FOUND_ERR:
|
||||
msg += 'File or directory not found';
|
||||
break;
|
||||
|
||||
case FileError.NOT_READABLE_ERR:
|
||||
msg += "File or directory not readable";
|
||||
break;
|
||||
case FileError.NOT_READABLE_ERR:
|
||||
msg += 'File or directory not readable';
|
||||
break;
|
||||
|
||||
case FileError.PATH_EXISTS_ERR:
|
||||
msg += "File or directory already exists";
|
||||
break;
|
||||
case FileError.PATH_EXISTS_ERR:
|
||||
msg += 'File or directory already exists';
|
||||
break;
|
||||
|
||||
case FileError.TYPE_MISMATCH_ERR:
|
||||
msg += "Invalid file type";
|
||||
break;
|
||||
case FileError.TYPE_MISMATCH_ERR:
|
||||
msg += 'Invalid file type';
|
||||
break;
|
||||
|
||||
default:
|
||||
msg += "Unknown Error";
|
||||
break;
|
||||
}
|
||||
default:
|
||||
msg += 'Unknown Error';
|
||||
break;
|
||||
}
|
||||
|
||||
// set it back to original value
|
||||
window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
|
||||
callback(msg);
|
||||
},
|
||||
gotFile = function (fileEntry) {
|
||||
fileEntry.file(function (file) {
|
||||
var reader = new FileReader();
|
||||
// set it back to original value
|
||||
window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
|
||||
callback(msg);
|
||||
};
|
||||
var gotFile = function (fileEntry) {
|
||||
fileEntry.file(function (file) {
|
||||
var reader = new FileReader();
|
||||
|
||||
reader.onloadend = function (e) {
|
||||
// set it back to original value
|
||||
window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
|
||||
callback(this.result);
|
||||
};
|
||||
reader.onloadend = function (e) {
|
||||
// set it back to original value
|
||||
window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
|
||||
callback(this.result);
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
}, errorHandler);
|
||||
},
|
||||
onInitFs = function (fs) {
|
||||
window.qnx.webplatform.getController().setFileSystemSandbox = false;
|
||||
fs.root.getFile(filePath, {create: false}, gotFile, errorHandler);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}, errorHandler);
|
||||
};
|
||||
var onInitFs = function (fs) {
|
||||
window.qnx.webplatform.getController().setFileSystemSandbox = false;
|
||||
fs.root.getFile(filePath, {create: false}, gotFile, errorHandler);
|
||||
};
|
||||
|
||||
window.webkitRequestFileSystem(window.TEMPORARY, 10 * 1024 * 1024, onInitFs, errorHandler); // set size to 10MB max
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
takePicture: function (success, fail, args, env) {
|
||||
var destinationType = JSON.parse(decodeURIComponent(args[1])),
|
||||
sourceType = JSON.parse(decodeURIComponent(args[2])),
|
||||
result = new PluginResult(args, env),
|
||||
done = function (data) {
|
||||
if (destinationType === DestinationType.FILE_URI) {
|
||||
data = "file://" + data;
|
||||
result.callbackOk(data, false);
|
||||
} else {
|
||||
encodeBase64(data, function (data) {
|
||||
if (/^data:/.test(data)) {
|
||||
data = data.slice(data.indexOf(",") + 1);
|
||||
result.callbackOk(data, false);
|
||||
} else {
|
||||
result.callbackError(data, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
cancel = function (reason) {
|
||||
result.callbackError(reason, false);
|
||||
},
|
||||
invoked = function (error) {
|
||||
if (error) {
|
||||
result.callbackError(error, false);
|
||||
}
|
||||
};
|
||||
var destinationType = JSON.parse(decodeURIComponent(args[1]));
|
||||
var sourceType = JSON.parse(decodeURIComponent(args[2]));
|
||||
var result = new PluginResult(args, env);
|
||||
var done = function (data) {
|
||||
if (destinationType === DestinationType.FILE_URI) {
|
||||
data = 'file://' + data;
|
||||
result.callbackOk(data, false);
|
||||
} else {
|
||||
encodeBase64(data, function (data) {
|
||||
if (/^data:/.test(data)) {
|
||||
data = data.slice(data.indexOf(',') + 1);
|
||||
result.callbackOk(data, false);
|
||||
} else {
|
||||
result.callbackError(data, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
var cancel = function (reason) {
|
||||
result.callbackError(reason, false);
|
||||
};
|
||||
var invoked = function (error) {
|
||||
if (error) {
|
||||
result.callbackError(error, false);
|
||||
}
|
||||
};
|
||||
|
||||
switch(sourceType) {
|
||||
switch (sourceType) {
|
||||
case PictureSourceType.CAMERA:
|
||||
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 {
|
||||
showCameraDialog(done, cancel, fail);
|
||||
}
|
||||
@@ -216,8 +216,8 @@ module.exports = {
|
||||
case PictureSourceType.PHOTOLIBRARY:
|
||||
case PictureSourceType.SAVEDPHOTOALBUM:
|
||||
window.qnx.webplatform.getApplication().cards.filePicker.open({
|
||||
mode: "Picker",
|
||||
type: ["picture"]
|
||||
mode: 'Picker',
|
||||
type: ['picture']
|
||||
}, done, cancel, invoked);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
|
||||
|
||||
function takePicture(success, error, opts) {
|
||||
function takePicture (success, error, opts) {
|
||||
if (opts && opts[2] === 1) {
|
||||
capture(success, error, opts);
|
||||
} else {
|
||||
@@ -32,9 +32,9 @@ function takePicture(success, error, opts) {
|
||||
input.type = 'file';
|
||||
input.name = 'files[]';
|
||||
|
||||
input.onchange = function(inputEvent) {
|
||||
var reader = new FileReader();
|
||||
reader.onload = function(readerEvent) {
|
||||
input.onchange = function (inputEvent) {
|
||||
var reader = new FileReader(); /* eslint no-undef : 0 */
|
||||
reader.onload = function (readerEvent) {
|
||||
input.parentNode.removeChild(input);
|
||||
|
||||
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 targetWidth = opts[3];
|
||||
var targetHeight = opts[4];
|
||||
|
||||
targetWidth = targetWidth == -1?320:targetWidth;
|
||||
targetHeight = targetHeight == -1?240:targetHeight;
|
||||
targetWidth = targetWidth === -1 ? 320 : targetWidth;
|
||||
targetHeight = targetHeight === -1 ? 240 : targetHeight;
|
||||
|
||||
var video = document.createElement('video');
|
||||
var button = document.createElement('button');
|
||||
@@ -70,7 +70,7 @@ function capture(success, errorCallback, opts) {
|
||||
video.height = targetHeight;
|
||||
button.innerHTML = 'Capture!';
|
||||
|
||||
button.onclick = function() {
|
||||
button.onclick = function () {
|
||||
// create a canvas and capture a frame from video stream
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.width = targetWidth;
|
||||
@@ -100,7 +100,7 @@ function capture(success, errorCallback, opts) {
|
||||
navigator.mozGetUserMedia ||
|
||||
navigator.msGetUserMedia;
|
||||
|
||||
var successCallback = function(stream) {
|
||||
var successCallback = function (stream) {
|
||||
localMediaStream = stream;
|
||||
video.src = window.URL.createObjectURL(localMediaStream);
|
||||
video.play();
|
||||
@@ -117,7 +117,7 @@ function capture(success, errorCallback, opts) {
|
||||
|
||||
module.exports = {
|
||||
takePicture: takePicture,
|
||||
cleanup: function(){}
|
||||
cleanup: function () {}
|
||||
};
|
||||
|
||||
require("cordova/exec/proxy").add("Camera",module.exports);
|
||||
require('cordova/exec/proxy').add('Camera', module.exports);
|
||||
|
||||
@@ -21,17 +21,17 @@
|
||||
|
||||
/* globals MozActivity */
|
||||
|
||||
function takePicture(success, error, opts) {
|
||||
function takePicture (success, error, opts) {
|
||||
var pick = new MozActivity({
|
||||
name: "pick",
|
||||
name: 'pick',
|
||||
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
|
||||
// we need to call success with url or base64 encoded image
|
||||
if (opts && opts.destinationType === 0) {
|
||||
@@ -47,7 +47,7 @@ function takePicture(success, error, opts) {
|
||||
|
||||
module.exports = {
|
||||
takePicture: takePicture,
|
||||
cleanup: function(){}
|
||||
cleanup: function () {}
|
||||
};
|
||||
|
||||
require("cordova/exec/proxy").add("Camera", module.exports);
|
||||
require('cordova/exec/proxy').add('Camera', module.exports);
|
||||
|
||||
@@ -42,7 +42,7 @@ static NSString* toBase64(NSData* data) {
|
||||
SEL s1 = NSSelectorFromString(@"cdv_base64EncodedString");
|
||||
SEL s2 = NSSelectorFromString(@"base64EncodedString");
|
||||
SEL s3 = NSSelectorFromString(@"base64EncodedStringWithOptions:");
|
||||
|
||||
|
||||
if ([data respondsToSelector:s1]) {
|
||||
NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s1];
|
||||
return func(data, s1);
|
||||
@@ -66,7 +66,7 @@ static NSString* toBase64(NSData* data) {
|
||||
pictureOptions.quality = [command argumentAtIndex:0 withDefault:@(50)];
|
||||
pictureOptions.destinationType = [[command argumentAtIndex:1 withDefault:@(DestinationTypeFileUri)] unsignedIntegerValue];
|
||||
pictureOptions.sourceType = [[command argumentAtIndex:2 withDefault:@(UIImagePickerControllerSourceTypeCamera)] unsignedIntegerValue];
|
||||
|
||||
|
||||
NSNumber* targetWidth = [command argumentAtIndex:3 withDefault:nil];
|
||||
NSNumber* targetHeight = [command argumentAtIndex:4 withDefault:nil];
|
||||
pictureOptions.targetSize = CGSizeMake(0, 0);
|
||||
@@ -81,10 +81,10 @@ static NSString* toBase64(NSData* data) {
|
||||
pictureOptions.saveToPhotoAlbum = [[command argumentAtIndex:9 withDefault:@(NO)] boolValue];
|
||||
pictureOptions.popoverOptions = [command argumentAtIndex:10 withDefault:nil];
|
||||
pictureOptions.cameraDirection = [[command argumentAtIndex:11 withDefault:@(UIImagePickerControllerCameraDeviceRear)] unsignedIntegerValue];
|
||||
|
||||
|
||||
pictureOptions.popoverSupported = NO;
|
||||
pictureOptions.usesGeolocation = NO;
|
||||
|
||||
|
||||
return pictureOptions;
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ static NSString* toBase64(NSData* data) {
|
||||
- (NSURL*) urlTransformer:(NSURL*)url
|
||||
{
|
||||
NSURL* urlToTransform = url;
|
||||
|
||||
|
||||
// for backwards compatibility - we check if this property is there
|
||||
SEL sel = NSSelectorFromString(@"urlTransformer");
|
||||
if ([self.commandDelegate respondsToSelector:sel]) {
|
||||
@@ -120,7 +120,7 @@ static NSString* toBase64(NSData* data) {
|
||||
urlToTransform = urlTransformer(url);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return urlToTransform;
|
||||
}
|
||||
|
||||
@@ -139,16 +139,16 @@ static NSString* toBase64(NSData* data) {
|
||||
- (void)takePicture:(CDVInvokedUrlCommand*)command
|
||||
{
|
||||
self.hasPendingOperation = YES;
|
||||
|
||||
|
||||
__weak CDVCamera* weakSelf = self;
|
||||
|
||||
[self.commandDelegate runInBackground:^{
|
||||
|
||||
|
||||
CDVPictureOptions* pictureOptions = [CDVPictureOptions createFromTakePictureArguments:command];
|
||||
pictureOptions.popoverSupported = [weakSelf popoverSupported];
|
||||
pictureOptions.usesGeolocation = [weakSelf usesGeolocation];
|
||||
pictureOptions.cropToSize = NO;
|
||||
|
||||
|
||||
BOOL hasCamera = [UIImagePickerController isSourceTypeAvailable:pictureOptions.sourceType];
|
||||
if (!hasCamera) {
|
||||
NSLog(@"Camera.getPicture: source type %lu not available.", (unsigned long)pictureOptions.sourceType);
|
||||
@@ -184,12 +184,12 @@ static NSString* toBase64(NSData* data) {
|
||||
|
||||
CDVCameraPicker* cameraPicker = [CDVCameraPicker createFromPictureOptions:pictureOptions];
|
||||
weakSelf.pickerController = cameraPicker;
|
||||
|
||||
|
||||
cameraPicker.delegate = weakSelf;
|
||||
cameraPicker.callbackId = command.callbackId;
|
||||
// we need to capture this state for memory warnings that dealloc this object
|
||||
cameraPicker.webView = weakSelf.webView;
|
||||
|
||||
|
||||
// Perform UI operations on the main thread
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// If a popover is already open, close it; we only want one at a time.
|
||||
@@ -291,7 +291,7 @@ static NSString* toBase64(NSData* data) {
|
||||
{
|
||||
if([navigationController isKindOfClass:[UIImagePickerController class]]){
|
||||
UIImagePickerController* cameraPicker = (UIImagePickerController*)navigationController;
|
||||
|
||||
|
||||
if(![cameraPicker.mediaTypes containsObject:(NSString*)kUTTypeImage]){
|
||||
[viewController.navigationItem setTitle:NSLocalizedString(@"Videos", nil)];
|
||||
}
|
||||
@@ -351,7 +351,7 @@ static NSString* toBase64(NSData* data) {
|
||||
- (NSData*)processImage:(UIImage*)image info:(NSDictionary*)info options:(CDVPictureOptions*)options
|
||||
{
|
||||
NSData* data = nil;
|
||||
|
||||
|
||||
switch (options.encodingType) {
|
||||
case EncodingTypePNG:
|
||||
data = UIImagePNGRepresentation(image);
|
||||
@@ -364,18 +364,18 @@ static NSString* toBase64(NSData* data) {
|
||||
} else {
|
||||
data = UIImageJPEGRepresentation(image, [options.quality floatValue] / 100.0f);
|
||||
}
|
||||
|
||||
|
||||
if (options.usesGeolocation) {
|
||||
NSDictionary* controllerMetadata = [info objectForKey:@"UIImagePickerControllerMediaMetadata"];
|
||||
if (controllerMetadata) {
|
||||
self.data = data;
|
||||
self.metadata = [[NSMutableDictionary alloc] init];
|
||||
|
||||
|
||||
NSMutableDictionary* EXIFDictionary = [[controllerMetadata objectForKey:(NSString*)kCGImagePropertyExifDictionary]mutableCopy];
|
||||
if (EXIFDictionary) {
|
||||
[self.metadata setObject:EXIFDictionary forKey:(NSString*)kCGImagePropertyExifDictionary];
|
||||
}
|
||||
|
||||
|
||||
if (IsAtLeastiOSVersion(@"8.0")) {
|
||||
[[self locationManager] performSelector:NSSelectorFromString(@"requestWhenInUseAuthorization") withObject:nil afterDelay:0];
|
||||
}
|
||||
@@ -387,7 +387,7 @@ static NSString* toBase64(NSData* data) {
|
||||
default:
|
||||
break;
|
||||
};
|
||||
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -396,13 +396,13 @@ static NSString* toBase64(NSData* data) {
|
||||
NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath];
|
||||
NSFileManager* fileMgr = [[NSFileManager alloc] init]; // recommended by Apple (vs [NSFileManager defaultManager]) to be threadsafe
|
||||
NSString* filePath;
|
||||
|
||||
|
||||
// generate unique file name
|
||||
int i = 1;
|
||||
do {
|
||||
filePath = [NSString stringWithFormat:@"%@/%@%03d.%@", docsPath, CDV_PHOTO_PREFIX, i++, extension];
|
||||
} while ([fileMgr fileExistsAtPath:filePath]);
|
||||
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@@ -415,13 +415,13 @@ static NSString* toBase64(NSData* data) {
|
||||
} else {
|
||||
image = [info objectForKey:UIImagePickerControllerOriginalImage];
|
||||
}
|
||||
|
||||
|
||||
if (options.correctOrientation) {
|
||||
image = [image imageCorrectedForCaptureOrientation];
|
||||
}
|
||||
|
||||
|
||||
UIImage* scaledImage = nil;
|
||||
|
||||
|
||||
if ((options.targetSize.width > 0) && (options.targetSize.height > 0)) {
|
||||
// if cropToSize, resize image and crop to target size, otherwise resize to fit target without cropping
|
||||
if (options.cropToSize) {
|
||||
@@ -430,7 +430,7 @@ static NSString* toBase64(NSData* data) {
|
||||
scaledImage = [image imageByScalingNotCroppingForSize:options.targetSize];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (scaledImage == nil ? image : scaledImage);
|
||||
}
|
||||
|
||||
@@ -472,11 +472,11 @@ static NSString* toBase64(NSData* data) {
|
||||
image = [self retrieveImage:info options:options];
|
||||
NSData* data = [self processImage:image info:info options:options];
|
||||
if (data) {
|
||||
|
||||
|
||||
NSString* extension = options.encodingType == EncodingTypePNG? @"png" : @"jpg";
|
||||
NSString* filePath = [self tempFilePath:extension];
|
||||
NSError* err = nil;
|
||||
|
||||
|
||||
// save file
|
||||
if (![data writeToFile:filePath options:NSAtomicWrite error:&err]) {
|
||||
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[err localizedDescription]];
|
||||
@@ -498,7 +498,7 @@ static NSString* toBase64(NSData* data) {
|
||||
default:
|
||||
break;
|
||||
};
|
||||
|
||||
|
||||
if (saveToPhotoAlbum && image) {
|
||||
ALAssetsLibrary* library = [ALAssetsLibrary new];
|
||||
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)(image.imageOrientation) completionBlock:nil];
|
||||
@@ -517,10 +517,10 @@ static NSString* toBase64(NSData* data) {
|
||||
{
|
||||
__weak CDVCameraPicker* cameraPicker = (CDVCameraPicker*)picker;
|
||||
__weak CDVCamera* weakSelf = self;
|
||||
|
||||
|
||||
dispatch_block_t invoke = ^(void) {
|
||||
__block CDVPluginResult* result = nil;
|
||||
|
||||
|
||||
NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
|
||||
if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
|
||||
[weakSelf resultForImage:cameraPicker.pictureOptions info:info completion:^(CDVPluginResult* res) {
|
||||
@@ -538,7 +538,7 @@ static NSString* toBase64(NSData* data) {
|
||||
weakSelf.pickerController = nil;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
if (cameraPicker.pictureOptions.popoverSupported && (cameraPicker.pickerPopoverController != nil)) {
|
||||
[cameraPicker.pickerPopoverController dismissPopoverAnimated:YES];
|
||||
cameraPicker.pickerPopoverController.delegate = nil;
|
||||
@@ -561,7 +561,7 @@ static NSString* toBase64(NSData* data) {
|
||||
{
|
||||
__weak CDVCameraPicker* cameraPicker = (CDVCameraPicker*)picker;
|
||||
__weak CDVCamera* weakSelf = self;
|
||||
|
||||
|
||||
dispatch_block_t invoke = ^ (void) {
|
||||
CDVPluginResult* result;
|
||||
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] != ALAuthorizationStatusAuthorized) {
|
||||
@@ -569,12 +569,12 @@ static NSString* toBase64(NSData* data) {
|
||||
} else if (picker.sourceType != UIImagePickerControllerSourceTypeCamera && [ALAssetsLibrary authorizationStatus] != ALAuthorizationStatusAuthorized) {
|
||||
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"has no access to assets"];
|
||||
} else {
|
||||
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"no image selected"];
|
||||
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No Image Selected"];
|
||||
}
|
||||
|
||||
|
||||
|
||||
[weakSelf.commandDelegate sendPluginResult:result callbackId:cameraPicker.callbackId];
|
||||
|
||||
|
||||
weakSelf.hasPendingOperation = NO;
|
||||
weakSelf.pickerController = nil;
|
||||
};
|
||||
@@ -587,11 +587,11 @@ static NSString* toBase64(NSData* data) {
|
||||
if (locationManager != nil) {
|
||||
return locationManager;
|
||||
}
|
||||
|
||||
|
||||
locationManager = [[CLLocationManager alloc] init];
|
||||
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
|
||||
[locationManager setDelegate:self];
|
||||
|
||||
|
||||
return locationManager;
|
||||
}
|
||||
|
||||
@@ -600,15 +600,15 @@ static NSString* toBase64(NSData* data) {
|
||||
if (locationManager == nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
[self.locationManager stopUpdatingLocation];
|
||||
self.locationManager = nil;
|
||||
|
||||
|
||||
NSMutableDictionary *GPSDictionary = [[NSMutableDictionary dictionary] init];
|
||||
|
||||
|
||||
CLLocationDegrees latitude = newLocation.coordinate.latitude;
|
||||
CLLocationDegrees longitude = newLocation.coordinate.longitude;
|
||||
|
||||
|
||||
// latitude
|
||||
if (latitude < 0.0) {
|
||||
latitude = latitude * -1.0f;
|
||||
@@ -617,7 +617,7 @@ static NSString* toBase64(NSData* data) {
|
||||
[GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];
|
||||
}
|
||||
[GPSDictionary setObject:[NSNumber numberWithFloat:latitude] forKey:(NSString*)kCGImagePropertyGPSLatitude];
|
||||
|
||||
|
||||
// longitude
|
||||
if (longitude < 0.0) {
|
||||
longitude = longitude * -1.0f;
|
||||
@@ -627,7 +627,7 @@ static NSString* toBase64(NSData* data) {
|
||||
[GPSDictionary setObject:@"E" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];
|
||||
}
|
||||
[GPSDictionary setObject:[NSNumber numberWithFloat:longitude] forKey:(NSString*)kCGImagePropertyGPSLongitude];
|
||||
|
||||
|
||||
// altitude
|
||||
CGFloat altitude = newLocation.altitude;
|
||||
if (!isnan(altitude)){
|
||||
@@ -639,7 +639,7 @@ static NSString* toBase64(NSData* data) {
|
||||
}
|
||||
[GPSDictionary setObject:[NSNumber numberWithFloat:altitude] forKey:(NSString *)kCGImagePropertyGPSAltitude];
|
||||
}
|
||||
|
||||
|
||||
// Time and date
|
||||
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
|
||||
[formatter setDateFormat:@"HH:mm:ss.SSSSSS"];
|
||||
@@ -647,7 +647,7 @@ static NSString* toBase64(NSData* data) {
|
||||
[GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSTimeStamp];
|
||||
[formatter setDateFormat:@"yyyy:MM:dd"];
|
||||
[GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSDateStamp];
|
||||
|
||||
|
||||
[self.metadata setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];
|
||||
[self imagePickerControllerReturnImageResult];
|
||||
}
|
||||
@@ -660,7 +660,7 @@ static NSString* toBase64(NSData* data) {
|
||||
|
||||
[self.locationManager stopUpdatingLocation];
|
||||
self.locationManager = nil;
|
||||
|
||||
|
||||
[self imagePickerControllerReturnImageResult];
|
||||
}
|
||||
|
||||
@@ -668,26 +668,26 @@ static NSString* toBase64(NSData* data) {
|
||||
{
|
||||
CDVPictureOptions* options = self.pickerController.pictureOptions;
|
||||
CDVPluginResult* result = nil;
|
||||
|
||||
|
||||
if (self.metadata) {
|
||||
CGImageSourceRef sourceImage = CGImageSourceCreateWithData((__bridge CFDataRef)self.data, NULL);
|
||||
CFStringRef sourceType = CGImageSourceGetType(sourceImage);
|
||||
|
||||
|
||||
CGImageDestinationRef destinationImage = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)self.data, sourceType, 1, NULL);
|
||||
CGImageDestinationAddImageFromSource(destinationImage, sourceImage, 0, (__bridge CFDictionaryRef)self.metadata);
|
||||
CGImageDestinationFinalize(destinationImage);
|
||||
|
||||
|
||||
CFRelease(sourceImage);
|
||||
CFRelease(destinationImage);
|
||||
}
|
||||
|
||||
|
||||
switch (options.destinationType) {
|
||||
case DestinationTypeFileUri:
|
||||
{
|
||||
NSError* err = nil;
|
||||
NSString* extension = self.pickerController.pictureOptions.encodingType == EncodingTypePNG ? @"png":@"jpg";
|
||||
NSString* filePath = [self tempFilePath:extension];
|
||||
|
||||
|
||||
// save file
|
||||
if (![self.data writeToFile:filePath options:NSAtomicWrite error:&err]) {
|
||||
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[err localizedDescription]];
|
||||
@@ -706,16 +706,16 @@ static NSString* toBase64(NSData* data) {
|
||||
default:
|
||||
break;
|
||||
};
|
||||
|
||||
|
||||
if (result) {
|
||||
[self.commandDelegate sendPluginResult:result callbackId:self.pickerController.callbackId];
|
||||
}
|
||||
|
||||
|
||||
self.hasPendingOperation = NO;
|
||||
self.pickerController = nil;
|
||||
self.data = nil;
|
||||
self.metadata = nil;
|
||||
|
||||
|
||||
if (options.saveToPhotoAlbum) {
|
||||
ALAssetsLibrary *library = [ALAssetsLibrary new];
|
||||
[library writeImageDataToSavedPhotosAlbum:self.data metadata:self.metadata completionBlock:nil];
|
||||
@@ -735,14 +735,14 @@ static NSString* toBase64(NSData* data) {
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
- (void)viewWillAppear:(BOOL)animated
|
||||
{
|
||||
SEL sel = NSSelectorFromString(@"setNeedsStatusBarAppearanceUpdate");
|
||||
if ([self respondsToSelector:sel]) {
|
||||
[self performSelector:sel withObject:nil afterDelay:0];
|
||||
}
|
||||
|
||||
|
||||
[super viewWillAppear:animated];
|
||||
}
|
||||
|
||||
@@ -752,7 +752,7 @@ static NSString* toBase64(NSData* data) {
|
||||
cameraPicker.pictureOptions = pictureOptions;
|
||||
cameraPicker.sourceType = pictureOptions.sourceType;
|
||||
cameraPicker.allowsEditing = pictureOptions.allowsEditing;
|
||||
|
||||
|
||||
if (cameraPicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
|
||||
// We only allow taking pictures (no video) in this API.
|
||||
cameraPicker.mediaTypes = @[(NSString*)kUTTypeImage];
|
||||
@@ -764,8 +764,8 @@ static NSString* toBase64(NSData* data) {
|
||||
NSArray* mediaArray = @[(NSString*)(pictureOptions.mediaType == MediaTypeVideo ? kUTTypeMovie : kUTTypeImage)];
|
||||
cameraPicker.mediaTypes = mediaArray;
|
||||
}
|
||||
|
||||
|
||||
return cameraPicker;
|
||||
}
|
||||
|
||||
@end
|
||||
@end
|
||||
|
||||
81
src/osx/CDVCamera.h
Normal file
81
src/osx/CDVCamera.h
Normal file
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
#import <Quartz/Quartz.h>
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <Cordova/CDVPlugin.h>
|
||||
|
||||
|
||||
|
||||
enum CDVDestinationType {
|
||||
DestinationTypeDataUrl = 0,
|
||||
DestinationTypeFileUri,
|
||||
DestinationTypeNativeUri
|
||||
};
|
||||
typedef NSUInteger CDVDestinationType;
|
||||
|
||||
enum CDVSourceType {
|
||||
SourceTypePhotoLibrary = 0,
|
||||
SourceTypeCamera,
|
||||
SourceTypePhotoAlbum
|
||||
};
|
||||
typedef NSUInteger CDVSourceType;
|
||||
|
||||
enum CDVEncodingType {
|
||||
EncodingTypeJPEG = 0,
|
||||
EncodingTypePNG
|
||||
};
|
||||
typedef NSUInteger CDVEncodingType;
|
||||
|
||||
enum CDVMediaType {
|
||||
MediaTypePicture = 0,
|
||||
MediaTypeVideo,
|
||||
MediaTypeAll
|
||||
};
|
||||
typedef NSUInteger CDVMediaType;
|
||||
|
||||
|
||||
// ======================================================================= //
|
||||
|
||||
|
||||
@interface CDVPictureOptions : NSObject
|
||||
|
||||
@property (strong) NSNumber *quality;
|
||||
@property (assign) CDVDestinationType destinationType;
|
||||
@property (assign) CDVSourceType sourceType;
|
||||
@property (assign) CGSize targetSize;
|
||||
@property (assign) CDVEncodingType encodingType;
|
||||
@property (assign) CDVMediaType mediaType;
|
||||
@property (assign) BOOL allowsEditing;
|
||||
@property (assign) BOOL correctOrientation;
|
||||
@property (assign) BOOL saveToPhotoAlbum;
|
||||
|
||||
+ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand *)command;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
// ======================================================================= //
|
||||
|
||||
|
||||
@interface CDVCamera : CDVPlugin
|
||||
|
||||
- (void)takePicture:(CDVInvokedUrlCommand *)command;
|
||||
- (void)cleanup:(CDVInvokedUrlCommand *)command;
|
||||
|
||||
@end
|
||||
258
src/osx/CDVCamera.m
Normal file
258
src/osx/CDVCamera.m
Normal file
@@ -0,0 +1,258 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
#import "CDVCamera.h"
|
||||
|
||||
|
||||
@implementation CDVPictureOptions
|
||||
|
||||
+ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand*)command {
|
||||
CDVPictureOptions *pictureOptions = [[CDVPictureOptions alloc] init];
|
||||
|
||||
pictureOptions.quality = [command argumentAtIndex:0 withDefault:@(50)];
|
||||
pictureOptions.destinationType = [[command argumentAtIndex:1 withDefault:@(DestinationTypeFileUri)] unsignedIntegerValue];
|
||||
pictureOptions.sourceType = [[command argumentAtIndex:2 withDefault:@(SourceTypeCamera)] unsignedIntegerValue];
|
||||
|
||||
NSNumber *targetWidth = [command argumentAtIndex:3 withDefault:nil];
|
||||
NSNumber *targetHeight = [command argumentAtIndex:4 withDefault:nil];
|
||||
pictureOptions.targetSize = CGSizeMake(0, 0);
|
||||
if ((targetWidth != nil) && (targetHeight != nil)) {
|
||||
pictureOptions.targetSize = CGSizeMake([targetWidth floatValue], [targetHeight floatValue]);
|
||||
}
|
||||
|
||||
pictureOptions.encodingType = [[command argumentAtIndex:5 withDefault:@(EncodingTypeJPEG)] unsignedIntegerValue];
|
||||
pictureOptions.mediaType = [[command argumentAtIndex:6 withDefault:@(MediaTypePicture)] unsignedIntegerValue];
|
||||
pictureOptions.allowsEditing = [[command argumentAtIndex:7 withDefault:@(NO)] boolValue];
|
||||
pictureOptions.correctOrientation = [[command argumentAtIndex:8 withDefault:@(NO)] boolValue];
|
||||
pictureOptions.saveToPhotoAlbum = [[command argumentAtIndex:9 withDefault:@(NO)] boolValue];
|
||||
|
||||
return pictureOptions;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
// ======================================================================= //
|
||||
|
||||
|
||||
@implementation CDVCamera
|
||||
|
||||
/*!
|
||||
Static array that stores the temporary created files allowing to delete them when calling navigator.camera.cleanup(...)
|
||||
*/
|
||||
static NSMutableArray *cleanUpFiles;
|
||||
|
||||
+ (void)initialize {
|
||||
cleanUpFiles = [NSMutableArray array];
|
||||
}
|
||||
|
||||
- (void)takePicture:(CDVInvokedUrlCommand *)command {
|
||||
CDVPictureOptions *pictureOptions = [CDVPictureOptions createFromTakePictureArguments:command];
|
||||
if (pictureOptions.sourceType == SourceTypeCamera) {
|
||||
[self takePictureFromCamera:command withOptions:pictureOptions];
|
||||
} else {
|
||||
[self takePictureFromFile:command withOptions:pictureOptions];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cleanup:(CDVInvokedUrlCommand*)command {
|
||||
[self.commandDelegate runInBackground:^{
|
||||
if (cleanUpFiles.count > 0) {
|
||||
for (int i=0; i<cleanUpFiles.count; i++) {
|
||||
NSString *path = [cleanUpFiles objectAtIndex:i];
|
||||
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
|
||||
}
|
||||
|
||||
[cleanUpFiles removeAllObjects];
|
||||
|
||||
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
|
||||
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Camera
|
||||
|
||||
/*!
|
||||
Takes a picture from the iSight camera using the default OS dialog.
|
||||
@see https://developer.apple.com/documentation/quartz/ikpicturetaker
|
||||
*/
|
||||
- (void)takePictureFromCamera:(CDVInvokedUrlCommand *)command withOptions:(CDVPictureOptions *)pictureOptions {
|
||||
IKPictureTaker *pictureTaker = [IKPictureTaker pictureTaker];
|
||||
[pictureTaker setValue:[NSNumber numberWithBool:YES] forKey:IKPictureTakerAllowsVideoCaptureKey];
|
||||
[pictureTaker setValue:[NSNumber numberWithBool:NO] forKey:IKPictureTakerAllowsFileChoosingKey];
|
||||
[pictureTaker setValue:[NSNumber numberWithBool:pictureOptions.allowsEditing] forKey:IKPictureTakerShowEffectsKey];
|
||||
[pictureTaker setValue:[NSNumber numberWithBool:pictureOptions.allowsEditing] forKey:IKPictureTakerAllowsEditingKey];
|
||||
|
||||
NSDictionary *contextInfo = @{ @"command": command, @"pictureOptions" : pictureOptions};
|
||||
[pictureTaker beginPictureTakerSheetForWindow:self.viewController.contentView.window withDelegate:self didEndSelector:@selector(pictureTakerDidEnd:returnCode:contextInfo:) contextInfo:(void *)CFBridgingRetain(contextInfo)];
|
||||
|
||||
}
|
||||
|
||||
- (void)pictureTakerDidEnd:(IKPictureTaker *)pictureTaker returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
|
||||
if (returnCode == NSOKButton) {
|
||||
NSDictionary *contextInfoDictionary = (NSDictionary *)CFBridgingRelease(contextInfo);
|
||||
CDVInvokedUrlCommand *command = [contextInfoDictionary valueForKey:@"command"];
|
||||
CDVPictureOptions *pictureOptions = [contextInfoDictionary valueForKey:@"pictureOptions"];
|
||||
|
||||
[self returnImage:pictureTaker.outputImage command:command options:pictureOptions];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - File
|
||||
|
||||
/*!
|
||||
Allows to select an image or video using the system native dialog.
|
||||
*/
|
||||
- (void)takePictureFromFile:(CDVInvokedUrlCommand *)command withOptions:(CDVPictureOptions *)pictureOptions {
|
||||
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
|
||||
openPanel.canChooseFiles = YES;
|
||||
openPanel.canChooseDirectories = NO;
|
||||
openPanel.canCreateDirectories = YES;
|
||||
openPanel.allowsMultipleSelection = NO;
|
||||
|
||||
NSMutableArray *allowedTypes = [NSMutableArray array];
|
||||
if (pictureOptions.mediaType == MediaTypePicture || pictureOptions.mediaType == MediaTypeAll) {
|
||||
[allowedTypes addObjectsFromArray:[NSImage imageTypes]];
|
||||
}
|
||||
if (pictureOptions.mediaType == MediaTypeVideo || pictureOptions.mediaType == MediaTypeAll) {
|
||||
[allowedTypes addObjectsFromArray:@[(NSString *)kUTTypeMovie]];
|
||||
}
|
||||
[openPanel setAllowedFileTypes:allowedTypes];
|
||||
|
||||
[openPanel beginSheetModalForWindow:self.viewController.contentView.window completionHandler:^(NSInteger result) {
|
||||
if (result == NSOKButton) {
|
||||
NSURL *fileURL = [openPanel.URLs objectAtIndex:0];
|
||||
|
||||
if ([self fileIsImage:fileURL]) {
|
||||
NSImage *image = [[NSImage alloc] initWithContentsOfFile:fileURL.path];
|
||||
[self returnImage:image command:command options:pictureOptions];
|
||||
} else {
|
||||
if (pictureOptions.destinationType == DestinationTypeDataUrl) {
|
||||
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Camera.DestinationType.DATA_URL is only available with image files"];
|
||||
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
|
||||
} else {
|
||||
[self returnUri:fileURL.path command:command options:pictureOptions];
|
||||
}
|
||||
}
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Common
|
||||
|
||||
/*!
|
||||
Returns to JavaScript a URI.
|
||||
Called when Camera.DestinationType.FILE_URI or Camera.DestinationType.NATIVE_URI.
|
||||
*/
|
||||
- (void)returnUri:(NSString *)path command:(CDVInvokedUrlCommand *)command options:(CDVPictureOptions *)pictureOptions {
|
||||
NSString *protocol = (pictureOptions.destinationType == DestinationTypeFileUri) ? @"file://" : @"";
|
||||
NSString *uri = [NSString stringWithFormat:@"%@%@", protocol, path];
|
||||
|
||||
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:uri];
|
||||
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns to JavaScript a base64 encoded image.
|
||||
Called when Camera.DestinationType.DATA_URL.
|
||||
*/
|
||||
- (void)returnImage:(NSImage *)image command:(CDVInvokedUrlCommand *)command options:(CDVPictureOptions *)pictureOptions {
|
||||
[self.commandDelegate runInBackground:^{
|
||||
NSData *processedImageData = [self processImage:image options:pictureOptions];
|
||||
|
||||
if (pictureOptions.destinationType == DestinationTypeDataUrl) {
|
||||
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[processedImageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
|
||||
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
|
||||
} else {
|
||||
NSString *tempFilePath = [self uniqueImageName:pictureOptions];
|
||||
[processedImageData writeToFile:tempFilePath atomically:YES];
|
||||
[cleanUpFiles addObject:tempFilePath];
|
||||
[self returnUri:tempFilePath command:command options:pictureOptions];
|
||||
}
|
||||
}];
|
||||
|
||||
}
|
||||
|
||||
/*!
|
||||
Top level method to apply the size and quality required changes to an image.
|
||||
*/
|
||||
- (NSData *)processImage:(NSImage *)image options:(CDVPictureOptions *)pictureOptions {
|
||||
NSImage *sourceImage = image;
|
||||
if (pictureOptions.targetSize.width > 0 && pictureOptions.targetSize.height > 0) {
|
||||
sourceImage = [self resizeImage:sourceImage toSize:pictureOptions.targetSize];
|
||||
}
|
||||
|
||||
CGImageRef cgRef = [sourceImage CGImageForProposedRect:NULL context:nil hints:nil];
|
||||
NSBitmapImageRep *imageRepresentation = [[NSBitmapImageRep alloc] initWithCGImage:cgRef];
|
||||
|
||||
NSData *data = (pictureOptions.encodingType == EncodingTypeJPEG)
|
||||
? [imageRepresentation representationUsingType:NSJPEGFileType properties:@{NSImageCompressionFactor: [NSNumber numberWithFloat:pictureOptions.quality.floatValue/100.f]}]
|
||||
: [imageRepresentation representationUsingType:NSPNGFileType properties:@{NSImageCompressionFactor: @1.0}];
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/*!
|
||||
Auxiliar method to resize an image.
|
||||
*/
|
||||
- (NSImage *)resizeImage:(NSImage *)image toSize:(CGSize)newSize {
|
||||
CGFloat aspectWidth = newSize.width / image.size.width;
|
||||
CGFloat aspectHeight = newSize.height / image.size.height;
|
||||
CGFloat aspectRatio = MIN(aspectWidth, aspectHeight);
|
||||
|
||||
CGSize scaledSize = NSMakeSize(image.size.width*aspectRatio, image.size.height*aspectRatio);
|
||||
|
||||
NSImage *smallImage = [[NSImage alloc] initWithSize: scaledSize];
|
||||
[smallImage lockFocus];
|
||||
[image setSize: scaledSize];
|
||||
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
|
||||
[image drawAtPoint:NSZeroPoint fromRect:CGRectMake(0, 0, scaledSize.width, scaledSize.height) operation:NSCompositeCopy fraction:1.0];
|
||||
[smallImage unlockFocus];
|
||||
return smallImage;
|
||||
}
|
||||
|
||||
/*!
|
||||
Auxiliar method to know if a given file is an image or not.
|
||||
*/
|
||||
- (BOOL)fileIsImage:(NSURL *)fileURL {
|
||||
NSString *type;
|
||||
BOOL isImage = NO;
|
||||
|
||||
if ([fileURL getResourceValue:&type forKey:NSURLTypeIdentifierKey error:nil]) {
|
||||
isImage = [[NSImage imageTypes] containsObject:type];
|
||||
}
|
||||
|
||||
return isImage;
|
||||
}
|
||||
|
||||
/*!
|
||||
Auxiliar method that generates an unique filename for an image in the temporary directory.
|
||||
*/
|
||||
- (NSString *)uniqueImageName:(CDVPictureOptions *)pictureOptions {
|
||||
NSString *tempDir = NSTemporaryDirectory();
|
||||
NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString] ;
|
||||
NSString *extension = (pictureOptions.encodingType == EncodingTypeJPEG) ? @"jpeg" : @"png";
|
||||
NSString *uniqueFileName = [NSString stringWithFormat:@"%@%@.%@", tempDir, guid, extension];
|
||||
return uniqueFileName;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -19,13 +19,10 @@
|
||||
*
|
||||
*/
|
||||
|
||||
/*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 getAppData = function () {
|
||||
return Windows.Storage.ApplicationData.current;
|
||||
};
|
||||
@@ -58,7 +55,7 @@ module.exports = {
|
||||
takePicture: function (successCallback, errorCallback, args) {
|
||||
var sourceType = args[2];
|
||||
|
||||
if (sourceType != Camera.PictureSourceType.CAMERA) {
|
||||
if (sourceType !== Camera.PictureSourceType.CAMERA) {
|
||||
takePictureFromFile(successCallback, errorCallback, args);
|
||||
} else {
|
||||
takePictureFromCamera(successCallback, errorCallback, args);
|
||||
@@ -67,8 +64,8 @@ module.exports = {
|
||||
};
|
||||
|
||||
// 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 windowsPhoneVideoContainers = [".avi", ".3gp", ".3g2", ".wmv", ".3gp", ".3g2", ".mp4", ".m4v"];
|
||||
var windowsVideoContainers = ['.avi', '.flv', '.asx', '.asf', '.mov', '.mp4', '.mpg', '.rm', '.srt', '.swf', '.wmv', '.vob'];
|
||||
var windowsPhoneVideoContainers = ['.avi', '.3gp', '.3g2', '.wmv', '.3gp', '.3g2', '.mp4', '.m4v'];
|
||||
|
||||
// Default aspect ratio 1.78 (16:9 hd video standard)
|
||||
var DEFAULT_ASPECT_RATIO = '1.8';
|
||||
@@ -77,16 +74,16 @@ var DEFAULT_ASPECT_RATIO = '1.8';
|
||||
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
|
||||
|
||||
// Resize method
|
||||
function resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) {
|
||||
var tempPhotoFileName = "";
|
||||
var targetContentType = "";
|
||||
function resizeImage (successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) {
|
||||
var tempPhotoFileName = '';
|
||||
var targetContentType = '';
|
||||
|
||||
if (encodingType == Camera.EncodingType.PNG) {
|
||||
tempPhotoFileName = "camera_cordova_temp_return.png";
|
||||
targetContentType = "image/png";
|
||||
if (encodingType === Camera.EncodingType.PNG) {
|
||||
tempPhotoFileName = 'camera_cordova_temp_return.png';
|
||||
targetContentType = 'image/png';
|
||||
} else {
|
||||
tempPhotoFileName = "camera_cordova_temp_return.jpg";
|
||||
targetContentType = "image/jpeg";
|
||||
tempPhotoFileName = 'camera_cordova_temp_return.jpg';
|
||||
targetContentType = 'image/jpeg';
|
||||
}
|
||||
|
||||
var storageFolder = getAppData().localFolder;
|
||||
@@ -94,12 +91,12 @@ function resizeImage(successCallback, errorCallback, file, targetWidth, targetHe
|
||||
.then(function (storageFile) {
|
||||
return fileIO.readBufferAsync(storageFile);
|
||||
})
|
||||
.then(function(buffer) {
|
||||
.then(function (buffer) {
|
||||
var strBase64 = encodeToBase64String(buffer);
|
||||
var imageData = "data:" + file.contentType + ";base64," + strBase64;
|
||||
var image = new Image();
|
||||
var imageData = 'data:' + file.contentType + ';base64,' + strBase64;
|
||||
var image = new Image(); /* eslint no-undef : 0 */
|
||||
image.src = imageData;
|
||||
image.onload = function() {
|
||||
image.onload = function () {
|
||||
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
|
||||
var imageWidth = ratio * this.width;
|
||||
var imageHeight = ratio * this.height;
|
||||
@@ -110,7 +107,7 @@ function resizeImage(successCallback, errorCallback, file, targetWidth, targetHe
|
||||
canvas.width = imageWidth;
|
||||
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];
|
||||
|
||||
@@ -123,26 +120,25 @@ function resizeImage(successCallback, errorCallback, file, targetWidth, targetHe
|
||||
return fileIO.writeBufferAsync(storagefile, content);
|
||||
})
|
||||
.done(function () {
|
||||
successCallback("ms-appdata:///local/" + storageFileName);
|
||||
successCallback('ms-appdata:///local/' + storageFileName);
|
||||
}, errorCallback);
|
||||
};
|
||||
})
|
||||
.done(null, function(err) {
|
||||
.done(null, function (err) {
|
||||
errorCallback(err);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Because of asynchronous method, so let the successCallback be called in it.
|
||||
function resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight) {
|
||||
fileIO.readBufferAsync(file).done( function(buffer) {
|
||||
function resizeImageBase64 (successCallback, errorCallback, file, targetWidth, targetHeight) {
|
||||
fileIO.readBufferAsync(file).done(function (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(); /* eslint no-undef : 0 */
|
||||
image.src = imageData;
|
||||
|
||||
image.onload = function() {
|
||||
image.onload = function () {
|
||||
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
|
||||
var imageWidth = ratio * this.width;
|
||||
var imageHeight = ratio * this.height;
|
||||
@@ -151,21 +147,21 @@ function resizeImageBase64(successCallback, errorCallback, file, targetWidth, ta
|
||||
canvas.width = imageWidth;
|
||||
canvas.height = imageHeight;
|
||||
|
||||
var ctx = canvas.getContext("2d");
|
||||
var ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
|
||||
|
||||
// The resized file ready for upload
|
||||
var finalFile = canvas.toDataURL(file.contentType);
|
||||
|
||||
// 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);
|
||||
successCallback(newStr);
|
||||
};
|
||||
}, function(err) { errorCallback(err); });
|
||||
}, function (err) { errorCallback(err); });
|
||||
}
|
||||
|
||||
function takePictureFromFile(successCallback, errorCallback, args) {
|
||||
function takePictureFromFile (successCallback, errorCallback, args) {
|
||||
// Detect Windows Phone
|
||||
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
|
||||
takePictureFromFileWP(successCallback, errorCallback, args);
|
||||
@@ -174,94 +170,87 @@ function takePictureFromFile(successCallback, errorCallback, args) {
|
||||
}
|
||||
}
|
||||
|
||||
function takePictureFromFileWP(successCallback, errorCallback, args) {
|
||||
var mediaType = args[6],
|
||||
destinationType = args[1],
|
||||
targetWidth = args[3],
|
||||
targetHeight = args[4],
|
||||
encodingType = args[5];
|
||||
function takePictureFromFileWP (successCallback, errorCallback, args) {
|
||||
var mediaType = args[6];
|
||||
var destinationType = args[1];
|
||||
var targetWidth = args[3];
|
||||
var targetHeight = args[4];
|
||||
var encodingType = args[5];
|
||||
|
||||
/*
|
||||
Need to add and remove an event listener to catch activation state
|
||||
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
|
||||
*/
|
||||
var filePickerActivationHandler = function(eventArgs) {
|
||||
var filePickerActivationHandler = function (eventArgs) {
|
||||
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) {
|
||||
var file = eventArgs.files[0];
|
||||
if (!file) {
|
||||
errorCallback("User didn't choose a file.");
|
||||
webUIApp.removeEventListener("activated", filePickerActivationHandler);
|
||||
webUIApp.removeEventListener('activated', filePickerActivationHandler);
|
||||
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) {
|
||||
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
var storageFolder = getAppData().localFolder;
|
||||
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
|
||||
if(destinationType == Camera.DestinationType.NATIVE_URI) {
|
||||
successCallback("ms-appdata:///local/" + storageFile.name);
|
||||
}
|
||||
else {
|
||||
if (destinationType === Camera.DestinationType.NATIVE_URI) {
|
||||
successCallback('ms-appdata:///local/' + storageFile.name);
|
||||
} else {
|
||||
successCallback(URL.createObjectURL(storageFile));
|
||||
}
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder.");
|
||||
});
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
|
||||
} else {
|
||||
fileIO.readBufferAsync(file).done(function (buffer) {
|
||||
var strBase64 =encodeToBase64String(buffer);
|
||||
var strBase64 = encodeToBase64String(buffer);
|
||||
successCallback(strBase64);
|
||||
}, errorCallback);
|
||||
}
|
||||
}
|
||||
webUIApp.removeEventListener("activated", filePickerActivationHandler);
|
||||
webUIApp.removeEventListener('activated', filePickerActivationHandler);
|
||||
}
|
||||
};
|
||||
|
||||
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
|
||||
if (mediaType == Camera.MediaType.PICTURE) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
|
||||
if (mediaType === Camera.MediaType.PICTURE) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(['.png', '.jpg', '.jpeg']);
|
||||
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
|
||||
}
|
||||
else if (mediaType == Camera.MediaType.VIDEO) {
|
||||
} else if (mediaType === Camera.MediaType.VIDEO) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(windowsPhoneVideoContainers);
|
||||
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
|
||||
}
|
||||
else {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
|
||||
} else {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(['*']);
|
||||
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
|
||||
}
|
||||
|
||||
webUIApp.addEventListener("activated", filePickerActivationHandler);
|
||||
webUIApp.addEventListener('activated', filePickerActivationHandler);
|
||||
fileOpenPicker.pickSingleFileAndContinue();
|
||||
}
|
||||
|
||||
function takePictureFromFileWindows(successCallback, errorCallback, args) {
|
||||
var mediaType = args[6],
|
||||
destinationType = args[1],
|
||||
targetWidth = args[3],
|
||||
targetHeight = args[4],
|
||||
encodingType = args[5];
|
||||
function takePictureFromFileWindows (successCallback, errorCallback, args) {
|
||||
var mediaType = args[6];
|
||||
var destinationType = args[1];
|
||||
var targetWidth = args[3];
|
||||
var targetHeight = args[4];
|
||||
var encodingType = args[5];
|
||||
|
||||
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
|
||||
if (mediaType == Camera.MediaType.PICTURE) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
|
||||
if (mediaType === Camera.MediaType.PICTURE) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(['.png', '.jpg', '.jpeg']);
|
||||
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
|
||||
}
|
||||
else if (mediaType == Camera.MediaType.VIDEO) {
|
||||
} else if (mediaType === Camera.MediaType.VIDEO) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(windowsVideoContainers);
|
||||
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
|
||||
}
|
||||
else {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
|
||||
} else {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(['*']);
|
||||
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
|
||||
}
|
||||
|
||||
@@ -270,30 +259,27 @@ function takePictureFromFileWindows(successCallback, errorCallback, args) {
|
||||
errorCallback("User didn't choose a file.");
|
||||
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) {
|
||||
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
var storageFolder = getAppData().localFolder;
|
||||
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
|
||||
if(destinationType == Camera.DestinationType.NATIVE_URI) {
|
||||
successCallback("ms-appdata:///local/" + storageFile.name);
|
||||
}
|
||||
else {
|
||||
successCallback(URL.createObjectURL(storageFile));
|
||||
}
|
||||
if (destinationType === Camera.DestinationType.NATIVE_URI) {
|
||||
successCallback('ms-appdata:///local/' + storageFile.name);
|
||||
} else {
|
||||
successCallback(URL.createObjectURL(storageFile));
|
||||
}
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder.");
|
||||
});
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
|
||||
} else {
|
||||
fileIO.readBufferAsync(file).done(function (buffer) {
|
||||
var strBase64 =encodeToBase64String(buffer);
|
||||
var strBase64 = encodeToBase64String(buffer);
|
||||
successCallback(strBase64);
|
||||
}, errorCallback);
|
||||
}
|
||||
@@ -303,7 +289,7 @@ function takePictureFromFileWindows(successCallback, errorCallback, args) {
|
||||
});
|
||||
}
|
||||
|
||||
function takePictureFromCamera(successCallback, errorCallback, args) {
|
||||
function takePictureFromCamera (successCallback, errorCallback, args) {
|
||||
// Check if necessary API available
|
||||
if (!Windows.Media.Capture.CameraCaptureUI) {
|
||||
takePictureFromCameraWP(successCallback, errorCallback, args);
|
||||
@@ -312,42 +298,42 @@ 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
|
||||
// so we need to use MediaCapture class instead and implement custom UI for camera
|
||||
var destinationType = args[1],
|
||||
targetWidth = args[3],
|
||||
targetHeight = args[4],
|
||||
encodingType = args[5],
|
||||
saveToPhotoAlbum = args[9],
|
||||
cameraDirection = args[11],
|
||||
capturePreview = null,
|
||||
cameraCaptureButton = null,
|
||||
cameraCancelButton = null,
|
||||
capture = null,
|
||||
captureSettings = null,
|
||||
CaptureNS = Windows.Media.Capture,
|
||||
sensor = null;
|
||||
var destinationType = args[1];
|
||||
var targetWidth = args[3];
|
||||
var targetHeight = args[4];
|
||||
var encodingType = args[5];
|
||||
var saveToPhotoAlbum = args[9];
|
||||
var cameraDirection = args[11];
|
||||
var capturePreview = null;
|
||||
var cameraCaptureButton = null;
|
||||
var cameraCancelButton = null;
|
||||
var capture = null;
|
||||
var captureSettings = null;
|
||||
var CaptureNS = Windows.Media.Capture;
|
||||
var sensor = null;
|
||||
|
||||
function createCameraUI() {
|
||||
function createCameraUI () {
|
||||
// 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
|
||||
// z-order style element for capturePreview and cameraCancelButton elts
|
||||
// is necessary to avoid overriding by another page elements, -1 sometimes is not enough
|
||||
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 = document.createElement('video');
|
||||
capturePreview.style.cssText = 'position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: ' + (HIGHEST_POSSIBLE_Z_INDEX - 1) + ';';
|
||||
|
||||
// Create capture button
|
||||
cameraCaptureButton = document.createElement("button");
|
||||
cameraCaptureButton.innerText = "Take";
|
||||
cameraCaptureButton.style.cssText = buttonStyle + "position: fixed; left: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
|
||||
cameraCaptureButton = document.createElement('button');
|
||||
cameraCaptureButton.innerText = 'Take';
|
||||
cameraCaptureButton.style.cssText = buttonStyle + 'position: fixed; left: 0; bottom: 0; margin: 20px; z-index: ' + HIGHEST_POSSIBLE_Z_INDEX + ';';
|
||||
|
||||
// Create cancel button
|
||||
cameraCancelButton = document.createElement("button");
|
||||
cameraCancelButton.innerText = "Cancel";
|
||||
cameraCancelButton.style.cssText = buttonStyle + "position: fixed; right: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
|
||||
cameraCancelButton = document.createElement('button');
|
||||
cameraCancelButton.innerText = 'Cancel';
|
||||
cameraCancelButton.style.cssText = buttonStyle + 'position: fixed; right: 0; bottom: 0; margin: 20px; z-index: ' + HIGHEST_POSSIBLE_Z_INDEX + ';';
|
||||
|
||||
capture = new CaptureNS.MediaCapture();
|
||||
|
||||
@@ -355,21 +341,21 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video;
|
||||
}
|
||||
|
||||
function continueVideoOnFocus() {
|
||||
function continueVideoOnFocus () {
|
||||
// if preview is defined it would be stuck, play it
|
||||
if (capturePreview) {
|
||||
capturePreview.play();
|
||||
}
|
||||
}
|
||||
|
||||
function startCameraPreview() {
|
||||
function startCameraPreview () {
|
||||
// Search for available camera devices
|
||||
// This is necessary to detect which camera (front or back) we should use
|
||||
var DeviceEnum = Windows.Devices.Enumeration;
|
||||
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
|
||||
window.addEventListener("focus", continueVideoOnFocus);
|
||||
window.addEventListener('focus', continueVideoOnFocus);
|
||||
|
||||
DeviceEnum.DeviceInformation.findAllAsync(DeviceEnum.DeviceClass.videoCapture).then(function (devices) {
|
||||
if (devices.length <= 0) {
|
||||
@@ -378,8 +364,8 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
return;
|
||||
}
|
||||
|
||||
devices.forEach(function(currDev) {
|
||||
if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
|
||||
devices.forEach(function (currDev) {
|
||||
if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel === expectedPanel) {
|
||||
captureSettings.videoDeviceId = currDev.id;
|
||||
}
|
||||
});
|
||||
@@ -418,7 +404,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
// Bind events to controls
|
||||
sensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault();
|
||||
if (sensor !== null) {
|
||||
sensor.addEventListener("orientationchanged", onOrientationChange);
|
||||
sensor.addEventListener('orientationchanged', onOrientationChange);
|
||||
}
|
||||
|
||||
// add click events to capture and cancel buttons
|
||||
@@ -459,7 +445,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
});
|
||||
}
|
||||
|
||||
function destroyCameraPreview() {
|
||||
function destroyCameraPreview () {
|
||||
// If sensor is available, remove event listener
|
||||
if (sensor !== null) {
|
||||
sensor.removeEventListener('orientationchanged', onOrientationChange);
|
||||
@@ -474,7 +460,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
cameraCancelButton.removeEventListener('click', onCameraCancelButtonClick);
|
||||
|
||||
// Remove the focus event handler
|
||||
window.removeEventListener("focus", continueVideoOnFocus);
|
||||
window.removeEventListener('focus', continueVideoOnFocus);
|
||||
|
||||
// Remove elements
|
||||
[capturePreview, cameraCaptureButton, cameraCancelButton].forEach(function (elem) {
|
||||
@@ -490,13 +476,13 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
}
|
||||
}
|
||||
|
||||
function captureAction() {
|
||||
function captureAction () {
|
||||
|
||||
var encodingProperties,
|
||||
fileName,
|
||||
tempFolder = getAppData().temporaryFolder;
|
||||
var encodingProperties;
|
||||
var fileName;
|
||||
var tempFolder = getAppData().temporaryFolder;
|
||||
|
||||
if (encodingType == Camera.EncodingType.PNG) {
|
||||
if (encodingType === Camera.EncodingType.PNG) {
|
||||
fileName = 'photo.png';
|
||||
encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createPng();
|
||||
} else {
|
||||
@@ -505,41 +491,41 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
}
|
||||
|
||||
tempFolder.createFileAsync(fileName, OptUnique)
|
||||
.then(function(tempCapturedFile) {
|
||||
.then(function (tempCapturedFile) {
|
||||
return new WinJS.Promise(function (complete) {
|
||||
var photoStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
|
||||
var finalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
|
||||
capture.capturePhotoToStreamAsync(encodingProperties, photoStream)
|
||||
.then(function() {
|
||||
.then(function () {
|
||||
return Windows.Graphics.Imaging.BitmapDecoder.createAsync(photoStream);
|
||||
})
|
||||
.then(function(dec) {
|
||||
.then(function (dec) {
|
||||
finalStream.size = 0; // BitmapEncoder requires the output stream to be empty
|
||||
return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(finalStream, dec);
|
||||
})
|
||||
.then(function(enc) {
|
||||
.then(function (enc) {
|
||||
// We need to rotate the photo wrt sensor orientation
|
||||
enc.bitmapTransform.rotation = orientationToRotation(sensor.getCurrentOrientation());
|
||||
return enc.flushAsync();
|
||||
})
|
||||
.then(function() {
|
||||
.then(function () {
|
||||
return tempCapturedFile.openAsync(Windows.Storage.FileAccessMode.readWrite);
|
||||
})
|
||||
.then(function(fileStream) {
|
||||
.then(function (fileStream) {
|
||||
return Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(finalStream, fileStream);
|
||||
})
|
||||
.done(function() {
|
||||
.done(function () {
|
||||
photoStream.close();
|
||||
finalStream.close();
|
||||
complete(tempCapturedFile);
|
||||
}, function() {
|
||||
}, function () {
|
||||
photoStream.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();
|
||||
savePhoto(capturedFile, {
|
||||
destinationType: destinationType,
|
||||
@@ -548,13 +534,13 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
encodingType: encodingType,
|
||||
saveToPhotoAlbum: saveToPhotoAlbum
|
||||
}, successCallback, errorCallback);
|
||||
}, function(err) {
|
||||
}, function (err) {
|
||||
destroyCameraPreview();
|
||||
errorCallback(err);
|
||||
});
|
||||
}
|
||||
|
||||
function getAspectRatios(capture) {
|
||||
function getAspectRatios (capture) {
|
||||
var videoDeviceController = capture.videoDeviceController;
|
||||
var photoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo).map(function (element) {
|
||||
return (element.width / element.height).toFixed(1);
|
||||
@@ -583,7 +569,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
});
|
||||
}
|
||||
|
||||
function setAspectRatio(capture, aspect) {
|
||||
function setAspectRatio (capture, aspect) {
|
||||
// Max photo resolution with desired aspect ratio
|
||||
var videoDeviceController = capture.videoDeviceController;
|
||||
var photoResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo)
|
||||
@@ -624,7 +610,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
/**
|
||||
* 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
|
||||
if (this.getAttribute('clicked') === '1') {
|
||||
return false;
|
||||
@@ -637,7 +623,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
/**
|
||||
* 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
|
||||
if (this.getAttribute('clicked') === '1') {
|
||||
return false;
|
||||
@@ -652,7 +638,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
* When the phone orientation change, get the event and change camera preview rotation
|
||||
* @param {Object} e - SimpleOrientationSensorOrientationChangedEventArgs
|
||||
*/
|
||||
function onOrientationChange(e) {
|
||||
function onOrientationChange (e) {
|
||||
setPreviewRotation(e.orientation);
|
||||
}
|
||||
|
||||
@@ -662,29 +648,29 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
|
||||
* @return {number} - Windows.Media.Capture.VideoRotation
|
||||
*/
|
||||
function orientationToRotation(orientation) {
|
||||
function orientationToRotation (orientation) {
|
||||
// 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.graphics.imaging.bitmaprotation.aspx
|
||||
|
||||
switch (orientation) {
|
||||
// portrait
|
||||
case Windows.Devices.Sensors.SimpleOrientation.notRotated:
|
||||
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
|
||||
// landscape
|
||||
case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise:
|
||||
return Windows.Media.Capture.VideoRotation.none;
|
||||
// portrait-flipped (not supported by WinPhone Apps)
|
||||
case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise:
|
||||
// Falling back to portrait default
|
||||
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
|
||||
// landscape-flipped
|
||||
case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise:
|
||||
return Windows.Media.Capture.VideoRotation.clockwise180Degrees;
|
||||
// faceup & facedown
|
||||
default:
|
||||
// Falling back to portrait default
|
||||
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
|
||||
// portrait
|
||||
case Windows.Devices.Sensors.SimpleOrientation.notRotated:
|
||||
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
|
||||
// landscape
|
||||
case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise:
|
||||
return Windows.Media.Capture.VideoRotation.none;
|
||||
// portrait-flipped (not supported by WinPhone Apps)
|
||||
case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise:
|
||||
// Falling back to portrait default
|
||||
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
|
||||
// landscape-flipped
|
||||
case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise:
|
||||
return Windows.Media.Capture.VideoRotation.clockwise180Degrees;
|
||||
// faceup & facedown
|
||||
default:
|
||||
// Falling back to portrait default
|
||||
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -692,7 +678,7 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
* Rotates the current MediaCapture's video
|
||||
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
|
||||
*/
|
||||
function setPreviewRotation(orientation) {
|
||||
function setPreviewRotation (orientation) {
|
||||
capture.setPreviewRotation(orientationToRotation(orientation));
|
||||
}
|
||||
|
||||
@@ -704,19 +690,19 @@ function takePictureFromCameraWP(successCallback, errorCallback, args) {
|
||||
}
|
||||
}
|
||||
|
||||
function takePictureFromCameraWindows(successCallback, errorCallback, args) {
|
||||
var destinationType = args[1],
|
||||
targetWidth = args[3],
|
||||
targetHeight = args[4],
|
||||
encodingType = args[5],
|
||||
allowCrop = !!args[7],
|
||||
saveToPhotoAlbum = args[9],
|
||||
WMCapture = Windows.Media.Capture,
|
||||
cameraCaptureUI = new WMCapture.CameraCaptureUI();
|
||||
function takePictureFromCameraWindows (successCallback, errorCallback, args) {
|
||||
var destinationType = args[1];
|
||||
var targetWidth = args[3];
|
||||
var targetHeight = args[4];
|
||||
var encodingType = args[5];
|
||||
var allowCrop = !!args[7];
|
||||
var saveToPhotoAlbum = args[9];
|
||||
var WMCapture = Windows.Media.Capture;
|
||||
var cameraCaptureUI = new WMCapture.CameraCaptureUI();
|
||||
|
||||
cameraCaptureUI.photoSettings.allowCropping = allowCrop;
|
||||
|
||||
if (encodingType == Camera.EncodingType.PNG) {
|
||||
if (encodingType === Camera.EncodingType.PNG) {
|
||||
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.png;
|
||||
} else {
|
||||
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.jpeg;
|
||||
@@ -727,14 +713,13 @@ function takePictureFromCameraWindows(successCallback, errorCallback, args) {
|
||||
var UIMaxRes = WMCapture.CameraCaptureUIMaxPhotoResolution;
|
||||
var totalPixels = targetWidth * targetHeight;
|
||||
|
||||
if (targetWidth == -1 && targetHeight == -1) {
|
||||
if (targetWidth === -1 && targetHeight === -1) {
|
||||
maxRes = UIMaxRes.highestAvailable;
|
||||
}
|
||||
// Temp fix for CB-10539
|
||||
/*else if (totalPixels <= 320 * 240) {
|
||||
/* else if (totalPixels <= 320 * 240) {
|
||||
maxRes = UIMaxRes.verySmallQvga;
|
||||
}*/
|
||||
else if (totalPixels <= 640 * 480) {
|
||||
} */
|
||||
} else if (totalPixels <= 640 * 480) {
|
||||
maxRes = UIMaxRes.smallVga;
|
||||
} else if (totalPixels <= 1024 * 768) {
|
||||
maxRes = UIMaxRes.mediumXga;
|
||||
@@ -752,7 +737,7 @@ function takePictureFromCameraWindows(successCallback, errorCallback, args) {
|
||||
|
||||
// define focus handler for windows phone 10.0
|
||||
var savePhotoOnFocus = function () {
|
||||
window.removeEventListener("focus", savePhotoOnFocus);
|
||||
window.removeEventListener('focus', savePhotoOnFocus);
|
||||
// call only when the app is in focus again
|
||||
savePhoto(cameraPicture, {
|
||||
destinationType: destinationType,
|
||||
@@ -765,14 +750,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 (navigator.appVersion.indexOf('Windows Phone 10.0') >= 0) {
|
||||
window.addEventListener("focus", savePhotoOnFocus);
|
||||
window.addEventListener('focus', savePhotoOnFocus);
|
||||
}
|
||||
|
||||
cameraCaptureUI.captureFileAsync(WMCapture.CameraCaptureUIMode.photo).done(function (picture) {
|
||||
if (!picture) {
|
||||
errorCallback("User didn't capture a photo.");
|
||||
// Remove the focus handler if present
|
||||
window.removeEventListener("focus", savePhotoOnFocus);
|
||||
window.removeEventListener('focus', savePhotoOnFocus);
|
||||
return;
|
||||
}
|
||||
cameraPicture = picture;
|
||||
@@ -788,31 +773,31 @@ function takePictureFromCameraWindows(successCallback, errorCallback, args) {
|
||||
}, successCallback, errorCallback);
|
||||
}
|
||||
}, function () {
|
||||
errorCallback("Fail to capture a photo.");
|
||||
window.removeEventListener("focus", savePhotoOnFocus);
|
||||
errorCallback('Fail to capture a photo.');
|
||||
window.removeEventListener('focus', savePhotoOnFocus);
|
||||
});
|
||||
}
|
||||
|
||||
function savePhoto(picture, options, successCallback, errorCallback) {
|
||||
function savePhoto (picture, options, successCallback, errorCallback) {
|
||||
// success callback for capture operation
|
||||
var success = function(picture) {
|
||||
if (options.destinationType == Camera.DestinationType.FILE_URI || options.destinationType == Camera.DestinationType.NATIVE_URI) {
|
||||
var success = function (picture) {
|
||||
if (options.destinationType === Camera.DestinationType.FILE_URI || options.destinationType === Camera.DestinationType.NATIVE_URI) {
|
||||
if (options.targetHeight > 0 && options.targetWidth > 0) {
|
||||
resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType);
|
||||
} else {
|
||||
picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) {
|
||||
successCallback("ms-appdata:///local/" + copiedFile.name);
|
||||
},errorCallback);
|
||||
successCallback('ms-appdata:///local/' + copiedFile.name);
|
||||
}, errorCallback);
|
||||
}
|
||||
} else {
|
||||
if (options.targetHeight > 0 && options.targetWidth > 0) {
|
||||
resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight);
|
||||
} else {
|
||||
fileIO.readBufferAsync(picture).done(function(buffer) {
|
||||
fileIO.readBufferAsync(picture).done(function (buffer) {
|
||||
var strBase64 = encodeToBase64String(buffer);
|
||||
picture.deleteAsync().done(function() {
|
||||
picture.deleteAsync().done(function () {
|
||||
successCallback(strBase64);
|
||||
}, function(err) {
|
||||
}, function (err) {
|
||||
errorCallback(err);
|
||||
});
|
||||
}, errorCallback);
|
||||
@@ -822,38 +807,38 @@ function savePhoto(picture, options, successCallback, errorCallback) {
|
||||
|
||||
if (!options.saveToPhotoAlbum) {
|
||||
success(picture);
|
||||
return;
|
||||
|
||||
} else {
|
||||
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
|
||||
var saveFile = function(file) {
|
||||
var saveFile = function (file) {
|
||||
if (file) {
|
||||
// Prevent updates to the remote version of the file until we're done
|
||||
Windows.Storage.CachedFileManager.deferUpdates(file);
|
||||
picture.moveAndReplaceAsync(file)
|
||||
.then(function() {
|
||||
.then(function () {
|
||||
// Let Windows know that we're finished changing the file so
|
||||
// the other app can update the remote version of the file.
|
||||
return Windows.Storage.CachedFileManager.completeUpdatesAsync(file);
|
||||
})
|
||||
.done(function(updateStatus) {
|
||||
.done(function (updateStatus) {
|
||||
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
|
||||
success(picture);
|
||||
} else {
|
||||
errorCallback("File update status is not complete.");
|
||||
errorCallback('File update status is not complete.');
|
||||
}
|
||||
}, errorCallback);
|
||||
} else {
|
||||
errorCallback("Failed to select a file.");
|
||||
errorCallback('Failed to select a file.');
|
||||
}
|
||||
};
|
||||
savePicker.suggestedStartLocation = pickerLocId.picturesLibrary;
|
||||
|
||||
if (options.encodingType === Camera.EncodingType.PNG) {
|
||||
savePicker.fileTypeChoices.insert("PNG", [".png"]);
|
||||
savePicker.suggestedFileName = "photo.png";
|
||||
savePicker.fileTypeChoices.insert('PNG', ['.png']);
|
||||
savePicker.suggestedFileName = 'photo.png';
|
||||
} else {
|
||||
savePicker.fileTypeChoices.insert("JPEG", [".jpg"]);
|
||||
savePicker.suggestedFileName = "photo.jpg";
|
||||
savePicker.fileTypeChoices.insert('JPEG', ['.jpg']);
|
||||
savePicker.suggestedFileName = 'photo.jpg';
|
||||
}
|
||||
|
||||
// If Windows Phone 8.1 use pickSaveFileAndContinue()
|
||||
@@ -863,14 +848,14 @@ function savePhoto(picture, options, successCallback, errorCallback) {
|
||||
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
|
||||
*/
|
||||
var fileSaveHandler = function(eventArgs) {
|
||||
var fileSaveHandler = function (eventArgs) {
|
||||
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
|
||||
var file = eventArgs.file;
|
||||
saveFile(file);
|
||||
webUIApp.removeEventListener("activated", fileSaveHandler);
|
||||
webUIApp.removeEventListener('activated', fileSaveHandler);
|
||||
}
|
||||
};
|
||||
webUIApp.addEventListener("activated", fileSaveHandler);
|
||||
webUIApp.addEventListener('activated', fileSaveHandler);
|
||||
savePicker.pickSaveFileAndContinue();
|
||||
} else {
|
||||
savePicker.pickSaveFileAsync()
|
||||
@@ -879,4 +864,4 @@ function savePhoto(picture, options, successCallback, errorCallback) {
|
||||
}
|
||||
}
|
||||
|
||||
require("cordova/exec/proxy").add("Camera",module.exports);
|
||||
require('cordova/exec/proxy').add('Camera', module.exports);
|
||||
|
||||
14
tests/package.json
Normal file
14
tests/package.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "cordova-plugin-camera-tests",
|
||||
"version": "2.4.1-dev",
|
||||
"description": "",
|
||||
"cordova": {
|
||||
"id": "cordova-plugin-camera-tests",
|
||||
"platforms": []
|
||||
},
|
||||
"keywords": [
|
||||
"ecosystem:cordova"
|
||||
],
|
||||
"author": "",
|
||||
"license": "Apache 2.0"
|
||||
}
|
||||
@@ -22,11 +22,11 @@
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:rim="http://www.blackberry.com/ns/widgets"
|
||||
id="cordova-plugin-camera-tests"
|
||||
version="2.4.0">
|
||||
version="3.0.0">
|
||||
<name>Cordova Camera Plugin Tests</name>
|
||||
<license>Apache 2.0</license>
|
||||
|
||||
<dependency id="cordova-plugin-file" version=">=2.0.0" />
|
||||
<dependency id="cordova-plugin-file-transfer" />
|
||||
|
||||
<js-module src="tests.js" name="tests">
|
||||
</js-module>
|
||||
|
||||
138
tests/tests.js
138
tests/tests.js
@@ -20,26 +20,26 @@
|
||||
*/
|
||||
|
||||
/* globals Camera, resolveLocalFileSystemURL, FileEntry, CameraPopoverOptions, FileTransfer, FileUploadOptions, LocalFileSystem, MSApp */
|
||||
/* jshint jasmine: true */
|
||||
/* eslint-env jasmine */
|
||||
|
||||
exports.defineAutoTests = function () {
|
||||
describe('Camera (navigator.camera)', function () {
|
||||
it("should exist", function () {
|
||||
it('should exist', function () {
|
||||
expect(navigator.camera).toBeDefined();
|
||||
});
|
||||
|
||||
it("should contain a getPicture function", function () {
|
||||
it('should contain a getPicture function', function () {
|
||||
expect(navigator.camera.getPicture).toBeDefined();
|
||||
expect(typeof navigator.camera.getPicture == 'function').toBe(true);
|
||||
expect(typeof navigator.camera.getPicture === 'function').toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Camera Constants (window.Camera + navigator.camera)', function () {
|
||||
it("camera.spec.1 window.Camera should exist", function () {
|
||||
it('camera.spec.1 window.Camera should exist', function () {
|
||||
expect(window.Camera).toBeDefined();
|
||||
});
|
||||
|
||||
it("camera.spec.2 should contain three DestinationType constants", function () {
|
||||
it('camera.spec.2 should contain three DestinationType constants', function () {
|
||||
expect(Camera.DestinationType.DATA_URL).toBe(0);
|
||||
expect(Camera.DestinationType.FILE_URI).toBe(1);
|
||||
expect(Camera.DestinationType.NATIVE_URI).toBe(2);
|
||||
@@ -48,14 +48,14 @@ exports.defineAutoTests = function () {
|
||||
expect(navigator.camera.DestinationType.NATIVE_URI).toBe(2);
|
||||
});
|
||||
|
||||
it("camera.spec.3 should contain two EncodingType constants", function () {
|
||||
it('camera.spec.3 should contain two EncodingType constants', function () {
|
||||
expect(Camera.EncodingType.JPEG).toBe(0);
|
||||
expect(Camera.EncodingType.PNG).toBe(1);
|
||||
expect(navigator.camera.EncodingType.JPEG).toBe(0);
|
||||
expect(navigator.camera.EncodingType.PNG).toBe(1);
|
||||
});
|
||||
|
||||
it("camera.spec.4 should contain three MediaType constants", function () {
|
||||
it('camera.spec.4 should contain three MediaType constants', function () {
|
||||
expect(Camera.MediaType.PICTURE).toBe(0);
|
||||
expect(Camera.MediaType.VIDEO).toBe(1);
|
||||
expect(Camera.MediaType.ALLMEDIA).toBe(2);
|
||||
@@ -64,7 +64,7 @@ exports.defineAutoTests = function () {
|
||||
expect(navigator.camera.MediaType.ALLMEDIA).toBe(2);
|
||||
});
|
||||
|
||||
it("camera.spec.5 should contain three PictureSourceType constants", function () {
|
||||
it('camera.spec.5 should contain three PictureSourceType constants', function () {
|
||||
expect(Camera.PictureSourceType.PHOTOLIBRARY).toBe(0);
|
||||
expect(Camera.PictureSourceType.CAMERA).toBe(1);
|
||||
expect(Camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2);
|
||||
@@ -75,7 +75,6 @@ exports.defineAutoTests = function () {
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
@@ -86,7 +85,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
var fileEntry = null;
|
||||
var pageStartTime = +new Date();
|
||||
|
||||
//default camera options
|
||||
// default camera options
|
||||
var camQualityDefault = ['50', 50];
|
||||
var camDestinationTypeDefault = ['FILE_URI', 1];
|
||||
var camPictureSourceTypeDefault = ['CAMERA', 1];
|
||||
@@ -96,12 +95,12 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
var camCorrectOrientationDefault = ['correctOrientation', false];
|
||||
var camSaveToPhotoAlbumDefault = ['saveToPhotoAlbum', true];
|
||||
|
||||
function log(value) {
|
||||
function log (value) {
|
||||
console.log(value);
|
||||
document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n';
|
||||
}
|
||||
|
||||
function clearStatus() {
|
||||
function clearStatus () {
|
||||
document.getElementById('camera_status').innerHTML = '';
|
||||
document.getElementById('camera_image').src = 'about:blank';
|
||||
var canvas = document.getElementById('canvas');
|
||||
@@ -111,11 +110,11 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
fileEntry = null;
|
||||
}
|
||||
|
||||
function setPicture(url, callback) {
|
||||
function setPicture (url, callback) {
|
||||
try {
|
||||
window.atob(url);
|
||||
// if we got here it is a base64 string (DATA_URL)
|
||||
url = "data:image/jpeg;base64," + url;
|
||||
url = 'data:image/jpeg;base64,' + url;
|
||||
} catch (e) {
|
||||
// not DATA_URL
|
||||
}
|
||||
@@ -134,11 +133,11 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
};
|
||||
}
|
||||
|
||||
function onGetPictureError(e) {
|
||||
function onGetPictureError (e) {
|
||||
log('Error getting picture: ' + (e.code || e));
|
||||
}
|
||||
|
||||
function getPictureWin(data) {
|
||||
function getPictureWin (data) {
|
||||
setPicture(data);
|
||||
// TODO: Fix resolveLocalFileSystemURI to work with native-uri.
|
||||
if (pictureUrl.indexOf('file:') === 0 || pictureUrl.indexOf('content:') === 0 || pictureUrl.indexOf('ms-appdata:') === 0 || pictureUrl.indexOf('assets-library:') === 0) {
|
||||
@@ -155,7 +154,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
}
|
||||
}
|
||||
|
||||
function getPicture() {
|
||||
function getPicture () {
|
||||
clearStatus();
|
||||
var options = extractOptions();
|
||||
log('Getting picture with options: ' + JSON.stringify(options));
|
||||
@@ -168,27 +167,27 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
};
|
||||
}
|
||||
|
||||
function uploadImage() {
|
||||
var ft = new FileTransfer(),
|
||||
options = new FileUploadOptions();
|
||||
options.fileKey = "photo";
|
||||
function uploadImage () {
|
||||
var ft = new FileTransfer();
|
||||
var options = new FileUploadOptions();
|
||||
options.fileKey = 'photo';
|
||||
options.fileName = 'test.jpg';
|
||||
options.mimeType = "image/jpeg";
|
||||
options.mimeType = 'image/jpeg';
|
||||
ft.onprogress = function (progressEvent) {
|
||||
console.log('progress: ' + progressEvent.loaded + ' of ' + progressEvent.total);
|
||||
};
|
||||
var server = "http://cordova-filetransfer.jitsu.com";
|
||||
var server = 'http://sheltered-retreat-43956.herokuapp.com';
|
||||
|
||||
ft.upload(pictureUrl, server + '/upload', win, fail, options);
|
||||
function win(information_back) {
|
||||
function win (information_back) {
|
||||
log('upload complete');
|
||||
}
|
||||
function fail(message) {
|
||||
function fail (message) {
|
||||
log('upload failed: ' + JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
|
||||
function logCallback(apiName, success) {
|
||||
function logCallback (apiName, success) {
|
||||
return function () {
|
||||
log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments)));
|
||||
};
|
||||
@@ -198,20 +197,21 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
* Select image from library using a NATIVE_URI destination type
|
||||
* This calls FileEntry.getMetadata, FileEntry.setMetadata, FileEntry.getParent, FileEntry.file, and FileReader.readAsDataURL.
|
||||
*/
|
||||
function readFile() {
|
||||
function onFileReadAsDataURL(evt) {
|
||||
function readFile () {
|
||||
function onFileReadAsDataURL (evt) {
|
||||
var img = document.getElementById('camera_image');
|
||||
img.style.visibility = "visible";
|
||||
img.style.display = "block";
|
||||
img.style.visibility = 'visible';
|
||||
img.style.display = 'block';
|
||||
img.src = evt.target.result;
|
||||
log("FileReader.readAsDataURL success");
|
||||
log('FileReader.readAsDataURL success');
|
||||
}
|
||||
|
||||
function onFileReceived(file) {
|
||||
function onFileReceived (file) {
|
||||
log('Got file: ' + JSON.stringify(file));
|
||||
fileObj = file;
|
||||
|
||||
/* eslint-disable no-undef */
|
||||
var reader = new FileReader();
|
||||
/* eslint-enable no-undef */
|
||||
reader.onload = function () {
|
||||
log('FileReader.readAsDataURL() - length = ' + reader.result.length);
|
||||
};
|
||||
@@ -228,10 +228,10 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
}
|
||||
}
|
||||
|
||||
function getFileInfo() {
|
||||
function getFileInfo () {
|
||||
// Test FileEntry API here.
|
||||
fileEntry.getMetadata(logCallback('FileEntry.getMetadata', true), logCallback('FileEntry.getMetadata', false));
|
||||
fileEntry.setMetadata(logCallback('FileEntry.setMetadata', true), logCallback('FileEntry.setMetadata', false), { "com.apple.MobileBackup": 1 });
|
||||
fileEntry.setMetadata(logCallback('FileEntry.setMetadata', true), logCallback('FileEntry.setMetadata', false), { 'com.apple.MobileBackup': 1 });
|
||||
fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
|
||||
fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
|
||||
}
|
||||
@@ -240,7 +240,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
* Copy image from library using a NATIVE_URI destination type
|
||||
* This calls FileEntry.copyTo and FileEntry.moveTo.
|
||||
*/
|
||||
function copyImage() {
|
||||
function copyImage () {
|
||||
var onFileSystemReceived = function (fileSystem) {
|
||||
var destDirEntry = fileSystem.root;
|
||||
var origName = fileEntry.name;
|
||||
@@ -249,17 +249,17 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
fileEntry.copyTo(destDirEntry, 'copied_file.png', logCallback('FileEntry.copyTo', true), logCallback('FileEntry.copyTo', false));
|
||||
fileEntry.moveTo(destDirEntry, 'moved_file.png', logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false));
|
||||
|
||||
//cleanup
|
||||
//rename moved file back to original name so other tests can reference image
|
||||
resolveLocalFileSystemURL(destDirEntry.nativeURL+'moved_file.png', function(fileEntry) {
|
||||
// cleanup
|
||||
// rename moved file back to original name so other tests can reference image
|
||||
resolveLocalFileSystemURL(destDirEntry.nativeURL + 'moved_file.png', function (fileEntry) {
|
||||
fileEntry.moveTo(destDirEntry, origName, logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false));
|
||||
console.log('Cleanup: successfully renamed file back to original name');
|
||||
}, function () {
|
||||
console.log('Cleanup: failed to rename file back to original name');
|
||||
});
|
||||
|
||||
//remove copied file
|
||||
resolveLocalFileSystemURL(destDirEntry.nativeURL+'copied_file.png', function(fileEntry) {
|
||||
// remove copied file
|
||||
resolveLocalFileSystemURL(destDirEntry.nativeURL + 'copied_file.png', function (fileEntry) {
|
||||
fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false));
|
||||
console.log('Cleanup: successfully removed copied file');
|
||||
}, function () {
|
||||
@@ -274,11 +274,11 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
* Write image to library using a NATIVE_URI destination type
|
||||
* This calls FileEntry.createWriter, FileWriter.write, and FileWriter.truncate.
|
||||
*/
|
||||
function writeImage() {
|
||||
function writeImage () {
|
||||
var onFileWriterReceived = function (fileWriter) {
|
||||
fileWriter.onwrite = logCallback('FileWriter.write', true);
|
||||
fileWriter.onerror = logCallback('FileWriter.write', false);
|
||||
fileWriter.write("some text!");
|
||||
fileWriter.write('some text!');
|
||||
};
|
||||
|
||||
var onFileTruncateWriterReceived = function (fileWriter) {
|
||||
@@ -291,7 +291,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
fileEntry.createWriter(onFileTruncateWriterReceived, null);
|
||||
}
|
||||
|
||||
function displayImageUsingCanvas() {
|
||||
function displayImageUsingCanvas () {
|
||||
var canvas = document.getElementById('canvas');
|
||||
var img = document.getElementById('camera_image');
|
||||
var w = img.width;
|
||||
@@ -308,11 +308,11 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
* Remove image from library using a NATIVE_URI destination type
|
||||
* This calls FileEntry.remove.
|
||||
*/
|
||||
function removeImage() {
|
||||
function removeImage () {
|
||||
fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false));
|
||||
}
|
||||
|
||||
function testInputTag(inputEl) {
|
||||
function testInputTag (inputEl) {
|
||||
clearStatus();
|
||||
// iOS 6 likes to dead-lock in the onchange context if you
|
||||
// do any alerts or try to remote-debug.
|
||||
@@ -321,7 +321,8 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function testNativeFile2(inputEl) {
|
||||
function testNativeFile2 (inputEl) {
|
||||
/* eslint-disable no-undef */
|
||||
if (!inputEl.value) {
|
||||
alert('No file selected.');
|
||||
return;
|
||||
@@ -331,6 +332,7 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
alert('Got value but no file.');
|
||||
return;
|
||||
}
|
||||
/* eslint-enable no-undef */
|
||||
var URLApi = window.URL || window.webkitURL;
|
||||
if (URLApi) {
|
||||
var blobURL = URLApi.createObjectURL(fileObj);
|
||||
@@ -346,26 +348,26 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
}
|
||||
}
|
||||
|
||||
function extractOptions() {
|
||||
function extractOptions () {
|
||||
var els = document.querySelectorAll('#image-options select');
|
||||
var ret = {};
|
||||
/*jshint -W084 */
|
||||
/* eslint-disable no-cond-assign */
|
||||
for (var i = 0, el; el = els[i]; ++i) {
|
||||
var value = el.value;
|
||||
if (value === '') continue;
|
||||
value = +value;
|
||||
|
||||
if (el.isBool) {
|
||||
ret[el.getAttribute("name")] = !!value;
|
||||
ret[el.getAttribute('name')] = !!value;
|
||||
} else {
|
||||
ret[el.getAttribute("name")] = value;
|
||||
ret[el.getAttribute('name')] = value;
|
||||
}
|
||||
}
|
||||
/*jshint +W084 */
|
||||
/* eslint-enable no-cond-assign */
|
||||
return ret;
|
||||
}
|
||||
|
||||
function createOptionsEl(name, values, selectionDefault) {
|
||||
function createOptionsEl (name, values, selectionDefault) {
|
||||
var openDiv = '<div style="display: inline-block">' + name + ': ';
|
||||
var select = '<select name=' + name + ' id="' + name + '">';
|
||||
|
||||
@@ -375,13 +377,13 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
}
|
||||
|
||||
var options = '';
|
||||
if (typeof values == 'boolean') {
|
||||
if (typeof values === 'boolean') {
|
||||
values = { 'true': 1, 'false': 0 };
|
||||
}
|
||||
for (var k in values) {
|
||||
var isSelected = '';
|
||||
if (selectionDefault) {
|
||||
if (selectionDefault[0] == k) {
|
||||
if (selectionDefault[0] === k) {
|
||||
isSelected = 'selected';
|
||||
}
|
||||
}
|
||||
@@ -400,8 +402,8 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
'<b>Status:</b> <div id="camera_status"></div>' +
|
||||
'img: <img width="100" id="camera_image">' +
|
||||
'canvas: <canvas id="canvas" width="1" height="1"></canvas>' +
|
||||
'</div>',
|
||||
options_div = '<h2>Cordova Camera API Options</h2>' +
|
||||
'</div>';
|
||||
var options_div = '<h2>Cordova Camera API Options</h2>' +
|
||||
'<div id="image-options">' +
|
||||
createOptionsEl('sourceType', Camera.PictureSourceType, camPictureSourceTypeDefault) +
|
||||
createOptionsEl('destinationType', Camera.DestinationType, camDestinationTypeDefault) +
|
||||
@@ -414,9 +416,9 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
createOptionsEl('correctOrientation', true, camCorrectOrientationDefault) +
|
||||
createOptionsEl('saveToPhotoAlbum', true, camSaveToPhotoAlbumDefault) +
|
||||
createOptionsEl('cameraDirection', Camera.Direction) +
|
||||
'</div>',
|
||||
getpicture_div = '<div id="getpicture"></div>',
|
||||
test_procedure = '<h4>Recommended Test Procedure</h4>' +
|
||||
'</div>';
|
||||
var getpicture_div = '<div id="getpicture"></div>';
|
||||
var test_procedure = '<h4>Recommended Test Procedure</h4>' +
|
||||
'Options not specified should be the default value' +
|
||||
'<br>Status box should update with image and info whenever an image is taken or selected from library' +
|
||||
'</p><div style="background:#B0C4DE;border:1px solid #FFA07A;margin:15px 6px 0px;min-width:295px;max-width:97%;padding:4px 0px 2px 10px;min-height:160px;max-height:200px;overflow:auto">' +
|
||||
@@ -429,14 +431,14 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
'</p><li>sourceType=PHOTOLIBRARY<br>mediaType=ALLMEDIA<br>allowEdit=true<br>Should be able to select pics and videos and edit picture if selected</li>' +
|
||||
'</p><li>sourceType=CAMERA<br>targetWidth & targetHeight=50<br>allowEdit=false<br>Do Get File Metadata test below and take note of size<br>Repeat test but with width and height=800. Size should be significantly larger.</li>' +
|
||||
'</p><li>quality=0<br>targetWidth & targetHeight=default<br>allowEdit=false<br>Do Get File Metadata test below and take note of size<br>Repeat test but with quality=80. Size should be significantly larger.</li>' +
|
||||
'</ol></div>',
|
||||
inputs_div = '<h2>Native File Inputs</h2>' +
|
||||
'</ol></div>';
|
||||
var inputs_div = '<h2>Native File Inputs</h2>' +
|
||||
'For the following tests, status box should update with file selected' +
|
||||
'</p><div>input type=file <input type="file" class="testInputTag"></div>' +
|
||||
'<div>capture=camera <input type="file" accept="image/*;capture=camera" class="testInputTag"></div>' +
|
||||
'<div>capture=camcorder <input type="file" accept="video/*;capture=camcorder" class="testInputTag"></div>' +
|
||||
'<div>capture=microphone <input type="file" accept="audio/*;capture=microphone" class="testInputTag"></div>',
|
||||
actions_div = '<h2>Actions</h2>' +
|
||||
'<div>capture=microphone <input type="file" accept="audio/*;capture=microphone" class="testInputTag"></div>';
|
||||
var actions_div = '<h2>Actions</h2>' +
|
||||
'For the following tests, ensure that an image is set in status box' +
|
||||
'</p><div id="metadata"></div>' +
|
||||
'Expected result: Get metadata about file selected.<br>Status box will show, along with the metadata, "Call to FileEntry.getMetadata success, Call to FileEntry.setMetadata success, Call to FileEntry.getParent success"' +
|
||||
@@ -456,20 +458,20 @@ exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
// We need to wrap this code due to Windows security restrictions
|
||||
// see http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences for details
|
||||
if (window.MSApp && window.MSApp.execUnsafeLocalFunction) {
|
||||
MSApp.execUnsafeLocalFunction(function() {
|
||||
MSApp.execUnsafeLocalFunction(function () {
|
||||
contentEl.innerHTML = info_div + options_div + getpicture_div + test_procedure + inputs_div + actions_div;
|
||||
});
|
||||
} else {
|
||||
contentEl.innerHTML = info_div + options_div + getpicture_div + test_procedure + inputs_div + actions_div;
|
||||
}
|
||||
|
||||
var elements = document.getElementsByClassName("testInputTag");
|
||||
var elements = document.getElementsByClassName('testInputTag');
|
||||
var listener = function (e) {
|
||||
testInputTag(e.target);
|
||||
};
|
||||
for (var i = 0; i < elements.length; ++i) {
|
||||
var item = elements[i];
|
||||
item.addEventListener("change", listener, false);
|
||||
item.addEventListener('change', listener, false);
|
||||
}
|
||||
|
||||
createActionButton('Get picture', function () {
|
||||
|
||||
@@ -19,11 +19,11 @@
|
||||
*
|
||||
*/
|
||||
|
||||
var argscheck = require('cordova/argscheck'),
|
||||
exec = require('cordova/exec'),
|
||||
Camera = require('./Camera');
|
||||
// XXX: commented out
|
||||
//CameraPopoverHandle = require('./CameraPopoverHandle');
|
||||
var argscheck = require('cordova/argscheck');
|
||||
var exec = require('cordova/exec');
|
||||
var Camera = require('./Camera');
|
||||
// XXX: commented out
|
||||
// CameraPopoverHandle = require('./CameraPopoverHandle');
|
||||
|
||||
/**
|
||||
* @namespace navigator
|
||||
@@ -131,7 +131,7 @@ for (var key in Camera) {
|
||||
* @param {module:camera.onError} errorCallback
|
||||
* @param {module:camera.CameraOptions} options CameraOptions
|
||||
*/
|
||||
cameraExport.getPicture = function(successCallback, errorCallback, options) {
|
||||
cameraExport.getPicture = function (successCallback, errorCallback, options) {
|
||||
argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
|
||||
options = options || {};
|
||||
var getValue = argscheck.getValue;
|
||||
@@ -150,11 +150,11 @@ cameraExport.getPicture = function(successCallback, errorCallback, options) {
|
||||
var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
|
||||
|
||||
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
|
||||
//return new CameraPopoverHandle();
|
||||
// return new CameraPopoverHandle();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -178,8 +178,8 @@ cameraExport.getPicture = function(successCallback, errorCallback, options) {
|
||||
* alert('Failed because: ' + message);
|
||||
* }
|
||||
*/
|
||||
cameraExport.cleanup = function(successCallback, errorCallback) {
|
||||
exec(successCallback, errorCallback, "Camera", "cleanup", []);
|
||||
cameraExport.cleanup = function (successCallback, errorCallback) {
|
||||
exec(successCallback, errorCallback, 'Camera', 'cleanup', []);
|
||||
};
|
||||
|
||||
module.exports = cameraExport;
|
||||
|
||||
@@ -23,79 +23,79 @@
|
||||
* @module Camera
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* @description
|
||||
* Defines the output format of `Camera.getPicture` call.
|
||||
* _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
|
||||
* `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
|
||||
* disable any image modifications (resize, quality change, cropping, etc.) due
|
||||
* to implementation specific.
|
||||
*
|
||||
* @enum {number}
|
||||
*/
|
||||
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 */
|
||||
DATA_URL: 0,
|
||||
/** Return file uri (content://media/external/images/media/2 for Android) */
|
||||
FILE_URI: 1,
|
||||
/** Return native uri (eg. asset-library://... for iOS) */
|
||||
NATIVE_URI: 2
|
||||
},
|
||||
/**
|
||||
* @enum {number}
|
||||
*/
|
||||
EncodingType:{
|
||||
/** Return JPEG encoded image */
|
||||
JPEG: 0,
|
||||
/** Return PNG encoded image */
|
||||
PNG: 1
|
||||
},
|
||||
/**
|
||||
* @enum {number}
|
||||
*/
|
||||
MediaType:{
|
||||
/** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */
|
||||
PICTURE: 0,
|
||||
/** Allow selection of video only, ONLY RETURNS URL */
|
||||
VIDEO: 1,
|
||||
/** Allow selection from all media types */
|
||||
ALLMEDIA : 2
|
||||
},
|
||||
/**
|
||||
* @description
|
||||
* Defines the output format of `Camera.getPicture` call.
|
||||
* _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
|
||||
* along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
|
||||
* change, cropping, etc.) due to implementation specific.
|
||||
*
|
||||
* @enum {number}
|
||||
*/
|
||||
PictureSourceType:{
|
||||
/** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */
|
||||
PHOTOLIBRARY : 0,
|
||||
/** Take picture from camera */
|
||||
CAMERA : 1,
|
||||
/** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */
|
||||
SAVEDPHOTOALBUM : 2
|
||||
},
|
||||
/**
|
||||
* Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
|
||||
* @enum {number}
|
||||
*/
|
||||
PopoverArrowDirection:{
|
||||
ARROW_UP : 1,
|
||||
ARROW_DOWN : 2,
|
||||
ARROW_LEFT : 4,
|
||||
ARROW_RIGHT : 8,
|
||||
ARROW_ANY : 15
|
||||
},
|
||||
/**
|
||||
* @enum {number}
|
||||
*/
|
||||
Direction:{
|
||||
/** Use the back-facing camera */
|
||||
BACK: 0,
|
||||
/** Use the front-facing camera */
|
||||
FRONT: 1
|
||||
}
|
||||
/**
|
||||
* @description
|
||||
* Defines the output format of `Camera.getPicture` call.
|
||||
* _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
|
||||
* `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
|
||||
* disable any image modifications (resize, quality change, cropping, etc.) due
|
||||
* to implementation specific.
|
||||
*
|
||||
* @enum {number}
|
||||
*/
|
||||
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 */
|
||||
DATA_URL: 0,
|
||||
/** Return file uri (content://media/external/images/media/2 for Android) */
|
||||
FILE_URI: 1,
|
||||
/** Return native uri (eg. asset-library://... for iOS) */
|
||||
NATIVE_URI: 2
|
||||
},
|
||||
/**
|
||||
* @enum {number}
|
||||
*/
|
||||
EncodingType: {
|
||||
/** Return JPEG encoded image */
|
||||
JPEG: 0,
|
||||
/** Return PNG encoded image */
|
||||
PNG: 1
|
||||
},
|
||||
/**
|
||||
* @enum {number}
|
||||
*/
|
||||
MediaType: {
|
||||
/** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */
|
||||
PICTURE: 0,
|
||||
/** Allow selection of video only, ONLY RETURNS URL */
|
||||
VIDEO: 1,
|
||||
/** Allow selection from all media types */
|
||||
ALLMEDIA: 2
|
||||
},
|
||||
/**
|
||||
* @description
|
||||
* Defines the output format of `Camera.getPicture` call.
|
||||
* _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
|
||||
* along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
|
||||
* change, cropping, etc.) due to implementation specific.
|
||||
*
|
||||
* @enum {number}
|
||||
*/
|
||||
PictureSourceType: {
|
||||
/** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */
|
||||
PHOTOLIBRARY: 0,
|
||||
/** Take picture from camera */
|
||||
CAMERA: 1,
|
||||
/** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */
|
||||
SAVEDPHOTOALBUM: 2
|
||||
},
|
||||
/**
|
||||
* Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
|
||||
* @enum {number}
|
||||
*/
|
||||
PopoverArrowDirection: {
|
||||
ARROW_UP: 1,
|
||||
ARROW_DOWN: 2,
|
||||
ARROW_LEFT: 4,
|
||||
ARROW_RIGHT: 8,
|
||||
ARROW_ANY: 15
|
||||
},
|
||||
/**
|
||||
* @enum {number}
|
||||
*/
|
||||
Direction: {
|
||||
/** Use the back-facing camera */
|
||||
BACK: 0,
|
||||
/** Use the front-facing camera */
|
||||
FRONT: 1
|
||||
}
|
||||
};
|
||||
|
||||
@@ -23,8 +23,8 @@
|
||||
* @ignore in favour of iOS' one
|
||||
* A handle to an image picker popover.
|
||||
*/
|
||||
var CameraPopoverHandle = function() {
|
||||
this.setPosition = function(popoverOptions) {
|
||||
var CameraPopoverHandle = function () {
|
||||
this.setPosition = function (popoverOptions) {
|
||||
console.log('CameraPopoverHandle.setPosition is only supported on iOS.');
|
||||
};
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
var Camera = require('./Camera');
|
||||
|
||||
/**
|
||||
/**
|
||||
* @namespace navigator
|
||||
*/
|
||||
|
||||
|
||||
@@ -25,9 +25,9 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
window.navigator.webkitGetUserMedia(
|
||||
{ video: true },
|
||||
function (stream) {
|
||||
var video = document.getElementById('v'),
|
||||
canvas = document.getElementById('c'),
|
||||
camera = document.getElementById('camera');
|
||||
var video = document.getElementById('v');
|
||||
var canvas = document.getElementById('c');
|
||||
var camera = document.getElementById('camera');
|
||||
video.autoplay = true;
|
||||
video.width = window.innerWidth;
|
||||
video.height = window.innerHeight - 100;
|
||||
|
||||
@@ -48,7 +48,7 @@ var exec = require('cordova/exec');
|
||||
* }
|
||||
* @module CameraPopoverHandle
|
||||
*/
|
||||
var CameraPopoverHandle = function() {
|
||||
var CameraPopoverHandle = function () {
|
||||
/**
|
||||
* Can be used to reposition the image selection dialog,
|
||||
* for example, when the device orientation changes.
|
||||
@@ -57,9 +57,9 @@ var CameraPopoverHandle = function() {
|
||||
* @method setPosition
|
||||
* @param {module:CameraPopoverOptions} popoverOptions
|
||||
*/
|
||||
this.setPosition = function(popoverOptions) {
|
||||
this.setPosition = function (popoverOptions) {
|
||||
var args = [ popoverOptions ];
|
||||
exec(null, null, "Camera", "repositionPopover", args);
|
||||
exec(null, null, 'Camera', 'repositionPopover', args);
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user