-
Notifications
You must be signed in to change notification settings - Fork 0
/
cordova-1.5.0.js
4137 lines (3634 loc) · 125 KB
/
cordova-1.5.0.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Cordova v1.5.0 */
/*
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.
*/
/*
* Some base contributions
* Copyright (c) 2011, Proyectos Equis Ka, S.L.
*/
if (typeof Cordova === "undefined") {
if (typeof(DeviceInfo) !== 'object'){
DeviceInfo = {};
}
/**
* This represents the Cordova API itself, and provides a global namespace for accessing
* information about the state of Cordova.
* @class
*/
Cordova = {
// This queue holds the currently executing command and all pending
// commands executed with Cordova.exec().
commandQueue: [],
// Indicates if we're currently in the middle of flushing the command
// queue on the native side.
commandQueueFlushing: false,
_constructors: [],
documentEventHandler: {}, // Collection of custom document event handlers
windowEventHandler: {}
};
/**
* List of resource files loaded by Cordova.
* This is used to ensure JS and other files are loaded only once.
*/
Cordova.resources = {base: true};
/**
* Determine if resource has been loaded by Cordova
*
* @param name
* @return
*/
Cordova.hasResource = function(name) {
return Cordova.resources[name];
};
/**
* Add a resource to list of loaded resources by Cordova
*
* @param name
*/
Cordova.addResource = function(name) {
Cordova.resources[name] = true;
};
/**
* Boolean flag indicating if the Cordova API is available and initialized.
*/ // TODO: Remove this, it is unused here ... -jm
Cordova.available = DeviceInfo.uuid != undefined;
/**
* Add an initialization function to a queue that ensures it will run and initialize
* application constructors only once Cordova has been initialized.
* @param {Function} func The function callback you want run once Cordova is initialized
*/
Cordova.addConstructor = function(func) {
var state = document.readyState;
if ( ( state == 'loaded' || state == 'complete' ) && DeviceInfo.uuid != null )
{
func();
}
else
{
Cordova._constructors.push(func);
}
};
(function()
{
var timer = setInterval(function()
{
var state = document.readyState;
if ( ( state == 'loaded' || state == 'complete' ) && DeviceInfo.uuid != null )
{
clearInterval(timer); // stop looking
// run our constructors list
while (Cordova._constructors.length > 0)
{
var constructor = Cordova._constructors.shift();
try
{
constructor();
}
catch(e)
{
if (typeof(console['log']) == 'function')
{
console.log("Failed to run constructor: " + console.processMessage(e));
}
else
{
alert("Failed to run constructor: " + e.message);
}
}
}
// all constructors run, now fire the deviceready event
var e = document.createEvent('Events');
e.initEvent('deviceready');
document.dispatchEvent(e);
}
}, 1);
})();
// session id for calls
Cordova.sessionKey = 0;
// centralized callbacks
Cordova.callbackId = 0;
Cordova.callbacks = {};
Cordova.callbackStatus = {
NO_RESULT: 0,
OK: 1,
CLASS_NOT_FOUND_EXCEPTION: 2,
ILLEGAL_ACCESS_EXCEPTION: 3,
INSTANTIATION_EXCEPTION: 4,
MALFORMED_URL_EXCEPTION: 5,
IO_EXCEPTION: 6,
INVALID_ACTION: 7,
JSON_EXCEPTION: 8,
ERROR: 9
};
/**
* Creates a gap bridge iframe used to notify the native code about queued
* commands.
*
* @private
*/
Cordova.createGapBridge = function() {
gapBridge = document.createElement("iframe");
gapBridge.setAttribute("style", "display:none;");
gapBridge.setAttribute("height","0px");
gapBridge.setAttribute("width","0px");
gapBridge.setAttribute("frameborder","0");
document.documentElement.appendChild(gapBridge);
return gapBridge;
}
/**
* Execute a Cordova command by queuing it and letting the native side know
* there are queued commands. The native side will then request all of the
* queued commands and execute them.
*
* Arguments may be in one of two formats:
*
* FORMAT ONE (preferable)
* The native side will call Cordova.callbackSuccess or
* Cordova.callbackError, depending upon the result of the action.
*
* @param {Function} success The success callback
* @param {Function} fail The fail callback
* @param {String} service The name of the service to use
* @param {String} action The name of the action to use
* @param {String[]} [args] Zero or more arguments to pass to the method
*
* FORMAT TWO
* @param {String} command Command to be run in Cordova, e.g.
* "ClassName.method"
* @param {String[]} [args] Zero or more arguments to pass to the method
* object parameters are passed as an array object
* [object1, object2] each object will be passed as
* JSON strings
*/
Cordova.exec = function() {
if (!Cordova.available) {
alert("ERROR: Attempting to call Cordova.exec()"
+" before 'deviceready'. Ignoring.");
return;
}
var successCallback, failCallback, service, action, actionArgs;
var callbackId = null;
if (typeof arguments[0] !== "string") {
// FORMAT ONE
successCallback = arguments[0];
failCallback = arguments[1];
service = arguments[2];
action = arguments[3];
actionArgs = arguments[4];
// Since we need to maintain backwards compatibility, we have to pass
// an invalid callbackId even if no callback was provided since plugins
// will be expecting it. The Cordova.exec() implementation allocates
// an invalid callbackId and passes it even if no callbacks were given.
callbackId = 'INVALID';
} else {
// FORMAT TWO
splitCommand = arguments[0].split(".");
action = splitCommand.pop();
service = splitCommand.join(".");
actionArgs = Array.prototype.splice.call(arguments, 1);
}
// Start building the command object.
var command = {
className: service,
methodName: action,
arguments: []
};
// Register the callbacks and add the callbackId to the positional
// arguments if given.
if (successCallback || failCallback) {
callbackId = service + Cordova.callbackId++;
Cordova.callbacks[callbackId] =
{success:successCallback, fail:failCallback};
}
if (callbackId != null) {
command.arguments.push(callbackId);
}
for (var i = 0; i < actionArgs.length; ++i) {
var arg = actionArgs[i];
if (arg == undefined || arg == null) {
continue;
} else if (typeof(arg) == 'object') {
command.options = arg;
} else {
command.arguments.push(arg);
}
}
// Stringify and queue the command. We stringify to command now to
// effectively clone the command arguments in case they are mutated before
// the command is executed.
Cordova.commandQueue.push(JSON.stringify(command));
// If the queue length is 1, then that means it was empty before we queued
// the given command, so let the native side know that we have some
// commands to execute, unless the queue is currently being flushed, in
// which case the command will be picked up without notification.
if (Cordova.commandQueue.length == 1 && !Cordova.commandQueueFlushing) {
if (!Cordova.gapBridge) {
Cordova.gapBridge = Cordova.createGapBridge();
}
Cordova.gapBridge.src = "gap://ready";
}
}
/**
* Called by native code to retrieve all queued commands and clear the queue.
*/
Cordova.getAndClearQueuedCommands = function() {
json = JSON.stringify(Cordova.commandQueue);
Cordova.commandQueue = [];
return json;
}
/**
* Called by native code when returning successful result from an action.
*
* @param callbackId
* @param args
* args.status - Cordova.callbackStatus
* args.message - return value
* args.keepCallback - 0 to remove callback, 1 to keep callback in Cordova.callbacks[]
*/
Cordova.callbackSuccess = function(callbackId, args) {
if (Cordova.callbacks[callbackId]) {
// If result is to be sent to callback
if (args.status == Cordova.callbackStatus.OK) {
try {
if (Cordova.callbacks[callbackId].success) {
Cordova.callbacks[callbackId].success(args.message);
}
}
catch (e) {
console.log("Error in success callback: "+callbackId+" = "+e);
}
}
// Clear callback if not expecting any more results
if (!args.keepCallback) {
delete Cordova.callbacks[callbackId];
}
}
};
/**
* Called by native code when returning error result from an action.
*
* @param callbackId
* @param args
*/
Cordova.callbackError = function(callbackId, args) {
if (Cordova.callbacks[callbackId]) {
try {
if (Cordova.callbacks[callbackId].fail) {
Cordova.callbacks[callbackId].fail(args.message);
}
}
catch (e) {
console.log("Error in error callback: "+callbackId+" = "+e);
}
// Clear callback if not expecting any more results
if (!args.keepCallback) {
delete Cordova.callbacks[callbackId];
}
}
};
/**
* Does a deep clone of the object.
*
* @param obj
* @return
*/
Cordova.clone = function(obj) {
if(!obj) {
return obj;
}
if(obj instanceof Array){
var retVal = new Array();
for(var i = 0; i < obj.length; ++i){
retVal.push(Cordova.clone(obj[i]));
}
return retVal;
}
if (obj instanceof Function) {
return obj;
}
if(!(obj instanceof Object)){
return obj;
}
if (obj instanceof Date) {
return obj;
}
retVal = new Object();
for(i in obj){
if(!(i in retVal) || retVal[i] != obj[i]) {
retVal[i] = Cordova.clone(obj[i]);
}
}
return retVal;
};
// Intercept calls to document.addEventListener
Cordova.m_document_addEventListener = document.addEventListener;
// Intercept calls to window.addEventListener
Cordova.m_window_addEventListener = window.addEventListener;
/**
* Add a custom window event handler.
*
* @param {String} event The event name that callback handles
* @param {Function} callback The event handler
*/
Cordova.addWindowEventHandler = function(event, callback) {
Cordova.windowEventHandler[event] = callback;
}
/**
* Add a custom document event handler.
*
* @param {String} event The event name that callback handles
* @param {Function} callback The event handler
*/
Cordova.addDocumentEventHandler = function(event, callback) {
Cordova.documentEventHandler[event] = callback;
}
/**
* Intercept adding document event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
document.addEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If subscribing to an event that is handled by a plugin
if (typeof Cordova.documentEventHandler[e] !== "undefined") {
if (Cordova.documentEventHandler[e](e, handler, true)) {
return; // Stop default behavior
}
}
Cordova.m_document_addEventListener.call(document, evt, handler, capture);
};
/**
* Intercept adding window event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
window.addEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If subscribing to an event that is handled by a plugin
if (typeof Cordova.windowEventHandler[e] !== "undefined") {
if (Cordova.windowEventHandler[e](e, handler, true)) {
return; // Stop default behavior
}
}
Cordova.m_window_addEventListener.call(window, evt, handler, capture);
};
// Intercept calls to document.removeEventListener and watch for events that
// are generated by Cordova native code
Cordova.m_document_removeEventListener = document.removeEventListener;
// Intercept calls to window.removeEventListener
Cordova.m_window_removeEventListener = window.removeEventListener;
/**
* Intercept removing document event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
document.removeEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If unsubcribing from an event that is handled by a plugin
if (typeof Cordova.documentEventHandler[e] !== "undefined") {
if (Cordova.documentEventHandler[e](e, handler, false)) {
return; // Stop default behavior
}
}
Cordova.m_document_removeEventListener.call(document, evt, handler, capture);
};
/**
* Intercept removing window event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
window.removeEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If unsubcribing from an event that is handled by a plugin
if (typeof Cordova.windowEventHandler[e] !== "undefined") {
if (Cordova.windowEventHandler[e](e, handler, false)) {
return; // Stop default behavior
}
}
Cordova.m_window_removeEventListener.call(window, evt, handler, capture);
};
/**
* Method to fire document event
*
* @param {String} type The event type to fire
* @param {Object} data Data to send with event
*/
Cordova.fireDocumentEvent = function(type, data) {
var e = document.createEvent('Events');
e.initEvent(type);
if (data) {
for (var i in data) {
e[i] = data[i];
}
}
document.dispatchEvent(e);
};
/**
* Method to fire window event
*
* @param {String} type The event type to fire
* @param {Object} data Data to send with event
*/
Cordova.fireWindowEvent = function(type, data) {
var e = document.createEvent('Events');
e.initEvent(type);
if (data) {
for (var i in data) {
e[i] = data[i];
}
}
window.dispatchEvent(e);
};
/**
* Method to fire event from native code
* Leaving this generic version to handle problems with iOS 3.x. Is currently used by orientation and battery events
* Remove when iOS 3.x no longer supported and call fireWindowEvent or fireDocumentEvent directly
*/
Cordova.fireEvent = function(type, target, data) {
var e = document.createEvent('Events');
e.initEvent(type);
if (data) {
for (var i in data) {
e[i] = data[i];
}
}
target = target || document;
if (target.dispatchEvent === undefined) { // ie window.dispatchEvent is undefined in iOS 3.x
target = document;
}
target.dispatchEvent(e);
};
/**
* Create a UUID
*
* @return
*/
Cordova.createUUID = function() {
return Cordova.UUIDcreatePart(4) + '-' +
Cordova.UUIDcreatePart(2) + '-' +
Cordova.UUIDcreatePart(2) + '-' +
Cordova.UUIDcreatePart(2) + '-' +
Cordova.UUIDcreatePart(6);
};
Cordova.UUIDcreatePart = function(length) {
var uuidpart = "";
for (var i=0; i<length; i++) {
var uuidchar = parseInt((Math.random() * 256)).toString(16);
if (uuidchar.length == 1) {
uuidchar = "0" + uuidchar;
}
uuidpart += uuidchar;
}
return uuidpart;
};
};
if (!Cordova.hasResource("debugconsole")) {
Cordova.addResource("debugconsole");
/**
* This class provides access to the debugging console.
* @constructor
*/
var DebugConsole = function() {
this.winConsole = window.console;
this.logLevel = DebugConsole.INFO_LEVEL;
}
// from most verbose, to least verbose
DebugConsole.ALL_LEVEL = 1; // same as first level
DebugConsole.INFO_LEVEL = 1;
DebugConsole.WARN_LEVEL = 2;
DebugConsole.ERROR_LEVEL = 4;
DebugConsole.NONE_LEVEL = 8;
DebugConsole.prototype.setLevel = function(level) {
this.logLevel = level;
};
/**
* Utility function for rendering and indenting strings, or serializing
* objects to a string capable of being printed to the console.
* @param {Object|String} message The string or object to convert to an indented string
* @private
*/
DebugConsole.prototype.processMessage = function(message, maxDepth) {
if (maxDepth === undefined) maxDepth = 0;
if (typeof(message) != 'object') {
return (this.isDeprecated ? "WARNING: debug object is deprecated, please use console object \n" + message : message);
} else {
/**
* @function
* @ignore
*/
function indent(str) {
return str.replace(/^/mg, " ");
}
/**
* @function
* @ignore
*/
function makeStructured(obj, depth) {
var str = "";
for (var i in obj) {
try {
if (typeof(obj[i]) == 'object' && depth < maxDepth) {
str += i + ":\n" + indent(makeStructured(obj[i])) + "\n";
} else {
str += i + " = " + indent(String(obj[i])).replace(/^ /, "") + "\n";
}
} catch(e) {
str += i + " = EXCEPTION: " + e.message + "\n";
}
}
return str;
}
return ("Object:\n" + makeStructured(message, maxDepth));
}
};
/**
* Print a normal log message to the console
* @param {Object|String} message Message or object to print to the console
*/
DebugConsole.prototype.log = function(message, maxDepth) {
if (Cordova.available && this.logLevel <= DebugConsole.INFO_LEVEL)
Cordova.exec(null, null, 'org.apache.cordova.debugconsole', 'log',
[ this.processMessage(message, maxDepth), { logLevel: 'INFO' } ]
);
else
this.winConsole.log(message);
};
/**
* Print a warning message to the console
* @param {Object|String} message Message or object to print to the console
*/
DebugConsole.prototype.warn = function(message, maxDepth) {
if (Cordova.available && this.logLevel <= DebugConsole.WARN_LEVEL)
Cordova.exec(null, null, 'org.apache.cordova.debugconsole', 'log',
[ this.processMessage(message, maxDepth), { logLevel: 'WARN' } ]
);
else
this.winConsole.error(message);
};
/**
* Print an error message to the console
* @param {Object|String} message Message or object to print to the console
*/
DebugConsole.prototype.error = function(message, maxDepth) {
if (Cordova.available && this.logLevel <= DebugConsole.ERROR_LEVEL)
Cordova.exec(null, null, 'org.apache.cordova.debugconsole', 'log',
[ this.processMessage(message, maxDepth), { logLevel: 'ERROR' } ]
);
else
this.winConsole.error(message);
};
Cordova.addConstructor(function() {
window.console = new DebugConsole();
});
};
if (!Cordova.hasResource("position")) {
Cordova.addResource("position");
/**
* This class contains position information.
* @param {Object} lat
* @param {Object} lng
* @param {Object} acc
* @param {Object} alt
* @param {Object} altAcc
* @param {Object} head
* @param {Object} vel
* @constructor
*/
Position = function(coords, timestamp) {
this.coords = Coordinates.cloneFrom(coords);
this.timestamp = timestamp || new Date().getTime();
};
Position.prototype.equals = function(other) {
return (this.coords && other && other.coords &&
this.coords.latitude == other.coords.latitude &&
this.coords.longitude == other.coords.longitude);
};
Position.prototype.clone = function()
{
return new Position(
this.coords? this.coords.clone() : null,
this.timestamp? this.timestamp : new Date().getTime()
);
}
Coordinates = function(lat, lng, alt, acc, head, vel, altAcc) {
/**
* The latitude of the position.
*/
this.latitude = lat;
/**
* The longitude of the position,
*/
this.longitude = lng;
/**
* The altitude of the position.
*/
this.altitude = alt;
/**
* The accuracy of the position.
*/
this.accuracy = acc;
/**
* The direction the device is moving at the position.
*/
this.heading = head;
/**
* The velocity with which the device is moving at the position.
*/
this.speed = vel;
/**
* The altitude accuracy of the position.
*/
this.altitudeAccuracy = (altAcc != 'undefined') ? altAcc : null;
};
Coordinates.prototype.clone = function()
{
return new Coordinates(
this.latitude,
this.longitude,
this.altitude,
this.accuracy,
this.heading,
this.speed,
this.altitudeAccuracy
);
};
Coordinates.cloneFrom = function(obj)
{
return new Coordinates(
obj.latitude,
obj.longitude,
obj.altitude,
obj.accuracy,
obj.heading,
obj.speed,
obj.altitudeAccuracy
);
};
/**
* This class specifies the options for requesting position data.
* @constructor
*/
PositionOptions = function(enableHighAccuracy, timeout, maximumAge) {
/**
* Specifies the desired position accuracy.
*/
this.enableHighAccuracy = enableHighAccuracy || false;
/**
* The timeout after which if position data cannot be obtained the errorCallback
* is called.
*/
this.timeout = timeout || 10000;
/**
* The age of a cached position whose age is no greater than the specified time
* in milliseconds.
*/
this.maximumAge = maximumAge || 0;
if (this.maximumAge < 0) {
this.maximumAge = 0;
}
};
/**
* This class contains information about any GPS errors.
* @constructor
*/
PositionError = function(code, message) {
this.code = code || 0;
this.message = message || "";
};
PositionError.UNKNOWN_ERROR = 0;
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
};if (!Cordova.hasResource("acceleration")) {
Cordova.addResource("acceleration");
/**
* This class contains acceleration information
* @constructor
* @param {Number} x The force applied by the device in the x-axis.
* @param {Number} y The force applied by the device in the y-axis.
* @param {Number} z The force applied by the device in the z-axis.
*/
Acceleration = function(x, y, z) {
/**
* The force applied by the device in the x-axis.
*/
this.x = x;
/**
* The force applied by the device in the y-axis.
*/
this.y = y;
/**
* The force applied by the device in the z-axis.
*/
this.z = z;
/**
* The time that the acceleration was obtained.
*/
this.timestamp = new Date().getTime();
}
/**
* This class specifies the options for requesting acceleration data.
* @constructor
*/
AccelerationOptions = function() {
/**
* The timeout after which if acceleration data cannot be obtained the errorCallback
* is called.
*/
this.timeout = 10000;
}
};if (!Cordova.hasResource("accelerometer")) {
Cordova.addResource("accelerometer");
/**
* This class provides access to device accelerometer data.
* @constructor
*/
Accelerometer = function()
{
/**
* The last known acceleration.
*/
this.lastAcceleration = new Acceleration(0,0,0);
}
/**
* Asynchronously aquires the current acceleration.
* @param {Function} successCallback The function to call when the acceleration
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the acceleration data.
* @param {AccelerationOptions} options The options for getting the accelerometer data
* such as timeout.
*/
Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) {
// If the acceleration is available then call success
// If the acceleration is not available then call error
// Created for iPhone, Iphone passes back _accel obj litteral
if (typeof successCallback == "function") {
successCallback(this.lastAcceleration);
}
};
// private callback called from Obj-C by name
Accelerometer.prototype._onAccelUpdate = function(x,y,z)
{
this.lastAcceleration = new Acceleration(x,y,z);
};
/**
* Asynchronously aquires the acceleration repeatedly at a given interval.
* @param {Function} successCallback The function to call each time the acceleration
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the acceleration data.
* @param {AccelerationOptions} options The options for getting the accelerometer data
* such as timeout.
*/
Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) {
//this.getCurrentAcceleration(successCallback, errorCallback, options);
// TODO: add the interval id to a list so we can clear all watches
var frequency = (options != undefined && options.frequency != undefined) ? options.frequency : 10000;
var updatedOptions = {
desiredFrequency:frequency
}
Cordova.exec(null, null, "org.apache.cordova.accelerometer", "start", [options]);
return setInterval(function() {
navigator.accelerometer.getCurrentAcceleration(successCallback, errorCallback, options);
}, frequency);
};
/**
* Clears the specified accelerometer watch.
* @param {String} watchId The ID of the watch returned from #watchAcceleration.
*/
Accelerometer.prototype.clearWatch = function(watchId) {
Cordova.exec(null, null, "org.apache.cordova.accelerometer", "stop", []);
clearInterval(watchId);
};
Accelerometer.install = function()
{
if (typeof navigator.accelerometer == "undefined") {
navigator.accelerometer = new Accelerometer();
}
};
Accelerometer.installDeviceMotionHandler = function()
{
if (!(window.DeviceMotionEvent == undefined)) {
// supported natively, so we don't have to add support
return;
}
var self = this;
var devicemotionEvent = 'devicemotion';
self.deviceMotionWatchId = null;
self.deviceMotionListenerCount = 0;
self.deviceMotionLastEventTimestamp = 0;
// backup original `window.addEventListener`, `window.removeEventListener`
var _addEventListener = window.addEventListener;
var _removeEventListener = window.removeEventListener;
var windowDispatchAvailable = !(window.dispatchEvent === undefined); // undefined in iOS 3.x
var accelWin = function(acceleration) {
var evt = document.createEvent('Events');
evt.initEvent(devicemotionEvent);
evt.acceleration = null; // not all devices have gyroscope, don't care for now if we actually have it.
evt.rotationRate = null; // not all devices have gyroscope, don't care for now if we actually have it:
evt.accelerationIncludingGravity = acceleration; // accelerometer, all iOS devices have it
var currentTime = new Date().getTime();
evt.interval = (self.deviceMotionLastEventTimestamp == 0) ? 0 : (currentTime - self.deviceMotionLastEventTimestamp);
self.deviceMotionLastEventTimestamp = currentTime;
if (windowDispatchAvailable) {
window.dispatchEvent(evt);
} else {
document.dispatchEvent(evt);
}
};
var accelFail = function() {
};
// override `window.addEventListener`
window.addEventListener = function() {
if (arguments[0] === devicemotionEvent) {
++(self.deviceMotionListenerCount);
if (self.deviceMotionListenerCount == 1) { // start
self.deviceMotionWatchId = navigator.accelerometer.watchAcceleration(accelWin, accelFail, { frequency:500});
}
}
if (!windowDispatchAvailable) {
return document.addEventListener.apply(this, arguments);
} else {
return _addEventListener.apply(this, arguments);
}
};
// override `window.removeEventListener'
window.removeEventListener = function() {
if (arguments[0] === devicemotionEvent) {
--(self.deviceMotionListenerCount);
if (self.deviceMotionListenerCount == 0) { // stop
navigator.accelerometer.clearWatch(self.deviceMotionWatchId);
}
}
if (!windowDispatchAvailable) {
return document.removeEventListener.apply(this, arguments);
} else {
return _removeEventListener.apply(this, arguments);
}
};