~ps-jenkins/cordova-ubuntu-tests/latestsnapshot-2.11+14.04.20131106-0ubuntu1

« back to all changes in this revision

Viewing changes to www/camera/index.html

  • Committer: VĂ­ctor R. Ruiz
  • Date: 2013-07-25 13:09:34 UTC
  • Revision ID: victor.ruiz@canonical.com-20130725130934-d4q95mh8eehbv363
Initial import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!DOCTYPE html>
 
2
<!--
 
3
 
 
4
 Licensed to the Apache Software Foundation (ASF) under one
 
5
 or more contributor license agreements.  See the NOTICE file
 
6
 distributed with this work for additional information
 
7
 regarding copyright ownership.  The ASF licenses this file
 
8
 to you under the Apache License, Version 2.0 (the
 
9
 "License"); you may not use this file except in compliance
 
10
 with the License.  You may obtain a copy of the License at
 
11
 
 
12
   http://www.apache.org/licenses/LICENSE-2.0
 
13
 
 
14
 Unless required by applicable law or agreed to in writing,
 
15
 software distributed under the License is distributed on an
 
16
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 
17
 KIND, either express or implied.  See the License for the
 
18
 specific language governing permissions and limitations
 
19
 under the License.
 
20
 
 
21
-->
 
22
 
 
23
 
 
24
<html>
 
25
  <head>
 
26
    <meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,maximum-scale=1.0,initial-scale=1.0" />
 
27
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <!-- ISO-8859-1 -->
 
28
    <title>Cordova Mobile Spec</title>
 
29
    <link rel="stylesheet" href="../master.css" type="text/css" media="screen" title="no title" charset="utf-8">
 
30
    <script type="text/javascript" charset="utf-8" src="../cordova-incl.js"></script>
 
31
 
 
32
 
 
33
<script type="text/javascript" charset="utf-8">
 
34
 
 
35
    var deviceReady = false;
 
36
    var platformId = cordova.require('cordova/platform').id;
 
37
    var pictureUrl = null;
 
38
    var fileObj = null;
 
39
    var fileEntry = null;
 
40
    var pageStartTime = +new Date();
 
41
    
 
42
    //default camera options
 
43
    var camQualityDefault = ['quality value', 50];
 
44
    var camDestinationTypeDefault = ['FILE_URI', 1];
 
45
    var camPictureSourceTypeDefault = ['CAMERA', 1];
 
46
    var camAllowEditDefault = ['allowEdit', false];
 
47
    var camEncodingTypeDefault = ['JPEG', 0];
 
48
    var camMediaTypeDefault = ['mediaType', 0];
 
49
    var camCorrectOrientationDefault = ['correctOrientation', false];
 
50
    var camSaveToPhotoAlbumDefault = ['saveToPhotoAlbum', true];
 
51
    
 
52
 
 
53
    //-------------------------------------------------------------------------
 
54
    // Camera
 
55
    //-------------------------------------------------------------------------
 
56
 
 
57
    function log(value) {
 
58
        console.log(value);
 
59
        document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n';
 
60
    }
 
61
 
 
62
    function clearStatus() {
 
63
        document.getElementById('camera_status').innerHTML = '';
 
64
        document.getElementById('camera_image').src = 'about:blank';
 
65
        var canvas = document.getElementById('canvas');
 
66
        canvas.width = canvas.height = 1;
 
67
        pictureUrl = null;
 
68
        fileObj = null;
 
69
        fileEntry = null;
 
70
    }
 
71
 
 
72
    function setPicture(url, callback) {
 
73
                try {
 
74
                        window.atob(url);
 
75
                        // if we got here it is a base64 string (DATA_URL)
 
76
                        url = "data:image/jpeg;base64," + url;
 
77
                } catch (e) {
 
78
                        // not DATA_URL
 
79
                    log('URL: ' + url.slice(0, 100));
 
80
                }    
 
81
    
 
82
        pictureUrl = url;
 
83
        var img = document.getElementById('camera_image');
 
84
        var startTime = new Date();
 
85
        img.src = url;
 
86
        img.onloadend = function() {
 
87
            log('Image tag load time: ' + (new Date() - startTime));
 
88
            callback && callback();
 
89
        };
 
90
    }
 
91
 
 
92
    function onGetPictureError(e) {
 
93
        log('Error getting picture: ' + e.code);
 
94
    }
 
