openEventsPlatformApp/plugins/cordova-plugin-camera/src/blackberry10/index.js
plugins/cordova-plugin-camera/src/blackberry10/index.jsRaw
1/*
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20*/
21
22/* globals qnx, FileError, PluginResult */
23
24var PictureSourceType = {
25 PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
26 CAMERA : 1, // Take picture from camera
27 SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
28 },
29 DestinationType = {
30 DATA_URL: 0, // Return base64 encoded string
31 FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
32 NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
33 },
34 savePath = window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', '') + '/shared/camera/',
35 invokeAvailable = true;
36
37//check for camera card - it isn't currently availble in work perimeter
38window.qnx.webplatform.getApplication().invocation.queryTargets(
39 {
40 type: 'image/jpeg',
41 action: 'bb.action.CAPTURE',
42 target_type: 'CARD'
43 },
44 function (error, targets) {
45 invokeAvailable = !error && targets && targets instanceof Array &&
46 targets.filter(function (t) { return t.default === 'sys.camera.card'; }).length > 0;
47 }
48);
49
50//open a webview with getUserMedia camera card implementation when camera card not available
51function showCameraDialog (done, cancel, fail) {
52 var wv = qnx.webplatform.createWebView(function () {
53 wv.url = 'local:///chrome/camera.html';
54 wv.allowQnxObject = true;
55 wv.allowRpc = true;
56 wv.zOrder = 1;
57 wv.setGeometry(0, 0, screen.width, screen.height);
58 wv.backgroundColor = 0x00000000;
59 wv.active = true;
60 wv.visible = true;
61 wv.on('UserMediaRequest', function (evt, args) {
62 wv.allowUserMedia(JSON.parse(args).id, 'CAMERA_UNIT_REAR');
63 });
64 wv.on('JavaScriptCallback', function (evt, data) {
65 var args = JSON.parse(data).args;
66 if (args[0] === 'cordova-plugin-camera') {
67 if (args[1] === 'cancel') {
68 cancel('User canceled');
69 } else if (args[1] === 'error') {
70 fail(args[2]);
71 } else {
72 saveImage(args[1], done, fail);
73 }
74 wv.un('JavaScriptCallback', arguments.callee);
75 wv.visible = false;
76 wv.destroy();
77 qnx.webplatform.getApplication().unlockRotation();
78 }
79 });
80 wv.on('Destroyed', function () {
81 wv.delete();
82 });
83 qnx.webplatform.getApplication().lockRotation();
84 qnx.webplatform.getController().dispatchEvent('webview.initialized', [wv]);
85 });
86}
87
88//create unique name for saved file (same pattern as BB10 camera app)
89function imgName() {
90 var date = new Date(),
91 pad = function (n) { return n < 10 ? '0' + n : n; };
92 return 'IMG_' + date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate()) + '_' +
93 pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds()) + '.png';
94}
95
96//convert dataURI to Blob
97function dataURItoBlob(dataURI) {
98 var byteString = atob(dataURI.split(',')[1]),
99 mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0],
100 arrayBuffer = new ArrayBuffer(byteString.length),
101 ia = new Uint8Array(arrayBuffer),
102 i;
103 for (i = 0; i < byteString.length; i++) {
104 ia[i] = byteString.charCodeAt(i);
105 }
106 return new Blob([new DataView(arrayBuffer)], { type: mimeString });
107}
108
109//save dataURI to file system and call success with path
110function saveImage(data, success, fail) {
111 var name = savePath + imgName();
112 require('lib/webview').setSandbox(false);
113 window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) {
114 fs.root.getFile(name, { create: true }, function (entry) {
115 entry.createWriter(function (writer) {
116 writer.onwriteend = function () {
117 success(name);
118 };
119 writer.onerror = fail;
120 writer.write(dataURItoBlob(data));
121 });
122 }, fail);
123 }, fail);
124}
125
126function encodeBase64(filePath, callback) {
127 var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox, // save original sandbox value
128 errorHandler = function (err) {
129 var msg = "An error occured: ";
130
131 switch (err.code) {
132 case FileError.NOT_FOUND_ERR:
133 msg += "File or directory not found";
134 break;
135
136 case FileError.NOT_READABLE_ERR:
137 msg += "File or directory not readable";
138 break;
139
140 case FileError.PATH_EXISTS_ERR:
141 msg += "File or directory already exists";
142 break;
143
144 case FileError.TYPE_MISMATCH_ERR:
145 msg += "Invalid file type";
146 break;
147
148 default:
149 msg += "Unknown Error";
150 break;
151 }
152
153 // set it back to original value
154 window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
155 callback(msg);
156 },
157 gotFile = function (fileEntry) {
158 fileEntry.file(function (file) {
159 var reader = new FileReader();
160
161 reader.onloadend = function (e) {
162 // set it back to original value
163 window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
164 callback(this.result);
165 };
166
167 reader.readAsDataURL(file);
168 }, errorHandler);
169 },
170 onInitFs = function (fs) {
171 window.qnx.webplatform.getController().setFileSystemSandbox = false;
172 fs.root.getFile(filePath, {create: false}, gotFile, errorHandler);
173 };
174
175 window.webkitRequestFileSystem(window.TEMPORARY, 10 * 1024 * 1024, onInitFs, errorHandler); // set size to 10MB max
176}
177
178module.exports = {
179 takePicture: function (success, fail, args, env) {
180 var destinationType = JSON.parse(decodeURIComponent(args[1])),
181 sourceType = JSON.parse(decodeURIComponent(args[2])),
182 result = new PluginResult(args, env),
183 done = function (data) {
184 if (destinationType === DestinationType.FILE_URI) {
185 data = "file://" + data;
186 result.callbackOk(data, false);
187 } else {
188 encodeBase64(data, function (data) {
189 if (/^data:/.test(data)) {
190 data = data.slice(data.indexOf(",") + 1);
191 result.callbackOk(data, false);
192 } else {
193 result.callbackError(data, false);
194 }
195 });
196 }
197 },
198 cancel = function (reason) {
199 result.callbackError(reason, false);
200 },
201 invoked = function (error) {
202 if (error) {
203 result.callbackError(error, false);
204 }
205 };
206
207 switch(sourceType) {
208 case PictureSourceType.CAMERA:
209 if (invokeAvailable) {
210 window.qnx.webplatform.getApplication().cards.camera.open("photo", done, cancel, invoked);
211 } else {
212 showCameraDialog(done, cancel, fail);
213 }
214 break;
215
216 case PictureSourceType.PHOTOLIBRARY:
217 case PictureSourceType.SAVEDPHOTOALBUM:
218 window.qnx.webplatform.getApplication().cards.filePicker.open({
219 mode: "Picker",
220 type: ["picture"]
221 }, done, cancel, invoked);
222 break;
223 }
224
225 result.noResult(true);
226 }
227};