Updated Branches:
  refs/heads/466 [created] 9f9935d3f

[CB-466] Rewrite accel for WP7


Project: http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/repo
Commit: 
http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/commit/9f9935d3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/tree/9f9935d3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/diff/9f9935d3

Branch: refs/heads/466
Commit: 9f9935d3fc1326d4107be1004a6bc135927daab8
Parents: 4251cf3
Author: filmaj <maj....@gmail.com>
Authored: Fri May 18 14:35:54 2012 -0700
Committer: filmaj <maj....@gmail.com>
Committed: Fri May 18 14:35:54 2012 -0700

----------------------------------------------------------------------
 example/www/cordova-1.7.0.js                |  627 ++-
 framework/Cordova/Commands/Accelerometer.cs |  200 +-
 templates/custom/www/cordova-1.7.0.js       | 5097 ++++++++++++++++++++++
 templates/custom/www/cordova-1.7.0rc1.js    | 4778 --------------------
 templates/custom/www/index.html             |    2 +-
 templates/full/www/cordova-1.7.0.js         |  605 ++-
 6 files changed, 6029 insertions(+), 5280 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/blob/9f9935d3/example/www/cordova-1.7.0.js
----------------------------------------------------------------------
diff --git a/example/www/cordova-1.7.0.js b/example/www/cordova-1.7.0.js
index 02ee44e..bee3d16 100644
--- a/example/www/cordova-1.7.0.js
+++ b/example/www/cordova-1.7.0.js
@@ -1,6 +1,6 @@
-// commit 97d4ff51d1c63ce1017fd54e1493795c193722f6
+// commit 4a4ba9985c920850fe3f229abc60de984e196ab5
 
-// File generated at :: Mon Apr 30 2012 12:27:44 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);
+    }
 };
 
 /**
@@ -721,6 +714,20 @@ module.exports = {
                 }
             }
         },
+        Cordova: {
+            children: {
+                exec: {
+                    path: 'cordova/exec'
+                }
+            }
+        },
+        PhoneGap:{
+            children: {
+                exec: {
+                    path: 'cordova/exec'
+                }
+            }
+        },
         navigator: {
             children: {
                 notification: {
@@ -757,6 +764,9 @@ module.exports = {
                             path: 'cordova/plugin/network'
                         }
                     }
+                },
+                splashscreen: {
+                    path: 'cordova/plugin/splashscreen'
                 }
             }
         },
@@ -891,6 +901,7 @@ module.exports = {
         }
     }
 };
+
 });
 
 // file: lib\wp7\exec.js
@@ -906,6 +917,8 @@ var cordova = require('cordova');
 var NamedArgs =  {
     File:{
         getFileMetadata:["fullPath"],
+        getMetadata:["fullPath"],
+        getParent:["fullPath"],
         readAsText:["fileName","encoding"],
         readAsDataURL:["fileName"],
         getDirectory:["fullPath","path","options"],
@@ -914,10 +927,13 @@ 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"]
+        upload:["filePath", "server", "fileKey", "fileName", "mimeType", 
"params", "debug", "chunkedMode"],
+        download:["url","filePath"]
     },
     Contacts:{
         search:["fields","options"]
@@ -964,6 +980,7 @@ var NamedArgs =  {
 
 module.exports = function(success, fail, service, action, args) {
 
+
     var callbackId = service + cordova.callbackId++;
     if (typeof success == "function" || typeof fail == "function")
     {
@@ -1023,8 +1040,7 @@ module.exports = {
     id: "wp7",
     initialize:function() {
 
-
-
+    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', {
@@ -1094,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
@@ -1725,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.
      */
@@ -1741,6 +1763,7 @@ var Coordinates = function(lat, lng, alt, acc, head, vel, 
altacc) {
 };
 
 module.exports = Coordinates;
+
 });
 
 // file: lib\common\plugin\DirectoryEntry.js