95
 
 
96
    function getPictureWin(data) {
 
97
        setPicture(data);
 
98
        // TODO: Fix resolveLocalFileSystemURI to work with native-uri.
 
99
        if (pictureUrl.indexOf('file:') == 0) {
 
100
            resolveLocalFileSystemURI(data, function(e) {
 
101
                fileEntry = e;
 
102
                logCallback('resolveLocalFileSystemURI()', true)(e);
 
103
            }, logCallback('resolveLocalFileSystemURI()', false));
 
104
        } else if (pictureUrl.indexOf('data:image/jpeg;base64' == 0)) {
 
105
                // do nothing
 
106
        } else {
 
107
            var path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' ');
 
108
            fileEntry = new FileEntry('image_name.png', path);
 
109
        }
 
110
    }
 
111
 
 
112
    function getPicture() {
 
113
        clearStatus();
 
114
        var options = extractOptions();
 
115
        log('Getting picture with options: ' + JSON.stringify(options));
 
116
        var popoverHandle = navigator.camera.getPicture(getPictureWin, onGetPictureError, options);
 
117
 
 
118
        // Reposition the popover if the orientation changes.
 
119
        window.onorientationchange = function() {
 
120
            var newPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, 0);
 
121
            popoverHandle.setPosition(newPopoverOptions);
 
122
        }
 
123
    }
 
124
 
 
125
    function uploadImage() {
 
126
        var ft = new FileTransfer(),
 
127
            uploadcomplete=0,
 
128
            progress = 0,
 
129
            options = new FileUploadOptions();
 
130
        options.fileKey="photo";
 
131
        options.fileName='test.jpg';
 
132
        options.mimeType="image/jpeg";
 
133
        ft.onprogress = function(progressEvent) {
 
134
            log('progress: ' + progressEvent.loaded + ' of ' + progressEvent.total);
 
135
        };
 
136
        var server = "http://cordova-filetransfer.jitsu.com";
 
137
 
 
138
        ft.upload(pictureUrl, server + '/upload', win, fail, options);
 
139
        function win(information_back){
 
140
            log('upload complete');
 
141
        }
 
142
        function fail(message) {
 
143
            log('upload failed: ' + JSON.stringify(message));
 
144
        }
 
145
    }
 
146
 
 
147
    function logCallback(apiName, success) {
 
148
        return function() {
 
149
            log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments)));
 
150
        };
 
151
    }
 
152
 
 
153
    /**
 
154
     * Select image from library using a NATIVE_URI destination type
 
155
     * This calls FileEntry.getMetadata, FileEntry.setMetadata, FileEntry.getParent, FileEntry.file, and FileReader.readAsDataURL.
 
156
     */
 
157
    function readFile() {
 
158
        function onFileReadAsDataURL(evt) {
 
159
            var img = document.getElementById('camera_image');
 
160
            img.style.visibility = "visible";
 
161
            img.style.display = "block";
 
162
            img.src = evt.target.result;
 
163
            log("FileReader.readAsDataURL success");
 
164
        };
 
165
 
 
166
        function onFileReceived(file) {
 
167
            log('Got file: ' + JSON.stringify(file));
 
168
            fileObj = file;
 
169
 
 
170
            var reader = new FileReader();
 
171
            reader.onload = function() {
 
172
                log('FileReader.readAsDataURL() - length = ' + reader.result.length);
 
173
            };
 
174
            reader.onerror = logCallback('FileReader.readAsDataURL', false);
 
175
            reader.readAsDataURL(file);
 
176
        };
 
177
        // Test out onFileReceived when the file object was set via a native <input> elements.
 
178
        if (fileObj) {
 
179
            onFileReceived(fileObj);
 
180
        } else {
 
181
            fileEntry.file(onFileReceived, logCallback('FileEntry.file', false));
 
182
        }
 
183
    }
 
184
    function getFileInfo() {
 
185
        // Test FileEntry API here.
 
186
        fileEntry.getMetadata(logCallback('FileEntry.getMetadata', true), logCallback('FileEntry.getMetadata', false));
 
187
        fileEntry.setMetadata(logCallback('FileEntry.setMetadata', true), logCallback('FileEntry.setMetadata', false), { "com.apple.MobileBackup": 1 });
 
188
        fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
 
189
        fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
 
190
    };
 
191
 
 
192
    /**
 
193
     * Copy image from library using a NATIVE_URI destination type
 
194
     * This calls FileEntry.copyTo and FileEntry.moveTo.
 
195
     */
 
