You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by fi...@apache.org on 2012/05/18 23:37:02 UTC
[4/4] [CB-466] Rewrite accel for WP7
http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/blob/9f9935d3/templates/custom/www/index.html
----------------------------------------------------------------------
diff --git a/templates/custom/www/index.html b/templates/custom/www/index.html
index f3bbbbb..283442a 100644
--- a/templates/custom/www/index.html
+++ b/templates/custom/www/index.html
@@ -8,7 +8,7 @@
<link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"/>
- <script type="text/javascript" charset="utf-8" src="cordova-1.7.0rc1.js"></script>
+ <script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript">
http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/blob/9f9935d3/templates/full/www/cordova-1.7.0.js
----------------------------------------------------------------------
diff --git a/templates/full/www/cordova-1.7.0.js b/templates/full/www/cordova-1.7.0.js
index 892ae76..bee3d16 100644
--- a/templates/full/www/cordova-1.7.0.js
+++ b/templates/full/www/cordova-1.7.0.js
@@ -1,6 +1,6 @@
-// commit 9cfdc134f83b5d51f655e52ec7d4ddab167437c7 WP7
+// commit 4a4ba9985c920850fe3f229abc60de984e196ab5
-// File generated at :: Tue May 01 2012 14:51:58 GMT-0700 (Pacific Daylight Time)
+// File generated at :: Fri May 18 2012 14:31:57 GMT-0700 (Pacific Daylight Time)
/*
Licensed to the Apache Software Foundation (ASF) under one
@@ -98,17 +98,7 @@ var documentEventHandlers = {},
document.addEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
- if (e == 'deviceready') {
- channel.onDeviceReady.subscribeOnce(handler);
- } else if (e == 'resume') {
- channel.onResume.subscribe(handler);
- // if subscribing listener after event has already fired, invoke the handler
- if (channel.onResume.fired && typeof handler == 'function') {
- handler();
- }
- } else if (e == 'pause') {
- channel.onPause.subscribe(handler);
- } else if (typeof documentEventHandlers[e] != 'undefined') {
+ if (typeof documentEventHandlers[e] != 'undefined') {
documentEventHandlers[e].subscribe(handler);
} else {
m_document_addEventListener.call(document, evt, handler, capture);
@@ -126,13 +116,8 @@ window.addEventListener = function(evt, handler, capture) {
document.removeEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
- // Check for pause/resume events first.
- if (e == 'resume') {
- channel.onResume.unsubscribe(handler);
- } else if (e == 'pause') {
- channel.onPause.unsubscribe(handler);
// If unsubcribing from an event that is handled by a plugin
- } else if (typeof documentEventHandlers[e] != "undefined") {
+ if (typeof documentEventHandlers[e] != "undefined") {
documentEventHandlers[e].unsubscribe(handler);
} else {
m_document_removeEventListener.call(document, evt, handler, capture);
@@ -318,6 +303,11 @@ var cordova = {
}
};
+// Register pause, resume and deviceready channels as events on document.
+channel.onPause = cordova.addDocumentEventHandler('pause');
+channel.onResume = cordova.addDocumentEventHandler('resume');
+channel.onDeviceReady = cordova.addDocumentEventHandler('deviceready');
+
// Adds deprecation warnings to functions of an object (but only logs a message once)
function deprecateFunctions(obj, objLabel) {
var newObj = {};
@@ -645,10 +635,13 @@ Channel.prototype.unsubscribe = function(g) {
if (g === null || g === undefined) { throw "You must pass _something_ into Channel.unsubscribe"; }
if (typeof g == 'function') { g = g.observer_guid; }
- this.handlers[g] = null;
- delete this.handlers[g];
- this.numHandlers--;
- if (this.events.onUnsubscribe) this.events.onUnsubscribe.call(this);
+ var handler = this.handlers[g];
+ if (handler) {
+ this.handlers[g] = null;
+ delete this.handlers[g];
+ this.numHandlers--;
+ if (this.events.onUnsubscribe) this.events.onUnsubscribe.call(this);
+ }
};
/**
@@ -771,6 +764,9 @@ module.exports = {
path: 'cordova/plugin/network'
}
}
+ },
+ splashscreen: {
+ path: 'cordova/plugin/splashscreen'
}
}
},
@@ -931,7 +927,9 @@ var NamedArgs = {
getFile:["fullPath","path","options"],
readEntries:["fullPath"],
write:["fileName","data","position"],
- truncate:["fileName","size"]
+ truncate:["fileName","size"],
+ copyTo:["fullPath","parent", "newName"],
+ moveTo:["fullPath","parent", "newName"]
},
FileTransfer:{
upload:["filePath", "server", "fileKey", "fileName", "mimeType", "params", "debug", "chunkedMode"],
@@ -1042,7 +1040,7 @@ module.exports = {
id: "wp7",
initialize:function() {
- window.alert = require("cordova/plugin/notification").alert;
+ window.alert = require("cordova/plugin/notification").alert;
// INject a lsitener for the backbutton, and tell native to override the flag (true/false) when we have 1 or more, or 0, listeners
var backButtonChannel = cordova.addDocumentEventHandler('backbutton', {
@@ -1112,13 +1110,14 @@ module.exports = {
// file: lib\common\plugin\Acceleration.js
define("cordova/plugin/Acceleration", function(require, exports, module) {
var Acceleration = function(x, y, z, timestamp) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.timestamp = timestamp || (new Date()).getTime();
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.timestamp = timestamp || (new Date()).getTime();
};
module.exports = Acceleration;
+
});
// file: lib\common\plugin\Camera.js
@@ -1743,15 +1742,20 @@ var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
/**
* The altitude of the position.
*/
- this.altitude = alt;
+ this.altitude = (alt !== undefined ? alt : null);
/**
* The direction the device is moving at the position.
*/
- this.heading = head;
+ this.heading = (head !== undefined ? head : null);
/**
* The velocity with which the device is moving at the position.
*/
- this.speed = vel;
+ this.speed = (vel !== undefined ? vel : null);
+
+ if (this.speed === 0 || this.speed === null) {
+ this.heading = NaN;
+ }
+
/**
* The altitude accuracy of the position.
*/
@@ -1759,6 +1763,7 @@ var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
};
module.exports = Coordinates;
+
});
// file: lib\common\plugin\DirectoryEntry.js
@@ -1943,6 +1948,21 @@ Entry.prototype.getMetadata = function(successCallback, errorCallback) {
};
/**
+ * Set the metadata of the entry.
+ *
+ * @param successCallback
+ * {Function} is called with a Metadata object
+ * @param errorCallback
+ * {Function} is called with a FileError
+ * @param metadataObject
+ * {Object} keys and values to set
+ */
+Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) {
+
+ exec(successCallback, errorCallback, "File", "setMetadata", [this.fullPath, metadataObject]);
+};
+
+/**
* Move a file or directory to a new location.
*
* @param parent
@@ -3226,11 +3246,16 @@ define("cordova/plugin/Position", function(require, exports, module) {
var Coordinates = require('cordova/plugin/Coordinates');
var Position = function(coords, timestamp) {
- this.coords = new Coordinates(coords.latitude, coords.longitude, coords.altitude, coords.accuracy, coords.heading, coords.velocity, coords.altitudeAccuracy);
+ if (coords) {
+ this.coords = new Coordinates(coords.latitude, coords.longitude, coords.altitude, coords.accuracy, coords.heading, coords.velocity, coords.altitudeAccuracy);
+ } else {
+ this.coords = new Coordinates();
+ }
this.timestamp = (timestamp !== undefined) ? timestamp : new Date().getTime();
};
module.exports = Position;
+
});
// file: lib\common\plugin\PositionError.js
@@ -3311,11 +3336,60 @@ define("cordova/plugin/accelerometer", function(require, exports, module) {
* @constructor
*/
var utils = require("cordova/utils"),
- exec = require("cordova/exec");
+ exec = require("cordova/exec"),
+ Acceleration = require('cordova/plugin/Acceleration');
-// Local singleton variables.
+// Is the accel sensor running?
+var running = false;
+
+// Keeps reference to watchAcceleration calls.
var timers = {};
+// Array of listeners; used to keep track of when we should call start and stop.
+var listeners = [];
+
+// Last returned acceleration object from native
+var accel = null;
+
+// Tells native to start.
+function start() {
+ exec(function(a) {
+ var tempListeners = listeners.slice(0);
+ accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
+ for (var i = 0, l = tempListeners.length; i < l; i++) {
+ tempListeners[i].win(accel);
+ }
+ }, function(e) {
+ var tempListeners = listeners.slice(0);
+ for (var i = 0, l = tempListeners.length; i < l; i++) {
+ tempListeners[i].fail(e);
+ }
+ }, "Accelerometer", "start", []);
+ running = true;
+}
+
+// Tells native to stop.
+function stop() {
+ exec(null, null, "Accelerometer", "stop", []);
+ running = false;
+}
+
+// Adds a callback pair to the listeners array
+function createCallbackPair(win, fail) {
+ return {win:win, fail:fail};
+}
+
+// Removes a win/fail listener pair from the listeners array
+function removeListeners(l) {
+ var idx = listeners.indexOf(l);
+ if (idx > -1) {
+ listeners.splice(idx, 1);
+ if (listeners.length === 0) {
+ stop();
+ }
+ }
+}
+
var accelerometer = {
/**
* Asynchronously aquires the current acceleration.
@@ -3325,21 +3399,27 @@ var accelerometer = {
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
*/
getCurrentAcceleration: function(successCallback, errorCallback, options) {
-
// successCallback required
if (typeof successCallback !== "function") {
- console.log("Accelerometer Error: successCallback is not a function");
- return;
+ throw "getCurrentAcceleration must be called with at least a success callback function as first parameter.";
}
- // errorCallback optional
- if (errorCallback && (typeof errorCallback !== "function")) {
- console.log("Accelerometer Error: errorCallback is not a function");
- return;
- }
+ var p;
+ var win = function(a) {
+ successCallback(a);
+ removeListeners(p);
+ };
+ var fail = function(e) {
+ errorCallback(e);
+ removeListeners(p);
+ };
+
+ p = createCallbackPair(win, fail);
+ listeners.push(p);
- // Get acceleration
- exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
+ if (!running) {
+ start();
+ }
},
/**
@@ -3351,36 +3431,38 @@ var accelerometer = {
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
watchAcceleration: function(successCallback, errorCallback, options) {
-
// Default interval (10 sec)
- var frequency = (options !== undefined && options.frequency !== undefined)? options.frequency : 10000;
+ var frequency = (options && options.frequency && typeof options.frequency == 'number') ? options.frequency : 10000;
// successCallback required
if (typeof successCallback !== "function") {
- console.log("Accelerometer Error: successCallback is not a function");
- return;
+ throw "watchAcceleration must be called with at least a success callback function as first parameter.";
}
- // errorCallback optional
- if (errorCallback && (typeof errorCallback !== "function")) {
- console.log("Accelerometer Error: errorCallback is not a function");
- return;
- }
+ // Keep reference to watch id, and report accel readings as often as defined in frequency
+ var id = utils.createUUID();
- // Make sure accelerometer timeout > frequency + 10 sec
- exec(
- function(timeout) {
- if (timeout < (frequency + 10000)) {
- exec(null, null, "Accelerometer", "setTimeout", [frequency + 10000]);
+ var p = createCallbackPair(function(){}, function(e) {
+ errorCallback(e);
+ removeListeners(p);
+ });
+ listeners.push(p);
+
+ timers[id] = {
+ timer:window.setInterval(function() {
+ if (accel) {
+ successCallback(accel);
}
- },
- function(e) { }, "Accelerometer", "getTimeout", []);
+ }, frequency),
+ listeners:p
+ };
- // Start watch timer
- var id = utils.createUUID();
- timers[id] = window.setInterval(function() {
- exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
- }, (frequency ? frequency : 1));
+ if (running) {
+ // If we're already running then immediately invoke the success callback
+ successCallback(accel);
+ } else {
+ start();
+ }
return id;
},
@@ -3391,16 +3473,17 @@ var accelerometer = {
* @param {String} id The id of the watch returned from #watchAcceleration.
*/
clearWatch: function(id) {
-
// Stop javascript timer & remove from timer list
- if (id && timers[id] !== undefined) {
- window.clearInterval(timers[id]);
+ if (id && timers[id]) {
+ window.clearInterval(timers[id].timer);
+ removeListeners(timers[id].listeners);
delete timers[id];
}
}
};
module.exports = accelerometer;
+
});
// file: lib\common\plugin\battery.js
@@ -3751,27 +3834,45 @@ var timers = {}; // list of timers in use
// Returns default params, overrides if provided with values
function parseParameters(options) {
var opt = {
- maximumAge: 10000,
+ maximumAge: 0,
enableHighAccuracy: false,
- timeout: 10000
+ timeout: Infinity
};
if (options) {
- if (options.maximumAge !== undefined) {
+ if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) {
opt.maximumAge = options.maximumAge;
}
if (options.enableHighAccuracy !== undefined) {
opt.enableHighAccuracy = options.enableHighAccuracy;
}
- if (options.timeout !== undefined) {
- opt.timeout = options.timeout;
+ if (options.timeout !== undefined && !isNaN(options.timeout)) {
+ if (options.timeout < 0) {
+ opt.timeout = 0;
+ } else {
+ opt.timeout = options.timeout;
+ }
}
}
return opt;
}
+// Returns a timeout failure, closed over a specified timeout value and error callback.
+function createTimeout(errorCallback, timeout) {
+ var t = setTimeout(function() {
+ clearTimeout(t);
+ t = null;
+ errorCallback({
+ code:PositionError.TIMEOUT,
+ message:"Position retrieval timed out."
+ });
+ }, timeout);
+ return t;
+}
+
var geolocation = {
+ lastPosition:null, // reference to last known (cached) position returned
/**
* Asynchronously aquires the current position.
*
@@ -3780,10 +3881,24 @@ var geolocation = {
* @param {PositionOptions} options The options for getting the position data. (OPTIONAL)
*/
getCurrentPosition:function(successCallback, errorCallback, options) {
+ if (arguments.length === 0) {
+ throw new Error("getCurrentPosition must be called with at least one argument.");
+ }
options = parseParameters(options);
+ // Timer var that will fire an error callback if no position is retrieved from native
+ // before the "timeout" param provided expires
+ var timeoutTimer = null;
+
var win = function(p) {
- successCallback(new Position(
+ clearTimeout(timeoutTimer);
+ if (!timeoutTimer) {
+ // Timeout already happened, or native fired error callback for
+ // this geo request.
+ // Don't continue with success callback.
+ return;
+ }
+ var pos = new Position(
{
latitude:p.latitude,
longitude:p.longitude,
@@ -3794,13 +3909,45 @@ var geolocation = {
altitudeAccuracy:p.altitudeAccuracy
},
p.timestamp || new Date()
- ));
+ );
+ geolocation.lastPosition = pos;
+ successCallback(pos);
};
var fail = function(e) {
- errorCallback(new PositionError(e.code, e.message));
+ clearTimeout(timeoutTimer);
+ timeoutTimer = null;
+ var err = new PositionError(e.code, e.message);
+ if (errorCallback) {
+ errorCallback(err);
+ }
};
- exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.timeout, options.maximumAge]);
+ // Check our cached position, if its timestamp difference with current time is less than the maximumAge, then just
+ // fire the success callback with the cached position.
+ if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp.getTime()) <= options.maximumAge)) {
+ successCallback(geolocation.lastPosition);
+ // If the cached position check failed and the timeout was set to 0, error out with a TIMEOUT error object.
+ } else if (options.timeout === 0) {
+ fail({
+ code:PositionError.TIMEOUT,
+ message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceed's provided PositionOptions' maximumAge parameter."
+ });
+ // Otherwise we have to call into native to retrieve a position.
+ } else {
+ if (options.timeout !== Infinity) {
+ // If the timeout value was not set to Infinity (default), then
+ // set up a timeout function that will fire the error callback
+ // if no successful position was retrieved before timeout expired.
+ timeoutTimer = createTimeout(fail, options.timeout);
+ } else {
+ // This is here so the check in the win function doesn't mess stuff up
+ // may seem weird but this guarantees timeoutTimer is
+ // always truthy before we call into native
+ timeoutTimer = true;
+ }
+ exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]);
+ }
+ return timeoutTimer;
},
/**
* Asynchronously watches the geolocation for changes to geolocation. When a change occurs,
@@ -3812,12 +3959,46 @@ var geolocation = {
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
watchPosition:function(successCallback, errorCallback, options) {
+ if (arguments.length === 0) {
+ throw new Error("watchPosition must be called with at least one argument.");
+ }
options = parseParameters(options);
var id = utils.createUUID();
- timers[id] = window.setInterval(function() {
- geolocation.getCurrentPosition(successCallback, errorCallback, options);
- }, options.timeout);
+
+ // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition
+ timers[id] = geolocation.getCurrentPosition(successCallback, errorCallback, options);
+
+ var fail = function(e) {
+ clearTimeout(timers[id]);
+ var err = new PositionError(e.code, e.message);
+ if (errorCallback) {
+ errorCallback(err);
+ }
+ };
+
+ var win = function(p) {
+ clearTimeout(timers[id]);
+ if (options.timeout !== Infinity) {
+ timers[id] = createTimeout(fail, options.timeout);
+ }
+ var pos = new Position(
+ {
+ latitude:p.latitude,
+ longitude:p.longitude,
+ altitude:p.altitude,
+ accuracy:p.accuracy,
+ heading:p.heading,
+ velocity:p.velocity,
+ altitudeAccuracy:p.altitudeAccuracy
+ },
+ p.timestamp || new Date()
+ );
+ geolocation.lastPosition = pos;
+ successCallback(pos);
+ };
+
+ exec(win, fail, "Geolocation", "addWatch", [id, options.enableHighAccuracy]);
return id;
},
@@ -3828,13 +4009,15 @@ var geolocation = {
*/
clearWatch:function(id) {
if (id && timers[id] !== undefined) {
- window.clearInterval(timers[id]);
+ clearTimeout(timers[id]);
delete timers[id];
+ exec(null, null, "Geolocation", "clearWatch", [id]);
}
}
};
module.exports = geolocation;
+
});
// file: lib\common\plugin\network.js
@@ -4052,6 +4235,19 @@ module.exports = function(uri, successCallback, errorCallback) {
});
+// file: lib\common\plugin\splashscreen.js
+define("cordova/plugin/splashscreen", function(require, exports, module) {
+var exec = require('cordova/exec');
+
+var splashscreen = {
+ hide:function() {
+ exec(null, null, "SplashScreen", "hide", []);
+ }
+};
+
+module.exports = splashscreen;
+});
+
// file: lib\wp7\plugin\wp7\CordovaCommandResult.js
define("cordova/plugin/wp7/CordovaCommandResult", function(require, exports, module) {
@@ -4066,11 +4262,11 @@ module.exports = function(status,callbackId,args,cast) {
return "true";
}
else if(status === "resume") {
- channel.onResume.fire();
+ cordova.fireDocumentEvent('resume');
return "true";
}
else if(status === "pause") {
- channel.onPause.fire();
+ cordova.fireDocumentEvent('pause');
return "true";
}
@@ -4106,6 +4302,7 @@ module.exports = function(status,callbackId,args,cast) {
cordova.callbackError(callbackId,parsedArgs,cast);
}
};
+
});
// file: lib\wp7\plugin\wp7\CordovaMediaonStatus.js
@@ -4667,104 +4864,175 @@ module.exports = function(uri, successCallback, errorCallback) {
// file: lib\common\utils.js
define("cordova/utils", function(require, exports, module) {
-function UUIDcreatePart(length) {
- var uuidpart = "";
- for (var i=0; i<length; i++) {
- var uuidchar = parseInt((Math.random() * 256), 10).toString(16);
- if (uuidchar.length == 1) {
- uuidchar = "0" + uuidchar;
- }
- uuidpart += uuidchar;
- }
- return uuidpart;
-}
+var utils = exports;
-var _self = {
- isArray:function(a) {
- return Object.prototype.toString.call(a) == '[object Array]';
- },
- isDate:function(d) {
- return Object.prototype.toString.call(d) == '[object Date]';
- },
- /**
- * Does a deep clone of the object.
- */
- clone: function(obj) {
- if(!obj || typeof obj == 'function' || _self.isDate(obj) || typeof obj != 'object') {
- return obj;
- }
+/**
+ * Returns an indication of whether the argument is an array or not
+ */
+utils.isArray = function(a) {
+ return Object.prototype.toString.call(a) == '[object Array]';
+};
- var retVal, i;
+/**
+ * Returns an indication of whether the argument is a Date or not
+ */
+utils.isDate = function(d) {
+ return Object.prototype.toString.call(d) == '[object Date]';
+};
- if(_self.isArray(obj)){
- retVal = [];
- for(i = 0; i < obj.length; ++i){
- retVal.push(_self.clone(obj[i]));
- }
- return retVal;
- }
+/**
+ * Does a deep clone of the object.
+ */
+utils.clone = function(obj) {
+ if(!obj || typeof obj == 'function' || utils.isDate(obj) || typeof obj != 'object') {
+ return obj;
+ }
- retVal = {};
- for(i in obj){
- if(!(i in retVal) || retVal[i] != obj[i]) {
- retVal[i] = _self.clone(obj[i]);
- }
+ var retVal, i;
+
+ if(utils.isArray(obj)){
+ retVal = [];
+ for(i = 0; i < obj.length; ++i){
+ retVal.push(utils.clone(obj[i]));
}
return retVal;
- },
+ }
- close: function(context, func, params) {
- if (typeof params == 'undefined') {
- return function() {
- return func.apply(context, arguments);
- };
- } else {
- return function() {
- return func.apply(context, params);
- };
+ retVal = {};
+ for(i in obj){
+ if(!(i in retVal) || retVal[i] != obj[i]) {
+ retVal[i] = utils.clone(obj[i]);
}
- },
-
- /**
- * Create a UUID
- */
- createUUID: function() {
- return UUIDcreatePart(4) + '-' +
- UUIDcreatePart(2) + '-' +
- UUIDcreatePart(2) + '-' +
- UUIDcreatePart(2) + '-' +
- UUIDcreatePart(6);
- },
+ }
+ return retVal;
+};
- /**
- * Extends a child object from a parent object using classical inheritance
- * pattern.
- */
- extend: (function() {
- // proxy used to establish prototype chain
- var F = function() {};
- // extend Child from Parent
- return function(Child, Parent) {
- F.prototype = Parent.prototype;
- Child.prototype = new F();
- Child.__super__ = Parent.prototype;
- Child.prototype.constructor = Child;
+/**
+ * Returns a wrappered version of the function
+ */
+utils.close = function(context, func, params) {
+ if (typeof params == 'undefined') {
+ return function() {
+ return func.apply(context, arguments);
+ };
+ } else {
+ return function() {
+ return func.apply(context, params);
};
- }()),
+ }
+};
- /**
- * Alerts a message in any available way: alert or console.log.
- */
- alert:function(msg) {
- if (alert) {
- alert(msg);
- } else if (console && console.log) {
- console.log(msg);
+/**
+ * Create a UUID
+ */
+utils.createUUID = function() {
+ return UUIDcreatePart(4) + '-' +
+ UUIDcreatePart(2) + '-' +
+ UUIDcreatePart(2) + '-' +
+ UUIDcreatePart(2) + '-' +
+ UUIDcreatePart(6);
+};
+
+/**
+ * Extends a child object from a parent object using classical inheritance
+ * pattern.
+ */
+utils.extend = (function() {
+ // proxy used to establish prototype chain
+ var F = function() {};
+ // extend Child from Parent
+ return function(Child, Parent) {
+ F.prototype = Parent.prototype;
+ Child.prototype = new F();
+ Child.__super__ = Parent.prototype;
+ Child.prototype.constructor = Child;
+ };
+}());
+
+/**
+ * Alerts a message in any available way: alert or console.log.
+ */
+utils.alert = function(msg) {
+ if (alert) {
+ alert(msg);
+ } else if (console && console.log) {
+ console.log(msg);
+ }
+};
+
+/**
+ * Formats a string and arguments following it ala sprintf()
+ *
+ * format chars:
+ * %j - format arg as JSON
+ * %o - format arg as JSON
+ * %c - format arg as ''
+ * %% - replace with '%'
+ * any other char following % will format it's
+ * arg via toString().
+ *
+ * for rationale, see FireBug's Console API:
+ * http://getfirebug.com/wiki/index.php/Console_API
+ */
+utils.format = function(formatString /* ,... */) {
+ if (formatString === null || formatString === undefined) return "";
+ if (arguments.length == 1) return formatString.toString();
+
+ var pattern = /(.*?)%(.)(.*)/;
+ var rest = formatString.toString();
+ var result = [];
+ var args = [].slice.call(arguments,1);
+
+ while (args.length) {
+ var arg = args.shift();
+ var match = pattern.exec(rest);
+
+ if (!match) break;
+
+ rest = match[3];
+
+ result.push(match[1]);
+
+ if (match[2] == '%') {
+ result.push('%');
+ args.unshift(arg);
+ continue;
}
+
+ result.push(formatted(arg, match[2]));
}
+
+ result.push(rest);
+
+ return result.join('');
};
-module.exports = _self;
+//------------------------------------------------------------------------------
+function UUIDcreatePart(length) {
+ var uuidpart = "";
+ for (var i=0; i<length; i++) {
+ var uuidchar = parseInt((Math.random() * 256), 10).toString(16);
+ if (uuidchar.length == 1) {
+ uuidchar = "0" + uuidchar;
+ }
+ uuidpart += uuidchar;
+ }
+ return uuidpart;
+}
+
+//------------------------------------------------------------------------------
+function formatted(object, formatChar) {
+
+ switch(formatChar) {
+ case 'j':
+ case 'o': return JSON.stringify(object);
+ case 'c': return '';
+ }
+
+ if (null === object) return Object.prototype.toString.call(object);
+
+ return object.toString();
+}
});
@@ -4806,7 +5074,7 @@ window.cordova = require('cordova');
// Fire onDeviceReady event once all constructors have run and
// cordova info has been received from native side.
channel.join(function() {
- channel.onDeviceReady.fire();
+ require('cordova').fireDocumentEvent('deviceready');
}, channel.deviceReadyChannelsArray);
}, [ channel.onDOMContentLoaded, channel.onNativeReady ]);
@@ -4825,4 +5093,5 @@ window.cordova = require('cordova');
}(window));
+
})();
\ No newline at end of file