You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by st...@apache.org on 2013/04/26 01:54:06 UTC
[3/3] git commit: added files for device-orientation
added files for device-orientation
Project: http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/commit/dbc80008
Tree: http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/tree/dbc80008
Diff: http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/diff/dbc80008
Branch: refs/heads/master
Commit: dbc800081633ab4e31091d847b644ba4c4e2c53e
Parents:
Author: Steven Gill <st...@gmail.com>
Authored: Thu Apr 25 16:53:58 2013 -0700
Committer: Steven Gill <st...@gmail.com>
Committed: Thu Apr 25 16:53:58 2013 -0700
----------------------------------------------------------------------
README.md | 4 +
docs/compass.clearWatch.md | 113 ++
docs/compass.clearWatchFilter.md | 23 +
docs/compass.getCurrentHeading.md | 98 +
docs/compass.md | 81 +
docs/compass.watchHeading.md | 134 ++
docs/compass.watchHeadingFilter.md | 23 +
docs/compassError/compassError.md | 40 +
docs/parameters/compassError.md | 30 +
docs/parameters/compassHeading.md | 48 +
docs/parameters/compassOptions.md | 45 +
docs/parameters/compassSuccess.md | 40 +
plugin.xml | 32 +
src/android/CompassListener.java | 296 +++
src/ios/CDVLocation.h | 104 +
src/ios/CDVLocation.m | 623 ++++++
test/autotest/html/HtmlReporter.js | 101 +
test/autotest/html/HtmlReporterHelpers.js | 60 +
test/autotest/html/ReporterView.js | 164 ++
test/autotest/html/SpecView.js | 79 +
test/autotest/html/SuiteView.js | 22 +
test/autotest/html/TrivialReporter.js | 192 ++
test/autotest/index.html | 59 +
test/autotest/jasmine.css | 81 +
test/autotest/jasmine.js | 2530 ++++++++++++++++++++++++
test/autotest/pages/.DS_Store | Bin 0 -> 6148 bytes
test/autotest/pages/compass.html | 71 +
test/autotest/test-runner.js | 62 +
test/autotest/tests/.DS_Store | Bin 0 -> 6148 bytes
test/autotest/tests/compass.tests.js | 98 +
test/compass/index.html | 150 ++
test/cordova.js | 71 +
test/index.html | 65 +
test/main.js | 163 ++
test/master.css | 164 ++
35 files changed, 5866 insertions(+), 0 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ec5ed7f
--- /dev/null
+++ b/README.md
@@ -0,0 +1,4 @@
+cordova-plugin-device-orientation
+============================
+
+Also known as compass. Need to break aparat CDVLocation as geolocation and this plugin both use it.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/compass.clearWatch.md
----------------------------------------------------------------------
diff --git a/docs/compass.clearWatch.md b/docs/compass.clearWatch.md
new file mode 100755
index 0000000..d6fd7a5
--- /dev/null
+++ b/docs/compass.clearWatch.md
@@ -0,0 +1,113 @@
+---
+license: 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.
+---
+
+compass.clearWatch
+========================
+
+Stop watching the compass referenced by the watch ID parameter.
+
+ navigator.compass.clearWatch(watchID);
+
+- __watchID__: The ID returned by `compass.watchHeading`.
+
+Supported Platforms
+-------------------
+
+- Android
+- iPhone
+- Windows Phone 7 and 8 ( if available in hardware )
+- Bada 1.2 & 2.x
+- webOS
+- Tizen
+- Windows 8
+
+Quick Example
+-------------
+
+ var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
+
+ // ... later on ...
+
+ navigator.compass.clearWatch(watchID);
+
+Full Example
+------------
+
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>Compass Example</title>
+
+ <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
+ <script type="text/javascript" charset="utf-8">
+
+ // The watch id references the current `watchHeading`
+ var watchID = null;
+
+ // Wait for Cordova to load
+ //
+ document.addEventListener("deviceready", onDeviceReady, false);
+
+ // Cordova is ready
+ //
+ function onDeviceReady() {
+ startWatch();
+ }
+
+ // Start watching the compass
+ //
+ function startWatch() {
+
+ // Update compass every 3 seconds
+ var options = { frequency: 3000 };
+
+ watchID = navigator.compass.watchHeading(onSuccess, onError, options);
+ }
+
+ // Stop watching the compass
+ //
+ function stopWatch() {
+ if (watchID) {
+ navigator.compass.clearWatch(watchID);
+ watchID = null;
+ }
+ }
+
+ // onSuccess: Get the current heading
+ //
+ function onSuccess(heading) {
+ var element = document.getElementById('heading');
+ element.innerHTML = 'Heading: ' + heading.magneticHeading;
+ }
+
+ // onError: Failed to get the heading
+ //
+ function onError(compassError) {
+ alert('Compass error: ' + compassError.code);
+ }
+
+
+ </script>
+ </head>
+ <body>
+ <div id="heading">Waiting for heading...</div>
+ <button onclick="startWatch();">Start Watching</button>
+ <button onclick="stopWatch();">Stop Watching</button>
+ </body>
+ </html>
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/compass.clearWatchFilter.md
----------------------------------------------------------------------
diff --git a/docs/compass.clearWatchFilter.md b/docs/compass.clearWatchFilter.md
new file mode 100644
index 0000000..8c92c03
--- /dev/null
+++ b/docs/compass.clearWatchFilter.md
@@ -0,0 +1,23 @@
+---
+license: 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.
+---
+
+compass.clearWatchFilter
+========================
+
+No longer supported as of 1.6. See `compass.clearWatch`.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/compass.getCurrentHeading.md
----------------------------------------------------------------------
diff --git a/docs/compass.getCurrentHeading.md b/docs/compass.getCurrentHeading.md
new file mode 100755
index 0000000..a59fc71
--- /dev/null
+++ b/docs/compass.getCurrentHeading.md
@@ -0,0 +1,98 @@
+---
+license: 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.
+---
+
+compass.getCurrentHeading
+=========================
+
+Get the current compass heading.
+
+ navigator.compass.getCurrentHeading(compassSuccess, compassError, compassOptions);
+
+Description
+-----------
+
+The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.
+
+The compass heading information is returned via a CompassHeading object using the `compassSuccess` callback function.
+
+Supported Platforms
+-------------------
+
+- Android
+- iPhone
+- Windows Phone 7 and 8 ( if available in hardware )
+- Bada 1.2 & 2.x
+- webOS
+- Tizen
+- Windows 8
+
+Quick Example
+-------------
+
+ function onSuccess(heading) {
+ alert('Heading: ' + heading.magneticHeading);
+ };
+
+ function onError(error) {
+ alert('CompassError: ' + error.code);
+ };
+
+ navigator.compass.getCurrentHeading(onSuccess, onError);
+
+Full Example
+------------
+
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>Compass Example</title>
+
+ <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
+ <script type="text/javascript" charset="utf-8">
+
+ // Wait for Cordova to load
+ //
+ document.addEventListener("deviceready", onDeviceReady, false);
+
+ // Cordova is ready
+ //
+ function onDeviceReady() {
+ navigator.compass.getCurrentHeading(onSuccess, onError);
+ }
+
+ // onSuccess: Get the current heading
+ //
+ function onSuccess(heading) {
+ alert('Heading: ' + heading.magneticHeading);
+ }
+
+ // onError: Failed to get the heading
+ //
+ function onError(compassError) {
+ alert('Compass Error: ' + compassError.code);
+ }
+
+ </script>
+ </head>
+ <body>
+ <h1>Example</h1>
+ <p>getCurrentHeading</p>
+ </body>
+ </html>
+
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/compass.md
----------------------------------------------------------------------
diff --git a/docs/compass.md b/docs/compass.md
new file mode 100755
index 0000000..d85be8c
--- /dev/null
+++ b/docs/compass.md
@@ -0,0 +1,81 @@
+---
+license: 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.
+---
+
+Compass
+=======
+
+> Obtains the direction that the device is pointing.
+
+Methods
+-------
+
+- compass.getCurrentHeading
+- compass.watchHeading
+- compass.clearWatch
+- compass.watchHeadingFilter (obsolete)
+- compass.clearWatchFilter (obsolete)
+
+Arguments
+---------
+
+- compassSuccess
+- compassError
+- compassOptions
+- compassHeading
+
+Permissions
+-----------
+
+### Android
+
+#### app/res/xml/config.xml
+
+ <plugin name="Compass" value="org.apache.cordova.CompassListener" />
+
+### Bada
+
+ No permissions are required.
+
+### BlackBerry WebWorks
+
+ No permissions are required.
+
+### iOS
+
+#### config.xml
+
+ <plugin name="Compass" value="CDVLocation" />
+
+### webOS
+
+ No permissions are required.
+
+### Windows Phone
+
+#### Properties/WPAppManifest.xml
+
+ <Capabilities>
+ <Capability Name="ID_CAP_SENSORS" />
+ </Capabilities>
+
+Reference: [Application Manifest for Windows Phone](http://msdn.microsoft.com/en-us/library/ff769509%28v=vs.92%29.aspx)
+
+### Tizen
+
+ No permissions are required.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/compass.watchHeading.md
----------------------------------------------------------------------
diff --git a/docs/compass.watchHeading.md b/docs/compass.watchHeading.md
new file mode 100755
index 0000000..ddf79ae
--- /dev/null
+++ b/docs/compass.watchHeading.md
@@ -0,0 +1,134 @@
+---
+license: 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.
+---
+
+compass.watchHeading
+====================
+
+At a regular interval, get the compass heading in degrees.
+
+ var watchID = navigator.compass.watchHeading(compassSuccess, compassError, [compassOptions]);
+
+Description
+-----------
+
+The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.
+
+The `compass.watchHeading` gets the device's current heading at a regular interval. Each time the heading is retrieved, the `headingSuccess` callback function is executed. Specify the interval in milliseconds via the `frequency` parameter in the `compassOptions` object.
+
+The returned watch ID references references the compass watch interval. The watch ID can be used with `compass.clearWatch` to stop watching the compass.
+
+Supported Platforms
+-------------------
+
+- Android
+- iPhone
+- Windows Phone 7 and 8 ( if available in hardware )
+- Bada 1.2 & 2.x
+- webOS
+- Tizen
+- Windows 8
+
+
+Quick Example
+-------------
+
+ function onSuccess(heading) {
+ var element = document.getElementById('heading');
+ element.innerHTML = 'Heading: ' + heading.magneticHeading;
+ };
+
+ function onError(compassError) {
+ alert('Compass error: ' + compassError.code);
+ };
+
+ var options = { frequency: 3000 }; // Update every 3 seconds
+
+ var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
+
+Full Example
+------------
+
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>Compass Example</title>
+
+ <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
+ <script type="text/javascript" charset="utf-8">
+
+ // The watch id references the current `watchHeading`
+ var watchID = null;
+
+ // Wait for Cordova to load
+ //
+ document.addEventListener("deviceready", onDeviceReady, false);
+
+ // Cordova is ready
+ //
+ function onDeviceReady() {
+ startWatch();
+ }
+
+ // Start watching the compass
+ //
+ function startWatch() {
+
+ // Update compass every 3 seconds
+ var options = { frequency: 3000 };
+
+ watchID = navigator.compass.watchHeading(onSuccess, onError, options);
+ }
+
+ // Stop watching the compass
+ //
+ function stopWatch() {
+ if (watchID) {
+ navigator.compass.clearWatch(watchID);
+ watchID = null;
+ }
+ }
+
+ // onSuccess: Get the current heading
+ //
+ function onSuccess(heading) {
+ var element = document.getElementById('heading');
+ element.innerHTML = 'Heading: ' + heading.magneticHeading;
+ }
+
+ // onError: Failed to get the heading
+ //
+ function onError(compassError) {
+ alert('Compass error: ' + compassError.code);
+ }
+
+ </script>
+ </head>
+ <body>
+ <div id="heading">Waiting for heading...</div>
+ <button onclick="startWatch();">Start Watching</button>
+ <button onclick="stopWatch();">Stop Watching</button>
+ </body>
+ </html>
+
+iOS Quirks
+--------------
+
+In iOS `compass.watchHeading` can also get the device's current heading when it changes by a specified number of degrees. Each time the heading changes by the specified number of degrees or more, the `headingSuccess` callback function is called. Specify the degrees of change via the `filter` parameter in the `compassOptions` object. Clear the watch as normal by passing the returned watch ID to `compass.clearWatch`. This functionality replaces the previously separate, iOS only functions, watchHeadingFilter and clearWatchFilter, which were removed in 1.6.
+
+In iOS only one watchHeading can be in effect at one time. If a watchHeading via filter is in effect, calling getCurrentHeading or watchHeading will use the existing filter value for specifying heading changes. On iOS watching heading changes via a filter is more efficient than via time.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/compass.watchHeadingFilter.md
----------------------------------------------------------------------
diff --git a/docs/compass.watchHeadingFilter.md b/docs/compass.watchHeadingFilter.md
new file mode 100644
index 0000000..6a0283f
--- /dev/null
+++ b/docs/compass.watchHeadingFilter.md
@@ -0,0 +1,23 @@
+---
+license: 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.
+---
+
+compass.watchHeadingFilter
+==========================
+
+No longer supported as of 1.6, see `compass.watchHeading` for equivalent functionality.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/compassError/compassError.md
----------------------------------------------------------------------
diff --git a/docs/compassError/compassError.md b/docs/compassError/compassError.md
new file mode 100644
index 0000000..989b4dc
--- /dev/null
+++ b/docs/compassError/compassError.md
@@ -0,0 +1,40 @@
+---
+license: 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.
+---
+
+CompassError
+==========
+
+A `CompassError` object is returned to the `compassError` callback function when an error occurs.
+
+Properties
+----------
+
+- __code:__ One of the predefined error codes listed below.
+
+Constants
+---------
+- `CompassError.COMPASS_INTERNAL_ERR`
+- `CompassError.COMPASS_NOT_SUPPORTED`
+
+Description
+-----------
+
+The `CompassError` object is returned to the user through the `compassError` callback function when an error occurs.
+
+
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/parameters/compassError.md
----------------------------------------------------------------------
diff --git a/docs/parameters/compassError.md b/docs/parameters/compassError.md
new file mode 100755
index 0000000..67023ec
--- /dev/null
+++ b/docs/parameters/compassError.md
@@ -0,0 +1,30 @@
+---
+license: 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.
+---
+
+compassError
+==========
+
+onError callback function for compass functions.
+
+Example
+-------
+
+ function(CompassError) {
+ // Handle the error
+ }
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/parameters/compassHeading.md
----------------------------------------------------------------------
diff --git a/docs/parameters/compassHeading.md b/docs/parameters/compassHeading.md
new file mode 100644
index 0000000..935ea06
--- /dev/null
+++ b/docs/parameters/compassHeading.md
@@ -0,0 +1,48 @@
+---
+license: 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.
+---
+
+compassHeading
+==========
+
+A `CompassHeading` object is returned to the `compassSuccess` callback function when an error occurs.
+
+Properties
+----------
+- __magneticHeading:__ The heading in degrees from 0 - 359.99 at a single moment in time. _(Number)_
+- __trueHeading:__ The heading relative to the geographic North Pole in degrees 0 - 359.99 at a single moment in time. A negative value indicates that the true heading could not be determined. _(Number)_
+- __headingAccuracy:__ The deviation in degrees between the reported heading and the true heading. _(Number)_
+- __timestamp:__ The time at which this heading was determined. _(milliseconds)_
+
+Description
+-----------
+
+The `CompassHeading` object is returned to the user through the `compassSuccess` callback function.
+
+Android Quirks
+--------------
+- trueHeading is not supported. It will report the same value as magneticHeading
+- headingAccuracy will always be 0 as there is no difference between the magneticHeading and trueHeading on Android.
+
+iOS Quirks
+----------
+
+- trueHeading is only returned when location services are running via `navigator.geolocation.watchLocation()`
+- For iOS > 4 devices, if the device is rotated and the app supports that orientation, the heading values will be reported
+back with respect to the current orientation.
+
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/parameters/compassOptions.md
----------------------------------------------------------------------
diff --git a/docs/parameters/compassOptions.md b/docs/parameters/compassOptions.md
new file mode 100755
index 0000000..d271a6d
--- /dev/null
+++ b/docs/parameters/compassOptions.md
@@ -0,0 +1,45 @@
+---
+license: 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.
+---
+
+compassOptions
+==============
+
+An optional parameter to customize the retrieval of the compass.
+
+Options
+-------
+
+- __frequency:__ How often to retrieve the compass heading in milliseconds. _(Number)_ (Default: 100)
+- __filter:__ The change in degrees required to initiate a watchHeading success callback. _(Number)_
+
+Android Quirks
+______________
+- filter is not supported.
+
+Windows Phone 7 and 8 Quirks
+--------------
+- filter is not supported.
+
+Bada Quirks
+-----------
+- filter is not supported.
+
+Tizen Quirks
+-----------
+- filter is not supported.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/docs/parameters/compassSuccess.md
----------------------------------------------------------------------
diff --git a/docs/parameters/compassSuccess.md b/docs/parameters/compassSuccess.md
new file mode 100644
index 0000000..1b0fc9c
--- /dev/null
+++ b/docs/parameters/compassSuccess.md
@@ -0,0 +1,40 @@
+---
+license: 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.
+---
+
+compassSuccess
+==============
+
+onSuccess callback function that provides the compass heading information via a compassHeading object.
+
+ function(heading) {
+ // Do something
+ }
+
+Parameters
+----------
+
+
+- __heading:__ The heading information. _(compassHeading)_
+
+Example
+-------
+
+ function onSuccess(heading) {
+ alert('Heading: ' + heading.magneticHeading);
+ };
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/plugin.xml
----------------------------------------------------------------------
diff --git a/plugin.xml b/plugin.xml
new file mode 100644
index 0000000..6edafc8
--- /dev/null
+++ b/plugin.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+xmlns:android="http://schemas.android.com/apk/res/android"
+id="org.apache.cordova.core.CompassListener"
+ version="0.1.0">
+
+ <name>Device Orientation</name>
+
+ <!-- android -->
+ <platform name="android">
+
+ <config-file target="res/xml/config.xml" parent="plugins">
+ <plugin name="Compass" value="org.apache.cordova.core.CompassListener" />
+ </config-file>
+
+ <source-file src="src/android/CompassListener.java" target-dir="src/org/apache/cordova/core" />
+ </platform>
+
+ <!-- ios -->
+ <platform name="ios">
+
+ <config-file target="config.xml" parent="plugins">
+ <plugin name="Compass" value="CDVLocation"/>
+ </config-file>
+
+ <header-file src="src/ios/CDVAccelerometer.h" />
+ <source-file src="src/ios/CDVAccelerometer.m" />
+
+ </platform>
+
+</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/src/android/CompassListener.java
----------------------------------------------------------------------
diff --git a/src/android/CompassListener.java b/src/android/CompassListener.java
new file mode 100755
index 0000000..8f39003
--- /dev/null
+++ b/src/android/CompassListener.java
@@ -0,0 +1,296 @@
+/*
+ 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.
+*/
+package org.apache.cordova.core;
+
+import java.util.List;
+
+import org.apache.cordova.CordovaWebView;
+import org.apache.cordova.api.CallbackContext;
+import org.apache.cordova.api.CordovaInterface;
+import org.apache.cordova.api.CordovaPlugin;
+import org.apache.cordova.api.PluginResult;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.content.Context;
+
+import android.os.Handler;
+import android.os.Looper;
+
+/**
+ * This class listens to the compass sensor and stores the latest heading value.
+ */
+public class CompassListener extends CordovaPlugin implements SensorEventListener {
+
+ public static int STOPPED = 0;
+ public static int STARTING = 1;
+ public static int RUNNING = 2;
+ public static int ERROR_FAILED_TO_START = 3;
+
+ public long TIMEOUT = 30000; // Timeout in msec to shut off listener
+
+ int status; // status of listener
+ float heading; // most recent heading value
+ long timeStamp; // time of most recent value
+ long lastAccessTime; // time the value was last retrieved
+ int accuracy; // accuracy of the sensor
+
+ private SensorManager sensorManager;// Sensor manager
+ Sensor mSensor; // Compass sensor returned by sensor manager
+
+ private CallbackContext callbackContext;
+
+ /**
+ * Constructor.
+ */
+ public CompassListener() {
+ this.heading = 0;
+ this.timeStamp = 0;
+ this.setStatus(CompassListener.STOPPED);
+ }
+
+ /**
+ * Sets the context of the Command. This can then be used to do things like
+ * get file paths associated with the Activity.
+ *
+ * @param cordova The context of the main Activity.
+ * @param webView The CordovaWebView Cordova is running in.
+ */
+ public void initialize(CordovaInterface cordova, CordovaWebView webView) {
+ super.initialize(cordova, webView);
+ this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
+ }
+
+ /**
+ * Executes the request and returns PluginResult.
+ *
+ * @param action The action to execute.
+ * @param args JSONArry of arguments for the plugin.
+ * @param callbackS=Context The callback id used when calling back into JavaScript.
+ * @return True if the action was valid.
+ * @throws JSONException
+ */
+ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ if (action.equals("start")) {
+ this.start();
+ }
+ else if (action.equals("stop")) {
+ this.stop();
+ }
+ else if (action.equals("getStatus")) {
+ int i = this.getStatus();
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, i));
+ }
+ else if (action.equals("getHeading")) {
+ // If not running, then this is an async call, so don't worry about waiting
+ if (this.status != CompassListener.RUNNING) {
+ int r = this.start();
+ if (r == CompassListener.ERROR_FAILED_TO_START) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START));
+ return true;
+ }
+ // Set a timeout callback on the main thread.
+ Handler handler = new Handler(Looper.getMainLooper());
+ handler.postDelayed(new Runnable() {
+ public void run() {
+ CompassListener.this.timeout();
+ }
+ }, 2000);
+ }
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getCompassHeading()));
+ }
+ else if (action.equals("setTimeout")) {
+ this.setTimeout(args.getLong(0));
+ }
+ else if (action.equals("getTimeout")) {
+ long l = this.getTimeout();
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
+ } else {
+ // Unsupported action
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Called when listener is to be shut down and object is being destroyed.
+ */
+ public void onDestroy() {
+ this.stop();
+ }
+
+ /**
+ * Called when app has navigated and JS listeners have been destroyed.
+ */
+ public void onReset() {
+ this.stop();
+ }
+
+ //--------------------------------------------------------------------------
+ // LOCAL METHODS
+ //--------------------------------------------------------------------------
+
+ /**
+ * Start listening for compass sensor.
+ *
+ * @return status of listener
+ */
+ public int start() {
+
+ // If already starting or running, then just return
+ if ((this.status == CompassListener.RUNNING) || (this.status == CompassListener.STARTING)) {
+ return this.status;
+ }
+
+ // Get compass sensor from sensor manager
+ @SuppressWarnings("deprecation")
+ List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
+
+ // If found, then register as listener
+ if (list != null && list.size() > 0) {
+ this.mSensor = list.get(0);
+ this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_NORMAL);
+ this.lastAccessTime = System.currentTimeMillis();
+ this.setStatus(CompassListener.STARTING);
+ }
+
+ // If error, then set status to error
+ else {
+ this.setStatus(CompassListener.ERROR_FAILED_TO_START);
+ }
+
+ return this.status;
+ }
+
+ /**
+ * Stop listening to compass sensor.
+ */
+ public void stop() {
+ if (this.status != CompassListener.STOPPED) {
+ this.sensorManager.unregisterListener(this);
+ }
+ this.setStatus(CompassListener.STOPPED);
+ }
+
+ public void onAccuracyChanged(Sensor sensor, int accuracy) {
+ // TODO Auto-generated method stub
+ }
+
+ /**
+ * Called after a delay to time out if the listener has not attached fast enough.
+ */
+ private void timeout() {
+ if (this.status == CompassListener.STARTING) {
+ this.setStatus(CompassListener.ERROR_FAILED_TO_START);
+ if (this.callbackContext != null) {
+ this.callbackContext.error("Compass listener failed to start.");
+ }
+ }
+ }
+
+ /**
+ * Sensor listener event.
+ *
+ * @param SensorEvent event
+ */
+ public void onSensorChanged(SensorEvent event) {
+
+ // We only care about the orientation as far as it refers to Magnetic North
+ float heading = event.values[0];
+
+ // Save heading
+ this.timeStamp = System.currentTimeMillis();
+ this.heading = heading;
+ this.setStatus(CompassListener.RUNNING);
+
+ // If heading hasn't been read for TIMEOUT time, then turn off compass sensor to save power
+ if ((this.timeStamp - this.lastAccessTime) > this.TIMEOUT) {
+ this.stop();
+ }
+ }
+
+ /**
+ * Get status of compass sensor.
+ *
+ * @return status
+ */
+ public int getStatus() {
+ return this.status;
+ }
+
+ /**
+ * Get the most recent compass heading.
+ *
+ * @return heading
+ */
+ public float getHeading() {
+ this.lastAccessTime = System.currentTimeMillis();
+ return this.heading;
+ }
+
+ /**
+ * Set the timeout to turn off compass sensor if getHeading() hasn't been called.
+ *
+ * @param timeout Timeout in msec.
+ */
+ public void setTimeout(long timeout) {
+ this.TIMEOUT = timeout;
+ }
+
+ /**
+ * Get the timeout to turn off compass sensor if getHeading() hasn't been called.
+ *
+ * @return timeout in msec
+ */
+ public long getTimeout() {
+ return this.TIMEOUT;
+ }
+
+ /**
+ * Set the status and send it to JavaScript.
+ * @param status
+ */
+ private void setStatus(int status) {
+ this.status = status;
+ }
+
+ /**
+ * Create the CompassHeading JSON object to be returned to JavaScript
+ *
+ * @return a compass heading
+ */
+ private JSONObject getCompassHeading() throws JSONException {
+ JSONObject obj = new JSONObject();
+
+ obj.put("magneticHeading", this.getHeading());
+ obj.put("trueHeading", this.getHeading());
+ // Since the magnetic and true heading are always the same our and accuracy
+ // is defined as the difference between true and magnetic always return zero
+ obj.put("headingAccuracy", 0);
+ obj.put("timestamp", this.timeStamp);
+
+ return obj;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/src/ios/CDVLocation.h
----------------------------------------------------------------------
diff --git a/src/ios/CDVLocation.h b/src/ios/CDVLocation.h
new file mode 100644
index 0000000..773599f
--- /dev/null
+++ b/src/ios/CDVLocation.h
@@ -0,0 +1,104 @@
+/*
+ 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.
+ */
+
+#import <UIKit/UIKit.h>
+#import <CoreLocation/CoreLocation.h>
+#import <Cordova/CDVPlugin.h>
+
+enum CDVHeadingStatus {
+ HEADINGSTOPPED = 0,
+ HEADINGSTARTING,
+ HEADINGRUNNING,
+ HEADINGERROR
+};
+typedef NSUInteger CDVHeadingStatus;
+
+enum CDVLocationStatus {
+ PERMISSIONDENIED = 1,
+ POSITIONUNAVAILABLE,
+ TIMEOUT
+};
+typedef NSUInteger CDVLocationStatus;
+
+// simple object to keep track of heading information
+@interface CDVHeadingData : NSObject {}
+
+@property (nonatomic, assign) CDVHeadingStatus headingStatus;
+@property (nonatomic, strong) CLHeading* headingInfo;
+@property (nonatomic, strong) NSMutableArray* headingCallbacks;
+@property (nonatomic, copy) NSString* headingFilter;
+@property (nonatomic, strong) NSDate* headingTimestamp;
+@property (assign) NSInteger timeout;
+
+@end
+
+// simple object to keep track of location information
+@interface CDVLocationData : NSObject {
+ CDVLocationStatus locationStatus;
+ NSMutableArray* locationCallbacks;
+ NSMutableDictionary* watchCallbacks;
+ CLLocation* locationInfo;
+}
+
+@property (nonatomic, assign) CDVLocationStatus locationStatus;
+@property (nonatomic, strong) CLLocation* locationInfo;
+@property (nonatomic, strong) NSMutableArray* locationCallbacks;
+@property (nonatomic, strong) NSMutableDictionary* watchCallbacks;
+
+@end
+
+@interface CDVLocation : CDVPlugin <CLLocationManagerDelegate>{
+ @private BOOL __locationStarted;
+ @private BOOL __highAccuracyEnabled;
+ CDVHeadingData* headingData;
+ CDVLocationData* locationData;
+}
+
+@property (nonatomic, strong) CLLocationManager* locationManager;
+@property (strong) CDVHeadingData* headingData;
+@property (nonatomic, strong) CDVLocationData* locationData;
+
+- (BOOL)hasHeadingSupport;
+- (void)getLocation:(CDVInvokedUrlCommand*)command;
+- (void)addWatch:(CDVInvokedUrlCommand*)command;
+- (void)clearWatch:(CDVInvokedUrlCommand*)command;
+- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback;
+- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message;
+- (void)startLocation:(BOOL)enableHighAccuracy;
+
+- (void)locationManager:(CLLocationManager*)manager
+ didUpdateToLocation:(CLLocation*)newLocation
+ fromLocation:(CLLocation*)oldLocation;
+
+- (void)locationManager:(CLLocationManager*)manager
+ didFailWithError:(NSError*)error;
+
+- (BOOL)isLocationServicesEnabled;
+
+- (void)getHeading:(CDVInvokedUrlCommand*)command;
+- (void)returnHeadingInfo:(NSString*)callbackId keepCallback:(BOOL)bRetain;
+- (void)watchHeadingFilter:(CDVInvokedUrlCommand*)command;
+- (void)stopHeading:(CDVInvokedUrlCommand*)command;
+- (void)startHeadingWithFilter:(CLLocationDegrees)filter;
+- (void)locationManager:(CLLocationManager*)manager
+ didUpdateHeading:(CLHeading*)heading;
+
+- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager*)manager;
+
+@end
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/src/ios/CDVLocation.m
----------------------------------------------------------------------
diff --git a/src/ios/CDVLocation.m b/src/ios/CDVLocation.m
new file mode 100644
index 0000000..ed9ec26
--- /dev/null
+++ b/src/ios/CDVLocation.m
@@ -0,0 +1,623 @@
+/*
+ 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.
+ */
+
+#import "CDVLocation.h"
+#import "NSArray+Comparisons.h"
+
+#pragma mark Constants
+
+#define kPGLocationErrorDomain @"kPGLocationErrorDomain"
+#define kPGLocationDesiredAccuracyKey @"desiredAccuracy"
+#define kPGLocationForcePromptKey @"forcePrompt"
+#define kPGLocationDistanceFilterKey @"distanceFilter"
+#define kPGLocationFrequencyKey @"frequency"
+
+#pragma mark -
+#pragma mark Categories
+
+@interface NSError (JSONMethods)
+
+- (NSString*)JSONRepresentation;
+
+@end
+
+@interface CLLocation (JSONMethods)
+
+- (NSString*)JSONRepresentation;
+
+@end
+
+@interface CLHeading (JSONMethods)
+
+- (NSString*)JSONRepresentation;
+
+@end
+
+#pragma mark -
+#pragma mark CDVHeadingData
+
+@implementation CDVHeadingData
+
+@synthesize headingStatus, headingInfo, headingCallbacks, headingFilter, headingTimestamp, timeout;
+- (CDVHeadingData*)init
+{
+ self = (CDVHeadingData*)[super init];
+ if (self) {
+ self.headingStatus = HEADINGSTOPPED;
+ self.headingInfo = nil;
+ self.headingCallbacks = nil;
+ self.headingFilter = nil;
+ self.headingTimestamp = nil;
+ self.timeout = 10;
+ }
+ return self;
+}
+
+@end
+
+@implementation CDVLocationData
+
+@synthesize locationStatus, locationInfo, locationCallbacks, watchCallbacks;
+- (CDVLocationData*)init
+{
+ self = (CDVLocationData*)[super init];
+ if (self) {
+ self.locationInfo = nil;
+ self.locationCallbacks = nil;
+ self.watchCallbacks = nil;
+ }
+ return self;
+}
+
+@end
+
+#pragma mark -
+#pragma mark CDVLocation
+
+@implementation CDVLocation
+
+@synthesize locationManager, headingData, locationData;
+
+- (CDVPlugin*)initWithWebView:(UIWebView*)theWebView
+{
+ self = (CDVLocation*)[super initWithWebView:(UIWebView*)theWebView];
+ if (self) {
+ self.locationManager = [[CLLocationManager alloc] init];
+ self.locationManager.delegate = self; // Tells the location manager to send updates to this object
+ __locationStarted = NO;
+ __highAccuracyEnabled = NO;
+ self.headingData = nil;
+ self.locationData = nil;
+ }
+ return self;
+}
+
+- (BOOL)hasHeadingSupport
+{
+ BOOL headingInstancePropertyAvailable = [self.locationManager respondsToSelector:@selector(headingAvailable)]; // iOS 3.x
+ BOOL headingClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(headingAvailable)]; // iOS 4.x
+
+ if (headingInstancePropertyAvailable) { // iOS 3.x
+ return [(id)self.locationManager headingAvailable];
+ } else if (headingClassPropertyAvailable) { // iOS 4.x
+ return [CLLocationManager headingAvailable];
+ } else { // iOS 2.x
+ return NO;
+ }
+}
+
+- (BOOL)isAuthorized
+{
+ BOOL authorizationStatusClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+
+
+ if (authorizationStatusClassPropertyAvailable) {
+ NSUInteger authStatus = [CLLocationManager authorizationStatus];
+ return (authStatus == kCLAuthorizationStatusAuthorized) || (authStatus == kCLAuthorizationStatusNotDetermined);
+ }
+
+ // by default, assume YES (for iOS < 4.2)
+ return YES;
+}
+
+- (BOOL)isLocationServicesEnabled
+{
+ BOOL locationServicesEnabledInstancePropertyAvailable = [self.locationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 3.x
+ BOOL locationServicesEnabledClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 4.x
+
+ if (locationServicesEnabledClassPropertyAvailable) { // iOS 4.x
+ return [CLLocationManager locationServicesEnabled];
+ } else if (locationServicesEnabledInstancePropertyAvailable) { // iOS 2.x, iOS 3.x
+ return [(id)self.locationManager locationServicesEnabled];
+ } else {
+ return NO;
+ }
+}
+
+- (void)startLocation:(BOOL)enableHighAccuracy
+{
+ if (![self isLocationServicesEnabled]) {
+ [self returnLocationError:PERMISSIONDENIED withMessage:@"Location services are not enabled."];
+ return;
+ }
+ if (![self isAuthorized]) {
+ NSString* message = nil;
+ BOOL authStatusAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+
+ if (authStatusAvailable) {
+ NSUInteger code = [CLLocationManager authorizationStatus];
+ if (code == kCLAuthorizationStatusNotDetermined) {
+ // could return POSITION_UNAVAILABLE but need to coordinate with other platforms
+ message = @"User undecided on application's use of location services.";
+ } else if (code == kCLAuthorizationStatusRestricted) {
+ message = @"Application's use of location services is restricted.";
+ }
+ }
+ // PERMISSIONDENIED is only PositionError that makes sense when authorization denied
+ [self returnLocationError:PERMISSIONDENIED withMessage:message];
+
+ return;
+ }
+
+ // Tell the location manager to start notifying us of location updates. We
+ // first stop, and then start the updating to ensure we get at least one
+ // update, even if our location did not change.
+ [self.locationManager stopUpdatingLocation];
+ [self.locationManager startUpdatingLocation];
+ __locationStarted = YES;
+ if (enableHighAccuracy) {
+ __highAccuracyEnabled = YES;
+ // Set to distance filter to "none" - which should be the minimum for best results.
+ self.locationManager.distanceFilter = kCLDistanceFilterNone;
+ // Set desired accuracy to Best.
+ self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
+ } else {
+ __highAccuracyEnabled = NO;
+ // TODO: Set distance filter to 10 meters? and desired accuracy to nearest ten meters? arbitrary.
+ self.locationManager.distanceFilter = 10;
+ self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
+ }
+}
+
+- (void)_stopLocation
+{
+ if (__locationStarted) {
+ if (![self isLocationServicesEnabled]) {
+ return;
+ }
+
+ [self.locationManager stopUpdatingLocation];
+ __locationStarted = NO;
+ __highAccuracyEnabled = NO;
+ }
+}
+
+- (void)locationManager:(CLLocationManager*)manager
+ didUpdateToLocation:(CLLocation*)newLocation
+ fromLocation:(CLLocation*)oldLocation
+{
+ CDVLocationData* cData = self.locationData;
+
+ cData.locationInfo = newLocation;
+ if (self.locationData.locationCallbacks.count > 0) {
+ for (NSString* callbackId in self.locationData.locationCallbacks) {
+ [self returnLocationInfo:callbackId andKeepCallback:NO];
+ }
+
+ [self.locationData.locationCallbacks removeAllObjects];
+ }
+ if (self.locationData.watchCallbacks.count > 0) {
+ for (NSString* timerId in self.locationData.watchCallbacks) {
+ [self returnLocationInfo:[self.locationData.watchCallbacks objectForKey:timerId] andKeepCallback:YES];
+ }
+ } else {
+ // No callbacks waiting on us anymore, turn off listening.
+ [self _stopLocation];
+ }
+}
+
+- (void)getLocation:(CDVInvokedUrlCommand*)command
+{
+ NSString* callbackId = command.callbackId;
+ BOOL enableHighAccuracy = [[command.arguments objectAtIndex:0] boolValue];
+
+ if ([self isLocationServicesEnabled] == NO) {
+ NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2];
+ [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"];
+ [posError setObject:@"Location services are disabled." forKey:@"message"];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError];
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ } else {
+ if (!self.locationData) {
+ self.locationData = [[CDVLocationData alloc] init];
+ }
+ CDVLocationData* lData = self.locationData;
+ if (!lData.locationCallbacks) {
+ lData.locationCallbacks = [NSMutableArray arrayWithCapacity:1];
+ }
+
+ if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) {
+ // add the callbackId into the array so we can call back when get data
+ if (callbackId != nil) {
+ [lData.locationCallbacks addObject:callbackId];
+ }
+ // Tell the location manager to start notifying us of heading updates
+ [self startLocation:enableHighAccuracy];
+ } else {
+ [self returnLocationInfo:callbackId andKeepCallback:NO];
+ }
+ }
+}
+
+- (void)addWatch:(CDVInvokedUrlCommand*)command
+{
+ NSString* callbackId = command.callbackId;
+ NSString* timerId = [command.arguments objectAtIndex:0];
+ BOOL enableHighAccuracy = [[command.arguments objectAtIndex:1] boolValue];
+
+ if (!self.locationData) {
+ self.locationData = [[CDVLocationData alloc] init];
+ }
+ CDVLocationData* lData = self.locationData;
+
+ if (!lData.watchCallbacks) {
+ lData.watchCallbacks = [NSMutableDictionary dictionaryWithCapacity:1];
+ }
+
+ // add the callbackId into the dictionary so we can call back whenever get data
+ [lData.watchCallbacks setObject:callbackId forKey:timerId];
+
+ if ([self isLocationServicesEnabled] == NO) {
+ NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2];
+ [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"];
+ [posError setObject:@"Location services are disabled." forKey:@"message"];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError];
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ } else {
+ if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) {
+ // Tell the location manager to start notifying us of location updates
+ [self startLocation:enableHighAccuracy];
+ }
+ }
+}
+
+- (void)clearWatch:(CDVInvokedUrlCommand*)command
+{
+ NSString* timerId = [command.arguments objectAtIndex:0];
+
+ if (self.locationData && self.locationData.watchCallbacks && [self.locationData.watchCallbacks objectForKey:timerId]) {
+ [self.locationData.watchCallbacks removeObjectForKey:timerId];
+ }
+}
+
+- (void)stopLocation:(CDVInvokedUrlCommand*)command
+{
+ [self _stopLocation];
+}
+
+- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback
+{
+ CDVPluginResult* result = nil;
+ CDVLocationData* lData = self.locationData;
+
+ if (lData && !lData.locationInfo) {
+ // return error
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:POSITIONUNAVAILABLE];
+ } else if (lData && lData.locationInfo) {
+ CLLocation* lInfo = lData.locationInfo;
+ NSMutableDictionary* returnInfo = [NSMutableDictionary dictionaryWithCapacity:8];
+ NSNumber* timestamp = [NSNumber numberWithDouble:([lInfo.timestamp timeIntervalSince1970] * 1000)];
+ [returnInfo setObject:timestamp forKey:@"timestamp"];
+ [returnInfo setObject:[NSNumber numberWithDouble:lInfo.speed] forKey:@"velocity"];
+ [returnInfo setObject:[NSNumber numberWithDouble:lInfo.verticalAccuracy] forKey:@"altitudeAccuracy"];
+ [returnInfo setObject:[NSNumber numberWithDouble:lInfo.horizontalAccuracy] forKey:@"accuracy"];
+ [returnInfo setObject:[NSNumber numberWithDouble:lInfo.course] forKey:@"heading"];
+ [returnInfo setObject:[NSNumber numberWithDouble:lInfo.altitude] forKey:@"altitude"];
+ [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.latitude] forKey:@"latitude"];
+ [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.longitude] forKey:@"longitude"];
+
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:returnInfo];
+ [result setKeepCallbackAsBool:keepCallback];
+ }
+ if (result) {
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }
+}
+
+- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message
+{
+ NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2];
+
+ [posError setObject:[NSNumber numberWithInt:errorCode] forKey:@"code"];
+ [posError setObject:message ? message:@"" forKey:@"message"];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError];
+
+ for (NSString* callbackId in self.locationData.locationCallbacks) {
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }
+
+ [self.locationData.locationCallbacks removeAllObjects];
+
+ for (NSString* callbackId in self.locationData.watchCallbacks) {
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }
+}
+
+// called to get the current heading
+// Will call location manager to startUpdatingHeading if necessary
+
+- (void)getHeading:(CDVInvokedUrlCommand*)command
+{
+ NSString* callbackId = command.callbackId;
+ NSDictionary* options = [command.arguments objectAtIndex:0 withDefault:nil];
+ NSNumber* filter = [options valueForKey:@"filter"];
+
+ if (filter) {
+ [self watchHeadingFilter:command];
+ return;
+ }
+ if ([self hasHeadingSupport] == NO) {
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:20];
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ } else {
+ // heading retrieval does is not affected by disabling locationServices and authorization of app for location services
+ if (!self.headingData) {
+ self.headingData = [[CDVHeadingData alloc] init];
+ }
+ CDVHeadingData* hData = self.headingData;
+
+ if (!hData.headingCallbacks) {
+ hData.headingCallbacks = [NSMutableArray arrayWithCapacity:1];
+ }
+ // add the callbackId into the array so we can call back when get data
+ [hData.headingCallbacks addObject:callbackId];
+
+ if ((hData.headingStatus != HEADINGRUNNING) && (hData.headingStatus != HEADINGERROR)) {
+ // Tell the location manager to start notifying us of heading updates
+ [self startHeadingWithFilter:0.2];
+ } else {
+ [self returnHeadingInfo:callbackId keepCallback:NO];
+ }
+ }
+}
+
+// called to request heading updates when heading changes by a certain amount (filter)
+- (void)watchHeadingFilter:(CDVInvokedUrlCommand*)command
+{
+ NSString* callbackId = command.callbackId;
+ NSDictionary* options = [command.arguments objectAtIndex:0 withDefault:nil];
+ NSNumber* filter = [options valueForKey:@"filter"];
+ CDVHeadingData* hData = self.headingData;
+
+ if ([self hasHeadingSupport] == NO) {
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:20];
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ } else {
+ if (!hData) {
+ self.headingData = [[CDVHeadingData alloc] init];
+ hData = self.headingData;
+ }
+ if (hData.headingStatus != HEADINGRUNNING) {
+ // Tell the location manager to start notifying us of heading updates
+ [self startHeadingWithFilter:[filter doubleValue]];
+ } else {
+ // if already running check to see if due to existing watch filter
+ if (hData.headingFilter && ![hData.headingFilter isEqualToString:callbackId]) {
+ // new watch filter being specified
+ // send heading data one last time to clear old successCallback
+ [self returnHeadingInfo:hData.headingFilter keepCallback:NO];
+ }
+ }
+ // save the new filter callback and update the headingFilter setting
+ hData.headingFilter = callbackId;
+ // check if need to stop and restart in order to change value???
+ self.locationManager.headingFilter = [filter doubleValue];
+ }
+}
+
+- (void)returnHeadingInfo:(NSString*)callbackId keepCallback:(BOOL)bRetain
+{
+ CDVPluginResult* result = nil;
+ CDVHeadingData* hData = self.headingData;
+
+ self.headingData.headingTimestamp = [NSDate date];
+
+ if (hData && (hData.headingStatus == HEADINGERROR)) {
+ // return error
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:0];
+ } else if (hData && (hData.headingStatus == HEADINGRUNNING) && hData.headingInfo) {
+ // if there is heading info, return it
+ CLHeading* hInfo = hData.headingInfo;
+ NSMutableDictionary* returnInfo = [NSMutableDictionary dictionaryWithCapacity:4];
+ NSNumber* timestamp = [NSNumber numberWithDouble:([hInfo.timestamp timeIntervalSince1970] * 1000)];
+ [returnInfo setObject:timestamp forKey:@"timestamp"];
+ [returnInfo setObject:[NSNumber numberWithDouble:hInfo.magneticHeading] forKey:@"magneticHeading"];
+ id trueHeading = __locationStarted ? (id)[NSNumber numberWithDouble : hInfo.trueHeading] : (id)[NSNull null];
+ [returnInfo setObject:trueHeading forKey:@"trueHeading"];
+ [returnInfo setObject:[NSNumber numberWithDouble:hInfo.headingAccuracy] forKey:@"headingAccuracy"];
+
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:returnInfo];
+ [result setKeepCallbackAsBool:bRetain];
+ }
+ if (result) {
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }
+}
+
+- (void)stopHeading:(CDVInvokedUrlCommand*)command
+{
+ // CDVHeadingData* hData = self.headingData;
+ if (self.headingData && (self.headingData.headingStatus != HEADINGSTOPPED)) {
+ if (self.headingData.headingFilter) {
+ // callback one last time to clear callback
+ [self returnHeadingInfo:self.headingData.headingFilter keepCallback:NO];
+ self.headingData.headingFilter = nil;
+ }
+ [self.locationManager stopUpdatingHeading];
+ NSLog(@"heading STOPPED");
+ self.headingData = nil;
+ }
+}
+
+// helper method to check the orientation and start updating headings
+- (void)startHeadingWithFilter:(CLLocationDegrees)filter
+{
+ // FYI UIDeviceOrientation and CLDeviceOrientation enums are currently the same
+ self.locationManager.headingOrientation = (CLDeviceOrientation)self.viewController.interfaceOrientation;
+ self.locationManager.headingFilter = filter;
+ [self.locationManager startUpdatingHeading];
+ self.headingData.headingStatus = HEADINGSTARTING;
+}
+
+- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager*)manager
+{
+ return YES;
+}
+
+- (void)locationManager:(CLLocationManager*)manager
+ didUpdateHeading:(CLHeading*)heading
+{
+ CDVHeadingData* hData = self.headingData;
+
+ // normally we would clear the delegate to stop getting these notifications, but
+ // we are sharing a CLLocationManager to get location data as well, so we do a nil check here
+ // ideally heading and location should use their own CLLocationManager instances
+ if (hData == nil) {
+ return;
+ }
+
+ // save the data for next call into getHeadingData
+ hData.headingInfo = heading;
+ BOOL bTimeout = NO;
+ if (!hData.headingFilter && hData.headingTimestamp) {
+ bTimeout = fabs([hData.headingTimestamp timeIntervalSinceNow]) > hData.timeout;
+ }
+
+ if (hData.headingStatus == HEADINGSTARTING) {
+ hData.headingStatus = HEADINGRUNNING; // so returnHeading info will work
+
+ // this is the first update
+ for (NSString* callbackId in hData.headingCallbacks) {
+ [self returnHeadingInfo:callbackId keepCallback:NO];
+ }
+
+ [hData.headingCallbacks removeAllObjects];
+ }
+ if (hData.headingFilter) {
+ [self returnHeadingInfo:hData.headingFilter keepCallback:YES];
+ } else if (bTimeout) {
+ [self stopHeading:nil];
+ }
+ hData.headingStatus = HEADINGRUNNING; // to clear any error
+}
+
+- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error
+{
+ NSLog(@"locationManager::didFailWithError %@", [error localizedFailureReason]);
+
+ // Compass Error
+ if ([error code] == kCLErrorHeadingFailure) {
+ CDVHeadingData* hData = self.headingData;
+ if (hData) {
+ if (hData.headingStatus == HEADINGSTARTING) {
+ // heading error during startup - report error
+ for (NSString* callbackId in hData.headingCallbacks) {
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:0];
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }
+
+ [hData.headingCallbacks removeAllObjects];
+ } // else for frequency watches next call to getCurrentHeading will report error
+ if (hData.headingFilter) {
+ CDVPluginResult* resultFilter = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:0];
+ [self.commandDelegate sendPluginResult:resultFilter callbackId:hData.headingFilter];
+ }
+ hData.headingStatus = HEADINGERROR;
+ }
+ }
+ // Location Error
+ else {
+ CDVLocationData* lData = self.locationData;
+ if (lData && __locationStarted) {
+ // TODO: probably have to once over the various error codes and return one of:
+ // PositionError.PERMISSION_DENIED = 1;
+ // PositionError.POSITION_UNAVAILABLE = 2;
+ // PositionError.TIMEOUT = 3;
+ NSUInteger positionError = POSITIONUNAVAILABLE;
+ if (error.code == kCLErrorDenied) {
+ positionError = PERMISSIONDENIED;
+ }
+ [self returnLocationError:positionError withMessage:[error localizedDescription]];
+ }
+ }
+
+ [self.locationManager stopUpdatingLocation];
+ __locationStarted = NO;
+}
+
+- (void)dealloc
+{
+ self.locationManager.delegate = nil;
+}
+
+- (void)onReset
+{
+ [self _stopLocation];
+ [self.locationManager stopUpdatingHeading];
+ self.headingData = nil;
+}
+
+@end
+
+#pragma mark -
+#pragma mark CLLocation(JSONMethods)
+
+@implementation CLLocation (JSONMethods)
+
+- (NSString*)JSONRepresentation
+{
+ return [NSString stringWithFormat:
+ @"{ timestamp: %.00f, \
+ coords: { latitude: %f, longitude: %f, altitude: %.02f, heading: %.02f, speed: %.02f, accuracy: %.02f, altitudeAccuracy: %.02f } \
+ }",
+ [self.timestamp timeIntervalSince1970] * 1000.0,
+ self.coordinate.latitude,
+ self.coordinate.longitude,
+ self.altitude,
+ self.course,
+ self.speed,
+ self.horizontalAccuracy,
+ self.verticalAccuracy
+ ];
+}
+
+@end
+
+#pragma mark NSError(JSONMethods)
+
+@implementation NSError (JSONMethods)
+
+- (NSString*)JSONRepresentation
+{
+ return [NSString stringWithFormat:
+ @"{ code: %d, message: '%@'}",
+ self.code,
+ [self localizedDescription]
+ ];
+}
+
+@end
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/test/autotest/html/HtmlReporter.js
----------------------------------------------------------------------
diff --git a/test/autotest/html/HtmlReporter.js b/test/autotest/html/HtmlReporter.js
new file mode 100644
index 0000000..7d9d924
--- /dev/null
+++ b/test/autotest/html/HtmlReporter.js
@@ -0,0 +1,101 @@
+jasmine.HtmlReporter = function(_doc) {
+ var self = this;
+ var doc = _doc || window.document;
+
+ var reporterView;
+
+ var dom = {};
+
+ // Jasmine Reporter Public Interface
+ self.logRunningSpecs = false;
+
+ self.reportRunnerStarting = function(runner) {
+ var specs = runner.specs() || [];
+
+ if (specs.length == 0) {
+ return;
+ }
+
+ createReporterDom(runner.env.versionString());
+ doc.body.appendChild(dom.reporter);
+
+ reporterView = new jasmine.HtmlReporter.ReporterView(dom);
+ reporterView.addSpecs(specs, self.specFilter);
+ };
+
+ self.reportRunnerResults = function(runner) {
+ reporterView && reporterView.complete();
+ };
+
+ self.reportSuiteResults = function(suite) {
+ reporterView.suiteComplete(suite);
+ };
+
+ self.reportSpecStarting = function(spec) {
+ if (self.logRunningSpecs) {
+ self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
+ }
+ };
+
+ self.reportSpecResults = function(spec) {
+ reporterView.specComplete(spec);
+ };
+
+ self.log = function() {
+ var console = jasmine.getGlobal().console;
+ if (console && console.log) {
+ if (console.log.apply) {
+ console.log.apply(console, arguments);
+ } else {
+ console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
+ }
+ }
+ };
+
+ self.specFilter = function(spec) {
+ if (!focusedSpecName()) {
+ return true;
+ }
+
+ return spec.getFullName().indexOf(focusedSpecName()) === 0;
+ };
+
+ return self;
+
+ function focusedSpecName() {
+ var specName;
+
+ (function memoizeFocusedSpec() {
+ if (specName) {
+ return;
+ }
+
+ var paramMap = [];
+ var params = doc.location.search.substring(1).split('&');
+
+ for (var i = 0; i < params.length; i++) {
+ var p = params[i].split('=');
+ paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
+ }
+
+ specName = paramMap.spec;
+ })();
+
+ return specName;
+ }
+
+ function createReporterDom(version) {
+ dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' },
+ dom.banner = self.createDom('div', { className: 'banner' },
+ self.createDom('span', { className: 'title' }, "Jasmine "),
+ self.createDom('span', { className: 'version' }, version)),
+
+ dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}),
+ dom.alert = self.createDom('div', {className: 'alert'}),
+ dom.results = self.createDom('div', {className: 'results'},
+ dom.summary = self.createDom('div', { className: 'summary' }),
+ dom.details = self.createDom('div', { id: 'details' }))
+ );
+ }
+};
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/test/autotest/html/HtmlReporterHelpers.js
----------------------------------------------------------------------
diff --git a/test/autotest/html/HtmlReporterHelpers.js b/test/autotest/html/HtmlReporterHelpers.js
new file mode 100644
index 0000000..745e1e0
--- /dev/null
+++ b/test/autotest/html/HtmlReporterHelpers.js
@@ -0,0 +1,60 @@
+jasmine.HtmlReporterHelpers = {};
+
+jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) {
+ var el = document.createElement(type);
+
+ for (var i = 2; i < arguments.length; i++) {
+ var child = arguments[i];
+
+ if (typeof child === 'string') {
+ el.appendChild(document.createTextNode(child));
+ } else {
+ if (child) {
+ el.appendChild(child);
+ }
+ }
+ }
+
+ for (var attr in attrs) {
+ if (attr == "className") {
+ el[attr] = attrs[attr];
+ } else {
+ el.setAttribute(attr, attrs[attr]);
+ }
+ }
+
+ return el;
+};
+
+jasmine.HtmlReporterHelpers.getSpecStatus = function(child) {
+ var results = child.results();
+ var status = results.passed() ? 'passed' : 'failed';
+ if (results.skipped) {
+ status = 'skipped';
+ }
+
+ return status;
+};
+
+jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
+ var parentDiv = this.dom.summary;
+ var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite';
+ var parent = child[parentSuite];
+
+ if (parent) {
+ if (typeof this.views.suites[parent.id] == 'undefined') {
+ this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
+ }
+ parentDiv = this.views.suites[parent.id].element;
+ }
+
+ parentDiv.appendChild(childElement);
+};
+
+
+jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
+ for(var fn in jasmine.HtmlReporterHelpers) {
+ ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
+ }
+};
+
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/test/autotest/html/ReporterView.js
----------------------------------------------------------------------
diff --git a/test/autotest/html/ReporterView.js b/test/autotest/html/ReporterView.js
new file mode 100644
index 0000000..6a6d005
--- /dev/null
+++ b/test/autotest/html/ReporterView.js
@@ -0,0 +1,164 @@
+jasmine.HtmlReporter.ReporterView = function(dom) {
+ this.startedAt = new Date();
+ this.runningSpecCount = 0;
+ this.completeSpecCount = 0;
+ this.passedCount = 0;
+ this.failedCount = 0;
+ this.skippedCount = 0;
+
+ this.createResultsMenu = function() {
+ this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'},
+ this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'),
+ ' | ',
+ this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing'));
+
+ this.summaryMenuItem.onclick = function() {
+ dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, '');
+ };
+
+ this.detailsMenuItem.onclick = function() {
+ showDetails();
+ };
+ };
+
+ this.addSpecs = function(specs, specFilter) {
+ this.totalSpecCount = specs.length;
+
+ this.views = {
+ specs: {},
+ suites: {}
+ };
+
+ for (var i = 0; i < specs.length; i++) {
+ var spec = specs[i];
+ this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
+ if (specFilter(spec)) {
+ this.runningSpecCount++;
+ }
+ }
+ };
+
+ this.specComplete = function(spec) {
+ this.completeSpecCount++;
+
+ if (isUndefined(this.views.specs[spec.id])) {
+ this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
+ }
+
+ var specView = this.views.specs[spec.id];
+
+ switch (specView.status()) {
+ case 'passed':
+ this.passedCount++;
+ break;
+
+ case 'failed':
+ this.failedCount++;
+ break;
+
+ case 'skipped':
+ this.skippedCount++;
+ break;
+ }
+
+ specView.refresh();
+ this.refresh();
+ };
+
+ this.suiteComplete = function(suite) {
+ var suiteView = this.views.suites[suite.id];
+ if (isUndefined(suiteView)) {
+ return;
+ }
+ suiteView.refresh();
+ };
+
+ this.refresh = function() {
+
+ if (isUndefined(this.resultsMenu)) {
+ this.createResultsMenu();
+ }
+
+ // currently running UI
+ if (isUndefined(this.runningAlert)) {
+ this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"});
+ dom.alert.appendChild(this.runningAlert);
+ }
+ this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount);
+
+ // skipped specs UI
+ if (isUndefined(this.skippedAlert)) {
+ this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"});
+ }
+
+ this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
+
+ if (this.skippedCount === 1 && isDefined(dom.alert)) {
+ dom.alert.appendChild(this.skippedAlert);
+ }
+
+ // passing specs UI
+ if (isUndefined(this.passedAlert)) {
+ this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"});
+ }
+ this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount);
+
+ // failing specs UI
+ if (isUndefined(this.failedAlert)) {
+ this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"});
+ }
+ this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount);
+
+ if (this.failedCount === 1 && isDefined(dom.alert)) {
+ dom.alert.appendChild(this.failedAlert);
+ dom.alert.appendChild(this.resultsMenu);
+ }
+
+ // summary info
+ this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount);
+ this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing";
+ };
+
+ this.complete = function() {
+ dom.alert.removeChild(this.runningAlert);
+
+ this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
+
+ if (this.failedCount === 0) {
+ dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount)));
+ } else {
+ showDetails();
+ }
+
+ dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"));
+ };
+
+ return this;
+
+ function showDetails() {
+ if (dom.reporter.className.search(/showDetails/) === -1) {
+ dom.reporter.className += " showDetails";
+ }
+ }
+
+ function isUndefined(obj) {
+ return typeof obj === 'undefined';
+ }
+
+ function isDefined(obj) {
+ return !isUndefined(obj);
+ }
+
+ function specPluralizedFor(count) {
+ var str = count + " spec";
+ if (count > 1) {
+ str += "s"
+ }
+ return str;
+ }
+
+};
+
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView);
+
+
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/test/autotest/html/SpecView.js
----------------------------------------------------------------------
diff --git a/test/autotest/html/SpecView.js b/test/autotest/html/SpecView.js
new file mode 100644
index 0000000..8769bb8
--- /dev/null
+++ b/test/autotest/html/SpecView.js
@@ -0,0 +1,79 @@
+jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
+ this.spec = spec;
+ this.dom = dom;
+ this.views = views;
+
+ this.symbol = this.createDom('li', { className: 'pending' });
+ this.dom.symbolSummary.appendChild(this.symbol);
+
+ this.summary = this.createDom('div', { className: 'specSummary' },
+ this.createDom('a', {
+ className: 'description',
+ href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
+ title: this.spec.getFullName()
+ }, this.spec.description)
+ );
+
+ this.detail = this.createDom('div', { className: 'specDetail' },
+ this.createDom('a', {
+ className: 'description',
+ href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
+ title: this.spec.getFullName()
+ }, this.spec.getFullName())
+ );
+};
+
+jasmine.HtmlReporter.SpecView.prototype.status = function() {
+ return this.getSpecStatus(this.spec);
+};
+
+jasmine.HtmlReporter.SpecView.prototype.refresh = function() {
+ this.symbol.className = this.status();
+
+ switch (this.status()) {
+ case 'skipped':
+ break;
+
+ case 'passed':
+ this.appendSummaryToSuiteDiv();
+ break;
+
+ case 'failed':
+ this.appendSummaryToSuiteDiv();
+ this.appendFailureDetail();
+ break;
+ }
+};
+
+jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() {
+ this.summary.className += ' ' + this.status();
+ this.appendToSummary(this.spec, this.summary);
+};
+
+jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
+ this.detail.className += ' ' + this.status();
+
+ var resultItems = this.spec.results().getItems();
+ var messagesDiv = this.createDom('div', { className: 'messages' });
+
+ for (var i = 0; i < resultItems.length; i++) {
+ var result = resultItems[i];
+
+ if (result.type == 'log') {
+ messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
+ } else if (result.type == 'expect' && result.passed && !result.passed()) {
+ messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
+
+ if (result.trace.stack) {
+ messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
+ }
+ }
+ }
+
+ if (messagesDiv.childNodes.length > 0) {
+ this.detail.appendChild(messagesDiv);
+ this.dom.details.appendChild(this.detail);
+ }
+};
+
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation/blob/dbc80008/test/autotest/html/SuiteView.js
----------------------------------------------------------------------
diff --git a/test/autotest/html/SuiteView.js b/test/autotest/html/SuiteView.js
new file mode 100644
index 0000000..19a1efa
--- /dev/null
+++ b/test/autotest/html/SuiteView.js
@@ -0,0 +1,22 @@
+jasmine.HtmlReporter.SuiteView = function(suite, dom, views) {
+ this.suite = suite;
+ this.dom = dom;
+ this.views = views;
+
+ this.element = this.createDom('div', { className: 'suite' },
+ this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description)
+ );
+
+ this.appendToSummary(this.suite, this.element);
+};
+
+jasmine.HtmlReporter.SuiteView.prototype.status = function() {
+ return this.getSpecStatus(this.suite);
+};
+
+jasmine.HtmlReporter.SuiteView.prototype.refresh = function() {
+ this.element.className += " " + this.status();
+};
+
+jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView);
+