196
    function copyImage() {
 
197
        var onFileSystemReceived = function(fileSystem) {
 
198
            var destDirEntry = fileSystem.root;
 
199
 
 
200
            // Test FileEntry API here.
 
201
            fileEntry.copyTo(destDirEntry, 'copied_file.png', logCallback('FileEntry.copyTo', true), logCallback('FileEntry.copyTo', false));
 
202
            fileEntry.moveTo(destDirEntry, 'moved_file.png', logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false));
 
203
        };
 
204
 
 
205
        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, onFileSystemReceived, null);
 
206
    };
 
207
 
 
208
    /**
 
209
     * Write image to library using a NATIVE_URI destination type
 
210
     * This calls FileEntry.createWriter, FileWriter.write, and FileWriter.truncate.
 
211
     */
 
212
    function writeImage() {
 
213
        var onFileWriterReceived = function(fileWriter) {
 
214
            fileWriter.onwrite = logCallback('FileWriter.write', true);
 
215
            fileWriter.onerror = logCallback('FileWriter.write', false);
 
216
            fileWriter.write("some text!");
 
217
        };
 
218
 
 
219
        var onFileTruncateWriterReceived = function(fileWriter) {
 
220
            fileWriter.onwrite = logCallback('FileWriter.truncate', true);
 
221
            fileWriter.onerror = logCallback('FileWriter.truncate', false);
 
222
            fileWriter.truncate(10);
 
223
        };
 
224
 
 
225
        fileEntry.createWriter(onFileWriterReceived, logCallback('FileEntry.createWriter', false));
 
226
        fileEntry.createWriter(onFileTruncateWriterReceived, null);
 
227
    };
 
228
 
 
229
    function displayImageUsingCanvas() {
 
230
        var canvas = document.getElementById('canvas');
 
231
        var img = document.getElementById('camera_image');
 
232
        var w = img.width;
 
233
        var h = img.height;
 
234
        h = 100 / w * h;
 
235
        w = 100;
 
236
        canvas.width = w;
 
237
        canvas.height= h;
 
238
        var context = canvas.getContext('2d');
 
239
        context.drawImage(img, 0, 0, w, h);
 
240
    };
 
241
 
 
242
    /**
 
243
     * Remove image from library using a NATIVE_URI destination type
 
244
     * This calls FileEntry.remove.
 
245
     */
 
246
    function removeImage() {
 
247
        fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false));
 
248
    };
 
249
 
 
250
    function testInputTag(inputEl) {
 
251
        clearStatus();
 
252
        // iOS 6 likes to dead-lock in the onchange context if you
 
253
        // do any alerts or try to remote-debug.
 
254
        window.setTimeout(function() {
 
255
            testNativeFile2(inputEl);
 
256
        }, 0);
 
257
    };
 
258
 
 
259
    function testNativeFile2(inputEl) {
 
260
        if (!inputEl.value) {
 
261
            alert('No file selected.');
 
262
            return;
 
263
        }
 
264
        fileObj = inputEl.files[0];
 
265
        if (!fileObj) {
 
266
            alert('Got value but no file.');
 
267
            return;
 
268
        }
 
269
        var URLApi = window.URL || window.webkitURL;
 
270
        if (URLApi) {
 
271
            var blobURL = URLApi.createObjectURL(fileObj);
 
272
            if (blobURL) {
 
273
                setPicture(blobURL, function() {
 
274
                    URLApi.revokeObjectURL(blobURL);
 
275
                });
 
276
            } else {
 
277
                log('URL.createObjectURL returned null');
 
278
            }
 
279
        } else {
 
280
            log('URL.createObjectURL() not supported.');
 
281
        }
 
282
    }
 
283
 
 
284
    function extractOptions() {
 
285
        var els = document.querySelectorAll('#image-options select');
 
286
        var ret = {};
 
287
        for (var i = 0, el; el = els[i]; ++i) {
 
288
            var value = el.value;
 
289
            if (value === '') continue;
 
290
            if (el.isBool) {
 
291
                ret[el.keyName] = !!+value;
 
292
            } else {
 
293
                ret[el.keyName] = +value;
 
294
            }
 
295
        }
 
296
        return ret;
 
297
    }
 
