Compare commits

...

64 Commits

Author SHA1 Message Date
Andrew Grieve
e5b0157971 Set VERSION to 3.1.0 (via coho) 2013-10-02 12:40:50 -04:00
Andrew Grieve
847b6fe7c9 Update JS snapshot to version 3.1.0 (via coho) 2013-10-02 12:40:49 -04:00
Joe Bowser
133c2dc902 CB-4961: shell.js returns the full path on ls, rebuilding the full path isn't really needed 2013-09-30 16:01:59 -07:00
Andrew Grieve
5592765f04 [CB-4892] Fix create script only escaping the first space instead of all spaces.
(cherry picked from commit 2d88a726b7)
2013-09-23 10:17:14 +02:00
Andrew Grieve
4441215e4c Fix update script to clobber cordova.js file (missing -f) 2013-09-19 15:48:15 -04:00
Andrew Grieve
734d4d3147 Add missing copyright header for Whitelist.java.
(cherry picked from commit b7ede8f9ba)
2013-09-17 14:21:20 -04:00
Andrew Grieve
d269b54aad [CB-4832] Add 3.1.0 RELEASENOTES.md
(cherry picked from commit 15f36cc19d)
2013-09-17 13:09:24 -04:00
Andrew Grieve
495ca45f76 Set VERSION to 3.1.0-rc1 (via coho) 2013-09-17 11:03:50 -04:00
Andrew Grieve
42a6e7972a Update JS snapshot to version 3.1.0-rc1 (via coho) 2013-09-17 11:03:50 -04:00
Joe Bowser
52d0a4fa78 Updating Android Version to RC1 2013-09-16 15:21:10 -07:00
Andrew Grieve
1d1cdb5ea4 Always have create script rebuild jar when on a dev version 2013-09-16 14:25:12 -04:00
Andrew Grieve
34bdef9c45 [CB-4817] Remove unused assets in project template. 2013-09-13 23:07:41 -04:00
Andrew Grieve
cad673f8cd [CB-4817] Avoid generating unused files in create script
by using "android update project" instead of "android create project"
2013-09-13 22:49:15 -04:00
Andrew Grieve
7c446b222d [CB-3542] Convert update script to be node-based. 2013-09-13 22:49:15 -04:00
Andrew Grieve
1bd0f8fcf4 [CB-3542] Delete old ant-based bin/create.xml file. 2013-09-13 22:49:14 -04:00
Andrew Grieve
dd3c261ba2 [CB-3542] Only update framework/ project when building the jar.
No need to do it during every check_reqs.
This also extracts the jar building into a helper function.
2013-09-13 22:49:14 -04:00
Andrew Grieve
70cc711ec1 [CB-3542] Delete custom replaceInFile with shelljs.sed(). 2013-09-13 22:07:38 -04:00
Andrew Grieve
485f2ee923 [CB-3542] Fail create script if a copy fails. 2013-09-13 22:07:35 -04:00
Andrew Grieve
129be6e476 [CB-3542] Delete extra message when check_reqs fails.
check_reqs already outputs a message.
2013-09-13 22:07:31 -04:00
Andrew Grieve
c08b64efb3 [CB-3542] Fix create script's check for whether cordova.jar exists. 2013-09-13 22:07:23 -04:00
Andrew Grieve
f4a0f55b13 Fail fast in create script if package name is not com.foo.bar. 2013-09-13 16:08:45 -04:00
Joe Bowser
39d32bcb5b CB-4620: Throwing this over the fence, since there is a problem actually in the wild here 2013-09-11 15:02:00 -07:00
Andrew Grieve
3351fdbc74 Restore deleted classes (FileHelper, etc) and deprecate them instead.
The classes are:
[CB-4766] JSONUtils.java
[CB-4765] ExifHelper.java
[CB-4764] DirectoryManager.java
[CB-4763] FileHelper.java
2013-09-11 11:13:57 -04:00
Andrew Grieve
7be1f018aa [CB-3542] Commit bin/node_modules so that it doesn't need to be npm installed. 2013-09-10 16:58:28 -04:00
Andrew Grieve
437daa368a [CB-4782] Convert ApplicationInfo.java -> appinfo.js 2013-09-10 16:32:42 -04:00
Andrew Grieve
3df09eacf2 Remove out-of-date create script tests.
They have clearly not been run in a long time. We verify create script
output manually during releases, and I think that's more meaningful.
2013-09-10 15:25:01 -04:00
Andrew Grieve
483dd3435a [CB-4769] Fix create script failure due to deleted version.js file 2013-09-10 09:21:57 -04:00
Andrew Grieve
2b0aa03380 [CB-4766] Delete JSONUtils.java 2013-09-09 16:47:55 -04:00
Andrew Grieve
fc7261b199 [CB-4765] Move ExifHelper.java out of core (and into camera plugin) 2013-09-09 16:17:53 -04:00
Andrew Grieve
3200c50b9f [CB-4764] Delete DirectoryManager.java 2013-09-09 16:11:41 -04:00
Andrew Grieve
862a8eab8d [CB-4763] Delete FileHelper.java, Move getMimeType() into CordovaResourceApi. 2013-09-09 15:43:04 -04:00
Andrew Grieve
1bfcc92677 Make version in version script easier to replace by coho 2013-09-09 15:37:00 -04:00
Andrew Grieve
80a09b8f36 [CB-4725] Add CordovaWebView.CORDOVA_VERSION constant
This used to be available as Device.cordovaVersion, but was broken in 3.0.
2013-09-09 11:22:18 -04:00
Joe Bowser
5f7ce4b868 Reverting CB-3949: Squeay wheel gets the grease 2013-08-28 14:42:23 -07:00
Joe Bowser
412d97fa0c Incremeting version check for Android 4.3 API Level 18 2013-08-28 14:41:42 -07:00
Benn Mapes
57bed98cf1 Added commit 150cdfd, override arg for project template
Conflicts:
	bin/create
2013-08-28 14:04:43 -07:00
Benn Mapes
b1d8788506 Fix for cli with new node scripts 2013-08-27 11:41:54 -07:00
Benn Mapes
1bd4900981 [CB-3542] rewrote cli tooling scripts in node 2013-08-26 14:45:28 -07:00
Ian Clelland
e6812f18a0 Allow CordovaChromeClient subclasses access to CordovaInterface and CordovaWebView members 2013-08-23 14:37:36 -04:00
Ian Clelland
f604988181 Refactor CordovaActivity.init so that subclasses can easily override factory methods for webview objects 2013-08-23 13:04:19 -04:00
Ian Clelland
150cdfd3ac [CB-4652] Allow default project template to be overridden on create 2013-08-23 13:04:19 -04:00
Joe Bowser
f42b34d6b4 CB-4318: We have docs, this doesn't need to be in the comments 2013-08-20 16:29:31 -07:00
Andrew Grieve
166b35bc6c Tweak the online bridge to not send excess online events.
It does so by having the JS tell it when online events have fired.
2013-08-15 15:55:08 -04:00
Tomaz Muraus
121b74fa0c [CB-4495] Modify start-emulator script to exit immediately on a fatal emulator error. 2013-08-15 11:46:50 -04:00
Andrew Grieve
5451320350 Log WebView IOExceptions only when they are not 404s 2013-08-15 11:33:38 -04:00
Andrew Grieve
fe45b29ef6 Use a higher threshold for slow exec() warnings when debugger is attached. 2013-08-13 15:08:54 -04:00
Andrew Grieve
4e1aa8aa59 Fix data URI decoding in CordovaResourceApi
It was not URI-decoding first, and so was broken for non-base64-encoded
URIs.
2013-08-13 14:11:40 -04:00
Ian Clelland
fa366eb7a8 [CB-4140] Fix master branch cordova version to 3.1.0-dev 2013-08-09 10:45:39 -04:00
Andrew Grieve
e086a706ba Remove plugin references in test project's config.xml 2013-08-02 13:19:14 -04:00
Benn Mapes
53b8da8198 [CB-4466] fixed jscript check_reqs to get target from project.properties 2013-08-01 17:57:58 -07:00
Fil Maj
c2c5f71018 [CB-4463] Updated bin/check_reqs to looks for android-18 target.Also fixed an issue in unix version of script that would invoke the android command if an error occurred. 2013-07-30 17:14:46 -07:00
Joe Bowser
2bdc849c2b CB-3819: Implemented Feature 2013-07-30 15:03:25 -07:00
Max Woghiren
7cbe8f5843 [CB-4013] Fixed loadUrlTimeoutValue preference. 2013-07-30 12:21:50 -04:00
Sharif Ahmed
810df61049 [CB-4410] Fixed @param mismatching 2013-07-30 11:21:02 -04:00
Joe Bowser
5c38101a9e Upgrading project to Android 4.3 2013-07-29 11:30:41 -07:00
Fil Maj
b4236b9783 [CB-4198] bin/create script should be better at handling non-word characters in activity name. Patched windows script as well. 2013-07-25 10:33:05 -07:00
Fil Maj
980c4699b0 [CB-4198] bin/create should handle spaces in activity better. 2013-07-24 21:21:41 -07:00
Ian Clelland
463c7b5027 [CB-4096] Implemente new unified whitelist for android 2013-07-23 11:23:14 -04:00
David Kemp
7c7230dd35 [CB-4280] handle invalid bridge mode request 2013-07-22 18:15:09 -04:00
Andrew Grieve
b915aafb5b [CB-3384] Fix thread assertion when plugins remap URIs 2013-07-18 01:38:47 -04:00
David Kemp
8202ab83fa [CB-4133] Add main thread warning for plugins that run too long 2013-07-16 21:19:11 -04:00
Joe Bowser
2fe6d14e56 We can remove the plugins tag now. Tested plugman, it's all good. 2013-07-16 15:00:28 -07:00
Ian Clelland
7ee285342f Update cordova.js to latest (3.0.0-rc1) version 2013-07-16 14:48:48 -04:00
Andrew Grieve
6fe18ae0ab [CB-3384] Use the ExposedJsApi to detect webCore thread instead of IceCreamCordovaWebViewClient.
Also removes a debug log statement.
2013-07-16 09:39:47 -04:00
106 changed files with 5054 additions and 7335 deletions

1
.gitignore vendored
View File

@@ -20,7 +20,6 @@ example
test/bin
test/assets/www/.tmp*
tmp/**
bin/node_modules
.metadata
tmp/**/*
Thumbs.db

54
RELEASENOTES.md Normal file
View File

@@ -0,0 +1,54 @@
<!--
#
# 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.
#
-->
## Release Notes for Cordova (Android) ##
### 3.1.0 (Sept 2013) ###
55 commits from 9 authors. Highlights include:
* [CB-4817] Remove unused assets in project template.
* Fail fast in create script if package name is not com.foo.bar.
* [CB-4782] Convert ApplicationInfo.java -> appinfo.js
* [CB-4766] Deprecated JSONUtils.java (moved into plugins)
* [CB-4765] Deprecated ExifHelper.java (moved into plugins)
* [CB-4764] Deprecated DirectoryManager.java (moved into plugins)
* [CB-4763] Deprecated FileHelper.java (moved into plugins), Move getMimeType() into CordovaResourceApi.
* [CB-4725] Add CordovaWebView.CORDOVA_VERSION constant
* Incremeting version check for Android 4.3 API Level 18
* [CB-3542] rewrote cli tooling scripts in node
* Allow CordovaChromeClient subclasses access to CordovaInterface and CordovaWebView members
* Refactor CordovaActivity.init so that subclasses can easily override factory methods for webview objects
* [CB-4652] Allow default project template to be overridden on create
* Tweak the online bridge to not send excess online events.
* [CB-4495] Modify start-emulator script to exit immediately on a fatal emulator error.
* Log WebView IOExceptions only when they are not 404s
* Use a higher threshold for slow exec() warnings when debugger is attached.
* Fix data URI decoding in CordovaResourceApi
* [CB-3819] Made it easier to set SplashScreen delay.
* [CB-4013] Fixed loadUrlTimeoutValue preference.
* Upgrading project to Android 4.3
* [CB-4198] bin/create script should be better at handling non-word characters in activity name. Patched windows script as well.
* [CB-4198] bin/create should handle spaces in activity better.
* [CB-4096] Implemented new unified whitelist for android
* [CB-3384] Fix thread assertion when plugins remap URIs
* [CB-4133] Add main thread warning for plugins that run too long
* [CB-3384] Use the ExposedJsApi to detect webCore thread instead of IceCreamCordovaWebViewClient.

View File

@@ -1 +1 @@
dev
3.1.0

View File

@@ -1,34 +1,27 @@
#! /bin/bash
# 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.
#
ROOT="$( cd "$( dirname "$0" )/.." && pwd )"
cmd=`android list target`
if [[ $? != 0 ]]; then
echo "The command `android` failed. Make sure you have the latest Android SDK installed, and the `android` command (inside the tools/ folder) added to your path."
exit 2
elif [[ ! $cmd =~ "android-17" ]]; then
echo "Please install Android target 17 (the Android 4.2 SDK). Make sure you have the latest Android tools installed as well. Run `android` from your command-line to install/update any missing SDKs or tools."
exit 2
else
cmd="android update project -p $ROOT -t android-17 1> /dev/null 2>&1"
eval $cmd
if [[ $? != 0 ]]; then
echo "Error updating the Cordova library to work with your Android environment."
exit 2
fi
fi
#!/usr/bin/env node
/*
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.
*/
var check_reqs = require('./lib/check_reqs');
if(!check_reqs.run()) {
process.exit(2);
}

View File