@@ -1925,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
@@ -3208,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
@@ -3293,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.
@@ -3307,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);
+        };
 
-        // Get acceleration
-        exec(successCallback, errorCallback, "Accelerometer", 
"getAcceleration", []);
+        p = createCallbackPair(win, fail);
+        listeners.push(p);
+
+        if (!running) {
+            start();
+        }
     },
 
     /**
@@ -3333,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();
+
+        var p = createCallbackPair(function(){}, function(e) {
+            errorCallback(e);
+            removeListeners(p);
+        });
+        listeners.push(p);
 
-        // Make sure accelerometer timeout > frequency + 10 sec
-        exec(
-            function(timeout) {
-                if (timeout < (frequency + 10000)) {
-                    exec(null, null, "Accelerometer", "setTimeout", [frequency 
+ 10000]);
+        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;
     },
@@ -3373,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
@@ -3733,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.
    *
@@ -3762,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,
@@ -3776,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,
@@ -3794,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;
     },
@@ -3810,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
@@ -4034,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) {
 
@@ -4048,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";
     }
 
@@ -4088,6 +4302,7 @@ module.exports = function(status,callbackId,args,cast) {
         cordova.callbackError(callbackId,parsedArgs,cast);
     }
 };
+
 });
 
 // file: lib\wp7\plugin\wp7\CordovaMediaonStatus.js
@@ -4649,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();
+}
 
 });
 
@@ -4788,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 ]);
@@ -4807,4 +5093,5 @@ window.cordova = require('cordova');
 
 }(window));
 
+
 })();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-cordova-wp7/blob/9f9935d3/framework/Cordova/Commands/Accelerometer.cs
----------------------------------------------------------------------
diff --git a/framework/Cordova/Commands/Accelerometer.cs 
b/framework/Cordova/Commands/Accelerometer.cs
index 80500dd..ae1e860 100644
--- a/framework/Cordova/Commands/Accelerometer.cs
+++ b/framework/Cordova/Commands/Accelerometer.cs
@@ -27,7 +27,7 @@ namespace WP7CordovaClassLib.Cordova.Commands
     /// </summary>
     public class Accelerometer : BaseCommand
     {
-#region AccelerometerOptions class
+        #region AccelerometerOptions class
         /// <summary>
         /// Represents Accelerometer options.
         /// </summary>
@@ -68,7 +68,7 @@ namespace WP7CordovaClassLib.Cordova.Commands
 
         #endregion
 
-#region Status codes and Constants
+        #region Status codes and Constants
 
         public const int Stopped = 0;
         public const int Starting = 1;
@@ -79,7 +79,7 @@ namespace WP7CordovaClassLib.Cordova.Commands
 
         #endregion
 
-#region Static members
+        #region Static members
 
         /// <summary>
         /// Status of listener
@@ -87,208 +87,82 @@ namespace WP7CordovaClassLib.Cordova.Commands
         private static int currentStatus;
 
         /// <summary>
-        /// Id for get getAcceleration method
-        /// </summary>
-        private static string getAccelId = "getAccelId";
-
-        /// <summary>
         /// Accelerometer
         /// </summary>
         private static Microsoft.Devices.Sensors.Accelerometer accelerometer = 
new Microsoft.Devices.Sensors.Accelerometer();
 
-        /// <summary>
-        /// Listeners for callbacks
-        /// </summary>
-        private static Dictionary<string, Accelerometer> watchers = new 
Dictionary<string, Accelerometer>();
-
         private static DateTime StartOfEpoch = new DateTime(1970, 1, 1, 0, 0, 
0);
 
         #endregion
 
         /// <summary>
-        /// Time the value was last changed
-        /// </summary>
-        private DateTime lastValueChangedTime;
+        /// Sensor listener event
+        /// </summary>        
+        private void accelerometer_CurrentValueChanged(object sender, 
SensorReadingEventArgs<AccelerometerReading> e)
+        {
+            this.SetStatus(Running);
 
-        /// <summary>
-        /// Accelerometer options
-        /// </summary>
-        private AccelerometerOptions accelOptions;
+            PluginResult result = new PluginResult(PluginResult.Status.OK, 
GetCurrentAccelerationFormatted());
+            result.KeepCallback = true;
+            DispatchCommandResult(result);
+        }
 
         /// <summary>
-        /// Start listening for acceleration sensor
+        /// Starts listening for acceleration sensor
         /// </summary>
-        public void startWatch(string options)
+        /// <returns>status of listener</returns>
+        public void start(string options)
         {
-            try
-            {
-                accelOptions = 
JSON.JsonHelper.Deserialize<AccelerometerOptions>(options);
-            }
-            catch (Exception ex)
-            {
-                this.DispatchCommandResult(new 
PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
-                return;
-            }
-
-            if (string.IsNullOrEmpty(accelOptions.Id))
+            if ((currentStatus == Running) || (currentStatus == Starting))
             {
-                this.DispatchCommandResult(new 
PluginResult(PluginResult.Status.JSON_EXCEPTION));
                 return;
             }
-
             try
             {
                 lock (accelerometer)
                 {
-                    watchers.Add(accelOptions.Id, this);
-                    accelerometer.CurrentValueChanged += 
watchers[accelOptions.Id].accelerometer_CurrentValueChanged;
+                    accelerometer.CurrentValueChanged += 
accelerometer_CurrentValueChanged;
                     accelerometer.Start();
                     this.SetStatus(Starting);
                 }
-            }
-            catch (Exception)
-            {
-                this.DispatchCommandResult(new 
PluginResult(PluginResult.Status.ERROR, ErrorFailedToStart));
-                return;
-            }
-        }
-
-        /// <summary>
-        /// Stops listening to acceleration sensor
-        /// </summary>
-        public void stopWatch(string options)
-        {
-            try
-            {
-                accelOptions = 
JSON.JsonHelper.Deserialize<AccelerometerOptions>(options);
-            }
-            catch (Exception ex)
-            {
-                this.DispatchCommandResult(new 
PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
-                return;
-            }
 
-            if (string.IsNullOrEmpty(accelOptions.Id))
-            {
-                this.DispatchCommandResult(new 
PluginResult(PluginResult.Status.JSON_EXCEPTION));
-                return;
-            }
-
-            if (currentStatus != Stopped)
-            {
-                lock (accelerometer)
+                long timeout = 2000;
+                while ((currentStatus == Starting) && (timeout > 0))
                 {
-                    Accelerometer watcher = watchers[accelOptions.Id];
-                    
-                    watcher.Dispose();
-                    accelerometer.CurrentValueChanged -= 
watcher.accelerometer_CurrentValueChanged;
-                    watchers.Remove(accelOptions.Id);
+                    timeout = timeout - 100;
+                    Thread.Sleep(100);
                 }
-            }
-            this.SetStatus(Stopped);
-
-            this.DispatchCommandResult();
-        }
 
-        /// <summary>
-        /// Gets current accelerometer coordinates
-        /// </summary>
-        public void getAcceleration(string options)
-        {
-            try
-            {
                 if (currentStatus != Running)
                 {
-                    int status = this.start();
-                    if (status == ErrorFailedToStart)
-                    {
-                        DispatchCommandResult(new 
PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart));
-                        return;
-                    }
-
-                    long timeout = 2000;
-                    while ((currentStatus == Starting) && (timeout > 0))
-                    {
-                        timeout = timeout - 100;
-                        Thread.Sleep(100);
-                    }
-
-                    if (currentStatus != Running)
-                    {
-                        DispatchCommandResult(new 
PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart));
-                        return;
-                    }
-                }
-                lock (accelerometer)
-                {
-                    if (watchers.ContainsKey(getAccelId))
-                    {
-                        accelerometer.CurrentValueChanged -= 
watchers[getAccelId].accelerometer_CurrentValueChanged;
-                        watchers.Remove(getAccelId);
-                    }
-                    DispatchCommandResult(new 
PluginResult(PluginResult.Status.OK, GetCurrentAccelerationFormatted()));
+                    this.SetStatus(ErrorFailedToStart);
+                    DispatchCommandResult(new 
PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart));
+                    return;
                 }
             }
-            catch (UnauthorizedAccessException)
-            {
-                DispatchCommandResult(new 
PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, ErrorFailedToStart));
-            }
             catch (Exception)
             {
-                DispatchCommandResult(new 
PluginResult(PluginResult.Status.ERROR, ErrorFailedToStart));
-            }
-        }
-
-        /// <summary>
-        /// Sensor listener event
-        /// </summary>        
-        private void accelerometer_CurrentValueChanged(object sender, 
SensorReadingEventArgs<AccelerometerReading> e)
-        {
-            this.SetStatus(Running);
-
-            if (accelOptions != null)
-            {
-                if (((DateTime.Now - lastValueChangedTime).TotalMilliseconds) 
> accelOptions.Frequency)
-                {
-                    lastValueChangedTime = DateTime.Now;
-                    PluginResult result = new 
PluginResult(PluginResult.Status.OK, GetCurrentAccelerationFormatted());
-                    result.KeepCallback = true;
-                    DispatchCommandResult(result);
-                }
-            }
-
-            if (watchers.Count == 0)
-            {
-                accelerometer.Stop();
-                this.SetStatus(Stopped);
+                this.SetStatus(ErrorFailedToStart);
+                DispatchCommandResult(new 
PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart));
+                return;
             }
+            PluginResult result = new 
PluginResult(PluginResult.Status.NO_RESULT);
+            result.KeepCallback = true;
+            DispatchCommandResult(result);
         }
 
-        /// <summary>
-        /// Starts listening for acceleration sensor
-        /// </summary>
-        /// <returns>status of listener</returns>
-        private int start()
+        public void stop(string options)
         {
-            if ((currentStatus == Running) || (currentStatus == Starting))
-            {
-                return currentStatus;
-            }
-            try
+            if (currentStatus == Running)
             {
                 lock (accelerometer)
                 {
-                    watchers.Add(getAccelId, this);
-                    accelerometer.CurrentValueChanged += 
watchers[getAccelId].accelerometer_CurrentValueChanged;
-                    accelerometer.Start();
-                    this.SetStatus(Starting);
+                    accelerometer.CurrentValueChanged -= 
accelerometer_CurrentValueChanged;
+                    accelerometer.Stop();
+                    this.SetStatus(Stopped);
                 }
             }
-            catch (Exception)
-            {
-                this.SetStatus(ErrorFailedToStart);
-            }
-            return currentStatus;
+            DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
         }
 
         /// <summary>
@@ -300,7 +174,7 @@ namespace WP7CordovaClassLib.Cordova.Commands
             // convert to unix timestamp
             long timestamp = ((accelerometer.CurrentValue.Timestamp.DateTime - 
StartOfEpoch).Ticks) / 10000;
             string resultCoordinates = 
String.Format("\"x\":{0},\"y\":{1},\"z\":{2},\"timestamp\":{3}",
-                            (accelerometer.CurrentValue.Acceleration.X * 
gConstant).ToString("0.00000",CultureInfo.InvariantCulture),
+                            (accelerometer.CurrentValue.Acceleration.X * 
gConstant).ToString("0.00000", CultureInfo.InvariantCulture),
                             (accelerometer.CurrentValue.Acceleration.Y * 
gConstant).ToString("0.00000", CultureInfo.InvariantCulture),
                             (accelerometer.CurrentValue.Acceleration.Z * 
gConstant).ToString("0.00000", CultureInfo.InvariantCulture),
                             timestamp.ToString());

Reply via email to