298
 
 
299
    function createOptionsEl(name, values, selectionDefault) {
 
300
        var container = document.createElement('div');
 
301
        container.style.display = 'inline-block';
 
302
        container.appendChild(document.createTextNode(name + ': '));
 
303
        var select = document.createElement('select');
 
304
        select.keyName = name;
 
305
        container.appendChild(select);
 
306
        
 
307
        // if we didn't get a default value, insert the blank <default> entry
 
308
        if (selectionDefault == undefined) {
 
309
            var opt = document.createElement('option');
 
310
            opt.value = '';
 
311
            opt.text = '<default>';
 
312
            select.appendChild(opt);
 
313
        }
 
314
        
 
315
        select.isBool = typeof values == 'boolean';
 
316
        if (select.isBool) {
 
317
            values = {'true': 1, 'false': 0};
 
318
        }
 
319
        
 
320
        for (var k in values) {
 
321
            var opt = document.createElement('option');
 
322
            opt.value = values[k];
 
323
            opt.textContent = k;
 
324
            if (selectionDefault) {
 
325
                if (selectionDefault[0] == k) {
 
326
                    opt.selected = true;
 
327
                }
 
328
            }
 
329
            select.appendChild(opt);
 
330
        }
 
331
        var optionsDiv = document.getElementById('image-options');
 
332
        optionsDiv.appendChild(container);
 
333
    }
 
334
 
 
335
    /**
 
336
     * Function called when page has finished loading.
 
337
     */
 
338
    function init() {
 
339
        document.addEventListener("deviceready", function() {
 
340
            deviceReady = true;
 
341
            console.log("Device="+device.platform+" "+device.version);
 
342
            createOptionsEl('sourceType', Camera.PictureSourceType, camPictureSourceTypeDefault);
 
343
            createOptionsEl('destinationType', Camera.DestinationType, camDestinationTypeDefault);
 
344
            createOptionsEl('encodingType', Camera.EncodingType, camEncodingTypeDefault);
 
345
            createOptionsEl('mediaType', Camera.MediaType, camMediaTypeDefault);
 
346
            createOptionsEl('quality', {'0': 0, '50': 50, '80': 80, '100': 100}, camQualityDefault);
 
347
            createOptionsEl('targetWidth', {'50': 50, '200': 200, '800': 800, '2048': 2048});
 
348
            createOptionsEl('targetHeight', {'50': 50, '200': 200, '800': 800, '2048': 2048});
 
349
            createOptionsEl('allowEdit', true, camAllowEditDefault);
 
350
            createOptionsEl('correctOrientation', true, camCorrectOrientationDefault);
 
351
            createOptionsEl('saveToPhotoAlbum', true, camSaveToPhotoAlbumDefault);
 
352
            createOptionsEl('cameraDirection', Camera.Direction);
 
353
                          
 
354
        }, false);
 
355
        window.setTimeout(function() {
 
356
            if (!deviceReady) {
 
357
                alert("Error: Apache Cordova did not initialize.  Demo will not run correctly.");
 
358
            }
 
359
        },1000);
 
360
    };
 
361
 
 
362
</script>
 
363
 
 
364
  </head>
 
365
  <body onload="init();" id="stage" class="theme">
 
366
 
 
367
    <h1>Camera</h1>
 
368
    <div id="info" style="white-space: pre-wrap">
 
369
        <b>Status:</b> <div id="camera_status"></div>
 
370
        img: <img width="100" id="camera_image">
 
371
        canvas: <canvas id="canvas" width="1" height="1"></canvas>
 
372
    </div>
 
373
    <h2>Cordova Camera API</h2>
 
374
    <div id="image-options"></div>
 
375
    <div class="btn large" onclick="getPicture();">camera.getPicture()</div>
 
376
    <h2>Native File Inputs</h2>
 
377
    <div>input type=file <input type="file" onchange="testInputTag(this)"></div>
 
378
    <div>capture=camera <input type="file" accept="image/*;capture=camera" onchange="testInputTag(this)"></div>
 
379
    <div>capture=camcorder <input type="file" accept="video/*;capture=camcorder" onchange="testInputTag(this)"></div>
 
380
    <div>capture=microphone <input type="file" accept="audio/*;capture=microphone" onchange="testInputTag(this)"></div>
 
381
    <h2>Actions</h2>
 
382
    <div class="btn large" onclick="getFileInfo();">Get File Metadata</div>
 
383
    <div class="btn large" onclick="readFile();">Read with FileReader</div>
 
384
    <div class="btn large" onclick="copyImage();">Copy Image</div>
 
385
    <div class="btn large" onclick="writeImage();">Write Image</div>
 
386
    <div class="btn large" onclick="uploadImage();">Upload Image</div>
 
387
    <div class="btn large" onclick="displayImageUsingCanvas();">Draw Using Canvas</div>
 
388
    <div class="btn large" onclick="removeImage();">Remove Image</div>
 
389
    <h2> </h2><div class="backBtn" onclick="backHome();">Back</div>
 
390
  </body>
 
391
</html>