@@ -16,11 +16,11 @@
:: under the License.
@ECHO OFF
SET full_path=%~dp0
IF EXIST %full_path%check_reqs.js (
cscript "%full_path%check_reqs.js" //nologo
SET script_path="%~dp0check_reqs"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'check_reqs.js' in 'bin' folder, aborting...>&2
ECHO ERROR: Could not find 'check_reqs' script in 'bin' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -1,81 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
var ROOT = WScript.ScriptFullName.split('\\bin\\check_reqs.js').join(''),
shell = WScript.CreateObject("WScript.Shell"),
fso = WScript.CreateObject('Scripting.FileSystemObject');
// executes a command in the shell, returns stdout or stderr if error
function exec_out(command) {
var oExec=shell.Exec(command);
var output = new String();
while (oExec.Status == 0) {
if (!oExec.StdOut.AtEndOfStream) {
var line = oExec.StdOut.ReadAll();
// XXX: Change to verbose mode
// WScript.StdOut.WriteLine(line);
output += line;
}
WScript.sleep(100);
}
//Check to make sure our scripts did not encounter an error
if (!oExec.StdErr.AtEndOfStream) {
var line = oExec.StdErr.ReadAll();
return {'error' : true, 'output' : line};
} else if (!oExec.StdOut.AtEndOfStream) {
var line = oExec.StdOut.ReadAll();
// XXX: Change to verbose mode
// WScript.StdOut.WriteLine(line);
output += line;
}
return {'error' : false, 'output' : output};
}
// log to stdout or stderr
function Log(msg, error) {
if (error) {
WScript.StdErr.WriteLine(msg);
}
else {
WScript.StdOut.WriteLine(msg);
}
}
// checks that android requirements are met
function check_requirements() {
var result = exec_out('%comspec% /c android list target');
if(result.error) {
Log('The command `android` failed. Make sure you have the latest Android SDK installed, and the `android` command (inside the tools/ folder) added to your path. Output: ' + result.output, true);
WScript.Quit(2);
}
else if(!result.output.match(/android[-]17/)) {
Log('Please install Android target 17 (the Android 4.2 SDK). Make sure you have the latest Android tools installed as well. Run `android` from your command-line to install/update any missing SDKs or tools.', true);
Log('Output : ' + result.output);
WScript.Quit(2);
}
else {
var cmd = '%comspec% /c android update project -p ' + ROOT + '\\framework -t android-17';
result = exec_out(cmd);
if(result.error) {
Log('Error updating the Cordova library to work with your Android environment. Command run: "' + cmd + '", output: ' + result.output, true);
WScript.Quit(2);
}
}
}
check_requirements();

View File

@@ -1,153 +1,36 @@
#! /bin/bash
# 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.
#
# create a cordova/android project
#
# USAGE
# ./create [path package activity]
#
set -e
#!/usr/bin/env node
if [ -z "$1" ] || [ "$1" == "-h" ]
then
echo "Usage: $0 <path_to_new_project> <package_name> <project_name>"
echo "Make sure the Android SDK tools folder is in your PATH!"
echo " <path_to_new_project>: Path to your new Cordova iOS project"
echo " <package_name>: Package name, following reverse-domain style convention"
echo " <project_name>: Project name"
exit 0
fi
/*
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
BUILD_PATH="$( cd "$( dirname "$0" )/.." && pwd )"
VERSION=$(cat "$BUILD_PATH"/VERSION)
http://www.apache.org/licenses/LICENSE-2.0
PROJECT_PATH="${1:-'./example'}"
PACKAGE=${2:-"org.apache.cordova.example"}
ACTIVITY=${3:-"cordovaExample"}
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.
*/
var path = require('path');
var create = require('./lib/create');
var args = process.argv;
# clobber any existing example
if [ -d "$PROJECT_PATH" ]
then
echo "Project already exists! Delete and recreate"
exit 1
fi
function createAppInfoJar {
pushd "$BUILD_PATH"/bin/templates/cordova/ApplicationInfo > /dev/null
javac ApplicationInfo.java
jar -cfe ../appinfo.jar ApplicationInfo ApplicationInfo.class
popd > /dev/null
// Support basic help commands
if(args.length < 3 || (args[2] == '--help' || args[2] == '/?' || args[2] == '-h' ||
args[2] == 'help' || args[2] == '-help' || args[2] == '/help')) {
console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'create')) + ' <path_to_new_project> <package_name> <project_name>');
console.log(' <path_to_new_project>: Path to your new Cordova Android project');
console.log(' <package_name>: Package name, following reverse-domain style convention');
console.log(' <project_name>: Project name');
process.exit(1);
} else {
create.createProject(args[2], args[3], args[4], args[5]);
}
function on_error {
echo "An unexpected error occurred: $previous_command exited with $?"
echo "Deleting project..."
[ -d "$PROJECT_PATH" ] && rm -rf "$PROJECT_PATH"
exit 1
}
function replace {
local pattern=$1
local filename=$2
# Mac OS X requires -i argument
if [[ "$OSTYPE" =~ "darwin" ]]
then
/usr/bin/sed -i '' -e $pattern "$filename"
elif [[ "$OSTYPE" =~ "linux" ]]
then
/bin/sed -i -e $pattern "$filename"
fi
}
# we do not want the script to silently fail
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
trap on_error ERR
ANDROID_BIN="${ANDROID_BIN:=$( which android )}"
PACKAGE_AS_PATH=$(echo $PACKAGE | sed 's/\./\//g')
ACTIVITY_PATH="$PROJECT_PATH"/src/$PACKAGE_AS_PATH/$ACTIVITY.java
MANIFEST_PATH="$PROJECT_PATH"/AndroidManifest.xml
TARGET=$("$ANDROID_BIN" list targets -c | grep '^android-' | tail -1 )
API_LEVEL=${TARGET##android-}
# check that build targets exist
if [ -z "$TARGET" ] || [ -z "$API_LEVEL" ]
then
echo "No Android Targets are installed. Please install at least one via the android SDK"
exit 1
fi
# if this a distribution release no need to build a jar
if [ ! -e "$BUILD_PATH"/cordova-$VERSION.jar ] && [ -d "$BUILD_PATH"/framework ]
then
# update the cordova-android framework for the desired target
"$ANDROID_BIN" update project --target $TARGET --path "$BUILD_PATH"/framework &> /dev/null
# compile cordova.js and cordova.jar
pushd "$BUILD_PATH"/framework > /dev/null
ant jar > /dev/null
popd > /dev/null
fi
# create new android project
"$ANDROID_BIN" create project --target $TARGET --path "$PROJECT_PATH" --package $PACKAGE --activity $ACTIVITY &> /dev/null
# copy project template
cp -r "$BUILD_PATH"/bin/templates/project/assets "$PROJECT_PATH"
cp -r "$BUILD_PATH"/bin/templates/project/res "$PROJECT_PATH"
# copy cordova.js, cordova.jar and res/xml
if [ -d "$BUILD_PATH"/framework ]
then
cp -r "$BUILD_PATH"/framework/res/xml "$PROJECT_PATH"/res
cp "$BUILD_PATH"/framework/assets/www/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
cp "$BUILD_PATH"/framework/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
else
cp -r "$BUILD_PATH"/xml "$PROJECT_PATH"/res/xml
cp "$BUILD_PATH"/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
cp "$BUILD_PATH"/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
fi
# interpolate the activity name and package
cp "$BUILD_PATH"/bin/templates/project/Activity.java "$ACTIVITY_PATH"
replace "s/__ACTIVITY__/${ACTIVITY}/g" "$ACTIVITY_PATH"
replace "s/__ID__/${PACKAGE}/g" "$ACTIVITY_PATH"
cp "$BUILD_PATH"/bin/templates/project/AndroidManifest.xml "$MANIFEST_PATH"
replace "s/__ACTIVITY__/${ACTIVITY}/g" "$MANIFEST_PATH"
replace "s/__PACKAGE__/${PACKAGE}/g" "$MANIFEST_PATH"
replace "s/__APILEVEL__/${API_LEVEL}/g" "$MANIFEST_PATH"
# creating cordova folder and copying run/build/log/launch scripts
mkdir "$PROJECT_PATH"/cordova
mkdir "$PROJECT_PATH"/cordova/lib
createAppInfoJar
cp "$BUILD_PATH"/bin/templates/cordova/appinfo.jar "$PROJECT_PATH"/cordova/appinfo.jar
cp "$BUILD_PATH"/bin/templates/cordova/build "$PROJECT_PATH"/cordova/build
cp "$BUILD_PATH"/bin/templates/cordova/clean "$PROJECT_PATH"/cordova/clean
cp "$BUILD_PATH"/bin/templates/cordova/log "$PROJECT_PATH"/cordova/log
cp "$BUILD_PATH"/bin/templates/cordova/run "$PROJECT_PATH"/cordova/run
cp "$BUILD_PATH"/bin/templates/cordova/version "$PROJECT_PATH"/cordova/version
cp "$BUILD_PATH"/bin/templates/cordova/lib/install-device "$PROJECT_PATH"/cordova/lib/install-device
cp "$BUILD_PATH"/bin/templates/cordova/lib/install-emulator "$PROJECT_PATH"/cordova/lib/install-emulator
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-devices "$PROJECT_PATH"/cordova/lib/list-devices
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-emulator-images "$PROJECT_PATH"/cordova/lib/list-emulator-images
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-started-emulators "$PROJECT_PATH"/cordova/lib/list-started-emulators
cp "$BUILD_PATH"/bin/templates/cordova/lib/start-emulator "$PROJECT_PATH"/cordova/lib/start-emulator

View File

@@ -1,5 +1,3 @@
@ECHO OFF
GOTO BEGIN
:: 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
@@ -17,38 +15,12 @@ GOTO BEGIN
:: specific language governing permissions and limitations
:: under the License.
:BEGIN
IF NOT DEFINED JAVA_HOME GOTO MISSING_JAVA_HOME
FOR %%X in (java.exe javac.exe ant.bat android.bat) do (
IF [%%~$PATH:X]==[] (
ECHO Cannot locate %%X using the PATH environment variable.
ECHO Retry after adding directory containing %%X to the PATH variable.
ECHO Remember to open a new command window after updating the PATH variable.
IF "%%X"=="java.exe" GOTO GET_JAVA
IF "%%X"=="javac.exe" GOTO GET_JAVA
IF "%%X"=="ant.bat" GOTO GET_ANT
IF "%%X"=="android.bat" GOTO GET_ANDROID
GOTO ERROR
)
)
cscript "%~dp0\create.js" %* //nologo
GOTO END
:MISSING_JAVA_HOME
ECHO The JAVA_HOME environment variable is not set.
ECHO Set JAVA_HOME to an existing JRE directory.
ECHO Remember to also add JAVA_HOME to the PATH variable.
ECHO After updating system variables, open a new command window and retry.
GOTO ERROR
:GET_JAVA
ECHO Visit http://java.oracle.com if you need to install Java (JDK).
GOTO ERROR
:GET_ANT
ECHO Visit http://ant.apache.org if you need to install Apache Ant.
GOTO ERROR
:GET_ANDROID
ECHO Visit http://developer.android.com if you need to install the Android SDK.
GOTO ERROR
:ERROR
EXIT /B 1
:END
@ECHO OFF
SET script_path="%~dp0create"
IF EXIST %script_path% (
node %script_path% %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'create' script in 'bin' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -1,210 +0,0 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/*
* create a cordova/android project
*
* USAGE
* ./create [path package activity]
*/
var args = WScript.Arguments, PROJECT_PATH="example",
PACKAGE="org.apache.cordova.example", ACTIVITY="cordovaExample",
shell=WScript.CreateObject("WScript.Shell"),
fso = WScript.CreateObject('Scripting.FileSystemObject');
function Usage() {
Log("Usage: create PathTONewProject [ PackageName AppName ]");
Log(" PathTONewProject : The path to where you wish to create the project");
Log(" PackageName : The package for the project (default is org.apache.cordova.example)")
Log(" AppName : The name of the application/activity (default is cordovaExample)");
Log("examples:");
Log(" create C:\\Users\\anonymous\\Desktop\\MyProject");
Log(" create C:\\Users\\anonymous\\Desktop\\MyProject io.Cordova.Example AnApp");
}
// logs messaged to stdout and stderr
function Log(msg, error) {
if (error) {
WScript.StdErr.WriteLine(msg);
}
else {
WScript.StdOut.WriteLine(msg);
}
}
function read(filename) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 1);
var s=f.ReadAll();
f.Close();
return s;
}
function checkTargets(targets) {
if(!targets) {
Log("You do not have any android targets setup. Please create at least one target with the `android` command", true);
WScript.Quit(69);
}
}
function setTarget() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/id: /, ""); // TODO: give users the option to set their target
}
function setApiLevel() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/API level:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/API level: /, "");
}
function write(filename, contents) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 2, true);
f.Write(contents);
f.Close();
}
function replaceInFile(filename, regexp, replacement) {
write(filename, read(filename).replace(regexp, replacement));
}
function exec(command) {
var oShell=shell.Exec(command);
while (oShell.Status == 0) {
if(!oShell.StdOut.AtEndOfStream) {
var line = oShell.StdOut.ReadLine();
// XXX: Change to verbose mode
// WScript.StdOut.WriteLine(line);
}
WScript.sleep(100);
}
}
function createAppInfoJar() {
if(!fso.FileExists(ROOT+"\\bin\\templates\\cordova\\appinfo.jar")) {
Log("Creating appinfo.jar...");
var cur = shell.CurrentDirectory;
shell.CurrentDirectory = ROOT+"\\bin\\templates\\cordova\\ApplicationInfo";
exec("javac ApplicationInfo.java");
exec("jar -cfe ..\\appinfo.jar ApplicationInfo ApplicationInfo.class");
shell.CurrentDirectory = cur;
}
}
// working dir
var ROOT = WScript.ScriptFullName.split('\\bin\\create.js').join('');
if (args.Count() > 0) {
// support help flags
if (args(0) == "--help" || args(0) == "/?" ||
args(0) == "help" || args(0) == "-help" || args(0) == "/help" || args(0) == "-h") {
Usage();
WScript.Quit(2);
}
PROJECT_PATH=args(0);
if (args.Count() > 1) {
PACKAGE = args(1);
}
if (args.Count() > 2) {
ACTIVITY = args(2);
}
}
else {
Log("Error : No project path provided.");
Usage();
WScript.Quit(2);
}
if(fso.FolderExists(PROJECT_PATH)) {
Log("Project path already exists!", true);
WScript.Quit(2);
}
var PACKAGE_AS_PATH=PACKAGE.replace(/\./g, '\\');
var ACTIVITY_DIR=PROJECT_PATH + '\\src\\' + PACKAGE_AS_PATH;
var ACTIVITY_PATH=ACTIVITY_DIR+'\\'+ACTIVITY+'.java';
var MANIFEST_PATH=PROJECT_PATH+'\\AndroidManifest.xml';
var TARGET=setTarget();
var API_LEVEL=setApiLevel();
var VERSION=read(ROOT+'\\VERSION').replace(/\r\n/,'').replace(/\n/,'');
// create the project
Log("Creating new android project...");
exec('android.bat create project --target "'+TARGET+'" --path "'+PROJECT_PATH+'" --package "'+PACKAGE+'" --activity "'+ACTIVITY+'"');
// build from source. distro should have these files
if (!fso.FileExists(ROOT+'\\cordova-'+VERSION+'.jar') &&
!fso.FileExists(ROOT+'\\cordova.js')) {
Log("Building jar and js files...");
// update the cordova framework project to a target that exists on this machine
exec('android.bat update project --target "'+TARGET+'" --path "'+ROOT+'\\framework"');
exec('ant.bat -f "'+ ROOT +'\\framework\\build.xml" jar');
}
// copy in the project template
Log("Copying template files...");
exec('%comspec% /c xcopy "'+ ROOT + '\\bin\\templates\\project\\res" "'+PROJECT_PATH+'\\res\\" /E /Y');
exec('%comspec% /c xcopy "'+ ROOT + '\\bin\\templates\\project\\assets" "'+PROJECT_PATH+'\\assets\\" /E /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\project\\AndroidManifest.xml" "' + PROJECT_PATH + '\\AndroidManifest.xml" /Y');
exec('%comspec% /c mkdir "' + ACTIVITY_DIR + '"');
exec('%comspec% /c copy "' + ROOT + '"\\bin\\templates\\project\\Activity.java "' + ACTIVITY_PATH + '" /Y');
// check if we have the source or the distro files
Log("Copying js, jar & config.xml files...");
if(fso.FolderExists(ROOT + '\\framework')) {
exec('%comspec% /c copy "'+ROOT+'\\framework\\assets\\www\\cordova.js" "'+PROJECT_PATH+'\\assets\\www\\cordova.js" /Y');
exec('%comspec% /c copy "'+ROOT+'\\framework\\cordova-'+VERSION+'.jar" "'+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar" /Y');
fso.CreateFolder(PROJECT_PATH + '\\res\\xml');
exec('%comspec% /c copy "'+ROOT+'\\framework\\res\\xml\\config.xml" "' + PROJECT_PATH + '\\res\\xml\\config.xml" /Y');
} else {
// copy in cordova.js
exec('%comspec% /c copy "'+ROOT+'\\cordova.js" "'+PROJECT_PATH+'\\assets\\www\\cordova.js" /Y');
// copy in cordova.jar
exec('%comspec% /c copy "'+ROOT+'\\cordova-'+VERSION+'.jar" "'+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar" /Y');
// copy in xml
fso.CreateFolder(PROJECT_PATH + '\\res\\xml');
exec('%comspec% /c copy "'+ROOT+'\\xml\\config.xml" "' + PROJECT_PATH + '\\res\\xml\\config.xml" /Y');
}
// copy cordova scripts
fso.CreateFolder(PROJECT_PATH + '\\cordova');
fso.CreateFolder(PROJECT_PATH + '\\cordova\\lib');
createAppInfoJar();
Log("Copying cordova command tools...");
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\appinfo.jar" "' + PROJECT_PATH + '\\cordova\\appinfo.jar" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\lib\\cordova.js" "' + PROJECT_PATH + '\\cordova\\lib\\cordova.js" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\lib\\install-device.bat" "' + PROJECT_PATH + '\\cordova\\lib\\install-device.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\lib\\install-emulator.bat" "' + PROJECT_PATH + '\\cordova\\lib\\install-emulator.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\lib\\list-emulator-images.bat" "' + PROJECT_PATH + '\\cordova\\lib\\list-emulator-images.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\lib\\list-devices.bat" "' + PROJECT_PATH + '\\cordova\\lib\\list-devices.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\lib\\list-started-emulators.bat" "' + PROJECT_PATH + '\\cordova\\lib\\list-started-emulators.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\lib\\start-emulator.bat" "' + PROJECT_PATH + '\\cordova\\lib\\start-emulator.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\cordova.bat" "' + PROJECT_PATH + '\\cordova\\cordova.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\clean.bat" "' + PROJECT_PATH + '\\cordova\\clean.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\build.bat" "' + PROJECT_PATH + '\\cordova\\build.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\log.bat" "' + PROJECT_PATH + '\\cordova\\log.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\run.bat" "' + PROJECT_PATH + '\\cordova\\run.bat" /Y');
exec('%comspec% /c copy "'+ROOT+'\\bin\\templates\\cordova\\version.bat" "' + PROJECT_PATH + '\\cordova\\version.bat" /Y');
// interpolate the activity name and package
Log("Updating AndroidManifest.xml and Main Activity...");
replaceInFile(ACTIVITY_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(ACTIVITY_PATH, /__ID__/, PACKAGE);
replaceInFile(MANIFEST_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(MANIFEST_PATH, /__PACKAGE__/, PACKAGE);
replaceInFile(MANIFEST_PATH, /__APILEVEL__/, API_LEVEL);

View File

@@ -1,98 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project name="cordova" default="create" basedir="../">
<property name="project.path" value="${basedir}/example"/>
<property name="package" value="org.apache.cordova.example"/>
<property name="activity" value="cordovaExample"/>
<target name="create">
<!-- this stuff is seriously stupid -->
<echo file="tmp/package.tmp">package-as-path=${package}</echo>
<replace file="tmp/package.tmp" token="." value="\\" />
<property file="tmp/package.tmp" />
<property name="activity.path" value="${project.path}/src/${package-as-path}/${activity}.java" />
<property name="manifest.path" value="${project.path}/AndroidManifest.xml" />
<!-- get the highest target on this machine -->
<!-- this stuff is also seriously stupid -->
<exec executable="cmd" osfamily="windows" output="tmp/target.list.tmp">
<arg line="/c android.bat list targets"/>
</exec>
<exec executable="android" osfamily="mac" output="tmp/target.list.tmp">
<arg line="list targets"/>
</exec>
<replaceregexp file="tmp/target.list.tmp" match=".*id:\s([0-9]).*" replace="target=\1" flags="s" />
<property file="tmp/target.list.tmp" />
<!-- var VERSION=read('VERSION').replace(/\r\n/,'').replace(/\n/,''); -->
<copy file="VERSION" tofile="tmp/VERSION.tmp" overwrite="true" />
<replaceregexp file="tmp/VERSION.tmp" match="^" replace="version=" />
<replaceregexp file="tmp/VERSION.tmp" match="\r\n" replace="" />
<property file="tmp/VERSION.tmp" />
<!-- clobber any existing example -->
<!-- create the project -->
<exec executable="cmd" osfamily="windows">
<arg line="/c android.bat create project --target ${target} --path ${project.path} --package ${package} --activity ${activity}"/>
</exec>
<exec executable="android" osfamily="mac">
<arg line="create project --target ${target} --path ${project.path} --package ${package} --activity ${activity}"/>
</exec>
<!-- update the framework dir -->
<exec executable="cmd" osfamily="windows">
<arg line="/c android.bat update project --target ${target} --path ${basedir}/framework"/>
</exec>
<exec executable="android" osfamily="mac">
<arg line="update project --target ${target} --path ${basedir}/framework"/>
</exec>
<!-- compile cordova.js and cordova.jar -->
<!-- // if you see an error about "Unable to resolve target" then you may need to
// update your android tools or install an additional Android platform version -->
<ant antfile="${basedir}/framework/build.xml" useNativeBasedir="true" inheritAll="false" />
<!-- copy in the project template -->
<copy todir="${project.path}" overwrite="true">
<fileset dir="${basedir}/bin/templates/project"/>
</copy>
<!-- copy in cordova.js -->
<copy file="${basedir}/framework/assets/www/cordova-${version}.js" todir="${project.path}/assets/www/" />
<!-- copy in cordova.jar -->
<copy file="${basedir}/framework/cordova-${version}.jar" todir="${project.path}/libs/" />
<!-- copy in default activity -->
<copy file="${basedir}/bin/templates/Activity.java" tofile="${activity.path}" overwrite="true" />
<!-- interpolate the activity name and package -->
<replaceregexp file="${activity.path}" match="__ACTIVITY__" replace="${activity}" />
<replaceregexp file="${activity.path}" match="__ID__" replace="${package}" />
<replaceregexp file="${manifest.path}" match="__ACTIVITY__" replace="${activity}" />
<replaceregexp file="${manifest.path}" match="__PACKAGE__" replace="${package}" />
</target>
</project>

78
bin/lib/check_reqs.js Normal file
View File

@@ -0,0 +1,78 @@
#!/usr/bin/env node
/*
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.
*/
var shell = require('shelljs'),
path = require('path'),
fs = require('fs'),
ROOT = path.join(__dirname, '..', '..');
// Get valid target from framework/project.properties
module.exports.get_target = function() {
if(fs.existsSync(path.join(ROOT, 'framework', 'project.properties'))) {
var target = shell.grep(/target=android-[\d+]/, path.join(ROOT, 'framework', 'project.properties'));
return target.split('=')[1].replace('\n', '').replace('\r', '').replace(' ', '');
} else if (fs.existsSync(path.join(ROOT, 'project.properties'))) {
// if no target found, we're probably in a project and project.properties is in ROOT.
var target = shell.grep(/target=android-[\d+]/, path.join(ROOT, 'project.properties'));
return target.split('=')[1].replace('\n', '').replace('\r', '').replace(' ', '');
}
}
module.exports.check_ant = function() {
var test = shell.exec('ant -version', {silent:true, async:false});
if(test.code > 0) {
console.error('ERROR : executing command \'ant\', make sure you have ant installed and added to your path.');
return false;
}
return true;
}
module.exports.check_java = function() {
if(process.env.JAVA_HOME) {
var test = shell.exec('java', {silent:true, async:false});
if(test.code > 0) {
console.error('ERROR : executing command \'java\', make sure you java environment is set up. Including your JDK and JRE.');
return false;
}
return true;
} else {
console.error('ERROR : Make sure JAVA_HOME is set, as well as paths to your JDK and JRE for java.');
return false;
}
}
module.exports.check_android = function() {
var valid_target = this.get_target();
var targets = shell.exec('android list targets', {silent:true, async:false});
if(targets.code > 0 && targets.output.match(/command\snot\sfound/)) {
console.error('The command \"android\" failed. Make sure you have the latest Android SDK installed, and the \"android\" command (inside the tools/ folder) is added to your path.');
return false;
} else if(!targets.output.match(valid_target)) {
console.error('Please install Android target ' + valid_target.split('-')[1] + ' (the Android newest SDK). Make sure you have the latest Android tools installed as well. Run \"android\" from your command-line to install/update any missing SDKs or tools.');
return false;
}
return true;
}
module.exports.run = function() {
return this.check_ant() && this.check_java && this.check_android();
}

204
bin/lib/create.js Executable file
View File

@@ -0,0 +1,204 @@
#!/usr/bin/env node
/*
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.
*/
var shell = require('shelljs'),
path = require('path'),
fs = require('fs'),
check_reqs = require('./check_reqs'),
ROOT = path.join(__dirname, '..', '..');
function exec(command) {
var result;
try {
result = shell.exec(command, {silent:false, async:false});
} catch(e) {
console.error('Command error on execuation : ' + command);
console.error(e);
process.exit(2);
}
if(result && result.code > 0) {
console.error('Command failed to execute : ' + command);
console.error(result.output);
process.exit(2);
} else {
return result;
}
}
function setShellFatal(value, func) {
var oldVal = shell.config.fatal;
shell.config.fatal = value;
func();
shell.config.fatal = oldVal;
}
function ensureJarIsBuilt(version, target_api) {
var isDevVersion = /-dev$/.test(version);
if (isDevVersion || !fs.existsSync(path.join(ROOT, 'framework', 'cordova-' + version + '.jar')) && fs.existsSync(path.join(ROOT, 'framework'))) {
var valid_target = check_reqs.get_target();
console.log('Building cordova-' + version + '.jar');
// update the cordova-android framework for the desired target
exec('android --silent update lib-project --target "' + target_api + '" --path "' + path.join(ROOT, 'framework') + '"');
// compile cordova.js and cordova.jar
var cwd = process.cwd();
process.chdir(path.join(ROOT, 'framework'));
exec('ant jar');
process.chdir(cwd);
}
}
function copyJsAndJar(projectPath, version) {
shell.cp('-f', path.join(ROOT, 'framework', 'assets', 'www', 'cordova.js'), path.join(projectPath, 'assets', 'www', 'cordova.js'));
// Don't fail if there are no old jars.
setShellFatal(false, function() {
shell.ls(path.join(projectPath, 'libs', 'cordova-*.jar')).forEach(function(oldJar) {
console.log("Deleting " + oldJar);
shell.rm('-f', path.join(oldJar));
});
});
shell.cp('-f', path.join(ROOT, 'framework', 'cordova-' + version + '.jar'), path.join(projectPath, 'libs', 'cordova-' + version + '.jar'));
}
function copyScripts(projectPath) {
var srcScriptsDir = path.join(ROOT, 'bin', 'templates', 'cordova');
var destScriptsDir = path.join(projectPath, 'cordova');
// Delete old scripts directory if this is an update.
shell.rm('-rf', destScriptsDir);
// Copy in the new ones.
shell.cp('-r', srcScriptsDir, projectPath);
shell.cp('-r', path.join(ROOT, 'bin', 'node_modules'), destScriptsDir);
shell.cp(path.join(ROOT, 'bin', 'check_reqs'), path.join(destScriptsDir, 'check_reqs'));
shell.cp(path.join(ROOT, 'bin', 'lib', 'check_reqs.js'), path.join(projectPath, 'cordova', 'lib', 'check_reqs.js'));
if (!/^win/.test(process.platform)) {
// Ensure they are all executable and delete .bat files.
shell.find(destScriptsDir).forEach(function(p) {
if (/\.bat$/.test(p)) {
shell.rm(p);
} else {
shell.chmod(755, p);
}
});
}
}
/**
* $ create [options]
*
* Creates an android application with the given options.
*
* Options:
*
* - `project_path` {String} Path to the new Cordova android project.
* - `package_name`{String} Package name, following reverse-domain style convention.
* - `project_name` {String} Project name.
* - 'project_template_dir' {String} Path to project template (override).
*/
exports.createProject = function(project_path, package_name, project_name, project_template_dir) {
var VERSION = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();
// Set default values for path, package and name
project_path = typeof project_path !== 'undefined' ? project_path : "CordovaExample";
project_path = path.relative(process.cwd(), project_path);
package_name = typeof package_name !== 'undefined' ? package_name : 'my.cordova.project';
project_name = typeof project_name !== 'undefined' ? project_name : 'CordovaExample';
project_template_dir = typeof project_template_dir !== 'undefined' ?
project_template_dir :
path.join(ROOT, 'bin', 'templates', 'project');
var safe_activity_name = project_name.replace(/\W/g, '');
var package_as_path = package_name.replace(/\./g, path.sep);
var activity_dir = path.join(project_path, 'src', package_as_path);
var activity_path = path.join(activity_dir, safe_activity_name + '.java');
var target_api = check_reqs.get_target();
var manifest_path = path.join(project_path, 'AndroidManifest.xml');
// Check if project already exists
if(fs.existsSync(project_path)) {
console.error('Project already exists! Delete and recreate');
process.exit(2);
}
if (!/[a-zA-Z0-9_]+\.[a-zA-Z0-9_](.[a-zA-Z0-9_])*/.test(package_name)) {
console.error('Package name must look like: com.company.Name');
process.exit(2);
}
// Check that requirements are met and proper targets are installed
if(!check_reqs.run()) {
process.exit(2);
}
// Log the given values for the project
console.log('Creating Cordova project for the Android platform:');
console.log('\tPath: ' + project_path);
console.log('\tPackage: ' + package_name);
console.log('\tName: ' + project_name);
console.log('\tAndroid target: ' + target_api);
// build from source. distro should have these files
ensureJarIsBuilt(VERSION, target_api);
console.log('Copying template files...');
setShellFatal(true, function() {
// copy project template
shell.cp('-r', path.join(project_template_dir, 'assets'), project_path);
shell.cp('-r', path.join(project_template_dir, 'res'), project_path);
// Manually create directories that would be empty within the template (since git doesn't track directories).
shell.mkdir(path.join(project_path, 'libs'));
// copy cordova.js, cordova.jar and res/xml
shell.cp('-r', path.join(ROOT, 'framework', 'res', 'xml'), path.join(project_path, 'res'));
copyJsAndJar(project_path, VERSION);
// interpolate the activity name and package
shell.mkdir('-p', activity_dir);
shell.cp('-f', path.join(project_template_dir, 'Activity.java'), activity_path);
shell.sed('-i', /__ACTIVITY__/, safe_activity_name, activity_path);
shell.sed('-i', /__NAME__/, project_name, path.join(project_path, 'res', 'values', 'strings.xml'));
shell.sed('-i', /__ID__/, package_name, activity_path);
shell.cp('-f', path.join(project_template_dir, 'AndroidManifest.xml'), manifest_path);
shell.sed('-i', /__ACTIVITY__/, safe_activity_name, manifest_path);
shell.sed('-i', /__PACKAGE__/, package_name, manifest_path);
shell.sed('-i', /__APILEVEL__/, target_api.split('-')[1], manifest_path);
copyScripts(project_path);
});
// Link it to local android install.
console.log('Running "android update project"');
exec('android --silent update project --target "'+target_api+'" --path "'+ project_path+'"');
console.log('Project successfully created.');
}
exports.updateProject = function(projectPath) {
// Check that requirements are met and proper targets are installed
if (!check_reqs.run()) {
process.exit(2);
}
var version = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();
var target_api = check_reqs.get_target();
ensureJarIsBuilt(version, target_api);
copyJsAndJar(projectPath, version);
copyScripts(projectPath);
console.log('Android project is now at version ' + version);
};

1
bin/node_modules/.bin/shjs generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../shelljs/bin/shjs

6
bin/node_modules/shelljs/.documentup.json generated vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"name": "ShellJS",
"twitter": [
"r2r"
]
}

1
bin/node_modules/shelljs/.npmignore generated vendored Normal file
View File

@@ -0,0 +1 @@
node_modules/

5
bin/node_modules/shelljs/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,5 @@
language: node_js
node_js:
- 0.6
- 0.8

26
bin/node_modules/shelljs/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,26 @@
Copyright (c) 2012, Artur Adib <aadib@mozilla.com>
All rights reserved.
You may use this project under the terms of the New BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Artur Adib nor the
names of the contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL ARTUR ADIB BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

513
bin/node_modules/shelljs/README.md generated vendored Normal file
View File

@@ -0,0 +1,513 @@
# ShellJS - Unix shell commands for Node.js [![Build Status](https://secure.travis-ci.org/arturadib/shelljs.png)](http://travis-ci.org/arturadib/shelljs)
ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
The project is [unit-tested](http://travis-ci.org/arturadib/shelljs) and battled-tested in projects like:
+ [PDF.js](http://github.com/mozilla/pdf.js) - Firefox's next-gen PDF reader
+ [Firebug](http://getfirebug.com/) - Firefox's infamous debugger
+ [JSHint](http://jshint.com) - Most popular JavaScript linter
+ [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers
+ [Yeoman](http://yeoman.io/) - Web application stack and development tool
+ [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation
and [many more](https://npmjs.org/browse/depended/shelljs).
## Installing
Via npm:
```bash
$ npm install [-g] shelljs
```
If the global option `-g` is specified, the binary `shjs` will be installed. This makes it possible to
run ShellJS scripts much like any shell script from the command line, i.e. without requiring a `node_modules` folder:
```bash
$ shjs my_script
```
You can also just copy `shell.js` into your project's directory, and `require()` accordingly.
## Examples
### JavaScript
```javascript
require('shelljs/global');
if (!which('git')) {
echo('Sorry, this script requires git');
exit(1);
}
// Copy files to release dir
mkdir('-p', 'out/Release');
cp('-R', 'stuff/*', 'out/Release');
// Replace macros in each .js file
cd('lib');
ls('*.js').forEach(function(file) {
sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
sed('-i', /.*REMOVE_THIS_LINE.*\n/, '', file);
sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat('macro.js'), file);
});
cd('..');
// Run external tool synchronously
if (exec('git commit -am "Auto-commit"').code !== 0) {
echo('Error: Git commit failed');
exit(1);
}
```
### CoffeeScript
```coffeescript
require 'shelljs/global'
if not which 'git'
echo 'Sorry, this script requires git'
exit 1
# Copy files to release dir
mkdir '-p', 'out/Release'
cp '-R', 'stuff/*', 'out/Release'
# Replace macros in each .js file
cd 'lib'
for file in ls '*.js'
sed '-i', 'BUILD_VERSION', 'v0.1.2', file
sed '-i', /.*REMOVE_THIS_LINE.*\n/, '', file
sed '-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat 'macro.js', file
cd '..'
# Run external tool synchronously
if (exec 'git commit -am "Auto-commit"').code != 0
echo 'Error: Git commit failed'
exit 1
```
## Global vs. Local
The example above uses the convenience script `shelljs/global` to reduce verbosity. If polluting your global namespace is not desirable, simply require `shelljs`.
Example:
```javascript
var shell = require('shelljs');
shell.echo('hello world');
```
## Make tool
A convenience script `shelljs/make` is also provided to mimic the behavior of a Unix Makefile. In this case all shell objects are global, and command line arguments will cause the script to execute only the corresponding function in the global `target` object. To avoid redundant calls, target functions are executed only once per script.
Example (CoffeeScript):
```coffeescript
require 'shelljs/make'
target.all = ->
target.bundle()
target.docs()
target.bundle = ->
cd __dirname
mkdir 'build'
cd 'lib'
(cat '*.js').to '../build/output.js'
target.docs = ->
cd __dirname
mkdir 'docs'
cd 'lib'
for file in ls '*.js'
text = grep '//@', file # extract special comments
text.replace '//@', '' # remove comment tags
text.to 'docs/my_docs.md'
```
To run the target `all`, call the above script without arguments: `$ node make`. To run the target `docs`: `$ node make docs`, and so on.
<!--
DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED
-->
## Command reference
All commands run synchronously, unless otherwise stated.
### cd('dir')
Changes to directory `dir` for the duration of the script
### pwd()
Returns the current directory.
### ls([options ,] path [,path ...])
### ls([options ,] path_array)
Available options:
+ `-R`: recursive
+ `-A`: all files (include files beginning with `.`, except for `.` and `..`)
Examples:
```javascript
ls('projs/*.js');
ls('-R', '/users/me', '/tmp');
ls('-R', ['/users/me', '/tmp']); // same as above
```
Returns array of files in the given path, or in current directory if no path provided.
### find(path [,path ...])
### find(path_array)
Examples:
```javascript
find('src', 'lib');
find(['src', 'lib']); // same as above
find('.').filter(function(file) { return file.match(/\.js$/); });
```
Returns array of all files (however deep) in the given paths.
The main difference from `ls('-R', path)` is that the resulting file names
include the base directories, e.g. `lib/resources/file1` instead of just `file1`.
### cp([options ,] source [,source ...], dest)
### cp([options ,] source_array, dest)
Available options:
+ `-f`: force
+ `-r, -R`: recursive
Examples:
```javascript
cp('file1', 'dir1');
cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp');
cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above
```
Copies files. The wildcard `*` is accepted.
### rm([options ,] file [, file ...])
### rm([options ,] file_array)
Available options:
+ `-f`: force
+ `-r, -R`: recursive
Examples:
```javascript
rm('-rf', '/tmp/*');
rm('some_file.txt', 'another_file.txt');
rm(['some_file.txt', 'another_file.txt']); // same as above
```
Removes files. The wildcard `*` is accepted.
### mv(source [, source ...], dest')
### mv(source_array, dest')
Available options:
+ `f`: force
Examples:
```javascript
mv('-f', 'file', 'dir/');
mv('file1', 'file2', 'dir/');
mv(['file1', 'file2'], 'dir/'); // same as above
```
Moves files. The wildcard `*` is accepted.
### mkdir([options ,] dir [, dir ...])
### mkdir([options ,] dir_array)
Available options:
+ `p`: full path (will create intermediate dirs if necessary)
Examples:
```javascript
mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g');
mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above
```
Creates directories.
### test(expression)
Available expression primaries:
+ `'-b', 'path'`: true if path is a block device
+ `'-c', 'path'`: true if path is a character device
+ `'-d', 'path'`: true if path is a directory
+ `'-e', 'path'`: true if path exists
+ `'-f', 'path'`: true if path is a regular file
+ `'-L', 'path'`: true if path is a symboilc link
+ `'-p', 'path'`: true if path is a pipe (FIFO)
+ `'-S', 'path'`: true if path is a socket
Examples:
```javascript
if (test('-d', path)) { /* do something with dir */ };
if (!test('-f', path)) continue; // skip if it's a regular file
```
Evaluates expression using the available primaries and returns corresponding value.
### cat(file [, file ...])
### cat(file_array)
Examples:
```javascript
var str = cat('file*.txt');
var str = cat('file1', 'file2');
var str = cat(['file1', 'file2']); // same as above
```
Returns a string containing the given file, or a concatenated string
containing the files if more than one file is given (a new line character is
introduced between each file). Wildcard `*` accepted.
### 'string'.to(file)
Examples:
```javascript
cat('input.txt').to('output.txt');
```
Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as
those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_
### sed([options ,] search_regex, replace_str, file)
Available options:
+ `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_
Examples:
```javascript
sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');
sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js');
```
Reads an input string from `file` and performs a JavaScript `replace()` on the input
using the given search regex and replacement string. Returns the new string after replacement.
### grep([options ,] regex_filter, file [, file ...])
### grep([options ,] regex_filter, file_array)
Available options:
+ `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
Examples:
```javascript
grep('-v', 'GLOBAL_VARIABLE', '*.js');
grep('GLOBAL_VARIABLE', '*.js');
```
Reads input string from given files and returns a string containing all lines of the
file that match the given `regex_filter`. Wildcard `*` accepted.
### which(command)
Examples:
```javascript
var nodeExec = which('node');
```
Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions.
Returns string containing the absolute path to the command.
### echo(string [,string ...])
Examples:
```javascript
echo('hello world');
var str = echo('hello world');
```
Prints string to stdout, and returns string with additional utility methods
like `.to()`.
### dirs([options | '+N' | '-N'])
Available options:
+ `-c`: Clears the directory stack by deleting all of the elements.
Arguments:
+ `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero.
+ `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero.
Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified.
See also: pushd, popd
### pushd([options,] [dir | '-N' | '+N'])
Available options:
+ `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated.
Arguments:
+ `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`.
+ `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
+ `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
Examples:
```javascript
// process.cwd() === '/usr'
pushd('/etc'); // Returns /etc /usr
pushd('+1'); // Returns /usr /etc
```
Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack.
### popd([options,] ['-N' | '+N'])
Available options:
+ `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated.
Arguments:
+ `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero.
+ `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero.
Examples:
```javascript
echo(process.cwd()); // '/usr'
pushd('/etc'); // '/etc /usr'
echo(process.cwd()); // '/etc'
popd(); // '/usr'
echo(process.cwd()); // '/usr'
```
When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack.
### exit(code)
Exits the current process with the given exit code.
### env['VAR_NAME']
Object containing environment variables (both getter and setter). Shortcut to process.env.
### exec(command [, options] [, callback])
Available options (all `false` by default):
+ `async`: Asynchronous execution. Defaults to true if a callback is provided.
+ `silent`: Do not echo program output to console.
Examples:
```javascript
var version = exec('node --version', {silent:true}).output;
var child = exec('some_long_running_process', {async:true});
child.stdout.on('data', function(data) {
/* ... do something with data ... */
});
exec('some_long_running_process', function(code, output) {
console.log('Exit code:', code);
console.log('Program output:', output);
});
```
Executes the given `command` _synchronously_, unless otherwise specified.
When in synchronous mode returns the object `{ code:..., output:... }`, containing the program's
`output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and
the `callback` gets the arguments `(code, output)`.
**Note:** For long-lived processes, it's best to run `exec()` asynchronously as
the current synchronous implementation uses a lot of CPU. This should be getting
fixed soon.
### chmod(octal_mode || octal_string, file)
### chmod(symbolic_mode, file)
Available options:
+ `-v`: output a diagnostic for every file processed
+ `-c`: like verbose but report only when a change is made
+ `-R`: change files and directories recursively
Examples:
```javascript
chmod(755, '/Users/brandon');
chmod('755', '/Users/brandon'); // same as above
chmod('u+x', '/Users/brandon');
```
Alters the permissions of a file or directory by either specifying the
absolute permissions in octal form or expressing the changes in symbols.
This command tries to mimic the POSIX behavior as much as possible.
Notable exceptions:
+ In symbolic modes, 'a-r' and '-r' are identical. No consideration is
given to the umask.
+ There is no "quiet" option since default behavior is to run silent.
## Configuration
### config.silent
Example:
```javascript
var silentState = config.silent; // save old silent state
config.silent = true;
/* ... */
config.silent = silentState; // restore old silent state
```
Suppresses all command output if `true`, except for `echo()` calls.
Default is `false`.
### config.fatal
Example:
```javascript
config.fatal = true;
cp('this_file_does_not_exist', '/dev/null'); // dies here
/* more commands... */
```
If `true` the script will die on errors. Default is `false`.
## Non-Unix commands
### tempdir()
Searches and returns string containing a writeable, platform-dependent temporary directory.
Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir).
### error()
Tests if error occurred in the last command. Returns `null` if no error occurred,
otherwise returns string explaining the error

51
bin/node_modules/shelljs/bin/shjs generated vendored Executable file
View File

@@ -0,0 +1,51 @@
#!/usr/bin/env node
require('../global');
if (process.argv.length < 3) {
console.log('ShellJS: missing argument (script name)');
console.log();
process.exit(1);
}
var args,
scriptName = process.argv[2];
env['NODE_PATH'] = __dirname + '/../..';
if (!scriptName.match(/\.js/) && !scriptName.match(/\.coffee/)) {
if (test('-f', scriptName + '.js'))
scriptName += '.js';
if (test('-f', scriptName + '.coffee'))
scriptName += '.coffee';
}
if (!test('-f', scriptName)) {
console.log('ShellJS: script not found ('+scriptName+')');
console.log();
process.exit(1);
}
args = process.argv.slice(3);
for (var i = 0, l = args.length; i < l; i++) {
if (args[i][0] !== "-"){
args[i] = '"' + args[i] + '"'; // fixes arguments with multiple words
}
}
if (scriptName.match(/\.coffee$/)) {
//
// CoffeeScript
//
if (which('coffee')) {
exec('coffee ' + scriptName + ' ' + args.join(' '), { async: true });
} else {
console.log('ShellJS: CoffeeScript interpreter not found');
console.log();
process.exit(1);
}
} else {
//
// JavaScript
//
exec('node ' + scriptName + ' ' + args.join(' '), { async: true });
}

3
bin/node_modules/shelljs/global.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
var shell = require('./shell.js');
for (var cmd in shell)
global[cmd] = shell[cmd];

4
bin/node_modules/shelljs/jshint.json generated vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"loopfunc": true,
"sub": true
}

48
bin/node_modules/shelljs/make.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
require('./global');
config.fatal = true;
global.target = {};
// This ensures we only execute the script targets after the entire script has
// been evaluated
var args = process.argv.slice(2);
setTimeout(function() {
var t;
if (args.length === 1 && args[0] === '--help') {
console.log('Available targets:');
for (t in target)
console.log(' ' + t);
return;
}
// Wrap targets to prevent duplicate execution
for (t in target) {
(function(t, oldTarget){
// Wrap it
target[t] = function(force) {
if (oldTarget.done && !force)
return;
oldTarget.done = true;
return oldTarget.apply(oldTarget, arguments);
};
})(t, target[t]);
}
// Execute desired targets
if (args.length > 0) {
args.forEach(function(arg) {
if (arg in target)
target[arg]();
else {
console.log('no such target: ' + arg);
exit(1);
}
});
} else if ('all' in target) {
target.all();
}
}, 0);

48
bin/node_modules/shelljs/package.json generated vendored Normal file

File diff suppressed because one or more lines are too long

15
bin/node_modules/shelljs/scripts/docs.js generated vendored Executable file
View File

@@ -0,0 +1,15 @@
#!/usr/bin/env node
require('../global');
echo('Appending docs to README.md');
cd(__dirname + '/..');
// Extract docs from shell.js
var docs = grep('//@', 'shell.js');
// Remove '//@'
docs = docs.replace(/\/\/\@ ?/g, '');
// Append docs to README
sed('-i', /## Command reference(.|\n)*/, '## Command reference\n\n' + docs, 'README.md');
echo('All done.');

50
bin/node_modules/shelljs/scripts/run-tests.js generated vendored Executable file
View File

@@ -0,0 +1,50 @@
#!/usr/bin/env node
require('../global');
var path = require('path');
var failed = false;
//
// Lint
//
JSHINT_BIN = './node_modules/jshint/bin/jshint';
cd(__dirname + '/..');
if (!test('-f', JSHINT_BIN)) {
echo('JSHint not found. Run `npm install` in the root dir first.');
exit(1);
}
if (exec(JSHINT_BIN + ' --config jshint.json *.js test/*.js').code !== 0) {
failed = true;
echo('*** JSHINT FAILED! (return code != 0)');
echo();
} else {
echo('All JSHint tests passed');
echo();
}
//
// Unit tests
//
cd(__dirname + '/../test');
ls('*.js').forEach(function(file) {
echo('Running test:', file);
if (exec('node ' + file).code !== 123) { // 123 avoids false positives (e.g. premature exit)
failed = true;
echo('*** TEST FAILED! (missing exit code "123")');
echo();
}
});
if (failed) {
echo();
echo('*******************************************************');
echo('WARNING: Some tests did not pass!');
echo('*******************************************************');
exit(1);
} else {
echo();
echo('All tests passed.');
}

1901
bin/node_modules/shelljs/shell.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

32
bin/package.json Normal file
View File

@@ -0,0 +1,32 @@
{
"name": "cordova-android",
"description": "Cordova tooling for the android platform.",
"version": "0.0.0",
"homepage": "http://github.com/apache/cordova-android",
"repository": {
"type": "git",
"url": "https://git-wip-us.apache.org/repos/asf/cordova-andorid.git"
},
"keywords": [
"cli",
"cordova",
"tooling"
],
"engineStrict": "true",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"shelljs" : "0.1.4"
},
"devDependencies": {
},
"optionalDependencies": {
},
"author": {
"name": "Benn Mapes",
"email": "bennmapes@gmail.com"
},
"contributors": [
]
}

View File

@@ -1,61 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import java.io.IOException;
public class ApplicationInfo {
private static void parseAndroidManifest(String path) {
// System.out.println(path);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(path);
// getting package information
Element manifest = dom.getDocumentElement();
String pakkage = manifest.getAttribute("package");
// getting activity name
String activity = ((Element)dom.getElementsByTagName("activity").item(0)).getAttribute("android:name");
System.out.println(String.format("%s/.%s", pakkage, activity.replace(".", "")));
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(SAXException se) {
se.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) {
String path;
if(args.length > 0) {
path = args[0];
} else {
path = System.getProperty("user.dir") + "/../AndroidManifest.xml";
}
parseAndroidManifest(path);
}
}

View File

@@ -1,39 +1,35 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_PATH=$( cd "$DIR/.." && pwd )
/*
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
if [[ "$#" -eq 1 ]] ; then
if [[ $1 == "--debug" ]] ; then
$DIR/clean
ant debug -f "$PROJECT_PATH"/build.xml
elif [[ $1 == "--release" ]] ; then
$DIR/clean
ant release -f "$PROJECT_PATH"/build.xml
elif [[ $1 == "--nobuild" ]] ; then
echo "Skipping build..."
else
echo "Error : Build command '$1' not recognized."
exit 2
fi
else
echo "Warning : [ --debug | --release | --nobuild ] not specified, defaulting to --debug"
$DIR/clean
ant debug -f "$PROJECT_PATH"/build.xml
fi
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.
*/
var build = require('./lib/build'),
reqs = require('./lib/check_reqs'),
args = process.argv;
// Support basic help commands
if(args[2] == '--help' || args[2] == '/?' || args[2] == '-h' ||
args[2] == 'help' || args[2] == '-help' || args[2] == '/help') {
build.help();
} else if(reqs.run()) {
build.run(args[2]);
process.exit(0);
} else {
process.exit(2);
}

View File

@@ -14,5 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
%~dp0\cordova.bat build %*
SET script_path="%~dp0build"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'build' script in 'cordova' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -1,22 +1,34 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_PATH=$( cd "$DIR/.." && pwd )
echo "Cleaning project..."
ant -f "$PROJECT_PATH/build.xml" clean
/*
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.
*/
var clean = require('./lib/clean'),
reqs = require('./lib/check_reqs'),
args = process.argv;
// Usage support for when args are given
if(args.length > 2) {
clean.help();
} else if(reqs.run()) {
clean.run();
process.exit(0);
} else {
process.exit(2);
}

View File

@@ -14,5 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
%~dp0\cordova.bat clean %*
SET script_path="%~dp0clean"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'clean' script in 'cordova' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -1,31 +0,0 @@
:: Licensed to the Apache Software Foundation (ASF) under one
:: or more contributor license agreements. See the NOTICE file
:: distributed with this work for additional information
:: regarding copyright ownership. The ASF licenses this file
:: to you under the Apache License, Version 2.0 (the
:: "License"); you may not use this file except in compliance
:: with the License. You may obtain a copy of the License at
::
:: http://www.apache.org/licenses/LICENSE-2.0
::
:: Unless required by applicable law or agreed to in writing,
:: software distributed under the License is distributed on an
:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
IF NOT DEFINED JAVA_HOME GOTO MISSING
FOR %%X in (java.exe ant.bat android.bat) do (
SET FOUND=%%~$PATH:X
IF NOT DEFINED FOUND GOTO MISSING
)
cscript %~dp0\lib\cordova.js %* //nologo
GOTO END
:MISSING
ECHO Missing one of the following:
ECHO JDK: http://java.oracle.com
ECHO Android SDK: http://developer.android.com
ECHO Apache ant: http://ant.apache.org
EXIT /B 1
:END

41
bin/templates/cordova/lib/appinfo.js vendored Normal file
View File

@@ -0,0 +1,41 @@
#!/usr/bin/env node
/*
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.
*/
var path = require('path');
var fs = require('fs');
var cachedAppInfo = null;
function readAppInfoFromManifest() {
var manifestPath = path.join(__dirname, '..', '..', 'AndroidManifest.xml');
var manifestData = fs.readFileSync(manifestPath, {encoding:'utf8'});
var packageName = /\bpackage\s*=\s*"(.+?)"/.exec(manifestData);
if (!packageName) throw new Error('Could not find package name within ' + manifestPath);
var activityTag = /<activity\b[\s\S]*<\/activity>/.exec(manifestData);
if (!activityTag) throw new Error('Could not find <activity> within ' + manifestPath);
var activityName = /\bandroid:name\s*=\s*"(.+?)"/.exec(activityTag);
if (!activityName) throw new Error('Could not find android:name within ' + manifestPath);
return packageName[1] + '/.' + activityName[1];
}
exports.getActivityName = function() {
return cachedAppInfo = cachedAppInfo || readAppInfoFromManifest();
};

89
bin/templates/cordova/lib/build.js vendored Normal file
View File

@@ -0,0 +1,89 @@
#!/usr/bin/env node
/*
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.
*/
var shell = require('shelljs'),
clean = require('./clean'),
path = require('path'),
fs = require('fs'),
ROOT = path.join(__dirname, '..', '..');
/*
* Builds the project with ant.
*/
module.exports.run = function(build_type) {
//default build type
build_type = typeof build_type !== 'undefined' ? build_type : "--debug";
var cmd;
switch(build_type) {
case '--debug' :
clean.run();
cmd = 'ant debug -f ' + path.join(ROOT, 'build.xml');
break;
case '--release' :
clean.run();
cmd = 'ant release -f ' + path.join(ROOT, 'build.xml');
break;
case '--nobuild' :
console.log('Skipping build...');
break;
default :
console.error('Build option \'' + build_type + '\' not recognized.');
process.exit(2);
break;
}
if(cmd) {
var result = shell.exec(cmd, {silent:false, async:false});
if(result.code > 0) {
console.error('ERROR: Failed to build android project.');
console.error(result.output);
process.exit(2);
}
}
}
/*
* Gets the path to the apk file, if not such file exists then
* the script will error out. (should we error or just return undefined?)
*/
module.exports.get_apk = function() {
if(fs.existsSync(path.join(ROOT, 'bin'))) {
var bin_files = fs.readdirSync(path.join(ROOT, 'bin'));
for (file in bin_files) {
if(path.extname(bin_files[file]) == '.apk') {
return path.join(ROOT, 'bin', bin_files[file]);
}
}
console.error('ERROR : No .apk found in \'bin\' folder');
process.exit(2);
} else {
console.error('ERROR : unable to find project bin folder, could not locate .apk');
process.exit(2);
}
}
module.exports.help = function() {
console.log('Usage: ' + path.relative(process.cwd(), path.join(ROOT, 'corodva', 'build')) + ' [build_type]');
console.log('Build Types : ');
console.log(' \'--debug\': Default build, will build project in using ant debug');
console.log(' \'--release\': will build project using ant release');
console.log(' \'--nobuild\': will skip build process (can be used with run command)');
process.exit(0);
}

43
bin/templates/cordova/lib/clean.js vendored Normal file
View File

@@ -0,0 +1,43 @@
#!/usr/bin/env node
/*
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.
*/
var shell = require('shelljs'),
path = require('path'),
ROOT = path.join(__dirname, '..', '..');
/*
* Cleans the project using ant
*/
module.exports.run = function() {
var cmd = 'ant clean -f ' + path.join(ROOT, 'build.xml');
var result = shell.exec(cmd, {silent:false, async:false});
if (result.code > 0) {
console.error('ERROR: Failed to clean android project.');
console.error(result.output);
process.exit(2);
}
}
module.exports.help = function() {
console.log('Usage: ' + path.relative(process.cwd(), process.argv[1]));
console.log('Cleans the project directory.');
process.exit(0);
}

View File

@@ -1,612 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
var ROOT = WScript.ScriptFullName.split('\\cordova\\lib\\cordova.js').join(''),
shell = WScript.CreateObject("WScript.Shell"),
fso = WScript.CreateObject('Scripting.FileSystemObject');
//device_id for targeting specific device
var device_id;
//build types
var NONE = 0,
DEBUG = '--debug',
RELEASE = '--release',
NO_BUILD = '--nobuild';
var build_type = NONE;
//deploy tpyes
var NONE = 0,
EMULATOR = 1,
DEVICE = 2,
TARGET = 3;
var deploy_type = NONE;
// log to stdout or stderr
function Log(msg, error) {
if (error) {
WScript.StdErr.WriteLine(msg);
}
else {
WScript.StdOut.WriteLine(msg);
}
}
// executes a commmand in the shell, returning stdout
function exec(command) {
var oExec=shell.Exec(command);
var output = new String();
while (oExec.Status == 0) {
if (!oExec.StdOut.AtEndOfStream) {
var line = oExec.StdOut.ReadLine();
output += line;
}
WScript.sleep(100);
}
return output;
}
// executes a command in the shell, returns stdout or stderr if error
function exec_out(command) {
var oExec=shell.Exec(command);
var output = new String();
while (oExec.Status == 0) {
if (!oExec.StdOut.AtEndOfStream) {
var line = oExec.StdOut.ReadLine();
// XXX: Change to verbose mode
// WScript.StdOut.WriteLine(line);
output += line;
}
WScript.sleep(100);
}
//Check to make sure our scripts did not encounter an error
if (!oExec.StdErr.AtEndOfStream) {
var line = oExec.StdErr.ReadAll();
return {'error' : true, 'output' : line};
}
return {'error' : false, 'output' : output};
}
// executes a commmand in the shell and outputs stdout and fails on stderr
function exec_verbose(command) {
//Log("Command: " + command);
var oShell=shell.Exec(command);
while (oShell.Status == 0) {
//Wait a little bit so we're not super looping
WScript.sleep(100);
//Print any stdout output from the script
if (!oShell.StdOut.AtEndOfStream) {
var line = oShell.StdOut.ReadLine();
Log(line);
}
}
//Check to make sure our scripts did not encounter an error
if (!oShell.StdErr.AtEndOfStream) {
var line = oShell.StdErr.ReadAll();
Log(line, true);
WScript.Quit(2);
}
}
function version(path) {
var cordovajs_path = path + "\\assets\\www\\cordova.js";
if(fso.FileExists(cordovajs_path)) {
var f = fso.OpenTextFile(cordovajs_path, 1,2);
var cordovajs = f.ReadAll();
f.Close();
var version_regex = /^.*CORDOVA_JS_BUILD_LABEL.*$/m;
var version_line = cordovajs.match(version_regex) + "";
var version = version_line.match(/(\d+)\.(\d+)\.(\d+)(rc\d)?/) + "";
// TODO : figure out why this isn't matching properly so we can remove this substring workaround.
Log(version.substr(0, ((version.length/2) -1)));
} else {
Log("Error : Could not find cordova js.", true);
Log("Expected Location : " + cordovajs_path, true);
WScript.Quit(2);
}
}
function get_devices() {
var device_list = []
var local_devices = shell.Exec("%comspec% /c adb devices").StdOut.ReadAll();
if (local_devices.match(/\w+\tdevice/)) {
devices = local_devices.split('\r\n');
//format (ID DESCRIPTION)
for (i in devices) {
if (devices[i].match(/\w+\tdevice/) && !devices[i].match(/emulator/)) {
device_list.push(devices[i].replace(/\t/, ' '));
}
}
}
return device_list
}
function list_devices() {
var devices = get_devices();
if (devices.length > 0) {
for (i in devices) {
Log(devices[i]);
}
}
else {
Log('No devices found, if your device is connected and not showing,');
Log(' then try and install the drivers for your device.');
Log(' http://developer.android.com/tools/extras/oem-usb.html');
}
}
function get_emulator_images() {
var avd_list = [];
var local_emulators = shell.Exec("%comspec% /c android list avds").StdOut.ReadAll();
if (local_emulators.match(/Name\:/)) {
emulators = local_emulators.split('\n');
var count = 0;
var output = '';
for (i in emulators) {
// Find the line with the emulator name.
if (emulators[i].match(/Name\:/)) {
// strip description
var emulator_name = emulators[i].replace(/\s*Name\:\s/, '') + ' ';
avd_list.push(emulator_name);
}
}
}
return avd_list;
}
function list_emulator_images() {
var images = get_emulator_images();
if (images.length > 0) {
for(i in images) {
Log(images[i]);
}
}
else {
Log('No emulators found, if you would like to create an emulator follow the instructions');
Log(' provided here : http://developer.android.com/tools/devices/index.html');
Log(' Or run \'android create avd --name <name> --target <targetID>\' in on the command line.');
}
}
function get_started_emulators() {
var started_emulators = [];
var local_devices = shell.Exec("%comspec% /c adb devices").StdOut.ReadAll();
if (local_devices.match(/emulator/)) {
devices = local_devices.split('\r\n');
//format (ID DESCRIPTION)
for (i in devices) {
if (devices[i].match(/\w+\tdevice/) && devices[i].match(/emulator/)) {
started_emulators.push(devices[i].replace(/\t/, ' '));
}
}
}
return started_emulators
}
function list_started_emulators() {
var images = get_started_emulators();
if (images.length > 0) {
for(i in images) {
Log(images[i]);
}
}
else {
Log('No started emulators found, if you would like to start an emulator call ');
Log('\'list-emulator-images\'');
Log(' to get the name of an emulator and then start the emulator with');
Log('\'start-emulator <Name>\'');
}
}
function create_emulator() {
//get targets
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s\d+/g);
if(targets) {
exec('%comspec% /c android create avd --name cordova_emulator --target ' + targets[targets.length - 1].replace(/id: /, ""));
} else {
Log("You do not have any android targets setup. Please create at least one target with the `android` command so that an emulator can be created.", true);
WScript.Quit(69);
}
}
function start_emulator(name) {
var emulators = get_emulator_images();
var started_emulators = get_started_emulators();
var num_started = started_emulators.length;
var emulator_name;
var started = false;
if (name) {
for (i in emulators) {
if (emulators[i].substr(0,name.length) == name) {
Log("Starting emulator : " + name);
shell.Exec("%comspec% /c emulator -avd " + name + " &");
//shell.Run("%comspec% /c start cmd /c emulator -cpu-delay 0 -no-boot-anim -cache %Temp%\cache -avd " + name);
started = true;
}
}
}
else {
if (emulators.length > 0 && started_emulators.length == 0) {
emulator_name = emulators[0].split(' ', 1)[0];
start_emulator(emulator_name);
return;
} else if (started_emulators.length > 0) {
Log("Emulator already started : " + started_emulators[0].split(' ', 1));
return;
} else {
Log("Error : unable to start emulator, ensure you have emulators availible by checking \'list-emulator-images\'", true);
WScript.Quit(2);
}
}
if (!started) {
Log("Error : unable to start emulator, ensure you have emulators availible by checking \'list-emulator-images\'", true);
WScript.Quit(2);
}
else {
// wait for emulator to get the ID
Log('Waiting for emulator...');
var boot_anim = null;
var emulator_ID = null;
var new_started = null;
var i = 0;
while(emulator_ID == null && i < 10) {
new_started = get_started_emulators();
if(new_started.length > started_emulators.length) {
// find new emulator that was just started to get it's ID
for(var i = 0; i < new_started.length; i++) {
if (new_started[i] != started_emulators[i]) {
emulator_ID = new_started[i].split(' ', 1)[0];
boot_anim = exec_out('%comspec% /c adb -s ' + emulator_ID + ' shell getprop init.svc.bootanim');
break;
}
}
}
}
if (i == 10) {
Log('\nEmulator start timed out.');
WScript.Quit(2);
}
i = 0;
WScript.Stdout.Write('Booting up emulator (this may take a while).');
// use boot animation property to tell when boot is complete.
while (!boot_anim.output.match(/stopped/) && i < 100) {
boot_anim = exec_out('%comspec% /c adb -s ' + emulator_ID + ' shell getprop init.svc.bootanim');
i++;
WScript.Stdout.Write('.');
WScript.Sleep(2000);
}
if (i < 100) {
Log('\nBoot Complete!');
// Unlock the device
shell.Exec("%comspec% /c adb -s " + emulator_ID + " shell input keyevent 82");
} else {
Log('\nEmulator boot timed out. Failed to load emulator');
WScript.Quit(2);
}
}
}
function get_apk(path) {
// check if file .apk has been created
if (fso.FolderExists(path + '\\bin')) {
var path_to_apk;
var out_folder = fso.GetFolder(path + '\\bin');
var out_files = new Enumerator(out_folder.Files);
for (;!out_files.atEnd(); out_files.moveNext()) {
var path = out_files.item() + '';
if (fso.GetExtensionName(path) == 'apk' && !path.match(/unaligned/)) {
path_to_apk = out_files.item();
break;
}
}
if (path_to_apk) {
return path_to_apk;
}
else {
Log('Failed to find apk, make sure you project is built and there is an ', true);
Log(' apk in <project>\\bin\\. To build your project use \'<project>\\cordova\\build\'', true);
WScript.Quit(2);
}
}
}
function install_device(path) {
var devices = get_devices();
var use_target = false;
if (devices.length < 1) {
Log("Error : No devices found to install to, make sure there are devices", true);
Log(" availible by checking \'<project_dir>\\cordova\\lib\\list-devices\'", true);
WScript.Quit(2);
}
launch(path, devices[0].split(' ', 1)[0], true);
}
function install_emulator(path) {
var emulators = get_started_emulators();
var use_target = false;
if (emulators.length < 1) {
Log("Error : No emulators found to install to, make sure there are emulators", true);
Log(" availible by checking \'<project_dir>\\cordova\\lib\\list-started-emulators\'", true);
WScript.Quit(2);
}
launch(path, emulators[0].split(' ', 1)[0], false);
}
function install_target(path) {
if(device_id) {
var device = false;
var emulators = get_started_emulators();
var devices = get_devices();
var exists = false;
for (i in emulators) {
if (emulators[i].substr(0,device_id.length) == device_id) {
exists = true;
break;
}
}
for (i in devices) {
if (devices[i].substr(0,device_id.length) == device_id) {
exists = true;
device = true
break;
}
}
if (!exists) {
Log("Error : Unable to find target " + device_id, true);
Log("Please ensure the target exists by checking \'<project>\\cordova\\lib\\list-started-emulators'");
Log(" Or \'<project>\\cordova\\lib\\list-devices'");
}
launch(path, device_id, device);
}
else {
Log("You cannot install to a target without providing a valid target ID.", true);
WScript.Quit(2);
}
}
function launch(path, id, device) {
if(id) {
var path_to_apk = get_apk(path);
if (path_to_apk) {
var launch_name = exec_out("%comspec% /c java -jar "+path+"\\cordova\\appinfo.jar "+path+"\\AndroidManifest.xml");
if (launch_name.error) {
Log("Failed to get application name from appinfo.jar + AndroidManifest : ", true);
Log("Output : " + launch_name.output, true);
WScript.Quit(2);
}
if (device) {
// install on device (-d)
Log("Installing app on device...");
} else {
// install on emulator (-e)
Log("Installing app on emulator...");
}
var cmd = '%comspec% /c adb -s ' + id + ' install -r ' + path_to_apk;
var install = exec_out(cmd);
if ( install.error && install.output.match(/Failure/)) {
Log("Error : Could not install apk to emulator : ", true);
Log(install.output, true);
WScript.Quit(2);
}
else {
Log(install.output);
}
// launch the application
Log("Launching application...");
cmd = '%comspec% /c adb -s ' + id + ' shell am start -W -a android.intent.action.MAIN -n ' + launch_name.output;
exec_verbose(cmd);
}
else {
Log('Failed to find apk, make sure you project is built and there is an ', true);
Log(' apk in <project>\\bin\\. To build your project use \'<project>\\cordova\\build\'', true);
WScript.Quit(2);
}
}
else {
Log("You cannot install to a target without providing a valid target ID.", true);
WScript.Quit(2);
}
}
function clean(path) {
Log("Cleaning project...");
exec("%comspec% /c ant.bat clean -f "+path+"\\build.xml 2>&1");
}
function log() {
// filter out nativeGetEnabledTags spam from latest sdk bug.
shell.Run("%comspec% /c adb logcat | grep -v nativeGetEnabledTags");
}
function build(path) {
switch (build_type) {
case DEBUG :
clean(path);
Log("Building project...");
exec_verbose("%comspec% /c ant.bat debug -f "+path+"\\build.xml 2>&1");
break;
case RELEASE :
clean(path);
Log("Building project...");
exec_verbose("%comspec% /c ant.bat release -f "+path+"\\build.xml 2>&1");
break;
case NO_BUILD :
Log("Skipping build process.");
break;
case NONE :
clean(path);
Log("WARNING: [ --debug | --release | --nobuild ] not specified, defaulting to --debug.");
exec_verbose("%comspec% /c ant.bat debug -f "+path+"\\build.xml 2>&1");
break;
default :
Log("Build option not recognized: " + build_type, true);
WScript.Quit(2);
break;
}
}
function run(path) {
switch(deploy_type) {
case EMULATOR :
build(path);
if(get_started_emulators().length == 0) {
start_emulator();
}
//TODO : Start emulator if one isn't started, and create one if none exists.
install_emulator(path);
break;
case DEVICE :
build(path);
install_device(path);
break;
case TARGET :
build(path);
install_target(path);
break;
case NONE :
if (get_devices().length > 0) {
Log("WARNING: [ --target=<ID> | --emulator | --device ] not specified, defaulting to --device");
deploy_type = DEVICE;
} else {
Log("WARNING: [ --target=<ID> | --emulator | --device ] not specified, defaulting to --emulator");
deploy_type = EMULATOR;
}
run(path);
break;
default :
Log("Deploy option not recognized: " + deploy_type, true);
WScript.Quit(2);
break;
}
}
var args = WScript.Arguments;
if (args.count() == 0) {
Log("Error: no args provided.");
WScript.Quit(2);
}
else {
// parse command
switch(args(0)) {
case "version" :
version(ROOT);
break;
case "build" :
if(args.Count() > 1) {
if (args(1) == "--release") {
build_type = RELEASE;
}
else if (args(1) == "--debug") {
build_type = DEBUG;
}
else if (args(1) == "--nobuild") {
build_type = NO_BUILD;
}
else {
Log('Error: \"' + args(i) + '\" is not recognized as a build option', true);
WScript.Quit(2);
}
}
build(ROOT);
break;
case "clean" :
clean();
break;
case "log" :
log();
break;
case "list-devices" :
list_devices();
break;
case "list-emulator-images" :
list_emulator_images();
break;
case "list-started-emulators" :
list_started_emulators();
break;
case "start-emulator" :
if (args.Count() > 1) {
start_emulator(args(1))
} else {
start_emulator();
}
break;
case "install-emulator" :
if (args.Count() == 2) {
if (args(1).substr(0,9) == "--target=") {
device_id = args(1).split('--target=').join('');
install_emulator(ROOT);
} else {
Log('Error: \"' + args(1) + '\" is not recognized as an install option', true);
WScript.Quit(2);
}
} else {
install_emulator(ROOT);
}
break;
case "install-device" :
if (args.Count() == 2) {
if (args(1).substr(0,9) == "--target=") {
device_id = args(1).split('--target=').join('');
install_target(ROOT);
} else {
Log('Error: \"' + args(1) + '\" is not recognized as an install option', true);
WScript.Quit(2);
}
} else {
install_device(ROOT);
}
break;
case "run" :
//parse args
for(var i = 1; i < args.Count(); i++) {
if (args(i) == "--release") {
build_type = RELEASE;
}
else if (args(i) == "--debug") {
build_type = DEBUG;
}
else if (args(i) == "--nobuild") {
build_type = NO_BUILD;
}
else if (args(i) == "--emulator" || args(i) == "-e") {
deploy_type = EMULATOR;
}
else if (args(i) == "--device" || args(i) == "-d") {
deploy_type = DEVICE;
}
else if (args(i).substr(0,9) == "--target=") {
device_id = args(i).split("--target=").join("");
deploy_type = TARGET;
}
else {
Log('Error: \"' + args(i) + '\" is not recognized as a run option', true);
WScript.Quit(2);
}
}
run(ROOT);
break;
default :
Log("Cordova does not regognize the command " + args(0), true);
WScript.Quit(2);
break;
}
}

95
bin/templates/cordova/lib/device.js vendored Normal file
View File

@@ -0,0 +1,95 @@
#!/usr/bin/env node
/*
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.
*/
var shell = require('shelljs'),
path = require('path'),
build = require('./build'),
appinfo = require('./appinfo'),
exec = require('child_process').exec,
ROOT = path.join(__dirname, '..', '..');
/**
* Returns a list of the device ID's found
*/
module.exports.list = function() {
var cmd = 'adb devices';
var result = shell.exec(cmd, {silent:true, async:false});
if (result.code > 0) {
console.error('Failed to execute android command \'' + cmd + '\'.');
process.exit(2);
} else {
var response = result.output.split('\n');
var device_list = [];
for (var i = 1; i < response.length; i++) {
if (response[i].match(/\w+\tdevice/) && !response[i].match(/emulator/)) {
device_list.push(response[i].replace(/\tdevice/, '').replace('\r', ''));
}
}
return device_list;
}
}
/*
* Installs a previously built application on the device
* and launches it.
*/
module.exports.install = function(target) {
var device_list = this.list();
if (device_list.length > 0) {
// default device
target = typeof target !== 'undefined' ? target : device_list[0];
if (device_list.indexOf(target) > -1) {
var apk_path = build.get_apk();
var launchName = appinfo.getActivityName();
console.log('Installing app on device...');
cmd = 'adb -s ' + target + ' install -r ' + apk_path;
var install = shell.exec(cmd, {silent:false, async:false});
if (install.error || install.output.match(/Failure/)) {
console.error('ERROR : Failed to install apk to device : ');
console.error(install.output);
process.exit(2);
}
//unlock screen
cmd = 'adb -s ' + target + ' shell input keyevent 82';
shell.exec(cmd, {silent:true, async:false});
// launch the application
console.log('Launching application...');
cmd = 'adb -s ' + target + ' shell am start -W -a android.intent.action.MAIN -n ' + launchName;
var launch = shell.exec(cmd, {silent:true, async:false});
if(launch.code > 0) {
console.error('ERROR : Failed to launch application on emulator : ' + launch.error);
console.error(launch.output);
process.exit(2);
} else {
console.log('LANCH SUCCESS');
}
} else {
console.error('ERROR : Unable to find target \'' + target + '\'.');
console.error('Failed to deploy to device.');
process.exit(2);
}
} else {
console.error('ERROR : Failed to deploy to device, no devices found.');
process.exit(2);
}
}

337
bin/templates/cordova/lib/emulator.js vendored Normal file
View File

@@ -0,0 +1,337 @@
#!/usr/bin/env node
/*
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.
*/
var shell = require('shelljs'),
path = require('path'),
appinfo = require('./appinfo'),
build = require('./build'),
ROOT = path.join(__dirname, '..', '..'),
new_emulator = 'cordova_emulator';
/**
* Returns a list of emulator images in the form of objects
* {
name : <emulator_name>,
path : <path_to_emulator_image>,
target : <api_target>,
abi : <cpu>,
skin : <skin>
}
*/
module.exports.list_images = function() {
var cmd = 'android list avds';
var result = shell.exec(cmd, {silent:true, async:false});
if (result.code > 0) {
console.error('Failed to execute android command \'' + cmd + '\'.');
process.exit(2);
} else {
var response = result.output.split('\n');
var emulator_list = [];
for (var i = 1; i < response.length; i++) {
// To return more detailed information use img_obj
var img_obj = {};
if (response[i].match(/Name:\s/)) {
img_obj['name'] = response[i].split('Name: ')[1].replace('\r', '');
if (response[i + 1].match(/Path:\s/)) {
i++;
img_obj['path'] = response[i].split('Path: ')[1].replace('\r', '');
}
if (response[i + 1].match(/\(API\slevel\s/)) {
i++;
img_obj['target'] = response[i].replace('\r', '');
}
if (response[i + 1].match(/ABI:\s/)) {
i++;
img_obj['abi'] = response[i].split('ABI: ')[1].replace('\r', '');
}
if (response[i + 1].match(/Skin:\s/)) {
i++;
img_obj['skin'] = response[i].split('Skin: ')[1].replace('\r', '');
}
emulator_list.push(img_obj);
}
/* To just return a list of names use this
if (response[i].match(/Name:\s/)) {
emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');
}*/
}
return emulator_list;
}
}
/**
* Will return the closest avd to the projects target
* or undefined if no avds exist.
*/
module.exports.best_image = function() {
var project_target = this.get_target().replace('android-', '');
var images = this.list_images();
var closest = 9999;
var best = images[0];
for (i in images) {
var target = images[i].target;
if(target) {
var num = target.split('(API level ')[1].replace(')', '');
if (num == project_target) {
return images[i];
} else if (project_target - num < closest && project_target > num) {
var closest = project_target - num;
best = images[i];
}
}
}
return best;
}
module.exports.list_started = function() {
var cmd = 'adb devices';
var result = shell.exec(cmd, {silent:true, async:false});
if (result.code > 0) {
console.error('Failed to execute android command \'' + cmd + '\'.');
process.exit(2);
} else {
var response = result.output.split('\n');
var started_emulator_list = [];
for (var i = 1; i < response.length; i++) {
if (response[i].match(/device/) && response[i].match(/emulator/)) {
started_emulator_list.push(response[i].replace(/\tdevice/, '').replace('\r', ''));
}
}
return started_emulator_list;
}
}
module.exports.get_target = function() {
var target = shell.grep(/target=android-[\d+]/, path.join(ROOT, 'project.properties'));
return target.split('=')[1].replace('\n', '').replace('\r', '').replace(' ', '');
}
module.exports.list_targets = function() {
var target_out = shell.exec('android list targets', {silent:true, async:false}).output.split('\n');
var targets = [];
for (var i = target_out.length; i >= 0; i--) {
if(target_out[i].match(/id:/)) {
targets.push(targets[i].split(' ')[1]);
}
}
return targets;
}
/*
* Starts an emulator with the given ID,
* and returns the started ID of that emulator.
* If no ID is given it will used the first image availible,
* if no image is availible it will error out (maybe create one?).
*/
module.exports.start = function(emulator_ID) {
var started_emulators = this.list_started();
var num_started = started_emulators.length;
if (typeof emulator_ID === 'undefined') {
var emulator_list = this.list_images();
if (emulator_list.length > 0) {
emulator_ID = this.best_image().name;
console.log('WARNING : no emulator specified, defaulting to ' + emulator_ID);
} else {
console.error('ERROR : No emulator images (avds) found, if you would like to create an');
console.error(' avd follow the instructions provided here : ');
console.error(' http://developer.android.com/tools/devices/index.html')
console.error(' Or run \'android create avd --name <name> --target <targetID>\' ');
console.error(' in on the command line.');
process.exit(2);
/*console.log('WARNING : no emulators availible, creating \'' + new_emulator + '\'.');
this.create_image(new_emulator, this.get_target());
emulator_ID = new_emulator;*/
}
}
var pipe_null = (process.platform == 'win32' || process.platform == 'win64'? '> NUL' : '> /dev/null');
var cmd = 'emulator -avd ' + emulator_ID + ' ' + pipe_null + ' &';
if(process.platform == 'win32' || process.platform == 'win64') {
cmd = '%comspec% /c start cmd /c ' + cmd;
}
var result = shell.exec(cmd, {silent:true, async:false}, function(code, output) {
if (code > 0) {
console.error('Failed to execute android command \'' + cmd + '\'.');
console.error(output);
process.exit(2);
}
});
// wait for emulator to start
console.log('Waiting for emulator...');
var new_started = this.wait_for_emulator(num_started);
var emulator_id;
if (new_started.length > 1) {
for (i in new_started) {
console.log(new_started[i]);
console.log(started_emulators.indexOf(new_started[i]));
if (started_emulators.indexOf(new_started[i]) < 0) {
emulator_id = new_started[i];
}
}
} else {
emulator_id = new_started[0];
}
if (!emulator_id) {
console.error('ERROR : Failed to start emulator, could not find new emulator');
process.exit(2);
}
//wait for emulator to boot up
process.stdout.write('Booting up emulator (this may take a while)...');
this.wait_for_boot(emulator_id);
console.log('BOOT COMPLETE');
//unlock screen
cmd = 'adb -s ' + emulator_id + ' shell input keyevent 82';
shell.exec(cmd, {silent:false, async:false});
//return the new emulator id for the started emulators
return emulator_id;
}
/*
* Waits for the new emulator to apear on the started-emulator list.
*/
module.exports.wait_for_emulator = function(num_running) {
var new_started = this.list_started();
if (new_started.length > num_running) {
return new_started;
} else {
this.sleep(1);
return this.wait_for_emulator(num_running);
}
}
/*
* Waits for the boot animation property of the emulator to switch to 'stopped'
*/
module.exports.wait_for_boot = function(emulator_id) {
var cmd;
// ShellJS opens a lot of file handles, and the default on OS X is too small.
// TODO : This is not working, need to find a better way to increese the ulimit.
if(process.platform == 'win32' || process.platform == 'win64') {
cmd = 'adb -s ' + emulator_id + ' shell getprop init.svc.bootanim';
} else {
cmd = 'ulimit -S -n 4096; adb -s ' + emulator_id + ' shell getprop init.svc.bootanim';
}
var boot_anim = shell.exec(cmd, {silent:true, async:false});
if (boot_anim.output.match(/stopped/)) {
return;
} else {
process.stdout.write('.');
this.sleep(3);
return this.wait_for_boot(emulator_id);
}
}
/*
* TODO : find a better way to wait for the emulator (maybe using async methods?)
*/
module.exports.sleep = function(time_sec) {
if (process.platform == 'win32' || process.platform == 'win64') {
shell.exec('ping 127.0.0.1 -n ' + time_sec, {silent:true, async:false});
} else {
shell.exec('sleep ' + time_sec, {silent:true, async:false});
}
}
/*
* Create avd
* TODO : Enter the stdin input required to complete the creation of an avd.
*/
module.exports.create_image = function(name, target) {
console.log('Creating avd named ' + name);
if (target) {
var cmd = 'android create avd --name ' + name + ' --target ' + target;
var create = shell.exec(cmd, {sient:false, async:false});
if (create.error) {
console.error('ERROR : Failed to create emulator image : ');
console.error(' Do you have the latest android targets including ' + target + '?');
console.error(create.output);
process.exit(2);
}
} else {
console.log('WARNING : Project target not found, creating avd with a different target but the project may fail to install.');
var cmd = 'android create avd --name ' + name + ' --target ' + this.list_targets()[0];
var create = shell.exec(cmd, {sient:false, async:false});
if (create.error) {
console.error('ERROR : Failed to create emulator image : ');
console.error(create.output);
process.exit(2);
}
console.error('ERROR : Unable to create an avd emulator, no targets found.');
console.error('Please insure you have targets availible by runing the "android" command').
process.exit(2);
}
}
/*
* Installs a previously built application on the emulator and launches it.
* If no target is specified, then it picks one.
* If no started emulators are found, error out.
*/
module.exports.install = function(target) {
var emulator_list = this.list_started();
if (emulator_list.length < 1) {
console.error('ERROR : No started emulators found, please start an emultor before deploying your project.');
process.exit(2);
/*console.log('WARNING : No started emulators found, attemting to start an avd...');
this.start(this.best_image().name);*/
}
// default emulator
target = typeof target !== 'undefined' ? target : emulator_list[0];
if (emulator_list.indexOf(target) > -1) {
console.log('Installing app on emulator...');
var apk_path = build.get_apk();
var cmd = 'adb -s ' + target + ' install -r ' + apk_path;
var install = shell.exec(cmd, {sient:false, async:false});
if (install.error || install.output.match(/Failure/)) {
console.error('ERROR : Failed to install apk to emulator : ');
console.error(install.output);
process.exit(2);
}
//unlock screen
cmd = 'adb -s ' + target + ' shell input keyevent 82';
shell.exec(cmd, {silent:true, async:false});
// launch the application
console.log('Launching application...');
var launchName = appinfo.getActivityName();
cmd = 'adb -s ' + target + ' shell am start -W -a android.intent.action.MAIN -n ' + launchName;
console.log(cmd);
var launch = shell.exec(cmd, {silent:false, async:false});
if(launch.code > 0) {
console.error('ERROR : Failed to launch application on emulator : ' + launch.error);
console.error(launch.output);
process.exit(2);
} else {
console.log('LANCH SUCCESS');
}
} else {
console.error('ERROR : Unable to find target \'' + target + '\'.');
console.error('Failed to deploy to emulator.');
process.exit(2);
}
}

View File

@@ -1,49 +1,38 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_PATH=$( cd "$DIR/../.." && pwd )
device_list=$("$DIR/list-devices")
if [ $? != 0 ]; then
echo "No devices found to deploy to. Please make sure your device is connected"
echo " and you can view it using the 'cordova/lib/list-devices' command."
exit 2
fi
/*
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
apks=`find $PROJECT_PATH/bin -type f -maxdepth 1 | egrep '\.apk$'`
apk_list=($apks)
if [[ ${#apk_list[@]} > 0 ]] ; then
# handle target
read -ra device_array <<< "$device_list"
if [[ "$#" -eq 1 ]] ; then
# deploy to given target
target=${1/--target=/}
else
# delete trailing space and 'device' after device ID
target=${device_array[0]}
fi
echo "Installing ${apk_list[0]} onto device $target..."
adb -s $target install -r ${apk_list[0]};
echo "Launching application..."
launch_str=$(java -jar "$PROJECT_PATH"/cordova/appinfo.jar "$PROJECT_PATH"/AndroidManifest.xml)
adb -s $target shell am start -W -a android.intent.action.MAIN -n $launch_str
else
echo "Application package not found, could not install to device"
echo " make sure your application is built before deploying."
exit 2
fi
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.
*/
var device = require('./device'),
args = process.argv;
if(args.length > 2) {
var install_target;
if (args[2].substring(0, 9) == '--target=') {
install_target = args[2].substring(9, args[2].length);
device.install(install_target);
process.exit(0);
} else {
console.error('ERROR : argument \'' + args[2] + '\' not recognized.');
process.exit(2);
}
} else {
device.install();
process.exit(0);
}

View File

@@ -14,12 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET full_path=%~dp0
IF EXIST %full_path%cordova.js (
cscript "%full_path%cordova.js" install-device %* //nologo
SET script_path="%~dp0install-device"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'cordova.js' in cordova/lib, aborting...>&2
ECHO.
ECHO ERROR: Could not find 'install-device' script in 'cordova\lib' folder, aborting...>&2
EXIT /B 1
)
)

View File

@@ -1,50 +1,38 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_PATH=$( cd "$DIR/../.." && pwd )
emulator_list=$("$DIR/list-started-emulators")
if [ $? != 0 ]; then
echo "No emulators found to deploy to. Please make sure your emulator is started"
echo " You can view it using the 'cordova/lib/list-started-emulators' command."
echo " You can view created emulator images using the 'cordova/lib/list-emulator-images' command."
echo " You can start an emulator image using the 'cordova/lib/start-emulator' command."
exit 2
fi
/*
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
apks=`find $PROJECT_PATH/bin -type f -maxdepth 1 | egrep '\.apk$'`
apk_list=($apks)
if [[ ${#apk_list[@]} > 0 ]] ; then
# handle target emulator
if [[ "$#" -eq 1 ]] ; then
# deploy to given target
target=${1/--target=/}
else
# delete trailing space and 'device' after emulator ID
target=${emulator_list[0]}
fi
echo "Installing ${apk_list[0]} onto emulator $target..."
adb -s $target install -r ${apk_list[0]};
echo "Launching application..."
launch_str=$(java -jar "$PROJECT_PATH"/cordova/appinfo.jar "$PROJECT_PATH"/AndroidManifest.xml)
adb -s $target shell am start -W -a android.intent.action.MAIN -n $launch_str
else
echo "Application package not found, could not install to device"
echo " make sure your application is built before deploying."
exit 2
fi
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.
*/
var emulator = require('./emulator'),
args = process.argv;
if(args.length > 2) {
var install_target;
if (args[2].substring(0, 9) == '--target=') {
install_target = args[2].substring(9, args[2].length);
emulator.install(install_target);
process.exit(0);
} else {
console.error('ERROR : argument \'' + args[2] + '\' not recognized.');
process.exit(2);
}
} else {
emulator.install();
process.exit(0);
}

View File

@@ -14,12 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET full_path=%~dp0
IF EXIST %full_path%cordova.js (
cscript "%full_path%cordova.js" install-emulator %* //nologo
SET script_path="%~dp0install-emulator"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'cordova.js' in cordova/lib, aborting...>&2
ECHO.
ECHO ERROR: Could not find 'install-emulator' script in 'cordova\lib' folder, aborting...>&2
EXIT /B 1
)
)

View File

@@ -1,30 +1,28 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
devices=`adb devices | awk '/List of devices attached/ { while(getline > 0) { print }}' | grep 'device' | grep -v 'emulator' | awk '{ print $1; }'`
device_list=($devices)
if [[ ${#device_list[@]} > 0 ]] ; then
for i in ${devices[@]}
do
echo $i
done
exit 0
else
echo "No devices found."
exit 2
fi
/*
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.
*/
var devices = require('./device');
// Usage support for when args are given
var device_list = devices.list();
for(device in device_list) {
console.log(device_list[device]);
}

View File

@@ -14,12 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET full_path=%~dp0
IF EXIST %full_path%cordova.js (
cscript "%full_path%cordova.js" list-devices //nologo
SET script_path="%~dp0list-devices"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'cordova.js' in cordova/lib, aborting...>&2
ECHO.
ECHO ERROR: Could not find 'list-devices' script in 'cordova\lib' folder, aborting...>&2
EXIT /B 1
)
)

View File

@@ -1,32 +1,29 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
emulator_images=`android list avds | grep "Name:" | cut -f 2 -d ":"`
emulator_list=($emulator_images)
if [[ ${#emulator_list[@]} > 0 ]] ; then
for i in ${emulator_list[@]}
do
echo $i
done
exit 0
else
echo "No emulators found, if you would like to create an emulator follow the instructions"
echo " provided here : http://developer.android.com/tools/devices/index.html"
echo " Or run 'android create avd --name <name> --target <targetID>' in on the command line."
exit 2
fi
/*
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.
*/
var emulators = require('./emulator');
// Usage support for when args are given
var emulator_list = emulators.list_images();
for(emulator in emulator_list) {
console.log(emulator_list[emulator].name);
process.exit(0);
}

View File

@@ -14,12 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET full_path=%~dp0
IF EXIST %full_path%cordova.js (
cscript "%full_path%cordova.js" list-emulator-images //nologo
SET script_path="%~dp0list-emulator-images"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'cordova.js' in cordova/lib, aborting...>&2
ECHO ERROR: Could not find 'list-emulator-images' script in 'cordova\lib' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -1,32 +1,29 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
devices=`adb devices | awk '/List of devices attached/ { while(getline > 0) { print $1;}}' | grep 'emulator' | grep -v 'offline'`
read -ra emulator_list <<< "$devices"
if [[ ${#emulator_list[@]} > 0 ]] ; then
for i in ${emulator_list[@]}
do
# remove space and 'device'
echo $i
done
exit 0
else
echo "No started emulators found (it may still be booting up), you can start an emulator by using the command"
echo " 'cordova/lib/start-emulator'"
exit 2
fi
/*
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.
*/
var emulators = require('./emulator');
// Usage support for when args are given
var emulator_list = emulators.list_started();
for(emulator in emulator_list) {
console.log(emulator_list[emulator]);
process.exit(0);
}

View File

@@ -14,12 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET full_path=%~dp0
IF EXIST %full_path%cordova.js (
cscript "%full_path%cordova.js" list-started-emulators //nologo
SET script_path="%~dp0list-started-emulators"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'cordova.js' in cordova/lib, aborting...>&2
ECHO.
ECHO ERROR: Could not find 'list-started-emulators' script in 'cordova\lib' folder, aborting...>&2
EXIT /B 1
)
)

43
bin/templates/cordova/lib/log.js vendored Normal file
View File

@@ -0,0 +1,43 @@
#!/usr/bin/env node
/*
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.
*/
var shell = require('shelljs'),
path = require('path'),
ROOT = path.join(__dirname, '..', '..');
/*
* Starts running logcat in the shell.
*/
module.exports.run = function() {
var cmd = 'adb logcat | grep -v nativeGetEnabledTags';
var result = shell.exec(cmd, {silent:false, async:false});
if (result.code > 0) {
console.error('ERROR: Failed to run logcat command.');
console.error(result.output);
process.exit(2);
}
}
module.exports.help = function() {
console.log('Usage: ' + path.relative(process.cwd(), path.join(ROOT, 'corodva', 'log')));
console.log('Gives the logcat output on the command line.');
process.exit(0);
}

123
bin/templates/cordova/lib/run.js vendored Normal file
View File

@@ -0,0 +1,123 @@
#!/usr/bin/env node
/*
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.
*/
var path = require('path'),
build = require('./build'),
emulator = require('./emulator'),
device = require('./device');
/*
* Runs the application on a device if availible.
* If not device is found, it will use a started emulator.
* If no started emulators are found it will attempt to start an avd.
* If no avds are found it will error out.
*/
module.exports.run = function(args) {
var build_type;
var install_target;
for (var i=2; i<args.length; i++) {
if (args[i] == '--debug') {
build_type = '--debug';
} else if (args[i] == '--release') {
build_type = '--release';
} else if (args[i] == '--nobuild') {
build_type = '--nobuild';
} else if (args[i] == '--device') {
install_target = '--device';
} else if (args[i] == '--emulator') {
install_target = '--emulator';
} else if (args[i].substring(0, 9) == '--target=') {
install_target = args[i].substring(9, args[i].length);
} else {
console.error('ERROR : Run option \'' + args[i] + '\' not recognized.');
process.exit(2);
}
}
build.run(build_type);
if (install_target == '--device') {
device.install();
} else if (install_target == '--emulator') {
if (emulator.list_started() == 0) {
emulator.start();
}
emulator.install();
} else if (install_target) {
var devices = device.list();
var started_emulators = emulator.list_started();
var avds = emulator.list_images();
if (devices.indexOf(install_target) > -1) {
device.install(install_target);
} else if (started_emulators.indexOf(install_target) > -1) {
emulator.install(install_target);
} else {
// if target emulator isn't started, then start it.
var emulator_ID;
for(avd in avds) {
if(avds[avd].name == install_target) {
emulator_ID = emulator.start(install_target);
emulator.install(emulator_ID);
break;
}
}
if(!emulator_ID) {
console.error('ERROR : Target \'' + install_target + '\' not found, unalbe to run project');
process.exit(2);
}
}
} else {
// no target given, deploy to device if availible, otherwise use the emulator.
var device_list = device.list();
if (device_list.length > 0) {
console.log('WARNING : No target specified, deploying to device \'' + device_list[0] + '\'.');
device.install(device_list[0])
} else {
var emulator_list = emulator.list_started();
if (emulator_list.length > 0) {
console.log('WARNING : No target specified, deploying to emulator \'' + emulator_list[0] + '\'.');
emulator.install(emulator_list[0]);
} else {
console.log('WARNING : No started emulators found, starting an emulator.');
var best_avd = emulator.best_image();
if(best_avd) {
var emulator_ID = emulator.start(best_avd.name);
console.log('WARNING : No target specified, deploying to emulator \'' + emulator_ID + '\'.');
emulator.install(emulator_ID);
} else {
emulator.start();
}
}
}
}
}
module.exports.help = function() {
console.log('Usage: ' + path.relative(process.cwd(), args[0]) + ' [options]');
console.log('Build options :');
console.log(' --debug : Builds project in debug mode');
console.log(' --release : Builds project in release mode');
console.log(' --nobuild : Runs the currently built project without recompiling');
console.log('Deploy options :');
console.log(' --device : Will deploy the built project to a device');
console.log(' --emulator : Will deploy the built project to an emulator if one exists');
console.log(' --target=<target_id> : Installs to the target with the specified id.');
process.exit(0);
}

View File

@@ -1,91 +1,38 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_PATH=$( cd "$( dirname "$0" )/../.." && pwd )
/*
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
function dot {
sleep 1
echo -n "."
}
http://www.apache.org/licenses/LICENSE-2.0
function wait_for_emulator {
local i="0"
echo -n "Waiting for emulator"
emulator_string=$($DIR/list-started-emulators)
while [ $? != 0 ]
do
dot
i=$[i+1]
emulator_string=$($DIR/list-started-emulators)
done
read -ra target <<< "$emulator_string"
echo ""
echo -n "Waiting for it to boot up (this can take a while)"
while [ $i -lt 300 ]
do
boot_anim=$(adb -s $target shell getprop init.svc.bootanim 2>&1)
if [[ "$boot_anim" =~ "stopped" ]] ; then
break
else
i=$[i+1]
dot
fi
done
# Device timeout: emulator has not started in time
if [ $i -eq 300 ]
then
echo ""
echo "Emulator timeout!"
exit 69
else
echo ""
echo "Connected!"
fi
# Unlock the device
adb -s $target shell input keyevent 82
exit 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.
*/
emulator_images=$("$DIR/list-emulator-images")
if [ $? != 0 ]; then
echo "No emulators found, if you would like to create an emulator follow the instructions"
echo " provided here : http://developer.android.com/tools/devices/index.html"
echo " Or run 'android create avd --name <name> --target <targetID>' in on the command line."
exit 2
fi
var emulator = require('./emulator'),
args = process.argv;
# if target emulator is provided
if [[ "$#" -eq 1 ]] ; then
# check that it exists
if [[ $emulator_images =~ $1 ]] ; then
#xterm -e emulator -avd $1 &
emulator -avd $1 1> /dev/null 2>&1 &
else
echo "Could not find the provided emulator '$1', make sure the emulator exists"
echo " by checking 'cordova/lib/list-emulator-images'"
exit 2
fi
else
# start first emulator
read -ra emulator_list <<< "$emulator_images"
#xterm -e emulator -avd ${emulator_list[0]} &
emulator -avd ${emulator_list[0]} 1> /dev/null 2>&1 &
fi
wait_for_emulator
if(args.length > 2) {
var install_target;
if (args[2].substring(0, 9) == '--target=') {
install_target = args[2].substring(9, args[2].length);
emulator.start(install_target);
process.exit(0);
} else {
console.error('ERROR : argument \'' + args[2] + '\' not recognized.');
process.exit(2);
}
} else {
emulator.start();
process.exit(0);
}

View File

@@ -14,12 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET full_path=%~dp0
IF EXIST %full_path%cordova.js (
cscript "%full_path%cordova.js" start-emulator %* //nologo
SET script_path="%~dp0start-emulator"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'cordova.js' in cordova/lib, aborting...>&2
ECHO.
ECHO ERROR: Could not find 'start-emulator' script in 'cordova\lib' folder, aborting...>&2
EXIT /B 1
)
)

View File

@@ -1,20 +1,33 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
# filter out nativeGetEnabledTags spam from latest sdk bug.
adb logcat | grep -v nativeGetEnabledTags
/*
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.
*/
var log = require('./lib/log'),
reqs = require('./lib/check_reqs'),
args = process.argv;
// Usage support for when args are given
if(args.length > 2) {
log.help();
} else if(reqs.run()) {
log.run();
} else {
process.exit(2);
}

View File

@@ -14,5 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
%~dp0\cordova.bat log %*
SET script_path="%~dp0log"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'log' script in 'cordova' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -1,81 +1,35 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_PATH=$( cd "$DIR/.." && pwd )
/*
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
function run_on_device_or_emulator {
devices=`$DIR/lib/list-devices`
if [ $? = 0 ]; then
$DIR/lib/install-device
else
run_on_emulator
fi
}
http://www.apache.org/licenses/LICENSE-2.0
function run_on_emulator {
emulators=`$DIR/lib/list-started-emulators`
if [ $? = 0 ] ; then
$DIR/lib/install-emulator
else
images=`$DIR/lib/list-emulator-images`
if [ $? = 0 ] ; then
$DIR/lib/start-emulator
$DIR/lib/install-emulator
else
echo "No devices/emulators started nor images available to start. How are we supposed to do this, then?"
exit 2
fi
fi
}
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.
*/
var run = require('./lib/run'),
reqs = require('./lib/check_reqs'),
args = process.argv;
if [[ "$#" -eq 2 ]] ; then
# TODO: the order of arguments here may be reversed from the assumption below
$DIR/build $2
if [[ $1 == "--device" ]] ; then
$DIR/lib/install-device
elif [[ $1 == "--emulator" ]] ; then
run_on_emulator
elif [[ $1 =~ "--target=" ]]; then
$DIR/lib/install-device $1
else
echo "Error : '$1' is not recognized as an install option"
fi
elif [[ "$#" -eq 1 ]] ; then
if [[ $1 == "--debug" || $1 == "--release" || $1 == "--nobuild" ]] ; then
$DIR/build $1
run_on_device_or_emulator
elif [[ $1 == "--device" ]] ; then
$DIR/build
$DIR/lib/install-device
elif [[ $1 == "--emulator" ]] ; then
$DIR/build
run_on_emulator
elif [[ $1 =~ "--target=" ]]; then
$DIR/build
$DIR/lib/install-device $1
else
echo "Error : '$1' is not recognized as an install option"
fi
else
echo "Warning : [ --device | --emulate | --target=<targetID> ] not specified, using defaults."
$DIR/build
run_on_device_or_emulator
fi
// Support basic help commands
if (args[2] == '--help' || args[2] == '/?' || args[2] == '-h' ||
args[2] == 'help' || args[2] == '-help' || args[2] == '/help') {
run.help();
} else if(reqs.run()) {
run.run(args);
process.exit(0);
} else {
process.exit(2);
}

View File

@@ -14,5 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
%~dp0\cordova.bat run %*
SET script_path="%~dp0run"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'run' script in 'cordova' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -1,19 +1,25 @@
#!/bin/bash
# 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.
#!/usr/bin/env node
echo "3.0.0-dev"
/*
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.
*/
// Coho updates this line:
var VERSION = "3.1.0";
console.log(VERSION);

View File

@@ -14,5 +14,13 @@
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
%~dp0\cordova.bat version %*
SET script_path="%~dp0version"
IF EXIST %script_path% (
node "%script_path%" %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'version' script in 'cordova' folder, aborting...>&2
EXIT /B 1
)

View File

@@ -22,12 +22,13 @@ package __ID__;
import android.os.Bundle;
import org.apache.cordova.*;
public class __ACTIVITY__ extends DroidGap
public class __ACTIVITY__ extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 213 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 478 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 493 KiB

View File

@@ -1,68 +0,0 @@
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<title>Jasmine Spec Runner</title>
<!-- jasmine source -->
<link rel="shortcut icon" type="image/png" href="spec/lib/jasmine-1.2.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="spec/lib/jasmine-1.2.0/jasmine.css">
<script type="text/javascript" src="spec/lib/jasmine-1.2.0/jasmine.js"></script>
<script type="text/javascript" src="spec/lib/jasmine-1.2.0/jasmine-html.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="js/index.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="spec/helper.js"></script>
<script type="text/javascript" src="spec/index.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
<div id="stage" style="display:none;"></div>
</body>
</html>

View File

@@ -1,33 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
afterEach(function() {
document.getElementById('stage').innerHTML = '';
});
var helper = {
trigger: function(obj, name) {
var e = document.createEvent('Event');
e.initEvent(name, true, true);
obj.dispatchEvent(e);
},
getComputedStyle: function(querySelector, property) {
var element = document.querySelector(querySelector);
return window.getComputedStyle(element).getPropertyValue(property);
}
};

View File

@@ -1,67 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
describe('app', function() {
describe('initialize', function() {
it('should bind deviceready', function() {
runs(function() {
spyOn(app, 'onDeviceReady');
app.initialize();
helper.trigger(window.document, 'deviceready');
});
waitsFor(function() {
return (app.onDeviceReady.calls.length > 0);
}, 'onDeviceReady should be called once', 500);
runs(function() {
expect(app.onDeviceReady).toHaveBeenCalled();
});
});
});
describe('onDeviceReady', function() {
it('should report that it fired', function() {
spyOn(app, 'receivedEvent');
app.onDeviceReady();
expect(app.receivedEvent).toHaveBeenCalledWith('deviceready');
});
});
describe('receivedEvent', function() {
beforeEach(function() {
var el = document.getElementById('stage');
el.innerHTML = ['<div id="deviceready">',
' <p class="event listening">Listening</p>',
' <p class="event received">Received</p>',
'</div>'].join('\n');
});
it('should hide the listening element', function() {
app.receivedEvent('deviceready');
var displayStyle = helper.getComputedStyle('#deviceready .listening', 'display');
expect(displayStyle).toEqual('none');
});
it('should show the received element', function() {
app.receivedEvent('deviceready');
var displayStyle = helper.getComputedStyle('#deviceready .received', 'display');
expect(displayStyle).toEqual('block');
});
});
});

View File

@@ -1,20 +0,0 @@
Copyright (c) 2008-2011 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,616 +0,0 @@
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];
}
};
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);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);
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);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);
/* @deprecated Use jasmine.HtmlReporter instead
*/
jasmine.TrivialReporter = function(doc) {
this.document = doc || document;
this.suiteDivs = {};
this.logRunningSpecs = false;
};
jasmine.TrivialReporter.prototype.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.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
var showPassed, showSkipped;
this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' },
this.createDom('div', { className: 'banner' },
this.createDom('div', { className: 'logo' },
this.createDom('span', { className: 'title' }, "Jasmine"),
this.createDom('span', { className: 'version' }, runner.env.versionString())),
this.createDom('div', { className: 'options' },
"Show ",
showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
)
),
this.runnerDiv = this.createDom('div', { className: 'runner running' },
this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
);
this.document.body.appendChild(this.outerDiv);
var suites = runner.suites();
for (var i = 0; i < suites.length; i++) {
var suite = suites[i];
var suiteDiv = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
this.suiteDivs[suite.id] = suiteDiv;
var parentDiv = this.outerDiv;
if (suite.parentSuite) {
parentDiv = this.suiteDivs[suite.parentSuite.id];
}
parentDiv.appendChild(suiteDiv);
}
this.startedAt = new Date();
var self = this;
showPassed.onclick = function(evt) {
if (showPassed.checked) {
self.outerDiv.className += ' show-passed';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
}
};
showSkipped.onclick = function(evt) {
if (showSkipped.checked) {
self.outerDiv.className += ' show-skipped';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
}
};
};
jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
var results = runner.results();
var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
this.runnerDiv.setAttribute("class", className);
//do it twice for IE
this.runnerDiv.setAttribute("className", className);
var specs = runner.specs();
var specCount = 0;
for (var i = 0; i < specs.length; i++) {
if (this.specFilter(specs[i])) {
specCount++;
}
}
var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
};
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
var results = suite.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.totalCount === 0) { // todo: change this to check results.skipped
status = 'skipped';
}
this.suiteDivs[suite.id].className += " " + status;
};
jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) {
if (this.logRunningSpecs) {
this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
var results = spec.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
var specDiv = this.createDom('div', { className: 'spec ' + status },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(spec.getFullName()),
title: spec.getFullName()
}, spec.description));
var resultItems = 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) {
specDiv.appendChild(messagesDiv);
}
this.suiteDivs[spec.suite.id].appendChild(specDiv);
};
jasmine.TrivialReporter.prototype.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
}
}
};
jasmine.TrivialReporter.prototype.getLocation = function() {
return this.document.location;
};
jasmine.TrivialReporter.prototype.specFilter = function(spec) {
var paramMap = {};
var params = this.getLocation().search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
if (!paramMap.spec) {
return true;
}
return spec.getFullName().indexOf(paramMap.spec) === 0;
};

View File

@@ -1,81 +0,0 @@
body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; }
#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; }
#HTMLReporter a { text-decoration: none; }
#HTMLReporter a:hover { text-decoration: underline; }
#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; }
#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; }
#HTMLReporter #jasmine_content { position: fixed; right: 100%; }
#HTMLReporter .version { color: #aaaaaa; }
#HTMLReporter .banner { margin-top: 14px; }
#HTMLReporter .duration { color: #aaaaaa; float: right; }
#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; }
#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; }
#HTMLReporter .symbolSummary li.passed { font-size: 14px; }
#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; }
#HTMLReporter .symbolSummary li.failed { line-height: 9px; }
#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; }
#HTMLReporter .symbolSummary li.skipped { font-size: 14px; }
#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; }
#HTMLReporter .symbolSummary li.pending { line-height: 11px; }
#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; }
#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; }
#HTMLReporter .runningAlert { background-color: #666666; }
#HTMLReporter .skippedAlert { background-color: #aaaaaa; }
#HTMLReporter .skippedAlert:first-child { background-color: #333333; }
#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; }
#HTMLReporter .passingAlert { background-color: #a6b779; }
#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; }
#HTMLReporter .failingAlert { background-color: #cf867e; }
#HTMLReporter .failingAlert:first-child { background-color: #b03911; }
#HTMLReporter .results { margin-top: 14px; }
#HTMLReporter #details { display: none; }
#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; }
#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; }
#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; }
#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; }
#HTMLReporter.showDetails .summary { display: none; }
#HTMLReporter.showDetails #details { display: block; }
#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; }
#HTMLReporter .summary { margin-top: 14px; }
#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; }
#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; }
#HTMLReporter .summary .specSummary.failed a { color: #b03911; }
#HTMLReporter .description + .suite { margin-top: 0; }
#HTMLReporter .suite { margin-top: 14px; }
#HTMLReporter .suite a { color: #333333; }
#HTMLReporter #details .specDetail { margin-bottom: 28px; }
#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; }
#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; }
#HTMLReporter .resultMessage span.result { display: block; }
#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; }
#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ }
#TrivialReporter a:visited, #TrivialReporter a { color: #303; }
#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; }
#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; }
#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; }
#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; }
#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; }
#TrivialReporter .runner.running { background-color: yellow; }
#TrivialReporter .options { text-align: right; font-size: .8em; }
#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; }
#TrivialReporter .suite .suite { margin: 5px; }
#TrivialReporter .suite.passed { background-color: #dfd; }
#TrivialReporter .suite.failed { background-color: #fdd; }
#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; }
#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; }
#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; }
#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; }
#TrivialReporter .spec.skipped { background-color: #bbb; }
#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; }
#TrivialReporter .passed { background-color: #cfc; display: none; }
#TrivialReporter .failed { background-color: #fbb; }
#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; }
#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; }
#TrivialReporter .resultMessage .mismatch { color: black; }
#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; }
#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; }
#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; }
#TrivialReporter #jasmine_content { position: fixed; right: 100%; }
#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; }

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">__NAME__</string>
</resources>

View File

@@ -1,152 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
var build_path = __dirname + '/../..',
project_path = '/tmp/example',
package_name = 'org.apache.cordova.example',
package_as_path = 'org/apache/cordova/example',
project_name = 'cordovaExample';
var path = require('path'),
fs = require('fs'),
util = require('util'),
assert = require('assert'),
spawn = require('child_process').spawn;
var version = fs.readFileSync(build_path + '/VERSION').toString().replace('\n', '');
assert(version !== undefined);
assert(version !== '');
var create_project = spawn(build_path + '/bin/create',
[project_path,
package_name,
project_name]);
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
spawn('rm', ['-rf', project_path], function(code) {
if(code != 0) {
console.log("Could not delete project directory");
}
});
});
create_project.on('exit', function(code) {
assert.equal(code, 0, 'Project did not get created');
// make sure the project was created
path.exists(project_path, function(exists) {
assert(exists, 'Project path does not exist');
});
// make sure the build directory was cleaned up
// path.exists(build_path + '/framework/libs', function(exists) {
// assert(!exists, 'libs directory did not get cleaned up');
// });
path.exists(build_path + util.format('/framework/assets/cordova-%s.js', version), function(exists) {
assert(!exists, 'javascript file did not get cleaned up');
});
path.exists(build_path + util.format('/framework/cordova-%s.jar', version), function(exists) {
assert(!exists, 'jar file did not get cleaned up');
});
// make sure AndroidManifest.xml was added
path.exists(util.format('%s/AndroidManifest.xml', project_path), function(exists) {
assert(exists, 'AndroidManifest.xml did not get created');
// TODO check that the activity name was properly substituted
});
// make sure main Activity was added
path.exists(util.format('%s/src/%s/%s.java', project_path, package_as_path, project_name), function(exists) {
assert(exists, 'Activity did not get created');
// TODO check that package name and activity name were substituted properly
});
// make sure plugins.xml was added
path.exists(util.format('%s/res/xml/plugins.xml', project_path), function(exists) {
assert(exists, 'plugins.xml did not get created');
});
// make sure cordova.xml was added
path.exists(util.format('%s/res/xml/cordova.xml', project_path), function(exists) {
assert(exists, 'plugins.xml did not get created');
});
// make sure cordova.jar was added
path.exists(util.format('%s/libs/cordova-%s.jar', project_path, version), function(exists) {
assert(exists, 'cordova.jar did not get added');
});
// make sure cordova.js was added
path.exists(util.format('%s/assets/www/cordova-%s.js', project_path, version), function(exists) {
assert(exists, 'cordova.js did not get added');
});
// make sure cordova master script was added
path.exists(util.format('%s/cordova/cordova', project_path), function(exists) {
assert(exists, 'cordova script did not get added');
});
// make sure debug script was added
path.exists(util.format('%s/cordova/debug', project_path), function(exists) {
assert(exists, 'debug script did not get added');
});
// make sure BOOM script was added
path.exists(util.format('%s/cordova/BOOM', project_path), function(exists) {
assert(exists, 'BOOM script did not get added');
});
// make sure log script was added
path.exists(util.format('%s/cordova/log', project_path), function(exists) {
assert(exists, 'log script did not get added');
});
// make sure clean script was added
path.exists(util.format('%s/cordova/clean', project_path), function(exists) {
assert(exists, 'clean script did not get added');
});
// make sure emulate script was added
path.exists(util.format('%s/cordova/emulate', project_path), function(exists) {
assert(exists, 'emulate script did not get added');
});
// make sure appinfo.jar script was added
path.exists(util.format('%s/cordova/appinfo.jar', project_path), function(exists) {
assert(exists, 'appinfo.jar script did not get added');
});
// check that project compiles && creates a cordovaExample-debug.apk
var compile_project = spawn('ant', ['debug'], {cwd: project_path});
compile_project.on('exit', function(code) {
assert.equal(code, 0, 'Cordova Android Project does not compile');
// make sure cordovaExample-debug.apk was created
path.exists(util.format('%s/bin/%s-debug.apk', project_path, project_name), function(exists) {
assert(exists, 'Package did not get created');
// if project compiles properly just AXE it
spawn('rm', ['-rf', project_path], function(code) {
assert.equal(code, 0, 'Could not remove project directory');
});
});
});
});

View File

@@ -1,155 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
var build_path = __dirname + '/../..'
project_path = process.env.Temp + '\\example',
package_name = 'org.apache.cordova.example',
package_as_path = 'org/apache/cordova/example',
project_name = 'cordovaExample';
var path = require('path'),
fs = require('fs'),
util = require('util'),
assert = require('assert'),
exec = require('child_process').exec,
spawn = require('child_process').spawn;
var version = fs.readFileSync(build_path + '/VERSION').toString().replace('\r\n', '');
assert(version !== undefined);
assert(version !== '');
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
exec('rd /s /q ' + project_path);
});
var create_project = spawn('cscript',
[build_path + '/bin/create.js',
project_path,
package_name,
project_name]
);
create_project.stderr.on('data', function (data) {
console.log('ps stderr: ' + data);
});
create_project.stderr.on('data', function(data) {
console.log(data.toString());
});
create_project.stdout.on('data', function(data) {
console.log(data.toString());
});
create_project.on('exit', function(code) {
assert.equal(code, 0, 'Project did not get created');
// make sure the project was created
path.exists(project_path, function(exists) {
assert(exists, 'Project path does not exist');
});
// make sure the build directory was cleaned up
// path.exists(build_path + '/framework/libs', function(exists) {
// assert(!exists, 'libs directory did not get cleaned up');
// });
path.exists(build_path + util.format('/framework/assets/cordova-%s.js', version), function(exists) {
assert(!exists, 'javascript file did not get cleaned up');
});
path.exists(build_path + util.format('/framework/cordova-%s.jar', version), function(exists) {
assert(!exists, 'jar file did not get cleaned up');
});
// make sure AndroidManifest.xml was added
path.exists(util.format('%s/AndroidManifest.xml', project_path), function(exists) {
assert(exists, 'AndroidManifest.xml did not get created');
// TODO check that the activity name was properly substituted
});
// make sure main Activity was added
path.exists(util.format('%s/src/%s/%s.java', project_path, package_as_path, project_name), function(exists) {
assert(exists, 'Activity did not get created');
// TODO check that package name and activity name were substituted properly
});
// make sure config.xml was added
path.exists(util.format('%s/res/xml/config.xml', project_path), function(exists) {
assert(exists, 'config.xml did not get created');
});
// make sure cordova.jar was added
path.exists(util.format('%s/libs/cordova-%s.jar', project_path, version), function(exists) {
assert(exists, 'cordova.jar did not get added');
});
// make sure cordova.js was added
path.exists(util.format('%s/assets/www/cordova-%s.js', project_path, version), function(exists) {
assert(exists, 'cordova.js did not get added');
});
// make sure cordova master script was added
path.exists(util.format('%s/cordova/cordova.bat', project_path), function(exists) {
assert(exists, 'cordova script did not get added');
});
// make sure debug script was added
path.exists(util.format('%s/cordova/debug.bat', project_path), function(exists) {
assert(exists, 'debug script did not get added');
});
// make sure BOOM script was added
path.exists(util.format('%s/cordova/BOOM.bat', project_path), function(exists) {
assert(exists, 'BOOM script did not get added');
});
// make sure log script was added
path.exists(util.format('%s/cordova/log.bat', project_path), function(exists) {
assert(exists, 'log script did not get added');
});
// make sure clean script was added
path.exists(util.format('%s/cordova/clean.bat', project_path), function(exists) {
assert(exists, 'clean script did not get added');
});
// make sure emulate script was added
path.exists(util.format('%s/cordova/emulate.bat', project_path), function(exists) {
assert(exists, 'emulate script did not get added');
});
// make sure appinfo.jar script was added
path.exists(util.format('%s/cordova/appinfo.jar', project_path), function(exists) {
assert(exists, 'appinfo.jar script did not get added');
});
// check that project compiles && creates a cordovaExample-debug.apk
// XXX: !@##!@# WINDOWS
exec('ant debug -f ' + project_path + "\\build.xml", function(error, stdout, stderr) {
assert(error == null, "Cordova Android Project does not compile");
path.exists(util.format('%s/bin/%s-debug.apk', project_path, project_name),
function(exists) {
assert(exists, 'Package did not get created');
// if project compiles properly just AXE it
exec('rd /s /q ' + project_path);
});
});
});

View File

@@ -1,133 +1,33 @@
#! /bin/bash
# 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.
#
# update a cordova/android project's command line tools
#
# USAGE
# ./update [path]
#
#!/usr/bin/env node
set -e
/*
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
if [ -z "$1" ] || [ "$1" == "-h" ]
then
echo 'usage: update path'
echo "Make sure the Android SDK tools folder is in your PATH!"
exit 0
fi
http://www.apache.org/licenses/LICENSE-2.0
BUILD_PATH="$( cd "$( dirname "$0" )/.." && pwd )"
VERSION=$(cat "$BUILD_PATH"/VERSION)
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.
*/
var path = require('path');
var args = process.argv;
var create = require('./lib/create');
PROJECT_PATH="${1:-'./example'}"
if [ ! -d "$PROJECT_PATH" ]
then
echo "The project path has to exist for it to be updated"
exit 0
fi
# cleanup after exit and/or on error
function on_exit {
if [ -f "$BUILD_PATH"/framework/cordova-$VERSION.jar ]
then
rm "$BUILD_PATH"/framework/cordova-$VERSION.jar
fi
// Support basic help commands
if(args.length < 3 || (args[2] == '--help' || args[2] == '/?' || args[2] == '-h' ||
args[2] == 'help' || args[2] == '-help' || args[2] == '/help')) {
console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'update')) + ' <path_to_project>');
process.exit(1);
} else {
create.updateProject(args[2]);
}
function createAppInfoJar {
(cd "$BUILD_PATH"/bin/templates/cordova/ApplicationInfo &&
javac ApplicationInfo.java &&
jar -cfe ../appinfo.jar ApplicationInfo ApplicationInfo.class
)
}
function on_error {
echo "An unexpected error occurred: $previous_command exited with $?"
exit 1
}
function replace {
local pattern=$1
local filename=$2
# Mac OS X requires -i argument
if [[ "$OSTYPE" =~ "darwin" ]]
then
/usr/bin/sed -i '' -e $pattern "$filename"
elif [[ "$OSTYPE" =~ "linux" ]]
then
/bin/sed -i -e $pattern "$filename"
fi
}
# we do not want the script to silently fail
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
trap on_error ERR
trap on_exit EXIT
ANDROID_BIN="${ANDROID_BIN:=$( which android )}"
TARGET=$("$ANDROID_BIN" list targets | grep id: | tail -1 | cut -f 2 -d ' ' )
API_LEVEL=$("$ANDROID_BIN" list target | grep "API level:" | tail -n 1 | cut -f 2 -d ':' | tr -d ' ')
# check that build targets exist
if [ -z "$TARGET" ] || [ -z "$API_LEVEL" ]
then
echo "No Android Targets are installed. Please install at least one via the android SDK"
exit 1
fi
# if this a distribution release no need to build a jar
if [ ! -e "$BUILD_PATH"/cordova-$VERSION.jar ] && [ -d "$BUILD_PATH"/framework ]
then
# update the cordova-android framework for the desired target
"$ANDROID_BIN" update project --target $TARGET --path "$BUILD_PATH"/framework &> /dev/null
# compile cordova.js and cordova.jar
(cd "$BUILD_PATH"/framework && ant jar &> /dev/null )
fi
# copy cordova.js, cordova.jar and res/xml
if [ -d "$BUILD_PATH"/framework ]
then
cp "$BUILD_PATH"/framework/assets/www/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
cp "$BUILD_PATH"/framework/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
else
cp "$BUILD_PATH"/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
cp "$BUILD_PATH"/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
fi
# creating cordova folder and copying run/build/log/launch scripts
if [ ! -e "$PROJECT_PATH/cordova" ]
then
mkdir "$PROJECT_PATH"/cordova
mkdir "$PROJECT_PATH"/cordova/lib
fi
cp "$BUILD_PATH"/bin/templates/cordova/appinfo.jar "$PROJECT_PATH"/cordova/appinfo.jar
cp "$BUILD_PATH"/bin/templates/cordova/build "$PROJECT_PATH"/cordova/build
cp "$BUILD_PATH"/bin/templates/cordova/clean "$PROJECT_PATH"/cordova/clean
cp "$BUILD_PATH"/bin/templates/cordova/log "$PROJECT_PATH"/cordova/log
cp "$BUILD_PATH"/bin/templates/cordova/run "$PROJECT_PATH"/cordova/run
cp "$BUILD_PATH"/bin/templates/cordova/lib/cordova.js "$PROJECT_PATH"/cordova/lib/cordova.js
cp "$BUILD_PATH"/bin/templates/cordova/lib/install-device "$PROJECT_PATH"/cordova/lib/install-device
cp "$BUILD_PATH"/bin/templates/cordova/lib/install-emulator "$PROJECT_PATH"/cordova/lib/install-emulator
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-devices "$PROJECT_PATH"/cordova/lib/list-devices
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-emulator-images "$PROJECT_PATH"/cordova/lib/list-emulator-images
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-started-emulators "$PROJECT_PATH"/cordova/lib/list-started-emulators
cp "$BUILD_PATH"/bin/templates/cordova/lib/start-emulator "$PROJECT_PATH"/cordova/lib/start-emulator

View File

@@ -16,17 +16,11 @@
:: under the License.
@ECHO OFF
IF NOT DEFINED JAVA_HOME GOTO MISSING
FOR %%X in (java.exe javac.exe ant.bat android.bat) do (
SET FOUND=%%~$PATH:X
IF NOT DEFINED FOUND GOTO MISSING
SET script_path="%~dp0update"
IF EXIST %script_path% (
node %script_path% %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'update' script in 'bin' folder, aborting...>&2
EXIT /B 1
)
cscript "%~dp0\update.js" %*
GOTO END
:MISSING
ECHO Missing one of the following:
ECHO JDK: http://java.oracle.com
ECHO Android SDK: http://developer.android.com
ECHO Apache ant: http://ant.apache.org
EXIT /B 1
:END

View File

@@ -1,157 +0,0 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/*
* create a cordova/android project
*
* USAGE
* ./update [path]
*/
var fso = WScript.CreateObject('Scripting.FileSystemObject');
function read(filename) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 1);
var s=f.ReadAll();
f.Close();
return s;
}
function checkTargets(targets) {
if(!targets) {
WScript.Echo("You do not have any android targets setup. Please create at least one target with the `android` command");
WScript.Quit(69);
}
}
function setTarget() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/id: /, ""); // TODO: give users the option to set their target
}
function setApiLevel() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/API level:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/API level: /, "");
}
function write(filename, contents) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 2, true);
f.Write(contents);
f.Close();
}
function replaceInFile(filename, regexp, replacement) {
write(filename, read(filename).replace(regexp, replacement));
}
function exec(command) {
var oShell=shell.Exec(command);
while (oShell.Status == 0) {
if(!oShell.StdOut.AtEndOfStream) {
var line = oShell.StdOut.ReadLine();
// XXX: Change to verbose mode
// WScript.StdOut.WriteLine(line);
}
WScript.sleep(100);
}
}
function createAppInfoJar() {
if(!fso.FileExists(ROOT+"\\bin\\templates\\cordova\\appinfo.jar")) {
WScript.Echo("Creating appinfo.jar...");
var cur = shell.CurrentDirectory;
shell.CurrentDirectory = ROOT+"\\bin\\templates\\cordova\\ApplicationInfo";
exec("javac ApplicationInfo.java");
exec("jar -cfe ..\\appinfo.jar ApplicationInfo ApplicationInfo.class");
shell.CurrentDirectory = cur;
}
}
function cleanup() {
if(fso.FileExists(ROOT + '\\framework\\cordova-'+VERSION+'.jar')) {
fso.DeleteFile(ROOT + '\\framework\\cordova-'+VERSION+'.jar');
}
if(fso.FileExists(ROOT + '\\framework\\assets\\www\\cordova-'+VERSION+'.js')) {
fso.DeleteFile(ROOT + '\\framework\\assets\\www\\cordova-'+VERSION+'.js');
}
}
var args = WScript.Arguments, PROJECT_PATH="example",
shell=WScript.CreateObject("WScript.Shell");
// working dir
var ROOT = WScript.ScriptFullName.split('\\bin\\update.js').join('');
if (args.Count() == 1) {
PROJECT_PATH=args(0);
}
if(!fso.FolderExists(PROJECT_PATH)) {
WScript.Echo("Project doesn't exist!");
WScript.Quit(1);
}
var TARGET=setTarget();
var API_LEVEL=setApiLevel();
var VERSION=read(ROOT+'\\VERSION').replace(/\r\n/,'').replace(/\n/,'');
// build from source. distro should have these files
if (!fso.FileExists(ROOT+'\\cordova-'+VERSION+'.jar') &&
!fso.FileExists(ROOT+'\\cordova-'+VERSION+'.js')) {
WScript.Echo("Building jar and js files...");
// update the cordova framework project to a target that exists on this machine
exec('android.bat update project --target '+TARGET+' --path '+ROOT+'\\framework');
exec('ant.bat -f \"'+ ROOT +'\\framework\\build.xml\" jar');
}
// check if we have the source or the distro files
WScript.Echo("Copying js, jar & config.xml files...");
if(fso.FolderExists(ROOT + '\\framework')) {
exec('%comspec% /c copy "'+ROOT+'"\\framework\\assets\\www\\cordova-'+VERSION+'.js '+PROJECT_PATH+'\\assets\\www\\cordova-'+VERSION+'.js /Y');
exec('%comspec% /c copy "'+ROOT+'"\\framework\\cordova-'+VERSION+'.jar '+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar /Y');
} else {
// copy in cordova.js
exec('%comspec% /c copy "'+ROOT+'"\\cordova-'+VERSION+'.js '+PROJECT_PATH+'\\assets\\www\\cordova-'+VERSION+'.js /Y');
// copy in cordova.jar
exec('%comspec% /c copy "'+ROOT+'"\\cordova-'+VERSION+'.jar '+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar /Y');
// copy in xml
}
// update cordova scripts
createAppInfoJar();
WScript.Echo("Copying cordova command tools...");
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\appinfo.jar ' + PROJECT_PATH + '\\cordova\\appinfo.jar /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\cordova.bat ' + PROJECT_PATH + '\\cordova\\cordova.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\clean.bat ' + PROJECT_PATH + '\\cordova\\clean.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\build.bat ' + PROJECT_PATH + '\\cordova\\build.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\log.bat ' + PROJECT_PATH + '\\cordova\\log.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\run.bat ' + PROJECT_PATH + '\\cordova\\run.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\cordova.js ' + PROJECT_PATH + '\\cordova\\lib\\cordova.js /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\install-device.bat ' + PROJECT_PATH + '\\cordova\\lib\\install-device.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\install-emulator.bat ' + PROJECT_PATH + '\\cordova\\lib\\install-emulator.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\list-emulator-images.bat ' + PROJECT_PATH + '\\cordova\\lib\\list-emulator-images.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\list-devices.bat ' + PROJECT_PATH + '\\cordova\\lib\\list-devices.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\list-started-emulators.bat ' + PROJECT_PATH + '\\cordova\\lib\\list-started-emulators.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\lib\\start-emulator.bat ' + PROJECT_PATH + '\\cordova\\lib\\start-emulator.bat /Y');
cleanup();

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
target=android-17
target=android-18
apk-configurations=
renderscript.opt.level=O0
android.library=true

View File

@@ -47,8 +47,4 @@
<feature name="App">
<param name="android-package" value="org.apache.cordova.App" />
</feature>
<!-- Deprecated plugins element. Remove in 3.0 -->
<plugins>
</plugins>
</widget>

View File

@@ -110,8 +110,6 @@ public class CallbackContext {
/**
* Helper for success callbacks that just returns the Status.OK by default
*
* @param message The message to add to the success result.
*/
public void success() {
sendPluginResult(new PluginResult(PluginResult.Status.OK));
@@ -130,7 +128,6 @@ public class CallbackContext {
* Helper for error callbacks that just returns the Status.ERROR by default
*
* @param message The message to add to the error result.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(String message) {
sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message));
@@ -140,7 +137,6 @@ public class CallbackContext {
* Helper for error callbacks that just returns the Status.ERROR by default
*
* @param message The message to add to the error result.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(int message) {
sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message));

View File

@@ -78,6 +78,11 @@ public class Config {
return;
}
// Add implicitly allowed URLs
whitelist.addWhiteListEntry("file:///*", false);
whitelist.addWhiteListEntry("content:///*", false);
whitelist.addWhiteListEntry("data:*", false);
XmlResourceParser xml = action.getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
@@ -131,6 +136,10 @@ public class Config {
int value = xml.getAttributeIntValue(null, "value", 20000);
action.getIntent().putExtra(name, value);
}
else if(name.equalsIgnoreCase("SplashScreenDelay")) {
int value = xml.getAttributeIntValue(null, "value", 3000);
action.getIntent().putExtra(name, value);
}
else if(name.equalsIgnoreCase("KeepRunning"))
{
boolean value = xml.getAttributeValue(null, "value").equals("true");

View File

@@ -123,16 +123,6 @@ import android.widget.LinearLayout;
* Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
* <log level="DEBUG" />
*
* Cordova plugins:
* Cordova uses a file at res/xml/plugins.xml to list all plugins that are installed.
* Before using a new plugin, a new element must be added to the file.
* name attribute is the service name passed to Cordova.exec() in JavaScript
* value attribute is the Java class name to call.
*
* <plugins>
* <plugin name="App" value="org.apache.cordova.App"/>
* ...
* </plugins>
*/
public class CordovaActivity extends Activity implements CordovaInterface {
public static String TAG = "CordovaActivity";
@@ -251,19 +241,6 @@ public class CordovaActivity extends Activity implements CordovaInterface {
}
}
//CB-3949: Workaround for weird Android Launcher Bug!
private void checkIntents()
{
Intent intent = getIntent();
String intentAction = intent.getAction();
if (!isTaskRoot() && intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null) {
if(intentAction.equals(Intent.ACTION_MAIN)) {
Log.d("Cordova", "This isn't the root activity. Clearing it and returning to the root activity.");
finish();
return;
}
}
}
/**
* Called when the activity is first created.
*
@@ -272,7 +249,6 @@ public class CordovaActivity extends Activity implements CordovaInterface {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
checkIntents();
Config.init(this);
LOG.d(TAG, "CordovaActivity.onCreate()");
super.onCreate(savedInstanceState);
@@ -321,21 +297,50 @@ public class CordovaActivity extends Activity implements CordovaInterface {
return this;
}
/**
* Construct the default web view object.
*
* This is intended to be overridable by subclasses of CordovaIntent which
* require a more specialized web view.
*/
protected CordovaWebView makeWebView() {
return new CordovaWebView(CordovaActivity.this);
}
/**
* Construct the client for the default web view object.
*
* This is intended to be overridable by subclasses of CordovaIntent which
* require a more specialized web view.
*
* @param webView the default constructed web view object
*/
protected CordovaWebViewClient makeWebViewClient(CordovaWebView webView) {
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
return new CordovaWebViewClient(this, webView);
} else {
return new IceCreamCordovaWebViewClient(this, webView);
}
}
/**
* Construct the chrome client for the default web view object.
*
* This is intended to be overridable by subclasses of CordovaIntent which
* require a more specialized web view.
*
* @param webView the default constructed web view object
*/
protected CordovaChromeClient makeChromeClient(CordovaWebView webView) {
return new CordovaChromeClient(this, webView);
}
/**
* Create and initialize web container with default web view objects.
*/
public void init() {
CordovaWebView webView = new CordovaWebView(CordovaActivity.this);
CordovaWebViewClient webViewClient;
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
{
webViewClient = new CordovaWebViewClient(this, webView);
}
else
{
webViewClient = new IceCreamCordovaWebViewClient(this, webView);
}
this.init(webView, webViewClient, new CordovaChromeClient(this, webView));
CordovaWebView webView = makeWebView();
this.init(webView, makeWebViewClient(webView), makeChromeClient(webView));
}
/**
@@ -391,6 +396,16 @@ public class CordovaActivity extends Activity implements CordovaInterface {
this.init();
}
this.splashscreenTime = this.getIntegerProperty("SplashScreenDelay", this.splashscreenTime);
if(this.splashscreenTime > 0)
{
this.splashscreen = this.getIntegerProperty("SplashScreen", 0);
if(this.splashscreen != 0)
{
this.showSplashScreen(this.splashscreenTime);
}
}
// Set backgroundColor
this.backgroundColor = this.getIntegerProperty("BackgroundColor", Color.BLACK);
this.root.setBackgroundColor(this.backgroundColor);
@@ -398,12 +413,49 @@ public class CordovaActivity extends Activity implements CordovaInterface {
// If keepRunning
this.keepRunning = this.getBooleanProperty("KeepRunning", true);
// Then load the spinner
this.loadSpinner();
this.appView.loadUrl(url);
//Check if the view is attached to anything
if(appView.getParent() != null)
{
// Then load the spinner
this.loadSpinner();
}
//Load the correct splashscreen
if(this.splashscreen != 0)
{
this.appView.loadUrl(url, this.splashscreenTime);
}
else
{
this.appView.loadUrl(url);
}
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
public void loadUrl(final String url, int time) {
this.splashscreenTime = time;
this.loadUrl(url);
/*
// Init web view if not already done
if (this.appView == null) {
this.init();
}
this.splashscreenTime = time;
this.splashscreen = this.getIntegerProperty("SplashScreen", 0);
this.showSplashScreen(this.splashscreenTime);
this.appView.loadUrl(url, time);
*/
}
/*
* Load the spinner
*/
@@ -437,25 +489,6 @@ public class CordovaActivity extends Activity implements CordovaInterface {
}
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
public void loadUrl(final String url, int time) {
// Init web view if not already done
if (this.appView == null) {
this.init();
}
this.splashscreenTime = time;
this.splashscreen = this.getIntegerProperty("SplashScreen", 0);
this.showSplashScreen(this.splashscreenTime);
this.appView.loadUrl(url, time);
}
/**
* Cancel loadUrl before it has been loaded.
@@ -776,7 +809,7 @@ public class CordovaActivity extends Activity implements CordovaInterface {
* Send JavaScript statement back to JavaScript.
* (This is a convenience method)
*
* @param message
* @param statement
*/
public void sendJavascript(String statement) {
if (this.appView != null) {
@@ -1048,8 +1081,8 @@ public class CordovaActivity extends Activity implements CordovaInterface {
root.setMinimumWidth(display.getWidth());
root.setOrientation(LinearLayout.VERTICAL);
root.setBackgroundColor(that.getIntegerProperty("backgroundColor", Color.BLACK));
root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
root.setBackgroundResource(that.splashscreen);
// Create and show the dialog

View File

@@ -54,8 +54,8 @@ public class CordovaChromeClient extends WebChromeClient {
private static final String LOG_TAG = "CordovaChromeClient";
private String TAG = "CordovaLog";
private long MAX_QUOTA = 100 * 1024 * 1024;
private CordovaInterface cordova;
private CordovaWebView appView;
protected CordovaInterface cordova;
protected CordovaWebView appView;
// the video progress view
private View mVideoProgressView;
@@ -228,13 +228,18 @@ public class CordovaChromeClient extends WebChromeClient {
// Sets the native->JS bridge mode.
else if (reqOk && defaultValue != null && defaultValue.equals("gap_bridge_mode:")) {
this.appView.exposedJsApi.setNativeToJsBridgeMode(Integer.parseInt(message));
result.confirm("");
try {
this.appView.exposedJsApi.setNativeToJsBridgeMode(Integer.parseInt(message));
result.confirm("");
} catch (NumberFormatException e){
result.confirm("");
e.printStackTrace();
}
}
// Polling for JavaScript messages
else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = this.appView.exposedJsApi.retrieveJsMessages();
String r = this.appView.exposedJsApi.retrieveJsMessages("1".equals(message));
result.confirm(r == null ? "" : r);
}

View File

@@ -148,7 +148,7 @@ public class CordovaPlugin {
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
}

View File

@@ -26,7 +26,7 @@ import android.database.Cursor;
import android.net.Uri;
import android.os.Looper;
import android.util.Base64;
import android.util.Base64InputStream;
import android.webkit.MimeTypeMap;
import com.squareup.okhttp.OkHttpClient;
@@ -43,6 +43,7 @@ import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.Locale;
public class CordovaResourceApi {
@SuppressWarnings("unused")
@@ -62,7 +63,7 @@ public class CordovaResourceApi {
// Creating this is light-weight.
private static OkHttpClient httpClient = new OkHttpClient();
static Thread webCoreThread;
static Thread jsThread;
private final AssetManager assetManager;
private final ContentResolver contentResolver;
@@ -151,19 +152,74 @@ public class CordovaResourceApi {
return null;
}
public String getMimeType(Uri uri) {
switch (getUriType(uri)) {
case URI_TYPE_FILE:
case URI_TYPE_ASSET:
return getMimeTypeFromPath(uri.getPath());
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE:
return contentResolver.getType(uri);
case URI_TYPE_DATA: {
return getDataUriMimeType(uri);
}
case URI_TYPE_HTTP:
case URI_TYPE_HTTPS: {
try {
HttpURLConnection conn = httpClient.open(new URL(uri.toString()));
conn.setDoInput(false);
conn.setRequestMethod("HEAD");
return conn.getHeaderField("Content-Type");
} catch (IOException e) {
}
}
}
return null;
}
private String getMimeTypeFromPath(String path) {
String extension = path;
int lastDot = extension.lastIndexOf('.');
if (lastDot != -1) {
extension = extension.substring(lastDot + 1);
}
// Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
extension = extension.toLowerCase(Locale.getDefault());
if (extension.equals("3ga")) {
return "audio/3gpp";
}
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
/**
* Opens a stream to the givne URI, also providing the MIME type & length.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
* @throws Throws an IllegalStateException if called on a foreground thread.
*/
public OpenForReadResult openForRead(Uri uri) throws IOException {
assertBackgroundThread();
return openForRead(uri, false);
}
/**
* Opens a stream to the givne URI, also providing the MIME type & length.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
* @throws Throws an IllegalStateException if called on a foreground thread and skipThreadCheck is false.
*/
public OpenForReadResult openForRead(Uri uri, boolean skipThreadCheck) throws IOException {
if (!skipThreadCheck) {
assertBackgroundThread();
}
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
FileInputStream inputStream = new FileInputStream(uri.getPath());
String mimeType = FileHelper.getMimeTypeForExtension(uri.getPath());
String mimeType = getMimeTypeFromPath(uri.getPath());
long length = inputStream.getChannel().size();
return new OpenForReadResult(uri, inputStream, mimeType, length, null);
}
@@ -180,7 +236,7 @@ public class CordovaResourceApi {
// Will occur if the file is compressed.
inputStream = assetManager.open(assetPath);
}
String mimeType = FileHelper.getMimeTypeForExtension(assetPath);
String mimeType = getMimeTypeFromPath(assetPath);
return new OpenForReadResult(uri, inputStream, mimeType, length, assetFd);
}
case URI_TYPE_CONTENT:
@@ -294,14 +350,27 @@ public class CordovaResourceApi {
if (curThread == Looper.getMainLooper().getThread()) {
throw new IllegalStateException("Do not perform IO operations on the UI thread. Use CordovaInterface.getThreadPool() instead.");
}
if (curThread == webCoreThread) {
if (curThread == jsThread) {
throw new IllegalStateException("Tried to perform an IO operation on the WebCore thread. Use CordovaInterface.getThreadPool() instead.");
}
}
}
private String getDataUriMimeType(Uri uri) {
String uriAsString = uri.getSchemeSpecificPart();
int commaPos = uriAsString.indexOf(',');
if (commaPos == -1) {
return null;
}
String[] mimeParts = uriAsString.substring(0, commaPos).split(";");
if (mimeParts.length > 0) {
return mimeParts[0];
}
return null;
}
private OpenForReadResult readDataUri(Uri uri) {
String uriAsString = uri.toString().substring(5);
String uriAsString = uri.getSchemeSpecificPart();
int commaPos = uriAsString.indexOf(',');
if (commaPos == -1) {
return null;

View File

@@ -23,6 +23,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaInterface;
@@ -57,7 +58,10 @@ import android.widget.FrameLayout;
public class CordovaWebView extends WebView {
public static final String TAG = "CordovaWebView";
public static final String CORDOVA_VERSION = "3.1.0";
private ArrayList<Integer> keyDownCodes = new ArrayList<Integer>();
private ArrayList<Integer> keyUpCodes = new ArrayList<Integer>();
@@ -425,7 +429,7 @@ public class CordovaWebView extends WebView {
// Create a timeout timer for loadUrl
final CordovaWebView me = this;
final int currentLoadUrlTimeout = me.loadUrlTimeout;
final int loadUrlTimeoutValue = Integer.parseInt(this.getProperty("loadUrlTimeoutValue", "20000"));
final int loadUrlTimeoutValue = Integer.parseInt(this.getProperty("LoadUrlTimeoutValue", "20000"));
// Timeout error method
final Runnable loadError = new Runnable() {
@@ -511,7 +515,7 @@ public class CordovaWebView extends WebView {
* Send JavaScript statement back to JavaScript.
* (This is a convenience method)
*
* @param message
* @param statement
*/
public void sendJavascript(String statement) {
this.jsMessageQueue.addJavaScript(statement);
@@ -521,7 +525,8 @@ public class CordovaWebView extends WebView {
* Send a plugin result back to JavaScript.
* (This is a convenience method)
*
* @param message
* @param result
* @param callbackId
*/
public void sendPluginResult(PluginResult result, String callbackId) {
this.jsMessageQueue.addPluginResult(result, callbackId);
@@ -620,7 +625,7 @@ public class CordovaWebView extends WebView {
*/
private void loadConfiguration() {
if ("true".equals(this.getProperty("fullscreen", "false"))) {
if ("true".equals(this.getProperty("Fullscreen", "false"))) {
this.cordova.getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
this.cordova.getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
@@ -638,6 +643,7 @@ public class CordovaWebView extends WebView {
if (bundle == null) {
return defaultValue;
}
name = name.toLowerCase(Locale.getDefault());
Object p = bundle.get(name);
if (p == null) {
return defaultValue;

View File

@@ -30,6 +30,7 @@ import android.os.StatFs;
*
* It is used by the FileUtils class.
*/
@Deprecated // Deprecated in 3.1. To be removed in 4.0.
public class DirectoryManager {
@SuppressWarnings("unused")

View File

@@ -22,6 +22,7 @@ import java.io.IOException;
import android.media.ExifInterface;
@Deprecated // Deprecated in 3.1. To be removed in 4.0.
public class ExifHelper {
private String aperture = null;
private String datetime = null;

View File

@@ -20,7 +20,6 @@ package org.apache.cordova;
import android.webkit.JavascriptInterface;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
/**
@@ -48,10 +47,13 @@ import org.json.JSONException;
jsMessageQueue.setPaused(true);
try {
// Tell the resourceApi what thread the JS is running on.
CordovaResourceApi.jsThread = Thread.currentThread();
pluginManager.exec(service, action, callbackId, arguments);
String ret = "";
if (!NativeToJsMessageQueue.DISABLE_EXEC_CHAINING) {
ret = jsMessageQueue.popAndEncode();
ret = jsMessageQueue.popAndEncode(false);
}
return ret;
} catch (Throwable e) {
@@ -68,7 +70,7 @@ import org.json.JSONException;
}
@JavascriptInterface
public String retrieveJsMessages() {
return jsMessageQueue.popAndEncode();
public String retrieveJsMessages(boolean fromOnlineEvent) {
return jsMessageQueue.popAndEncode(fromOnlineEvent);
}
}

View File

@@ -34,6 +34,7 @@ import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Locale;
@Deprecated // Deprecated in 3.1. To be removed in 4.0.
public class FileHelper {
private static final String LOG_TAG = "FileUtils";
private static final String _DATA = "_data";

View File

@@ -18,6 +18,7 @@
*/
package org.apache.cordova;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.cordova.CordovaInterface;
@@ -27,7 +28,6 @@ import org.apache.cordova.LOG;
import android.annotation.TargetApi;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
@@ -46,9 +46,6 @@ public class IceCreamCordovaWebViewClient extends CordovaWebViewClient {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
// Tell the Thread-Checking resolve what thread the WebCore thread is.
CordovaResourceApi.webCoreThread = Thread.currentThread();
Log.e("WHAAAA", "FOOD " + CordovaResourceApi.webCoreThread);
try {
// Check the against the white-list.
if ((url.startsWith("http:") || url.startsWith("https:")) && !Config.isUrlWhiteListed(url)) {
@@ -63,13 +60,15 @@ public class IceCreamCordovaWebViewClient extends CordovaWebViewClient {
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri)) {
OpenForReadResult result = resourceApi.openForRead(remappedUri);
OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file.", e);
if (!(e instanceof FileNotFoundException)) {
LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}

Some files were not shown because too many files have changed in this diff Show More