TagSpaces is an offline, open source, document manager with tagging support
updating cordova subproject
Ilian Sapundshiev719c23add32b
diff --git a/cordova/.gitignore b/cordova/.gitignorenew file mode 100644index 000000000..117aeabbd--- /dev/null+++ b/cordova/.gitignore@@ -0,0 +1,32 @@+# Logs+logs+*.log++# Runtime data+pids+*.pid+*.seed++# node-waf configuration+.lock-wscript++build/Release+.eslintcache++# Dependency directory+node_modules++# OSX+.DS_Store++node_modules/*+www/*+!cordova/www/index.html++platforms/android/.gradle/*+platforms/android/app/build/*+platforms/android/build/*+platforms/android/CordovaLib/build/*+platforms/android/assets/www/*+plugins/**/*+diff --git a/cordova/config.xml b/cordova/config.xmlindex 6de2c7ebd..7e13b7964 100644--- a/cordova/config.xml+++ b/cordova/config.xml@@ -22,13 +22,5 @@<allow-intent href="itms:*" /><allow-intent href="itms-apps:*" /></platform>- <engine name="android" spec="^6.2.3" /><plugin name="cordova-plugin-whitelist" spec="^1.3.2" />- <plugin name="cordova-plugin-crosswalk-webview" spec="^2.3.0">- <variable name="XWALK_VERSION" value="23+" />- <variable name="XWALK_LITEVERSION" value="xwalk_core_library_canary:17+" />- <variable name="XWALK_COMMANDLINE" value="--disable-pull-to-refresh-effect" />- <variable name="XWALK_MODE" value="embedded" />- <variable name="XWALK_MULTIPLEAPK" value="true" />- </plugin></widget>diff --git a/cordova/package.json b/cordova/package.jsonindex 3e153cd19..d72650b79 100644--- a/cordova/package.json+++ b/cordova/package.json@@ -10,23 +10,13 @@"author": "Apache Cordova Team","license": "Apache-2.0","dependencies": {- "cordova-android": "^6.2.3",- "cordova-plugin-crosswalk-webview": "^2.3.0",+ "cordova-android": "^7.1.2","cordova-plugin-whitelist": "^1.3.2"},"cordova": {"plugins": {- "cordova-plugin-whitelist": {},- "cordova-plugin-crosswalk-webview": {- "XWALK_VERSION": "23+",- "XWALK_LITEVERSION": "xwalk_core_library_canary:17+",- "XWALK_COMMANDLINE": "--disable-pull-to-refresh-effect",- "XWALK_MODE": "embedded",- "XWALK_MULTIPLEAPK": "true"- }+ "cordova-plugin-whitelist": {}},- "platforms": [- "android"- ]+ "platforms": []}-}\ No newline at end of file+}diff --git a/cordova/platforms/android/CordovaLib/AndroidManifest.xml b/cordova/platforms/android/CordovaLib/AndroidManifest.xmlindex 3feb903cf..1625b896b 100755--- a/cordova/platforms/android/CordovaLib/AndroidManifest.xml+++ b/cordova/platforms/android/CordovaLib/AndroidManifest.xml@@ -19,5 +19,5 @@--><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="org.apache.cordova" android:versionName="1.0" android:versionCode="1">- <uses-sdk android:minSdkVersion="14" />+ <uses-sdk android:minSdkVersion="19" /></manifest>diff --git a/cordova/platforms/android/CordovaLib/build.gradle b/cordova/platforms/android/CordovaLib/build.gradleindex da3b45bf1..28c5e5946 100644--- a/cordova/platforms/android/CordovaLib/build.gradle+++ b/cordova/platforms/android/CordovaLib/build.gradle@@ -24,12 +24,14 @@ ext {buildscript {repositories {- mavenCentral()+ maven {+ url "https://maven.google.com"+ }jcenter()}dependencies {- classpath 'com.android.tools.build:gradle:2.2.3'+ classpath 'com.android.tools.build:gradle:3.0.1'classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'}@@ -40,7 +42,7 @@ apply plugin: 'com.github.dcendents.android-maven'apply plugin: 'com.jfrog.bintray'group = 'org.apache.cordova'-version = '6.2.3'+version = '7.1.2'android {compileSdkVersion cdvCompileSdkVersion@@ -48,8 +50,8 @@ android {publishNonDefault truecompileOptions {- sourceCompatibility JavaVersion.VERSION_1_6- targetCompatibility JavaVersion.VERSION_1_6+ sourceCompatibility JavaVersion.VERSION_1_8+ targetCompatibility JavaVersion.VERSION_1_8}sourceSets {@@ -127,9 +129,9 @@ bintray {licenses = ['Apache-2.0']labels = ['android', 'cordova', 'phonegap']version {- name = '6.2.3'+ name = '7.1.2'released = new Date()- vcsTag = '6.2.3'+ vcsTag = '7.1.2'}}}diff --git a/cordova/platforms/android/CordovaLib/cordova.gradle b/cordova/platforms/android/CordovaLib/cordova.gradleindex 21a01bb58..6c6819a17 100644--- a/cordova/platforms/android/CordovaLib/cordova.gradle+++ b/cordova/platforms/android/CordovaLib/cordova.gradle@@ -29,7 +29,11 @@ String doEnsureValueExists(filePath, props, key) {String doGetProjectTarget() {def props = new Properties()- file('project.properties').withReader { reader ->+ def propertiesFile = 'project.properties';+ if(!(file(propertiesFile).exists())) {+ propertiesFile = '../project.properties';+ }+ file(propertiesFile).withReader { reader ->props.load(reader)}return doEnsureValueExists('project.properties', props, 'target')@@ -161,7 +165,7 @@ def doPromptForPassword(msg) {}def doGetConfigXml() {- def xml = file("res/xml/config.xml").getText()+ def xml = file("src/main/res/xml/config.xml").getText()// Disable namespace awareness since Cordova doesn't use them properlyreturn new XmlParser(false, false).parseText(xml)}diff --git a/cordova/platforms/android/CordovaLib/project.properties b/cordova/platforms/android/CordovaLib/project.propertiesindex df3c73c42..0a372ee40 100644--- a/cordova/platforms/android/CordovaLib/project.properties+++ b/cordova/platforms/android/CordovaLib/project.properties@@ -10,7 +10,7 @@# Indicates whether an apk should be generated for each density.split.density=false# Project target.-target=android-25+target=android-27apk-configurations=renderscript.opt.level=O0android.library=truediff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/BuildHelper.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/BuildHelper.javanew file mode 100644index 000000000..6d9daa471--- /dev/null+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/BuildHelper.java@@ -0,0 +1,70 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++package org.apache.cordova;++/*+ * This is a utility class that allows us to get the BuildConfig variable, which is required+ * for the use of different providers. This is not guaranteed to work, and it's better for this+ * to be set in the build step in config.xml+ *+ */++import android.app.Activity;+import android.content.Context;++import java.lang.reflect.Field;+++public class BuildHelper {+++ private static String TAG="BuildHelper";++ /*+ * This needs to be implemented if you wish to use the Camera Plugin or other plugins+ * that read the Build Configuration.+ *+ * Thanks to Phil@Medtronic and Graham Borland for finding the answer and posting it to+ * StackOverflow. This is annoying as hell! However, this method does not work with+ * ProGuard, and you should use the config.xml to define the application_id+ *+ */++ public static Object getBuildConfigValue(Context ctx, String key)+ {+ try+ {+ Class<?> clazz = Class.forName(ctx.getPackageName() + ".BuildConfig");+ Field field = clazz.getField(key);+ return field.get(null);+ } catch (ClassNotFoundException e) {+ LOG.d(TAG, "Unable to get the BuildConfig, is this built with ANT?");+ e.printStackTrace();+ } catch (NoSuchFieldException e) {+ LOG.d(TAG, key + " is not a valid field. Check your build.gradle");+ } catch (IllegalAccessException e) {+ LOG.d(TAG, "Illegal Access Exception: Let's print a stack trace.");+ e.printStackTrace();+ }++ return null;+ }++}\ No newline at end of filediff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.javaindex 85eeb53a5..dbbb48f69 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.java@@ -123,7 +123,7 @@ public class CordovaActivity extends Activity {if (preferences.getBoolean("Fullscreen", false)) {// NOTE: use the FullscreenNotImmersive configuration key to set the activity in a REAL full screen// (as was the case in previous cordova versions)- if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) && !preferences.getBoolean("FullscreenNotImmersive", false)) {+ if (!preferences.getBoolean("FullscreenNotImmersive", false)) {immersiveMode = true;} else {getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,@@ -319,6 +319,7 @@ public class CordovaActivity extends Activity {/*** Called when view focus is changed*/+ @SuppressLint("InlinedApi")@Overridepublic void onWindowFocusChanged(boolean hasFocus) {super.onWindowFocusChanged(hasFocus);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.javaindex 9459a1134..28c407f3d 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.java@@ -18,6 +18,8 @@*/package org.apache.cordova;+import android.annotation.SuppressLint;+import java.security.SecureRandom;import org.json.JSONArray;@@ -110,6 +112,9 @@ public class CordovaBridge {}/** Called by cordova.js to initialize the bridge. */+ //On old Androids SecureRandom isn't really secure, this is the least of your problems if+ //you're running Android 4.3 and below in 2017+ @SuppressLint("TrulyRandom")int generateBridgeSecret() {SecureRandom randGen = new SecureRandom();expectedBridgeSecret = randGen.nextInt(Integer.MAX_VALUE);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.javaindex 5dd0ecaec..ccda0272a 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.java@@ -22,10 +22,12 @@ import java.security.Principal;import java.security.PrivateKey;import java.security.cert.X509Certificate;+import android.annotation.SuppressLint;import android.webkit.ClientCertRequest;/*** Implementation of the ICordovaClientCertRequest for Android WebView.+ **/public class CordovaClientCertRequest implements ICordovaClientCertRequest {@@ -38,6 +40,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {/*** Cancel this request*/+ @SuppressLint("NewApi")public void cancel(){request.cancel();@@ -46,6 +49,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {/** Returns the host name of the server requesting the certificate.*/+ @SuppressLint("NewApi")public String getHost(){return request.getHost();@@ -54,6 +58,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {/** Returns the acceptable types of asymmetric keys (can be null).*/+ @SuppressLint("NewApi")public String[] getKeyTypes(){return request.getKeyTypes();@@ -62,6 +67,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {/** Returns the port number of the server requesting the certificate.*/+ @SuppressLint("NewApi")public int getPort(){return request.getPort();@@ -70,6 +76,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {/** Returns the acceptable certificate issuers for the certificate matching the private key (can be null).*/+ @SuppressLint("NewApi")public Principal[] getPrincipals(){return request.getPrincipals();@@ -78,6 +85,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {/** Ignore the request for now. Do not remember user's choice.*/+ @SuppressLint("NewApi")public void ignore(){request.ignore();@@ -89,6 +97,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {* @param privateKey The privateKey* @param chain The certificate chain*/+ @SuppressLint("NewApi")public void proceed(PrivateKey privateKey, X509Certificate[] chain){request.proceed(privateKey, chain);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.javaindex 3b8468f3b..ff9068346 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.java@@ -19,6 +19,7 @@package org.apache.cordova;import android.app.Activity;+import android.content.Context;import android.content.Intent;import org.apache.cordova.CordovaPlugin;@@ -51,10 +52,18 @@ public interface CordovaInterface {/*** Get the Android activity.*+ * If a custom engine lives outside of the Activity's lifecycle the return value may be null.+ ** @return the Activity*/public abstract Activity getActivity();-++ /**+ * Get the Android context.+ *+ * @return the Context+ */+ public Context getContext();/*** Called when a message is sent to plugin.diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterfaceImpl.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterfaceImpl.javaindex 71dcb7828..9a6e9245f 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterfaceImpl.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterfaceImpl.java@@ -19,7 +19,9 @@package org.apache.cordova;+import android.annotation.SuppressLint;import android.app.Activity;+import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.os.Build;@@ -84,6 +86,11 @@ public class CordovaInterfaceImpl implements CordovaInterface {return activity;}+ @Override+ public Context getContext() {+ return activity;+ }+@Overridepublic Object onMessage(String id, Object data) {if ("exit".equals(id)) {@@ -221,6 +228,7 @@ public class CordovaInterfaceImpl implements CordovaInterface {requestPermissions(plugin, requestCode, permissions);}+ @SuppressLint("NewApi")public void requestPermissions(CordovaPlugin plugin, int requestCode, String [] permissions) {int mappedRequestCode = permissionResultCallbacks.registerCallback(plugin, requestCode);getActivity().requestPermissions(permissions, mappedRequestCode);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.javaindex e725e2555..3c438e21b 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.java@@ -263,6 +263,7 @@ public class CordovaResourceApi {} catch (FileNotFoundException e) {// Will occur if the file is compressed.inputStream = assetManager.open(assetPath);+ length = inputStream.available();}String mimeType = getMimeTypeFromPath(assetPath);return new OpenForReadResult(uri, inputStream, mimeType, length, assetFd);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.javaindex 713884b95..64d410ea2 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java@@ -31,7 +31,7 @@ import android.webkit.WebChromeClient.CustomViewCallback;* are not expected to implement it.*/public interface CordovaWebView {- public static final String CORDOVA_VERSION = "6.2.3";+ public static final String CORDOVA_VERSION = "7.1.2";void init(CordovaInterface cordova, List<PluginEntry> pluginEntries, CordovaPreferences preferences);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.javaindex 85a0b5f5d..fb99c3443 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java@@ -18,6 +18,7 @@*/package org.apache.cordova;+import android.annotation.SuppressLint;import android.content.Context;import android.content.Intent;import android.net.Uri;@@ -91,6 +92,7 @@ public class CordovaWebViewImpl implements CordovaWebView {init(cordova, new ArrayList<PluginEntry>(), new CordovaPreferences());}+ @SuppressLint("Assert")@Overridepublic void init(CordovaInterface cordova, List<PluginEntry> pluginEntries, CordovaPreferences preferences) {if (this.cordova != null) {diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.javaindex a8f59fad9..d17b1c43a 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.java@@ -511,6 +511,9 @@ public class NativeToJsMessageQueue {.append(pluginResult.getMessage()).append("')");break;+ case PluginResult.MESSAGE_TYPE_NULL:+ sb.append("null");+ break;default:sb.append(pluginResult.getMessage());}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/PermissionHelper.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/PermissionHelper.javanew file mode 100644index 000000000..52f6e1403--- /dev/null+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/PermissionHelper.java@@ -0,0 +1,87 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/+package org.apache.cordova;++import java.util.Arrays;++import org.json.JSONException;++import android.content.pm.PackageManager;++/**+ * This class provides reflective methods for permission requesting and checking so that plugins+ * written for cordova-android 5.0.0+ can still compile with earlier cordova-android versions.+ */+public class PermissionHelper {+ private static final String LOG_TAG = "CordovaPermissionHelper";++ /**+ * Requests a "dangerous" permission for the application at runtime. This is a helper method+ * alternative to cordovaInterface.requestPermission() that does not require the project to be+ * built with cordova-android 5.0.0++ *+ * @param plugin The plugin the permission is being requested for+ * @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult()+ * along with the result of the permission request+ * @param permission The permission to be requested+ */+ public static void requestPermission(CordovaPlugin plugin, int requestCode, String permission) {+ PermissionHelper.requestPermissions(plugin, requestCode, new String[] {permission});+ }++ /**+ * Requests "dangerous" permissions for the application at runtime. This is a helper method+ * alternative to cordovaInterface.requestPermissions() that does not require the project to be+ * built with cordova-android 5.0.0++ *+ * @param plugin The plugin the permissions are being requested for+ * @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult()+ * along with the result of the permissions request+ * @param permissions The permissions to be requested+ */+ public static void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) {+ plugin.cordova.requestPermissions(plugin, requestCode, permissions);+ }++ /**+ * Checks at runtime to see if the application has been granted a permission. This is a helper+ * method alternative to cordovaInterface.hasPermission() that does not require the project to+ * be built with cordova-android 5.0.0++ *+ * @param plugin The plugin the permission is being checked against+ * @param permission The permission to be checked+ *+ * @return True if the permission has already been granted and false otherwise+ */+ public static boolean hasPermission(CordovaPlugin plugin, String permission) {+ return plugin.cordova.hasPermission(permission);+ }++ private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) {+ // Generate the request results+ int[] requestResults = new int[permissions.length];+ Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED);++ try {+ plugin.onRequestPermissionResult(requestCode, permissions, requestResults);+ } catch (JSONException e) {+ LOG.e(LOG_TAG, "JSONException when delivering permissions results", e);+ }+ }+}\ No newline at end of filediff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.javaindex 3ea5e5765..a27fc6af4 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java@@ -149,21 +149,6 @@ public class SystemWebChromeClient extends WebChromeClient {quotaUpdater.updateQuota(MAX_QUOTA);}- // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html- // Expect this to not compile in a future Android release!- @SuppressWarnings("deprecation")- @Override- public void onConsoleMessage(String message, int lineNumber, String sourceID)- {- //This is only for Android 2.1- if(android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.ECLAIR_MR1)- {- LOG.d(LOG_TAG, "%s: Line %d : %s", sourceID, lineNumber, message);- super.onConsoleMessage(message, lineNumber, sourceID);- }- }-- @TargetApi(8)@Overridepublic boolean onConsoleMessage(ConsoleMessage consoleMessage){diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.javaindex d17650240..0b6a577ea 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java@@ -112,7 +112,7 @@ public class SystemWebViewClient extends WebViewClient {* @param request*/@Override- @TargetApi(21)+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)public void onReceivedClientCertRequest (WebView view, ClientCertRequest request){@@ -219,7 +219,6 @@ public class SystemWebViewClient extends WebViewClient {* @param handler An SslErrorHandler object that will handle the user's response.* @param error The SSL error object.*/- @TargetApi(8)@Overridepublic void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {@@ -316,7 +315,6 @@ public class SystemWebViewClient extends WebViewClient {this.authenticationTokens.clear();}- @TargetApi(Build.VERSION_CODES.HONEYCOMB)@Overridepublic WebResourceResponse shouldInterceptRequest(WebView view, String url) {try {@@ -349,7 +347,7 @@ public class SystemWebViewClient extends WebViewClient {}private static boolean needsKitKatContentUrlFix(Uri uri) {- return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && "content".equals(uri.getScheme());+ return "content".equals(uri.getScheme());}private static boolean needsSpecialsInAssetUrlFix(Uri uri) {@@ -364,11 +362,6 @@ public class SystemWebViewClient extends WebViewClient {return false;}- switch(android.os.Build.VERSION.SDK_INT){- case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH:- case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1:- return true;- }return false;}}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.javaindex 3be7d940a..1cbd7f8bb 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java@@ -110,16 +110,19 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.OnlineEventsBridgeMode(new NativeToJsMessageQueue.OnlineEventsBridgeMode.OnlineEventsBridgeModeDelegate() {@Overridepublic void setNetworkAvailable(boolean value) {- webView.setNetworkAvailable(value);+ //sometimes this can be called after calling webview.destroy() on destroy()+ //thus resulting in a NullPointerException+ if(webView!=null) {+ webView.setNetworkAvailable(value);+ }}@Overridepublic void runOnUiThread(Runnable r) {SystemWebViewEngine.this.cordova.getActivity().runOnUiThread(r);}}));- if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2)- nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.EvalBridgeMode(this, cordova));- bridge = new CordovaBridge(pluginManager, nativeToJsMessageQueue);+ nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.EvalBridgeMode(this, cordova));+ bridge = new CordovaBridge(pluginManager, nativeToJsMessageQueue);exposeJsInterface(webView, bridge);}@@ -149,26 +152,8 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {settings.setJavaScriptCanOpenWindowsAutomatically(true);settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);- // Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated entirely for Jellybean 4.2)- try {- Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", new Class[] { boolean.class });-- String manufacturer = android.os.Build.MANUFACTURER;- LOG.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);- if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB &&- android.os.Build.MANUFACTURER.contains("HTC"))- {- gingerbread_getMethod.invoke(settings, true);- }- } catch (NoSuchMethodException e) {- LOG.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8");- } catch (IllegalArgumentException e) {- LOG.d(TAG, "Doing the NavDump failed with bad arguments");- } catch (IllegalAccessException e) {- LOG.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore");- } catch (InvocationTargetException e) {- LOG.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore.");- }+ String manufacturer = android.os.Build.MANUFACTURER;+ LOG.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);//We don't save any form data in the applicationsettings.setSaveFormData(false);@@ -176,12 +161,9 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {// Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist// while we do this- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {- settings.setAllowUniversalAccessFromFileURLs(true);- }- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {- settings.setMediaPlaybackRequiresUserGesture(false);- }+ settings.setAllowUniversalAccessFromFileURLs(true);+ settings.setMediaPlaybackRequiresUserGesture(false);+// Enable database// We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16String databasePath = webView.getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();@@ -191,8 +173,7 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {//Determine whether we're in debug or release mode, and turn on Debugging!ApplicationInfo appInfo = webView.getContext().getApplicationContext().getApplicationInfo();- if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0 &&- android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {+ if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {enableRemoteDebugging();}@@ -210,11 +191,6 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {settings.setAppCachePath(databasePath);settings.setAppCacheEnabled(true);- // Enable scaling- // Fix for CB-12015- settings.setUseWideViewPort(true);- settings.setLoadWithOverviewMode(true);-// Fix for CB-1405// Google issue 4641String defaultUserAgent = settings.getUserAgentString();@@ -245,7 +221,6 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {// end CB-1405}- @TargetApi(Build.VERSION_CODES.KITKAT)private void enableRemoteDebugging() {try {WebView.setWebContentsDebuggingEnabled(true);@@ -255,14 +230,9 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {}}+ // Yeah, we know. It'd be great if lint was just a little smarter.+ @SuppressLint("AddJavascriptInterface")private static void exposeJsInterface(WebView webView, CordovaBridge bridge) {- if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)) {- LOG.i(TAG, "Disabled addJavascriptInterface() bridge since Android version is old.");- // Bug being that Java Strings do not get converted to JS strings automatically.- // This isn't hard to work-around on the JS side, but it's easier to just- // use the prompt bridge instead.- return;- }SystemExposedJsApi exposedJsApi = new SystemExposedJsApi(bridge);webView.addJavascriptInterface(exposedJsApi, "_cordovaNative");}@@ -344,12 +314,6 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {@Overridepublic void evaluateJavascript(String js, ValueCallback<String> callback) {- if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {- webView.evaluateJavascript(js, callback);- }- else- {- LOG.d(TAG, "This webview is using the old bridge");- }+ webView.evaluateJavascript(js, callback);}}diff --git a/cordova/platforms/android/android.json b/cordova/platforms/android/android.jsonindex 9b85b2b1e..fc4fe6e67 100644--- a/cordova/platforms/android/android.json+++ b/cordova/platforms/android/android.json@@ -4,78 +4,8 @@"uninstalled": []},"config_munge": {- "files": {- "res/xml/config.xml": {- "parents": {- "/*": [- {- "xml": "<feature name=\"Whitelist\"><param name=\"android-package\" value=\"org.apache.cordova.whitelist.WhitelistPlugin\" /><param name=\"onload\" value=\"true\" /></feature>",- "count": 1- },- {- "xml": "<preference name=\"webView\" value=\"org.crosswalk.engine.XWalkWebViewEngine\" />",- "count": 1- },- {- "xml": "<preference name=\"xwalkVersion\" value=\"23+\" />",- "count": 1- },- {- "xml": "<preference name=\"xwalkLiteVersion\" value=\"xwalk_core_library_canary:17+\" />",- "count": 1- },- {- "xml": "<preference name=\"xwalkCommandLine\" value=\"--disable-pull-to-refresh-effect\" />",- "count": 1- },- {- "xml": "<preference name=\"xwalkMode\" value=\"embedded\" />",- "count": 1- },- {- "xml": "<preference name=\"xwalkMultipleApk\" value=\"true\" />",- "count": 1- },- {- "xml": "<preference name=\"android-minSdkVersion\" value=\"16\" />",- "count": 1- }- ]- }- },- "AndroidManifest.xml": {- "parents": {- "/*": [- {- "xml": "<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />",- "count": 1- },- {- "xml": "<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" />",- "count": 1- }- ]- }- }- }+ "files": {}},- "installed_plugins": {- "cordova-plugin-whitelist": {- "PACKAGE_NAME": "org.tagspaces.mobile"- },- "cordova-plugin-crosswalk-webview": {- "XWALK_VERSION": "23+",- "XWALK_LITEVERSION": "xwalk_core_library_canary:17+",- "XWALK_COMMANDLINE": "--disable-pull-to-refresh-effect",- "XWALK_MODE": "embedded",- "XWALK_MULTIPLEAPK": "true",- "PACKAGE_NAME": "org.tagspaces.mobile"- }- },- "dependent_plugins": {},- "modules": [],- "plugin_metadata": {- "cordova-plugin-whitelist": "1.3.2",- "cordova-plugin-crosswalk-webview": "2.3.0"- }+ "installed_plugins": {},+ "dependent_plugins": {}}\ No newline at end of filediff --git a/cordova/platforms/android/app/build.gradle b/cordova/platforms/android/app/build.gradlenew file mode 100644index 000000000..a1ea273bf--- /dev/null+++ b/cordova/platforms/android/app/build.gradle@@ -0,0 +1,323 @@+/*+ 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.+*/++apply plugin: 'com.android.application'++buildscript {+ repositories {+ mavenCentral()+ maven {+ url "https://maven.google.com"+ }+ jcenter()+ }++ dependencies {+ classpath 'com.android.tools.build:gradle:3.0.1'+ }+}++// Allow plugins to declare Maven dependencies via build-extras.gradle.+allprojects {+ repositories {+ mavenCentral();+ jcenter()+ }+}++task wrapper(type: Wrapper) {+ gradleVersion = '4.1.0'+}++// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.+// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html+ext {+ apply from: '../CordovaLib/cordova.gradle'+ // The value for android.compileSdkVersion.+ if (!project.hasProperty('cdvCompileSdkVersion')) {+ cdvCompileSdkVersion = null;+ }+ // The value for android.buildToolsVersion.+ if (!project.hasProperty('cdvBuildToolsVersion')) {+ cdvBuildToolsVersion = null;+ }+ // Sets the versionCode to the given value.+ if (!project.hasProperty('cdvVersionCode')) {+ cdvVersionCode = null+ }+ // Sets the minSdkVersion to the given value.+ if (!project.hasProperty('cdvMinSdkVersion')) {+ cdvMinSdkVersion = null+ }+ // Whether to build architecture-specific APKs.+ if (!project.hasProperty('cdvBuildMultipleApks')) {+ cdvBuildMultipleApks = null+ }+ // Whether to append a 0 "abi digit" to versionCode when only a single APK is build+ if (!project.hasProperty('cdvVersionCodeForceAbiDigit')) {+ cdvVersionCodeForceAbiDigit = null+ }+ // .properties files to use for release signing.+ if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {+ cdvReleaseSigningPropertiesFile = null+ }+ // .properties files to use for debug signing.+ if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {+ cdvDebugSigningPropertiesFile = null+ }+ // Set by build.js script.+ if (!project.hasProperty('cdvBuildArch')) {+ cdvBuildArch = null+ }++ // Plugin gradle extensions can append to this to have code run at the end.+ cdvPluginPostBuildExtras = []+}++// PLUGIN GRADLE EXTENSIONS START+// PLUGIN GRADLE EXTENSIONS END++def hasBuildExtras = file('build-extras.gradle').exists()+if (hasBuildExtras) {+ apply from: 'build-extras.gradle'+}++// Set property defaults after extension .gradle files.+if (ext.cdvCompileSdkVersion == null) {+ ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()+ //ext.cdvCompileSdkVersion = project.ext.defaultCompileSdkVersion+}+if (ext.cdvBuildToolsVersion == null) {+ ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()+ //ext.cdvBuildToolsVersion = project.ext.defaultBuildToolsVersion+}+if (ext.cdvDebugSigningPropertiesFile == null && file('../debug-signing.properties').exists()) {+ ext.cdvDebugSigningPropertiesFile = '../debug-signing.properties'+}+if (ext.cdvReleaseSigningPropertiesFile == null && file('../release-signing.properties').exists()) {+ ext.cdvReleaseSigningPropertiesFile = '../release-signing.properties'+}++// Cast to appropriate types.+ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();+ext.cdvVersionCodeForceAbiDigit = cdvVersionCodeForceAbiDigit == null ? false : cdvVersionCodeForceAbiDigit.toBoolean();+ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : defaultMinSdkVersion+ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)++def computeBuildTargetName(debugBuild) {+ def ret = 'assemble'+ if (cdvBuildMultipleApks && cdvBuildArch) {+ def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch+ ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);+ }+ return ret + (debugBuild ? 'Debug' : 'Release')+}++// Make cdvBuild a task that depends on the debug/arch-sepecific task.+task cdvBuildDebug+cdvBuildDebug.dependsOn {+ return computeBuildTargetName(true)+}++task cdvBuildRelease+cdvBuildRelease.dependsOn {+ return computeBuildTargetName(false)+}++task cdvPrintProps << {+ println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)+ println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)+ println('cdvVersionCode=' + cdvVersionCode)+ println('cdvVersionCodeForceAbiDigit=' + cdvVersionCodeForceAbiDigit)+ println('cdvMinSdkVersion=' + cdvMinSdkVersion)+ println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)+ println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)+ println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)+ println('cdvBuildArch=' + cdvBuildArch)+ println('computedVersionCode=' + android.defaultConfig.versionCode)+ android.productFlavors.each { flavor ->+ println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)+ }+}++android {++ defaultConfig {+ versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))+ applicationId privateHelpers.extractStringFromManifest("package")++ if (cdvMinSdkVersion != null) {+ minSdkVersion cdvMinSdkVersion+ }+ }++ lintOptions {+ abortOnError false;+ }++ compileSdkVersion cdvCompileSdkVersion+ buildToolsVersion cdvBuildToolsVersion++ //This code exists for Crosswalk and other Native APIs.+ //By default, we multiply the existing version code in the Android Manifest by 10 and+ //add a number for each architecture. If you are not using Crosswalk or SQLite, you can+ //ignore this chunk of code, and your version codes will be respected.++ if (Boolean.valueOf(cdvBuildMultipleApks)) {+ flavorDimensions "default"++ productFlavors {+ armeabi {+ versionCode defaultConfig.versionCode*10 + 1+ ndk {+ abiFilters = ["armeabi"]+ }+ }+ armv7 {+ versionCode defaultConfig.versionCode*10 + 2+ ndk {+ abiFilters = ["armeabi-v7a"]+ }+ }+ arm64 {+ versionCode defaultConfig.versionCode*10 + 3+ ndk {+ abiFilters = ["arm64-v8a"]+ }+ }+ x86 {+ versionCode defaultConfig.versionCode*10 + 4+ ndk {+ abiFilters = ["x86"]+ }+ }+ x86_64 {+ versionCode defaultConfig.versionCode*10 + 5+ ndk {+ abiFilters = ["x86_64"]+ }+ }+ }+ } else if (Boolean.valueOf(cdvVersionCodeForceAbiDigit)) {+ // This provides compatibility to the default logic for versionCode before cordova-android 5.2.0+ defaultConfig {+ versionCode defaultConfig.versionCode*10+ }+ }++ compileOptions {+ sourceCompatibility JavaVersion.VERSION_1_8+ targetCompatibility JavaVersion.VERSION_1_8+ }++ if (cdvReleaseSigningPropertiesFile) {+ signingConfigs {+ release {+ // These must be set or Gradle will complain (even if they are overridden).+ keyAlias = ""+ keyPassword = "__unset" // And these must be set to non-empty in order to have the signing step added to the task graph.+ storeFile = null+ storePassword = "__unset"+ }+ }+ buildTypes {+ release {+ signingConfig signingConfigs.release+ }+ }+ addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)+ }+ if (cdvDebugSigningPropertiesFile) {+ addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)+ }+}++/*+ * WARNING: Cordova Lib and platform scripts do management inside of this code here,+ * if you are adding the dependencies manually, do so outside the comments, otherwise+ * the Cordova tools will overwrite them+ */+++dependencies {+ implementation fileTree(dir: 'libs', include: '*.jar')+ // SUB-PROJECT DEPENDENCIES START+ implementation(project(path: ":CordovaLib"))+ // SUB-PROJECT DEPENDENCIES END+}++def promptForReleaseKeyPassword() {+ if (!cdvReleaseSigningPropertiesFile) {+ return;+ }+ if ('__unset'.equals(android.signingConfigs.release.storePassword)) {+ android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')+ }+ if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {+ android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');+ }+}++gradle.taskGraph.whenReady { taskGraph ->+ taskGraph.getAllTasks().each() { task ->+ if(['validateReleaseSigning', 'validateSigningRelease', 'validateSigningArmv7Release', 'validateSigningX76Release'].contains(task.name)) {+ promptForReleaseKeyPassword()+ }+ }+}++def addSigningProps(propsFilePath, signingConfig) {+ def propsFile = file(propsFilePath)+ def props = new Properties()+ propsFile.withReader { reader ->+ props.load(reader)+ }++ def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))+ if (!storeFile.isAbsolute()) {+ storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())+ }+ if (!storeFile.exists()) {+ throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())+ }+ signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')+ signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))+ signingConfig.storeFile = storeFile+ signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))+ def storeType = props.get('storeType', props.get('key.store.type', ''))+ if (!storeType) {+ def filename = storeFile.getName().toLowerCase();+ if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {+ storeType = 'pkcs12'+ } else {+ storeType = signingConfig.storeType // "jks"+ }+ }+ signingConfig.storeType = storeType+}++for (def func : cdvPluginPostBuildExtras) {+ func()+}++// This can be defined within build-extras.gradle as:+// ext.postBuildExtras = { ... code here ... }+if (hasProperty('postBuildExtras')) {+ postBuildExtras()+}diff --git a/cordova/platforms/android/AndroidManifest.xml b/cordova/platforms/android/app/src/main/AndroidManifest.xmlsimilarity index 70%rename from cordova/platforms/android/AndroidManifest.xmlrename to cordova/platforms/android/app/src/main/AndroidManifest.xmlindex 60643c35d..f09fe2131 100644--- a/cordova/platforms/android/AndroidManifest.xml+++ b/cordova/platforms/android/app/src/main/AndroidManifest.xml@@ -3,15 +3,12 @@<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" /><uses-permission android:name="android.permission.INTERNET" /><application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">- <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:resizeableActivity="true" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">+ <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize"><intent-filter android:label="@string/launcher_name"><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application>- <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />- <uses-feature android:name="android.hardware.touchscreen" android:required="false" />+ <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" /></manifest>diff --git a/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/android/nativeapiprovider.js b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/android/nativeapiprovider.jsnew file mode 100644index 000000000..2e9aa67bb--- /dev/null+++ b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/android/nativeapiprovider.js@@ -0,0 +1,36 @@+/*+ * 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.+*/++/**+ * Exports the ExposedJsApi.java object if available, otherwise exports the PromptBasedNativeApi.+ */++var nativeApi = this._cordovaNative || require('cordova/android/promptbasednativeapi');+var currentApi = nativeApi;++module.exports = {+ get: function() { return currentApi; },+ setPreferPrompt: function(value) {+ currentApi = value ? require('cordova/android/promptbasednativeapi') : nativeApi;+ },+ // Used only by tests.+ set: function(value) {+ currentApi = value;+ }+};diff --git a/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/android/promptbasednativeapi.js b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/android/promptbasednativeapi.jsnew file mode 100644index 000000000..f7fb6bc7f--- /dev/null+++ b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/android/promptbasednativeapi.js@@ -0,0 +1,35 @@+/*+ * 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.+*/++/**+ * Implements the API of ExposedJsApi.java, but uses prompt() to communicate.+ * This is used pre-JellyBean, where addJavascriptInterface() is disabled.+ */++module.exports = {+ exec: function(bridgeSecret, service, action, callbackId, argsJson) {+ return prompt(argsJson, 'gap:'+JSON.stringify([bridgeSecret, service, action, callbackId]));+ },+ setNativeToJsBridgeMode: function(bridgeSecret, value) {+ prompt(value, 'gap_bridge_mode:' + bridgeSecret);+ },+ retrieveJsMessages: function(bridgeSecret, fromOnlineEvent) {+ return prompt(+fromOnlineEvent, 'gap_poll:' + bridgeSecret);+ }+};diff --git a/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/exec.js b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/exec.jsnew file mode 100644index 000000000..f73d87a12--- /dev/null+++ b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/exec.js@@ -0,0 +1,297 @@+/*+ *+ * 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.+ *+*/++/**+ * Execute a cordova command. It is up to the native side whether this action+ * is synchronous or asynchronous. The native side can return:+ * Synchronous: PluginResult object as a JSON string+ * Asynchronous: Empty string ""+ * If async, the native side will cordova.callbackSuccess or cordova.callbackError,+ * depending upon the result of the action.+ *+ * @param {Function} success The success callback+ * @param {Function} fail The fail callback+ * @param {String} service The name of the service to use+ * @param {String} action Action to be run in cordova+ * @param {String[]} [args] Zero or more arguments to pass to the method+ */+var cordova = require('cordova'),+ nativeApiProvider = require('cordova/android/nativeapiprovider'),+ utils = require('cordova/utils'),+ base64 = require('cordova/base64'),+ channel = require('cordova/channel'),+ jsToNativeModes = {+ PROMPT: 0,+ JS_OBJECT: 1+ },+ nativeToJsModes = {+ // Polls for messages using the JS->Native bridge.+ POLLING: 0,+ // For LOAD_URL to be viable, it would need to have a work-around for+ // the bug where the soft-keyboard gets dismissed when a message is sent.+ LOAD_URL: 1,+ // For the ONLINE_EVENT to be viable, it would need to intercept all event+ // listeners (both through addEventListener and window.ononline) as well+ // as set the navigator property itself.+ ONLINE_EVENT: 2,+ EVAL_BRIDGE: 3+ },+ jsToNativeBridgeMode, // Set lazily.+ nativeToJsBridgeMode = nativeToJsModes.EVAL_BRIDGE,+ pollEnabled = false,+ bridgeSecret = -1;++var messagesFromNative = [];+var isProcessing = false;+var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();+var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };++function androidExec(success, fail, service, action, args) {+ if (bridgeSecret < 0) {+ // If we ever catch this firing, we'll need to queue up exec()s+ // and fire them once we get a secret. For now, I don't think+ // it's possible for exec() to be called since plugins are parsed but+ // not run until until after onNativeReady.+ throw new Error('exec() called without bridgeSecret');+ }+ // Set default bridge modes if they have not already been set.+ // By default, we use the failsafe, since addJavascriptInterface breaks too often+ if (jsToNativeBridgeMode === undefined) {+ androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);+ }++ // If args is not provided, default to an empty array+ args = args || [];++ // Process any ArrayBuffers in the args into a string.+ for (var i = 0; i < args.length; i++) {+ if (utils.typeName(args[i]) == 'ArrayBuffer') {+ args[i] = base64.fromArrayBuffer(args[i]);+ }+ }++ var callbackId = service + cordova.callbackId++,+ argsJson = JSON.stringify(args);+ if (success || fail) {+ cordova.callbacks[callbackId] = {success:success, fail:fail};+ }++ var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);+ // If argsJson was received by Java as null, try again with the PROMPT bridge mode.+ // This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.+ if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "@Null arguments.") {+ androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);+ androidExec(success, fail, service, action, args);+ androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);+ } else if (msgs) {+ messagesFromNative.push(msgs);+ // Always process async to avoid exceptions messing up stack.+ nextTick(processMessages);+ }+}++androidExec.init = function() {+ //CB-11828+ //This failsafe checks the version of Android and if it's Jellybean, it switches it to+ //using the Online Event bridge for communicating from Native to JS+ //+ //It's ugly, but it's necessary.+ var check = navigator.userAgent.toLowerCase().match(/android\s[0-9].[0-9]/);+ var version_code = check && check[0].match(/4.[0-3].*/);+ if (version_code != null && nativeToJsBridgeMode == nativeToJsModes.EVAL_BRIDGE) {+ nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT;+ }++ bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode);+ channel.onNativeReady.fire();+};++function pollOnceFromOnlineEvent() {+ pollOnce(true);+}++function pollOnce(opt_fromOnlineEvent) {+ if (bridgeSecret < 0) {+ // This can happen when the NativeToJsMessageQueue resets the online state on page transitions.+ // We know there's nothing to retrieve, so no need to poll.+ return;+ }+ var msgs = nativeApiProvider.get().retrieveJsMessages(bridgeSecret, !!opt_fromOnlineEvent);+ if (msgs) {+ messagesFromNative.push(msgs);+ // Process sync since we know we're already top-of-stack.+ processMessages();+ }+}++function pollingTimerFunc() {+ if (pollEnabled) {+ pollOnce();+ setTimeout(pollingTimerFunc, 50);+ }+}++function hookOnlineApis() {+ function proxyEvent(e) {+ cordova.fireWindowEvent(e.type);+ }+ // The network module takes care of firing online and offline events.+ // It currently fires them only on document though, so we bridge them+ // to window here (while first listening for exec()-releated online/offline+ // events).+ window.addEventListener('online', pollOnceFromOnlineEvent, false);+ window.addEventListener('offline', pollOnceFromOnlineEvent, false);+ cordova.addWindowEventHandler('online');+ cordova.addWindowEventHandler('offline');+ document.addEventListener('online', proxyEvent, false);+ document.addEventListener('offline', proxyEvent, false);+}++hookOnlineApis();++androidExec.jsToNativeModes = jsToNativeModes;+androidExec.nativeToJsModes = nativeToJsModes;++androidExec.setJsToNativeBridgeMode = function(mode) {+ if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) {+ mode = jsToNativeModes.PROMPT;+ }+ nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT);+ jsToNativeBridgeMode = mode;+};++androidExec.setNativeToJsBridgeMode = function(mode) {+ if (mode == nativeToJsBridgeMode) {+ return;+ }+ if (nativeToJsBridgeMode == nativeToJsModes.POLLING) {+ pollEnabled = false;+ }++ nativeToJsBridgeMode = mode;+ // Tell the native side to switch modes.+ // Otherwise, it will be set by androidExec.init()+ if (bridgeSecret >= 0) {+ nativeApiProvider.get().setNativeToJsBridgeMode(bridgeSecret, mode);+ }++ if (mode == nativeToJsModes.POLLING) {+ pollEnabled = true;+ setTimeout(pollingTimerFunc, 1);+ }+};++function buildPayload(payload, message) {+ var payloadKind = message.charAt(0);+ if (payloadKind == 's') {+ payload.push(message.slice(1));+ } else if (payloadKind == 't') {+ payload.push(true);+ } else if (payloadKind == 'f') {+ payload.push(false);+ } else if (payloadKind == 'N') {+ payload.push(null);+ } else if (payloadKind == 'n') {+ payload.push(+message.slice(1));+ } else if (payloadKind == 'A') {+ var data = message.slice(1);+ payload.push(base64.toArrayBuffer(data));+ } else if (payloadKind == 'S') {+ payload.push(window.atob(message.slice(1)));+ } else if (payloadKind == 'M') {+ var multipartMessages = message.slice(1);+ while (multipartMessages !== "") {+ var spaceIdx = multipartMessages.indexOf(' ');+ var msgLen = +multipartMessages.slice(0, spaceIdx);+ var multipartMessage = multipartMessages.substr(spaceIdx + 1, msgLen);+ multipartMessages = multipartMessages.slice(spaceIdx + msgLen + 1);+ buildPayload(payload, multipartMessage);+ }+ } else {+ payload.push(JSON.parse(message));+ }+}++// Processes a single message, as encoded by NativeToJsMessageQueue.java.+function processMessage(message) {+ var firstChar = message.charAt(0);+ if (firstChar == 'J') {+ // This is deprecated on the .java side. It doesn't work with CSP enabled.+ eval(message.slice(1));+ } else if (firstChar == 'S' || firstChar == 'F') {+ var success = firstChar == 'S';+ var keepCallback = message.charAt(1) == '1';+ var spaceIdx = message.indexOf(' ', 2);+ var status = +message.slice(2, spaceIdx);+ var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);+ var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);+ var payloadMessage = message.slice(nextSpaceIdx + 1);+ var payload = [];+ buildPayload(payload, payloadMessage);+ cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);+ } else {+ console.log("processMessage failed: invalid message: " + JSON.stringify(message));+ }+}++function processMessages() {+ // Check for the reentrant case.+ if (isProcessing) {+ return;+ }+ if (messagesFromNative.length === 0) {+ return;+ }+ isProcessing = true;+ try {+ var msg = popMessageFromQueue();+ // The Java side can send a * message to indicate that it+ // still has messages waiting to be retrieved.+ if (msg == '*' && messagesFromNative.length === 0) {+ nextTick(pollOnce);+ return;+ }+ processMessage(msg);+ } finally {+ isProcessing = false;+ if (messagesFromNative.length > 0) {+ nextTick(processMessages);+ }+ }+}++function popMessageFromQueue() {+ var messageBatch = messagesFromNative.shift();+ if (messageBatch == '*') {+ return '*';+ }++ var spaceIdx = messageBatch.indexOf(' ');+ var msgLen = +messageBatch.slice(0, spaceIdx);+ var message = messageBatch.substr(spaceIdx + 1, msgLen);+ messageBatch = messageBatch.slice(spaceIdx + msgLen + 1);+ if (messageBatch) {+ messagesFromNative.unshift(messageBatch);+ }+ return message;+}++module.exports = androidExec;diff --git a/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/platform.js b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/platform.jsnew file mode 100644index 000000000..2bfd02471--- /dev/null+++ b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/platform.js@@ -0,0 +1,125 @@+/*+ *+ * 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.+ *+*/++// The last resume event that was received that had the result of a plugin call.+var lastResumeEvent = null;++module.exports = {+ id: 'android',+ bootstrap: function() {+ var channel = require('cordova/channel'),+ cordova = require('cordova'),+ exec = require('cordova/exec'),+ modulemapper = require('cordova/modulemapper');++ // Get the shared secret needed to use the bridge.+ exec.init();++ // TODO: Extract this as a proper plugin.+ modulemapper.clobbers('cordova/plugin/android/app', 'navigator.app');++ var APP_PLUGIN_NAME = Number(cordova.platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App';++ // Inject a listener for the backbutton on the document.+ var backButtonChannel = cordova.addDocumentEventHandler('backbutton');+ backButtonChannel.onHasSubscribersChange = function() {+ // If we just attached the first handler or detached the last handler,+ // let native know we need to override the back button.+ exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [this.numHandlers == 1]);+ };++ // Add hardware MENU and SEARCH button handlers+ cordova.addDocumentEventHandler('menubutton');+ cordova.addDocumentEventHandler('searchbutton');++ function bindButtonChannel(buttonName) {+ // generic button bind used for volumeup/volumedown buttons+ var volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button');+ volumeButtonChannel.onHasSubscribersChange = function() {+ exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]);+ };+ }+ // Inject a listener for the volume buttons on the document.+ bindButtonChannel('volumeup');+ bindButtonChannel('volumedown');++ // The resume event is not "sticky", but it is possible that the event+ // will contain the result of a plugin call. We need to ensure that the+ // plugin result is delivered even after the event is fired (CB-10498)+ var cordovaAddEventListener = document.addEventListener;++ document.addEventListener = function(evt, handler, capture) {+ cordovaAddEventListener(evt, handler, capture);++ if (evt === 'resume' && lastResumeEvent) {+ handler(lastResumeEvent);+ }+ };++ // Let native code know we are all done on the JS side.+ // Native code will then un-hide the WebView.+ channel.onCordovaReady.subscribe(function() {+ exec(onMessageFromNative, null, APP_PLUGIN_NAME, 'messageChannel', []);+ exec(null, null, APP_PLUGIN_NAME, "show", []);+ });+ }+};++function onMessageFromNative(msg) {+ var cordova = require('cordova');+ var action = msg.action;++ switch (action)+ {+ // Button events+ case 'backbutton':+ case 'menubutton':+ case 'searchbutton':+ // App life cycle events+ case 'pause':+ // Volume events+ case 'volumedownbutton':+ case 'volumeupbutton':+ cordova.fireDocumentEvent(action);+ break;+ case 'resume':+ if(arguments.length > 1 && msg.pendingResult) {+ if(arguments.length === 2) {+ msg.pendingResult.result = arguments[1];+ } else {+ // The plugin returned a multipart message+ var res = [];+ for(var i = 1; i < arguments.length; i++) {+ res.push(arguments[i]);+ }+ msg.pendingResult.result = res;+ }++ // Save the plugin result so that it can be delivered to the js+ // even if they miss the initial firing of the event+ lastResumeEvent = msg;+ }+ cordova.fireDocumentEvent(action, msg);+ break;+ default:+ throw new Error('Unknown event action ' + action);+ }+}diff --git a/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/plugin/android/app.js b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/plugin/android/app.jsnew file mode 100644index 000000000..22cf96e81--- /dev/null+++ b/cordova/platforms/android/app/src/main/assets/www/cordova-js-src/plugin/android/app.js@@ -0,0 +1,108 @@+/*+ *+ * 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 exec = require('cordova/exec');+var APP_PLUGIN_NAME = Number(require('cordova').platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App';++module.exports = {+ /**+ * Clear the resource cache.+ */+ clearCache:function() {+ exec(null, null, APP_PLUGIN_NAME, "clearCache", []);+ },++ /**+ * Load the url into the webview or into new browser instance.+ *+ * @param url The URL to load+ * @param props Properties that can be passed in to the activity:+ * wait: int => wait msec before loading URL+ * loadingDialog: "Title,Message" => display a native loading dialog+ * loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error+ * clearHistory: boolean => clear webview history (default=false)+ * openExternal: boolean => open in a new browser (default=false)+ *+ * Example:+ * navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});+ */+ loadUrl:function(url, props) {+ exec(null, null, APP_PLUGIN_NAME, "loadUrl", [url, props]);+ },++ /**+ * Cancel loadUrl that is waiting to be loaded.+ */+ cancelLoadUrl:function() {+ exec(null, null, APP_PLUGIN_NAME, "cancelLoadUrl", []);+ },++ /**+ * Clear web history in this web view.+ * Instead of BACK button loading the previous web page, it will exit the app.+ */+ clearHistory:function() {+ exec(null, null, APP_PLUGIN_NAME, "clearHistory", []);+ },++ /**+ * Go to previous page displayed.+ * This is the same as pressing the backbutton on Android device.+ */+ backHistory:function() {+ exec(null, null, APP_PLUGIN_NAME, "backHistory", []);+ },++ /**+ * Override the default behavior of the Android back button.+ * If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired.+ *+ * Note: The user should not have to call this method. Instead, when the user+ * registers for the "backbutton" event, this is automatically done.+ *+ * @param override T=override, F=cancel override+ */+ overrideBackbutton:function(override) {+ exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [override]);+ },++ /**+ * Override the default behavior of the Android volume button.+ * If overridden, when the volume button is pressed, the "volume[up|down]button"+ * JavaScript event will be fired.+ *+ * Note: The user should not have to call this method. Instead, when the user+ * registers for the "volume[up|down]button" event, this is automatically done.+ *+ * @param button volumeup, volumedown+ * @param override T=override, F=cancel override+ */+ overrideButton:function(button, override) {+ exec(null, null, APP_PLUGIN_NAME, "overrideButton", [button, override]);+ },++ /**+ * Exit and terminate the application.+ */+ exitApp:function() {+ return exec(null, null, APP_PLUGIN_NAME, "exitApp", []);+ }+};diff --git a/cordova/platforms/android/app/src/main/assets/www/cordova.js b/cordova/platforms/android/app/src/main/assets/www/cordova.jsnew file mode 100644index 000000000..a9f8bb0dd--- /dev/null+++ b/cordova/platforms/android/app/src/main/assets/www/cordova.js@@ -0,0 +1,2189 @@+// Platform: android+// 9e8e1b716252c4a08abcd31a13013b868d6f4141+/*+ 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.+*/+;(function() {+var PLATFORM_VERSION_BUILD_LABEL = '7.1.2';+// file: src/scripts/require.js++/* jshint -W079 */+/* jshint -W020 */++var require;+var define;++(function () {+ var modules = {};+ // Stack of moduleIds currently being built.+ var requireStack = [];+ // Map of module ID -> index into requireStack of modules currently being built.+ var inProgressModules = {};+ var SEPARATOR = '.';++ function build (module) {+ var factory = module.factory;+ var localRequire = function (id) {+ var resultantId = id;+ // Its a relative path, so lop off the last portion and add the id (minus "./")+ if (id.charAt(0) === '.') {+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2);+ }+ return require(resultantId);+ };+ module.exports = {};+ delete module.factory;+ factory(localRequire, module.exports, module);+ return module.exports;+ }++ require = function (id) {+ if (!modules[id]) {+ throw 'module ' + id + ' not found';+ } else if (id in inProgressModules) {+ var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;+ throw 'Cycle in require graph: ' + cycle;+ }+ if (modules[id].factory) {+ try {+ inProgressModules[id] = requireStack.length;+ requireStack.push(id);+ return build(modules[id]);+ } finally {+ delete inProgressModules[id];+ requireStack.pop();+ }+ }+ return modules[id].exports;+ };++ define = function (id, factory) {+ if (modules[id]) {+ throw 'module ' + id + ' already defined';+ }++ modules[id] = {+ id: id,+ factory: factory+ };+ };++ define.remove = function (id) {+ delete modules[id];+ };++ define.moduleMap = modules;+})();++// Export for use in node+if (typeof module === 'object' && typeof require === 'function') {+ module.exports.require = require;+ module.exports.define = define;+}++// file: src/cordova.js+define("cordova", function(require, exports, module) {++// Workaround for Windows 10 in hosted environment case+// http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object+if (window.cordova && !(window.cordova instanceof HTMLElement)) { // eslint-disable-line no-undef+ throw new Error('cordova already defined');+}++var channel = require('cordova/channel');+var platform = require('cordova/platform');++/**+ * Intercept calls to addEventListener + removeEventListener and handle deviceready,+ * resume, and pause events.+ */+var m_document_addEventListener = document.addEventListener;+var m_document_removeEventListener = document.removeEventListener;+var m_window_addEventListener = window.addEventListener;+var m_window_removeEventListener = window.removeEventListener;++/**+ * Houses custom event handlers to intercept on document + window event listeners.+ */+var documentEventHandlers = {};+var windowEventHandlers = {};++document.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].subscribe(handler);+ } else {+ m_document_addEventListener.call(document, evt, handler, capture);+ }+};++window.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].subscribe(handler);+ } else {+ m_window_addEventListener.call(window, evt, handler, capture);+ }+};++document.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].unsubscribe(handler);+ } else {+ m_document_removeEventListener.call(document, evt, handler, capture);+ }+};++window.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].unsubscribe(handler);+ } else {+ m_window_removeEventListener.call(window, evt, handler, capture);+ }+};++function createEvent (type, data) {+ var event = document.createEvent('Events');+ event.initEvent(type, false, false);+ if (data) {+ for (var i in data) {+ if (data.hasOwnProperty(i)) {+ event[i] = data[i];+ }+ }+ }+ return event;+}++/* eslint-disable no-undef */+var cordova = {+ define: define,+ require: require,+ version: PLATFORM_VERSION_BUILD_LABEL,+ platformVersion: PLATFORM_VERSION_BUILD_LABEL,+ platformId: platform.id,++ /* eslint-enable no-undef */++ /**+ * Methods to add/remove your own addEventListener hijacking on document + window.+ */+ addWindowEventHandler: function (event) {+ return (windowEventHandlers[event] = channel.create(event));+ },+ addStickyDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.createSticky(event));+ },+ addDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.create(event));+ },+ removeWindowEventHandler: function (event) {+ delete windowEventHandlers[event];+ },+ removeDocumentEventHandler: function (event) {+ delete documentEventHandlers[event];+ },+ /**+ * Retrieve original event handlers that were replaced by Cordova+ *+ * @return object+ */+ getOriginalHandlers: function () {+ return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},+ 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};+ },+ /**+ * Method to fire event from native code+ * bNoDetach is required for events which cause an exception which needs to be caught in native code+ */+ fireDocumentEvent: function (type, data, bNoDetach) {+ var evt = createEvent(type, data);+ if (typeof documentEventHandlers[type] !== 'undefined') {+ if (bNoDetach) {+ documentEventHandlers[type].fire(evt);+ } else {+ setTimeout(function () {+ // Fire deviceready on listeners that were registered before cordova.js was loaded.+ if (type === 'deviceready') {+ document.dispatchEvent(evt);+ }+ documentEventHandlers[type].fire(evt);+ }, 0);+ }+ } else {+ document.dispatchEvent(evt);+ }+ },+ fireWindowEvent: function (type, data) {+ var evt = createEvent(type, data);+ if (typeof windowEventHandlers[type] !== 'undefined') {+ setTimeout(function () {+ windowEventHandlers[type].fire(evt);+ }, 0);+ } else {+ window.dispatchEvent(evt);+ }+ },++ /**+ * Plugin callback mechanism.+ */+ // Randomize the starting callbackId to avoid collisions after refreshing or navigating.+ // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.+ callbackId: Math.floor(Math.random() * 2000000000),+ callbacks: {},+ callbackStatus: {+ NO_RESULT: 0,+ OK: 1,+ CLASS_NOT_FOUND_EXCEPTION: 2,+ ILLEGAL_ACCESS_EXCEPTION: 3,+ INSTANTIATION_EXCEPTION: 4,+ MALFORMED_URL_EXCEPTION: 5,+ IO_EXCEPTION: 6,+ INVALID_ACTION: 7,+ JSON_EXCEPTION: 8,+ ERROR: 9+ },++ /**+ * Called by native code when returning successful result from an action.+ */+ callbackSuccess: function (callbackId, args) {+ cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning error result from an action.+ */+ callbackError: function (callbackId, args) {+ // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.+ // Derive success from status.+ cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning the result from an action.+ */+ callbackFromNative: function (callbackId, isSuccess, status, args, keepCallback) {+ try {+ var callback = cordova.callbacks[callbackId];+ if (callback) {+ if (isSuccess && status === cordova.callbackStatus.OK) {+ callback.success && callback.success.apply(null, args);+ } else if (!isSuccess) {+ callback.fail && callback.fail.apply(null, args);+ }+ /*+ else+ Note, this case is intentionally not caught.+ this can happen if isSuccess is true, but callbackStatus is NO_RESULT+ which is used to remove a callback from the list without calling the callbacks+ typically keepCallback is false in this case+ */+ // Clear callback if not expecting any more results+ if (!keepCallback) {+ delete cordova.callbacks[callbackId];+ }+ }+ } catch (err) {+ var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;+ console && console.log && console.log(msg);+ console && console.log && err.stack && console.log(err.stack);+ cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ throw err;+ }+ },+ addConstructor: function (func) {+ channel.onCordovaReady.subscribe(function () {+ try {+ func();+ } catch (e) {+ console.log('Failed to run constructor: ' + e);+ }+ });+ }+};++module.exports = cordova;++});++// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/android/nativeapiprovider.js+define("cordova/android/nativeapiprovider", function(require, exports, module) {++/**+ * Exports the ExposedJsApi.java object if available, otherwise exports the PromptBasedNativeApi.+ */++var nativeApi = this._cordovaNative || require('cordova/android/promptbasednativeapi');+var currentApi = nativeApi;++module.exports = {+ get: function() { return currentApi; },+ setPreferPrompt: function(value) {+ currentApi = value ? require('cordova/android/promptbasednativeapi') : nativeApi;+ },+ // Used only by tests.+ set: function(value) {+ currentApi = value;+ }+};++});++// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/android/promptbasednativeapi.js+define("cordova/android/promptbasednativeapi", function(require, exports, module) {++/**+ * Implements the API of ExposedJsApi.java, but uses prompt() to communicate.+ * This is used pre-JellyBean, where addJavascriptInterface() is disabled.+ */++module.exports = {+ exec: function(bridgeSecret, service, action, callbackId, argsJson) {+ return prompt(argsJson, 'gap:'+JSON.stringify([bridgeSecret, service, action, callbackId]));+ },+ setNativeToJsBridgeMode: function(bridgeSecret, value) {+ prompt(value, 'gap_bridge_mode:' + bridgeSecret);+ },+ retrieveJsMessages: function(bridgeSecret, fromOnlineEvent) {+ return prompt(+fromOnlineEvent, 'gap_poll:' + bridgeSecret);+ }+};++});++// file: src/common/argscheck.js+define("cordova/argscheck", function(require, exports, module) {++var utils = require('cordova/utils');++var moduleExports = module.exports;++var typeMap = {+ 'A': 'Array',+ 'D': 'Date',+ 'N': 'Number',+ 'S': 'String',+ 'F': 'Function',+ 'O': 'Object'+};++function extractParamName (callee, argIndex) {+ return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];+}++function checkArgs (spec, functionName, args, opt_callee) {+ if (!moduleExports.enableChecks) {+ return;+ }+ var errMsg = null;+ var typeName;+ for (var i = 0; i < spec.length; ++i) {+ var c = spec.charAt(i);+ var cUpper = c.toUpperCase();+ var arg = args[i];+ // Asterix means allow anything.+ if (c === '*') {+ continue;+ }+ typeName = utils.typeName(arg);+ if ((arg === null || arg === undefined) && c === cUpper) {+ continue;+ }+ if (typeName !== typeMap[cUpper]) {+ errMsg = 'Expected ' + typeMap[cUpper];+ break;+ }+ }+ if (errMsg) {+ errMsg += ', but got ' + typeName + '.';+ errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;+ // Don't log when running unit tests.+ if (typeof jasmine === 'undefined') {+ console.error(errMsg);+ }+ throw TypeError(errMsg);+ }+}++function getValue (value, defaultValue) {+ return value === undefined ? defaultValue : value;+}++moduleExports.checkArgs = checkArgs;+moduleExports.getValue = getValue;+moduleExports.enableChecks = true;++});++// file: src/common/base64.js+define("cordova/base64", function(require, exports, module) {++var base64 = exports;++base64.fromArrayBuffer = function (arrayBuffer) {+ var array = new Uint8Array(arrayBuffer);+ return uint8ToBase64(array);+};++base64.toArrayBuffer = function (str) {+ var decodedStr = typeof atob !== 'undefined' ? atob(str) : Buffer.from(str, 'base64').toString('binary'); // eslint-disable-line no-undef+ var arrayBuffer = new ArrayBuffer(decodedStr.length);+ var array = new Uint8Array(arrayBuffer);+ for (var i = 0, len = decodedStr.length; i < len; i++) {+ array[i] = decodedStr.charCodeAt(i);+ }+ return arrayBuffer;+};++// ------------------------------------------------------------------------------++/* This code is based on the performance tests at http://jsperf.com/b64tests+ * This 12-bit-at-a-time algorithm was the best performing version on all+ * platforms tested.+ */++var b64_6bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';+var b64_12bit;++var b64_12bitTable = function () {+ b64_12bit = [];+ for (var i = 0; i < 64; i++) {+ for (var j = 0; j < 64; j++) {+ b64_12bit[i * 64 + j] = b64_6bit[i] + b64_6bit[j];+ }+ }+ b64_12bitTable = function () { return b64_12bit; };+ return b64_12bit;+};++function uint8ToBase64 (rawData) {+ var numBytes = rawData.byteLength;+ var output = '';+ var segment;+ var table = b64_12bitTable();+ for (var i = 0; i < numBytes - 2; i += 3) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8) + rawData[i + 2];+ output += table[segment >> 12];+ output += table[segment & 0xfff];+ }+ if (numBytes - i === 2) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8);+ output += table[segment >> 12];+ output += b64_6bit[(segment & 0xfff) >> 6];+ output += '=';+ } else if (numBytes - i === 1) {+ segment = (rawData[i] << 16);+ output += table[segment >> 12];+ output += '==';+ }+ return output;+}++});++// file: src/common/builder.js+define("cordova/builder", function(require, exports, module) {++var utils = require('cordova/utils');++function each (objects, func, context) {+ for (var prop in objects) {+ if (objects.hasOwnProperty(prop)) {+ func.apply(context, [objects[prop], prop]);+ }+ }+}++function clobber (obj, key, value) {+ exports.replaceHookForTesting(obj, key);+ var needsProperty = false;+ try {+ obj[key] = value;+ } catch (e) {+ needsProperty = true;+ }+ // Getters can only be overridden by getters.+ if (needsProperty || obj[key] !== value) {+ utils.defineGetter(obj, key, function () {+ return value;+ });+ }+}++function assignOrWrapInDeprecateGetter (obj, key, value, message) {+ if (message) {+ utils.defineGetter(obj, key, function () {+ console.log(message);+ delete obj[key];+ clobber(obj, key, value);+ return value;+ });+ } else {+ clobber(obj, key, value);+ }+}++function include (parent, objects, clobber, merge) {+ each(objects, function (obj, key) {+ try {+ var result = obj.path ? require(obj.path) : {};++ if (clobber) {+ // Clobber if it doesn't exist.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else if (typeof obj.path !== 'undefined') {+ // If merging, merge properties onto parent, otherwise, clobber.+ if (merge) {+ recursiveMerge(parent[key], result);+ } else {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ }+ }+ result = parent[key];+ } else {+ // Overwrite if not currently defined.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else {+ // Set result to what already exists, so we can build children into it if they exist.+ result = parent[key];+ }+ }++ if (obj.children) {+ include(result, obj.children, clobber, merge);+ }+ } catch (e) {+ utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');+ }+ });+}++/**+ * Merge properties from one object onto another recursively. Properties from+ * the src object will overwrite existing target property.+ *+ * @param target Object to merge properties into.+ * @param src Object to merge properties from.+ */+function recursiveMerge (target, src) {+ for (var prop in src) {+ if (src.hasOwnProperty(prop)) {+ if (target.prototype && target.prototype.constructor === target) {+ // If the target object is a constructor override off prototype.+ clobber(target.prototype, prop, src[prop]);+ } else {+ if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {+ recursiveMerge(target[prop], src[prop]);+ } else {+ clobber(target, prop, src[prop]);+ }+ }+ }+ }+}++exports.buildIntoButDoNotClobber = function (objects, target) {+ include(target, objects, false, false);+};+exports.buildIntoAndClobber = function (objects, target) {+ include(target, objects, true, false);+};+exports.buildIntoAndMerge = function (objects, target) {+ include(target, objects, true, true);+};+exports.recursiveMerge = recursiveMerge;+exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;+exports.replaceHookForTesting = function () {};++});++// file: src/common/channel.js+define("cordova/channel", function(require, exports, module) {++var utils = require('cordova/utils');+var nextGuid = 1;++/**+ * Custom pub-sub "channel" that can have functions subscribed to it+ * This object is used to define and control firing of events for+ * cordova initialization, as well as for custom events thereafter.+ *+ * The order of events during page load and Cordova startup is as follows:+ *+ * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.+ * onNativeReady* Internal event that indicates the Cordova native side is ready.+ * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.+ * onDeviceReady* User event fired to indicate that Cordova is ready+ * onResume User event fired to indicate a start/resume lifecycle event+ * onPause User event fired to indicate a pause lifecycle event+ *+ * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.+ * All listeners that subscribe after the event is fired will be executed right away.+ *+ * The only Cordova events that user code should register for are:+ * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript+ * pause App has moved to background+ * resume App has returned to foreground+ *+ * Listeners can be registered as:+ * document.addEventListener("deviceready", myDeviceReadyListener, false);+ * document.addEventListener("resume", myResumeListener, false);+ * document.addEventListener("pause", myPauseListener, false);+ *+ * The DOM lifecycle events should be used for saving and restoring state+ * window.onload+ * window.onunload+ *+ */++/**+ * Channel+ * @constructor+ * @param type String the channel name+ */+var Channel = function (type, sticky) {+ this.type = type;+ // Map of guid -> function.+ this.handlers = {};+ // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.+ this.state = sticky ? 1 : 0;+ // Used in sticky mode to remember args passed to fire().+ this.fireArgs = null;+ // Used by onHasSubscribersChange to know if there are any listeners.+ this.numHandlers = 0;+ // Function that is called when the first listener is subscribed, or when+ // the last listener is unsubscribed.+ this.onHasSubscribersChange = null;+};+var channel = {+ /**+ * Calls the provided function only after all of the channels specified+ * have been fired. All channels must be sticky channels.+ */+ join: function (h, c) {+ var len = c.length;+ var i = len;+ var f = function () {+ if (!(--i)) h();+ };+ for (var j = 0; j < len; j++) {+ if (c[j].state === 0) {+ throw Error('Can only use join with sticky channels.');+ }+ c[j].subscribe(f);+ }+ if (!len) h();+ },+ /* eslint-disable no-return-assign */+ create: function (type) {+ return channel[type] = new Channel(type, false);+ },+ createSticky: function (type) {+ return channel[type] = new Channel(type, true);+ },+ /* eslint-enable no-return-assign */+ /**+ * cordova Channels that must fire before "deviceready" is fired.+ */+ deviceReadyChannelsArray: [],+ deviceReadyChannelsMap: {},++ /**+ * Indicate that a feature needs to be initialized before it is ready to be used.+ * This holds up Cordova's "deviceready" event until the feature has been initialized+ * and Cordova.initComplete(feature) is called.+ *+ * @param feature {String} The unique feature name+ */+ waitForInitialization: function (feature) {+ if (feature) {+ var c = channel[feature] || this.createSticky(feature);+ this.deviceReadyChannelsMap[feature] = c;+ this.deviceReadyChannelsArray.push(c);+ }+ },++ /**+ * Indicate that initialization code has completed and the feature is ready to be used.+ *+ * @param feature {String} The unique feature name+ */+ initializationComplete: function (feature) {+ var c = this.deviceReadyChannelsMap[feature];+ if (c) {+ c.fire();+ }+ }+};++function checkSubscriptionArgument (argument) {+ if (typeof argument !== 'function' && typeof argument.handleEvent !== 'function') {+ throw new Error(+ 'Must provide a function or an EventListener object ' ++ 'implementing the handleEvent interface.'+ );+ }+}++/**+ * Subscribes the given function to the channel. Any time that+ * Channel.fire is called so too will the function.+ * Optionally specify an execution context for the function+ * and a guid that can be used to stop subscribing to the channel.+ * Returns the guid.+ */+Channel.prototype.subscribe = function (eventListenerOrFunction, eventListener) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ eventListener = eventListenerOrFunction;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ if (this.state === 2) {+ handleEvent.apply(eventListener || this, this.fireArgs);+ return;+ }++ guid = eventListenerOrFunction.observer_guid;+ if (typeof eventListener === 'object') {+ handleEvent = utils.close(eventListener, handleEvent);+ }++ if (!guid) {+ // First time any channel has seen this subscriber+ guid = '' + nextGuid++;+ }+ handleEvent.observer_guid = guid;+ eventListenerOrFunction.observer_guid = guid;++ // Don't add the same handler more than once.+ if (!this.handlers[guid]) {+ this.handlers[guid] = handleEvent;+ this.numHandlers++;+ if (this.numHandlers === 1) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Unsubscribes the function with the given guid from the channel.+ */+Channel.prototype.unsubscribe = function (eventListenerOrFunction) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid, handler;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ guid = handleEvent.observer_guid;+ handler = this.handlers[guid];+ if (handler) {+ delete this.handlers[guid];+ this.numHandlers--;+ if (this.numHandlers === 0) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Calls all functions subscribed to this channel.+ */+Channel.prototype.fire = function (e) {+ var fail = false; // eslint-disable-line no-unused-vars+ var fireArgs = Array.prototype.slice.call(arguments);+ // Apply stickiness.+ if (this.state === 1) {+ this.state = 2;+ this.fireArgs = fireArgs;+ }+ if (this.numHandlers) {+ // Copy the values first so that it is safe to modify it from within+ // callbacks.+ var toCall = [];+ for (var item in this.handlers) {+ toCall.push(this.handlers[item]);+ }+ for (var i = 0; i < toCall.length; ++i) {+ toCall[i].apply(this, fireArgs);+ }+ if (this.state === 2 && this.numHandlers) {+ this.numHandlers = 0;+ this.handlers = {};+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++// defining them here so they are ready super fast!+// DOM event that is received when the web page is loaded and parsed.+channel.createSticky('onDOMContentLoaded');++// Event to indicate the Cordova native side is ready.+channel.createSticky('onNativeReady');++// Event to indicate that all Cordova JavaScript objects have been created+// and it's time to run plugin constructors.+channel.createSticky('onCordovaReady');++// Event to indicate that all automatically loaded JS plugins are loaded and ready.+// FIXME remove this+channel.createSticky('onPluginsReady');++// Event to indicate that Cordova is ready+channel.createSticky('onDeviceReady');++// Event to indicate a resume lifecycle event+channel.create('onResume');++// Event to indicate a pause lifecycle event+channel.create('onPause');++// Channels that must fire before "deviceready" is fired.+channel.waitForInitialization('onCordovaReady');+channel.waitForInitialization('onDOMContentLoaded');++module.exports = channel;++});++// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/exec.js+define("cordova/exec", function(require, exports, module) {++/**+ * Execute a cordova command. It is up to the native side whether this action+ * is synchronous or asynchronous. The native side can return:+ * Synchronous: PluginResult object as a JSON string+ * Asynchronous: Empty string ""+ * If async, the native side will cordova.callbackSuccess or cordova.callbackError,+ * depending upon the result of the action.+ *+ * @param {Function} success The success callback+ * @param {Function} fail The fail callback+ * @param {String} service The name of the service to use+ * @param {String} action Action to be run in cordova+ * @param {String[]} [args] Zero or more arguments to pass to the method+ */+var cordova = require('cordova'),+ nativeApiProvider = require('cordova/android/nativeapiprovider'),+ utils = require('cordova/utils'),+ base64 = require('cordova/base64'),+ channel = require('cordova/channel'),+ jsToNativeModes = {+ PROMPT: 0,+ JS_OBJECT: 1+ },+ nativeToJsModes = {+ // Polls for messages using the JS->Native bridge.+ POLLING: 0,+ // For LOAD_URL to be viable, it would need to have a work-around for+ // the bug where the soft-keyboard gets dismissed when a message is sent.+ LOAD_URL: 1,+ // For the ONLINE_EVENT to be viable, it would need to intercept all event+ // listeners (both through addEventListener and window.ononline) as well+ // as set the navigator property itself.+ ONLINE_EVENT: 2,+ EVAL_BRIDGE: 3+ },+ jsToNativeBridgeMode, // Set lazily.+ nativeToJsBridgeMode = nativeToJsModes.EVAL_BRIDGE,+ pollEnabled = false,+ bridgeSecret = -1;++var messagesFromNative = [];+var isProcessing = false;+var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();+var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };++function androidExec(success, fail, service, action, args) {+ if (bridgeSecret < 0) {+ // If we ever catch this firing, we'll need to queue up exec()s+ // and fire them once we get a secret. For now, I don't think+ // it's possible for exec() to be called since plugins are parsed but+ // not run until until after onNativeReady.+ throw new Error('exec() called without bridgeSecret');+ }+ // Set default bridge modes if they have not already been set.+ // By default, we use the failsafe, since addJavascriptInterface breaks too often+ if (jsToNativeBridgeMode === undefined) {+ androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);+ }++ // If args is not provided, default to an empty array+ args = args || [];++ // Process any ArrayBuffers in the args into a string.+ for (var i = 0; i < args.length; i++) {+ if (utils.typeName(args[i]) == 'ArrayBuffer') {+ args[i] = base64.fromArrayBuffer(args[i]);+ }+ }++ var callbackId = service + cordova.callbackId++,+ argsJson = JSON.stringify(args);+ if (success || fail) {+ cordova.callbacks[callbackId] = {success:success, fail:fail};+ }++ var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);+ // If argsJson was received by Java as null, try again with the PROMPT bridge mode.+ // This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.+ if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "@Null arguments.") {+ androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);+ androidExec(success, fail, service, action, args);+ androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);+ } else if (msgs) {+ messagesFromNative.push(msgs);+ // Always process async to avoid exceptions messing up stack.+ nextTick(processMessages);+ }+}++androidExec.init = function() {+ //CB-11828+ //This failsafe checks the version of Android and if it's Jellybean, it switches it to+ //using the Online Event bridge for communicating from Native to JS+ //+ //It's ugly, but it's necessary.+ var check = navigator.userAgent.toLowerCase().match(/android\s[0-9].[0-9]/);+ var version_code = check && check[0].match(/4.[0-3].*/);+ if (version_code != null && nativeToJsBridgeMode == nativeToJsModes.EVAL_BRIDGE) {+ nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT;+ }++ bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode);+ channel.onNativeReady.fire();+};++function pollOnceFromOnlineEvent() {+ pollOnce(true);+}++function pollOnce(opt_fromOnlineEvent) {+ if (bridgeSecret < 0) {+ // This can happen when the NativeToJsMessageQueue resets the online state on page transitions.+ // We know there's nothing to retrieve, so no need to poll.+ return;+ }+ var msgs = nativeApiProvider.get().retrieveJsMessages(bridgeSecret, !!opt_fromOnlineEvent);+ if (msgs) {+ messagesFromNative.push(msgs);+ // Process sync since we know we're already top-of-stack.+ processMessages();+ }+}++function pollingTimerFunc() {+ if (pollEnabled) {+ pollOnce();+ setTimeout(pollingTimerFunc, 50);+ }+}++function hookOnlineApis() {+ function proxyEvent(e) {+ cordova.fireWindowEvent(e.type);+ }+ // The network module takes care of firing online and offline events.+ // It currently fires them only on document though, so we bridge them+ // to window here (while first listening for exec()-releated online/offline+ // events).+ window.addEventListener('online', pollOnceFromOnlineEvent, false);+ window.addEventListener('offline', pollOnceFromOnlineEvent, false);+ cordova.addWindowEventHandler('online');+ cordova.addWindowEventHandler('offline');+ document.addEventListener('online', proxyEvent, false);+ document.addEventListener('offline', proxyEvent, false);+}++hookOnlineApis();++androidExec.jsToNativeModes = jsToNativeModes;+androidExec.nativeToJsModes = nativeToJsModes;++androidExec.setJsToNativeBridgeMode = function(mode) {+ if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) {+ mode = jsToNativeModes.PROMPT;+ }+ nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT);+ jsToNativeBridgeMode = mode;+};++androidExec.setNativeToJsBridgeMode = function(mode) {+ if (mode == nativeToJsBridgeMode) {+ return;+ }+ if (nativeToJsBridgeMode == nativeToJsModes.POLLING) {+ pollEnabled = false;+ }++ nativeToJsBridgeMode = mode;+ // Tell the native side to switch modes.+ // Otherwise, it will be set by androidExec.init()+ if (bridgeSecret >= 0) {+ nativeApiProvider.get().setNativeToJsBridgeMode(bridgeSecret, mode);+ }++ if (mode == nativeToJsModes.POLLING) {+ pollEnabled = true;+ setTimeout(pollingTimerFunc, 1);+ }+};++function buildPayload(payload, message) {+ var payloadKind = message.charAt(0);+ if (payloadKind == 's') {+ payload.push(message.slice(1));+ } else if (payloadKind == 't') {+ payload.push(true);+ } else if (payloadKind == 'f') {+ payload.push(false);+ } else if (payloadKind == 'N') {+ payload.push(null);+ } else if (payloadKind == 'n') {+ payload.push(+message.slice(1));+ } else if (payloadKind == 'A') {+ var data = message.slice(1);+ payload.push(base64.toArrayBuffer(data));+ } else if (payloadKind == 'S') {+ payload.push(window.atob(message.slice(1)));+ } else if (payloadKind == 'M') {+ var multipartMessages = message.slice(1);+ while (multipartMessages !== "") {+ var spaceIdx = multipartMessages.indexOf(' ');+ var msgLen = +multipartMessages.slice(0, spaceIdx);+ var multipartMessage = multipartMessages.substr(spaceIdx + 1, msgLen);+ multipartMessages = multipartMessages.slice(spaceIdx + msgLen + 1);+ buildPayload(payload, multipartMessage);+ }+ } else {+ payload.push(JSON.parse(message));+ }+}++// Processes a single message, as encoded by NativeToJsMessageQueue.java.+function processMessage(message) {+ var firstChar = message.charAt(0);+ if (firstChar == 'J') {+ // This is deprecated on the .java side. It doesn't work with CSP enabled.+ eval(message.slice(1));+ } else if (firstChar == 'S' || firstChar == 'F') {+ var success = firstChar == 'S';+ var keepCallback = message.charAt(1) == '1';+ var spaceIdx = message.indexOf(' ', 2);+ var status = +message.slice(2, spaceIdx);+ var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);+ var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);+ var payloadMessage = message.slice(nextSpaceIdx + 1);+ var payload = [];+ buildPayload(payload, payloadMessage);+ cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);+ } else {+ console.log("processMessage failed: invalid message: " + JSON.stringify(message));+ }+}++function processMessages() {+ // Check for the reentrant case.+ if (isProcessing) {+ return;+ }+ if (messagesFromNative.length === 0) {+ return;+ }+ isProcessing = true;+ try {+ var msg = popMessageFromQueue();+ // The Java side can send a * message to indicate that it+ // still has messages waiting to be retrieved.+ if (msg == '*' && messagesFromNative.length === 0) {+ nextTick(pollOnce);+ return;+ }+ processMessage(msg);+ } finally {+ isProcessing = false;+ if (messagesFromNative.length > 0) {+ nextTick(processMessages);+ }+ }+}++function popMessageFromQueue() {+ var messageBatch = messagesFromNative.shift();+ if (messageBatch == '*') {+ return '*';+ }++ var spaceIdx = messageBatch.indexOf(' ');+ var msgLen = +messageBatch.slice(0, spaceIdx);+ var message = messageBatch.substr(spaceIdx + 1, msgLen);+ messageBatch = messageBatch.slice(spaceIdx + msgLen + 1);+ if (messageBatch) {+ messagesFromNative.unshift(messageBatch);+ }+ return message;+}++module.exports = androidExec;++});++// file: src/common/exec/proxy.js+define("cordova/exec/proxy", function(require, exports, module) {++// internal map of proxy function+var CommandProxyMap = {};++module.exports = {++ // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);+ add: function (id, proxyObj) {+ console.log('adding proxy for ' + id);+ CommandProxyMap[id] = proxyObj;+ return proxyObj;+ },++ // cordova.commandProxy.remove("Accelerometer");+ remove: function (id) {+ var proxy = CommandProxyMap[id];+ delete CommandProxyMap[id];+ CommandProxyMap[id] = null;+ return proxy;+ },++ get: function (service, action) {+ return (CommandProxyMap[service] ? CommandProxyMap[service][action] : null);+ }+};++});++// file: src/common/init.js+define("cordova/init", function(require, exports, module) {++var channel = require('cordova/channel');+var cordova = require('cordova');+var modulemapper = require('cordova/modulemapper');+var platform = require('cordova/platform');+var pluginloader = require('cordova/pluginloader');+var utils = require('cordova/utils');++var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];++function logUnfiredChannels (arr) {+ for (var i = 0; i < arr.length; ++i) {+ if (arr[i].state !== 2) {+ console.log('Channel not fired: ' + arr[i].type);+ }+ }+}++window.setTimeout(function () {+ if (channel.onDeviceReady.state !== 2) {+ console.log('deviceready has not fired after 5 seconds.');+ logUnfiredChannels(platformInitChannelsArray);+ logUnfiredChannels(channel.deviceReadyChannelsArray);+ }+}, 5000);++// Replace navigator before any modules are required(), to ensure it happens as soon as possible.+// We replace it so that properties that can't be clobbered can instead be overridden.+function replaceNavigator (origNavigator) {+ var CordovaNavigator = function () {};+ CordovaNavigator.prototype = origNavigator;+ var newNavigator = new CordovaNavigator();+ // This work-around really only applies to new APIs that are newer than Function.bind.+ // Without it, APIs such as getGamepads() break.+ if (CordovaNavigator.bind) {+ for (var key in origNavigator) {+ if (typeof origNavigator[key] === 'function') {+ newNavigator[key] = origNavigator[key].bind(origNavigator);+ } else {+ (function (k) {+ utils.defineGetterSetter(newNavigator, key, function () {+ return origNavigator[k];+ });+ })(key);+ }+ }+ }+ return newNavigator;+}++if (window.navigator) {+ window.navigator = replaceNavigator(window.navigator);+}++if (!window.console) {+ window.console = {+ log: function () {}+ };+}+if (!window.console.warn) {+ window.console.warn = function (msg) {+ this.log('warn: ' + msg);+ };+}++// Register pause, resume and deviceready channels as events on document.+channel.onPause = cordova.addDocumentEventHandler('pause');+channel.onResume = cordova.addDocumentEventHandler('resume');+channel.onActivated = cordova.addDocumentEventHandler('activated');+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');++// Listen for DOMContentLoaded and notify our channel subscribers.+if (document.readyState === 'complete' || document.readyState === 'interactive') {+ channel.onDOMContentLoaded.fire();+} else {+ document.addEventListener('DOMContentLoaded', function () {+ channel.onDOMContentLoaded.fire();+ }, false);+}++// _nativeReady is global variable that the native side can set+// to signify that the native code is ready. It is a global since+// it may be called before any cordova JS is ready.+if (window._nativeReady) {+ channel.onNativeReady.fire();+}++modulemapper.clobbers('cordova', 'cordova');+modulemapper.clobbers('cordova/exec', 'cordova.exec');+modulemapper.clobbers('cordova/exec', 'Cordova.exec');++// Call the platform-specific initialization.+platform.bootstrap && platform.bootstrap();++// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.+// The delay allows the attached modules to be defined before the plugin loader looks for them.+setTimeout(function () {+ pluginloader.load(function () {+ channel.onPluginsReady.fire();+ });+}, 0);++/**+ * Create all cordova objects once native side is ready.+ */+channel.join(function () {+ modulemapper.mapModules(window);++ platform.initialize && platform.initialize();++ // Fire event to notify that all objects are created+ channel.onCordovaReady.fire();++ // Fire onDeviceReady event once page has fully loaded, all+ // constructors have run and cordova info has been received from native+ // side.+ channel.join(function () {+ require('cordova').fireDocumentEvent('deviceready');+ }, channel.deviceReadyChannelsArray);++}, platformInitChannelsArray);++});++// file: src/common/init_b.js+define("cordova/init_b", function(require, exports, module) {++var channel = require('cordova/channel');+var cordova = require('cordova');+var modulemapper = require('cordova/modulemapper');+var platform = require('cordova/platform');+var pluginloader = require('cordova/pluginloader');+var utils = require('cordova/utils');++var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeReady, channel.onPluginsReady];++// setting exec+cordova.exec = require('cordova/exec');++function logUnfiredChannels (arr) {+ for (var i = 0; i < arr.length; ++i) {+ if (arr[i].state !== 2) {+ console.log('Channel not fired: ' + arr[i].type);+ }+ }+}++window.setTimeout(function () {+ if (channel.onDeviceReady.state !== 2) {+ console.log('deviceready has not fired after 5 seconds.');+ logUnfiredChannels(platformInitChannelsArray);+ logUnfiredChannels(channel.deviceReadyChannelsArray);+ }+}, 5000);++// Replace navigator before any modules are required(), to ensure it happens as soon as possible.+// We replace it so that properties that can't be clobbered can instead be overridden.+function replaceNavigator (origNavigator) {+ var CordovaNavigator = function () {};+ CordovaNavigator.prototype = origNavigator;+ var newNavigator = new CordovaNavigator();+ // This work-around really only applies to new APIs that are newer than Function.bind.+ // Without it, APIs such as getGamepads() break.+ if (CordovaNavigator.bind) {+ for (var key in origNavigator) {+ if (typeof origNavigator[key] === 'function') {+ newNavigator[key] = origNavigator[key].bind(origNavigator);+ } else {+ (function (k) {+ utils.defineGetterSetter(newNavigator, key, function () {+ return origNavigator[k];+ });+ })(key);+ }+ }+ }+ return newNavigator;+}+if (window.navigator) {+ window.navigator = replaceNavigator(window.navigator);+}++if (!window.console) {+ window.console = {+ log: function () {}+ };+}+if (!window.console.warn) {+ window.console.warn = function (msg) {+ this.log('warn: ' + msg);+ };+}++// Register pause, resume and deviceready channels as events on document.+channel.onPause = cordova.addDocumentEventHandler('pause');+channel.onResume = cordova.addDocumentEventHandler('resume');+channel.onActivated = cordova.addDocumentEventHandler('activated');+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');++// Listen for DOMContentLoaded and notify our channel subscribers.+if (document.readyState === 'complete' || document.readyState === 'interactive') {+ channel.onDOMContentLoaded.fire();+} else {+ document.addEventListener('DOMContentLoaded', function () {+ channel.onDOMContentLoaded.fire();+ }, false);+}++// _nativeReady is global variable that the native side can set+// to signify that the native code is ready. It is a global since+// it may be called before any cordova JS is ready.+if (window._nativeReady) {+ channel.onNativeReady.fire();+}++// Call the platform-specific initialization.+platform.bootstrap && platform.bootstrap();++// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.+// The delay allows the attached modules to be defined before the plugin loader looks for them.+setTimeout(function () {+ pluginloader.load(function () {+ channel.onPluginsReady.fire();+ });+}, 0);++/**+ * Create all cordova objects once native side is ready.+ */+channel.join(function () {+ modulemapper.mapModules(window);++ platform.initialize && platform.initialize();++ // Fire event to notify that all objects are created+ channel.onCordovaReady.fire();++ // Fire onDeviceReady event once page has fully loaded, all+ // constructors have run and cordova info has been received from native+ // side.+ channel.join(function () {+ require('cordova').fireDocumentEvent('deviceready');+ }, channel.deviceReadyChannelsArray);++}, platformInitChannelsArray);++});++// file: src/common/modulemapper.js+define("cordova/modulemapper", function(require, exports, module) {++var builder = require('cordova/builder');+var moduleMap = define.moduleMap; // eslint-disable-line no-undef+var symbolList;+var deprecationMap;++exports.reset = function () {+ symbolList = [];+ deprecationMap = {};+};++function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {+ if (!(moduleName in moduleMap)) {+ throw new Error('Module ' + moduleName + ' does not exist.');+ }+ symbolList.push(strategy, moduleName, symbolPath);+ if (opt_deprecationMessage) {+ deprecationMap[symbolPath] = opt_deprecationMessage;+ }+}++// Note: Android 2.3 does have Function.bind().+exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('c', moduleName, symbolPath, opt_deprecationMessage);+};++exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('m', moduleName, symbolPath, opt_deprecationMessage);+};++exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('d', moduleName, symbolPath, opt_deprecationMessage);+};++exports.runs = function (moduleName) {+ addEntry('r', moduleName, null);+};++function prepareNamespace (symbolPath, context) {+ if (!symbolPath) {+ return context;+ }+ var parts = symbolPath.split('.');+ var cur = context;+ for (var i = 0, part; part = parts[i]; ++i) { // eslint-disable-line no-cond-assign+ cur = cur[part] = cur[part] || {};+ }+ return cur;+}++exports.mapModules = function (context) {+ var origSymbols = {};+ context.CDV_origSymbols = origSymbols;+ for (var i = 0, len = symbolList.length; i < len; i += 3) {+ var strategy = symbolList[i];+ var moduleName = symbolList[i + 1];+ var module = require(moduleName);+ // <runs/>+ if (strategy === 'r') {+ continue;+ }+ var symbolPath = symbolList[i + 2];+ var lastDot = symbolPath.lastIndexOf('.');+ var namespace = symbolPath.substr(0, lastDot);+ var lastName = symbolPath.substr(lastDot + 1);++ var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;+ var parentObj = prepareNamespace(namespace, context);+ var target = parentObj[lastName];++ if (strategy === 'm' && target) {+ builder.recursiveMerge(target, module);+ } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {+ if (!(symbolPath in origSymbols)) {+ origSymbols[symbolPath] = target;+ }+ builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);+ }+ }+};++exports.getOriginalSymbol = function (context, symbolPath) {+ var origSymbols = context.CDV_origSymbols;+ if (origSymbols && (symbolPath in origSymbols)) {+ return origSymbols[symbolPath];+ }+ var parts = symbolPath.split('.');+ var obj = context;+ for (var i = 0; i < parts.length; ++i) {+ obj = obj && obj[parts[i]];+ }+ return obj;+};++exports.reset();++});++// file: src/common/modulemapper_b.js+define("cordova/modulemapper_b", function(require, exports, module) {++var builder = require('cordova/builder');+var symbolList = [];+var deprecationMap;++exports.reset = function () {+ symbolList = [];+ deprecationMap = {};+};++function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {+ symbolList.push(strategy, moduleName, symbolPath);+ if (opt_deprecationMessage) {+ deprecationMap[symbolPath] = opt_deprecationMessage;+ }+}++// Note: Android 2.3 does have Function.bind().+exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('c', moduleName, symbolPath, opt_deprecationMessage);+};++exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('m', moduleName, symbolPath, opt_deprecationMessage);+};++exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('d', moduleName, symbolPath, opt_deprecationMessage);+};++exports.runs = function (moduleName) {+ addEntry('r', moduleName, null);+};++function prepareNamespace (symbolPath, context) {+ if (!symbolPath) {+ return context;+ }+ var parts = symbolPath.split('.');+ var cur = context;+ for (var i = 0, part; part = parts[i]; ++i) { // eslint-disable-line no-cond-assign+ cur = cur[part] = cur[part] || {};+ }+ return cur;+}++exports.mapModules = function (context) {+ var origSymbols = {};+ context.CDV_origSymbols = origSymbols;+ for (var i = 0, len = symbolList.length; i < len; i += 3) {+ var strategy = symbolList[i];+ var moduleName = symbolList[i + 1];+ var module = require(moduleName);+ // <runs/>+ if (strategy === 'r') {+ continue;+ }+ var symbolPath = symbolList[i + 2];+ var lastDot = symbolPath.lastIndexOf('.');+ var namespace = symbolPath.substr(0, lastDot);+ var lastName = symbolPath.substr(lastDot + 1);++ var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;+ var parentObj = prepareNamespace(namespace, context);+ var target = parentObj[lastName];++ if (strategy === 'm' && target) {+ builder.recursiveMerge(target, module);+ } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {+ if (!(symbolPath in origSymbols)) {+ origSymbols[symbolPath] = target;+ }+ builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);+ }+ }+};++exports.getOriginalSymbol = function (context, symbolPath) {+ var origSymbols = context.CDV_origSymbols;+ if (origSymbols && (symbolPath in origSymbols)) {+ return origSymbols[symbolPath];+ }+ var parts = symbolPath.split('.');+ var obj = context;+ for (var i = 0; i < parts.length; ++i) {+ obj = obj && obj[parts[i]];+ }+ return obj;+};++exports.reset();++});++// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/platform.js+define("cordova/platform", function(require, exports, module) {++// The last resume event that was received that had the result of a plugin call.+var lastResumeEvent = null;++module.exports = {+ id: 'android',+ bootstrap: function() {+ var channel = require('cordova/channel'),+ cordova = require('cordova'),+ exec = require('cordova/exec'),+ modulemapper = require('cordova/modulemapper');++ // Get the shared secret needed to use the bridge.+ exec.init();++ // TODO: Extract this as a proper plugin.+ modulemapper.clobbers('cordova/plugin/android/app', 'navigator.app');++ var APP_PLUGIN_NAME = Number(cordova.platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App';++ // Inject a listener for the backbutton on the document.+ var backButtonChannel = cordova.addDocumentEventHandler('backbutton');+ backButtonChannel.onHasSubscribersChange = function() {+ // If we just attached the first handler or detached the last handler,+ // let native know we need to override the back button.+ exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [this.numHandlers == 1]);+ };++ // Add hardware MENU and SEARCH button handlers+ cordova.addDocumentEventHandler('menubutton');+ cordova.addDocumentEventHandler('searchbutton');++ function bindButtonChannel(buttonName) {+ // generic button bind used for volumeup/volumedown buttons+ var volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button');+ volumeButtonChannel.onHasSubscribersChange = function() {+ exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]);+ };+ }+ // Inject a listener for the volume buttons on the document.+ bindButtonChannel('volumeup');+ bindButtonChannel('volumedown');++ // The resume event is not "sticky", but it is possible that the event+ // will contain the result of a plugin call. We need to ensure that the+ // plugin result is delivered even after the event is fired (CB-10498)+ var cordovaAddEventListener = document.addEventListener;++ document.addEventListener = function(evt, handler, capture) {+ cordovaAddEventListener(evt, handler, capture);++ if (evt === 'resume' && lastResumeEvent) {+ handler(lastResumeEvent);+ }+ };++ // Let native code know we are all done on the JS side.+ // Native code will then un-hide the WebView.+ channel.onCordovaReady.subscribe(function() {+ exec(onMessageFromNative, null, APP_PLUGIN_NAME, 'messageChannel', []);+ exec(null, null, APP_PLUGIN_NAME, "show", []);+ });+ }+};++function onMessageFromNative(msg) {+ var cordova = require('cordova');+ var action = msg.action;++ switch (action)+ {+ // Button events+ case 'backbutton':+ case 'menubutton':+ case 'searchbutton':+ // App life cycle events+ case 'pause':+ // Volume events+ case 'volumedownbutton':+ case 'volumeupbutton':+ cordova.fireDocumentEvent(action);+ break;+ case 'resume':+ if(arguments.length > 1 && msg.pendingResult) {+ if(arguments.length === 2) {+ msg.pendingResult.result = arguments[1];+ } else {+ // The plugin returned a multipart message+ var res = [];+ for(var i = 1; i < arguments.length; i++) {+ res.push(arguments[i]);+ }+ msg.pendingResult.result = res;+ }++ // Save the plugin result so that it can be delivered to the js+ // even if they miss the initial firing of the event+ lastResumeEvent = msg;+ }+ cordova.fireDocumentEvent(action, msg);+ break;+ default:+ throw new Error('Unknown event action ' + action);+ }+}++});++// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/plugin/android/app.js+define("cordova/plugin/android/app", function(require, exports, module) {++var exec = require('cordova/exec');+var APP_PLUGIN_NAME = Number(require('cordova').platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App';++module.exports = {+ /**+ * Clear the resource cache.+ */+ clearCache:function() {+ exec(null, null, APP_PLUGIN_NAME, "clearCache", []);+ },++ /**+ * Load the url into the webview or into new browser instance.+ *+ * @param url The URL to load+ * @param props Properties that can be passed in to the activity:+ * wait: int => wait msec before loading URL+ * loadingDialog: "Title,Message" => display a native loading dialog+ * loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error+ * clearHistory: boolean => clear webview history (default=false)+ * openExternal: boolean => open in a new browser (default=false)+ *+ * Example:+ * navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});+ */+ loadUrl:function(url, props) {+ exec(null, null, APP_PLUGIN_NAME, "loadUrl", [url, props]);+ },++ /**+ * Cancel loadUrl that is waiting to be loaded.+ */+ cancelLoadUrl:function() {+ exec(null, null, APP_PLUGIN_NAME, "cancelLoadUrl", []);+ },++ /**+ * Clear web history in this web view.+ * Instead of BACK button loading the previous web page, it will exit the app.+ */+ clearHistory:function() {+ exec(null, null, APP_PLUGIN_NAME, "clearHistory", []);+ },++ /**+ * Go to previous page displayed.+ * This is the same as pressing the backbutton on Android device.+ */+ backHistory:function() {+ exec(null, null, APP_PLUGIN_NAME, "backHistory", []);+ },++ /**+ * Override the default behavior of the Android back button.+ * If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired.+ *+ * Note: The user should not have to call this method. Instead, when the user+ * registers for the "backbutton" event, this is automatically done.+ *+ * @param override T=override, F=cancel override+ */+ overrideBackbutton:function(override) {+ exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [override]);+ },++ /**+ * Override the default behavior of the Android volume button.+ * If overridden, when the volume button is pressed, the "volume[up|down]button"+ * JavaScript event will be fired.+ *+ * Note: The user should not have to call this method. Instead, when the user+ * registers for the "volume[up|down]button" event, this is automatically done.+ *+ * @param button volumeup, volumedown+ * @param override T=override, F=cancel override+ */+ overrideButton:function(button, override) {+ exec(null, null, APP_PLUGIN_NAME, "overrideButton", [button, override]);+ },++ /**+ * Exit and terminate the application.+ */+ exitApp:function() {+ return exec(null, null, APP_PLUGIN_NAME, "exitApp", []);+ }+};++});++// file: src/common/pluginloader.js+define("cordova/pluginloader", function(require, exports, module) {++var modulemapper = require('cordova/modulemapper');++// Helper function to inject a <script> tag.+// Exported for testing.+exports.injectScript = function (url, onload, onerror) {+ var script = document.createElement('script');+ // onload fires even when script fails loads with an error.+ script.onload = onload;+ // onerror fires for malformed URLs.+ script.onerror = onerror;+ script.src = url;+ document.head.appendChild(script);+};++function injectIfNecessary (id, url, onload, onerror) {+ onerror = onerror || onload;+ if (id in define.moduleMap) { // eslint-disable-line no-undef+ onload();+ } else {+ exports.injectScript(url, function () {+ if (id in define.moduleMap) { // eslint-disable-line no-undef+ onload();+ } else {+ onerror();+ }+ }, onerror);+ }+}++function onScriptLoadingComplete (moduleList, finishPluginLoading) {+ // Loop through all the plugins and then through their clobbers and merges.+ for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign+ if (module.clobbers && module.clobbers.length) {+ for (var j = 0; j < module.clobbers.length; j++) {+ modulemapper.clobbers(module.id, module.clobbers[j]);+ }+ }++ if (module.merges && module.merges.length) {+ for (var k = 0; k < module.merges.length; k++) {+ modulemapper.merges(module.id, module.merges[k]);+ }+ }++ // Finally, if runs is truthy we want to simply require() the module.+ if (module.runs) {+ modulemapper.runs(module.id);+ }+ }++ finishPluginLoading();+}++// Handler for the cordova_plugins.js content.+// See plugman's plugin_loader.js for the details of this object.+// This function is only called if the really is a plugins array that isn't empty.+// Otherwise the onerror response handler will just call finishPluginLoading().+function handlePluginsObject (path, moduleList, finishPluginLoading) {+ // Now inject the scripts.+ var scriptCounter = moduleList.length;++ if (!scriptCounter) {+ finishPluginLoading();+ return;+ }+ function scriptLoadedCallback () {+ if (!--scriptCounter) {+ onScriptLoadingComplete(moduleList, finishPluginLoading);+ }+ }++ for (var i = 0; i < moduleList.length; i++) {+ injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback);+ }+}++function findCordovaPath () {+ var path = null;+ var scripts = document.getElementsByTagName('script');+ var term = '/cordova.js';+ for (var n = scripts.length - 1; n > -1; n--) {+ var src = scripts[n].src.replace(/\?.*$/, ''); // Strip any query param (CB-6007).+ if (src.indexOf(term) === (src.length - term.length)) {+ path = src.substring(0, src.length - term.length) + '/';+ break;+ }+ }+ return path;+}++// Tries to load all plugins' js-modules.+// This is an async process, but onDeviceReady is blocked on onPluginsReady.+// onPluginsReady is fired when there are no plugins to load, or they are all done.+exports.load = function (callback) {+ var pathPrefix = findCordovaPath();+ if (pathPrefix === null) {+ console.log('Could not find cordova.js script tag. Plugin loading may fail.');+ pathPrefix = '';+ }+ injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function () {+ var moduleList = require('cordova/plugin_list');+ handlePluginsObject(pathPrefix, moduleList, callback);+ }, callback);+};++});++// file: src/common/pluginloader_b.js+define("cordova/pluginloader_b", function(require, exports, module) {++var modulemapper = require('cordova/modulemapper');++// Handler for the cordova_plugins.js content.+// See plugman's plugin_loader.js for the details of this object.+function handlePluginsObject (moduleList) {+ // if moduleList is not defined or empty, we've nothing to do+ if (!moduleList || !moduleList.length) {+ return;+ }++ // Loop through all the modules and then through their clobbers and merges.+ for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign+ if (module.clobbers && module.clobbers.length) {+ for (var j = 0; j < module.clobbers.length; j++) {+ modulemapper.clobbers(module.id, module.clobbers[j]);+ }+ }++ if (module.merges && module.merges.length) {+ for (var k = 0; k < module.merges.length; k++) {+ modulemapper.merges(module.id, module.merges[k]);+ }+ }++ // Finally, if runs is truthy we want to simply require() the module.+ if (module.runs) {+ modulemapper.runs(module.id);+ }+ }+}++// Loads all plugins' js-modules. Plugin loading is syncronous in browserified bundle+// but the method accepts callback to be compatible with non-browserify flow.+// onDeviceReady is blocked on onPluginsReady. onPluginsReady is fired when there are+// no plugins to load, or they are all done.+exports.load = function (callback) {+ var moduleList = require('cordova/plugin_list');+ handlePluginsObject(moduleList);++ callback();+};++});++// file: src/common/urlutil.js+define("cordova/urlutil", function(require, exports, module) {++/**+ * For already absolute URLs, returns what is passed in.+ * For relative URLs, converts them to absolute ones.+ */+exports.makeAbsolute = function makeAbsolute (url) {+ var anchorEl = document.createElement('a');+ anchorEl.href = url;+ return anchorEl.href;+};++});++// file: src/common/utils.js+define("cordova/utils", function(require, exports, module) {++var utils = exports;++/**+ * Defines a property getter / setter for obj[key].+ */+utils.defineGetterSetter = function (obj, key, getFunc, opt_setFunc) {+ if (Object.defineProperty) {+ var desc = {+ get: getFunc,+ configurable: true+ };+ if (opt_setFunc) {+ desc.set = opt_setFunc;+ }+ Object.defineProperty(obj, key, desc);+ } else {+ obj.__defineGetter__(key, getFunc);+ if (opt_setFunc) {+ obj.__defineSetter__(key, opt_setFunc);+ }+ }+};++/**+ * Defines a property getter for obj[key].+ */+utils.defineGetter = utils.defineGetterSetter;++utils.arrayIndexOf = function (a, item) {+ if (a.indexOf) {+ return a.indexOf(item);+ }+ var len = a.length;+ for (var i = 0; i < len; ++i) {+ if (a[i] === item) {+ return i;+ }+ }+ return -1;+};++/**+ * Returns whether the item was found in the array.+ */+utils.arrayRemove = function (a, item) {+ var index = utils.arrayIndexOf(a, item);+ if (index !== -1) {+ a.splice(index, 1);+ }+ return index !== -1;+};++utils.typeName = function (val) {+ return Object.prototype.toString.call(val).slice(8, -1);+};++/**+ * Returns an indication of whether the argument is an array or not+ */+utils.isArray = Array.isArray ||+ function (a) { return utils.typeName(a) === 'Array'; };++/**+ * Returns an indication of whether the argument is a Date or not+ */+utils.isDate = function (d) {+ return (d instanceof Date);+};++/**+ * Does a deep clone of the object.+ */+utils.clone = function (obj) {+ if (!obj || typeof obj === 'function' || utils.isDate(obj) || typeof obj !== 'object') {+ return obj;+ }++ var retVal, i;++ if (utils.isArray(obj)) {+ retVal = [];+ for (i = 0; i < obj.length; ++i) {+ retVal.push(utils.clone(obj[i]));+ }+ return retVal;+ }++ retVal = {};+ for (i in obj) {+ // https://issues.apache.org/jira/browse/CB-11522 'unknown' type may be returned in+ // custom protocol activation case on Windows Phone 8.1 causing "No such interface supported" exception+ // on cloning.+ if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') { // eslint-disable-line valid-typeof+ retVal[i] = utils.clone(obj[i]);+ }+ }+ return retVal;+};++/**+ * Returns a wrapped version of the function+ */+utils.close = function (context, func, params) {+ return function () {+ var args = params || arguments;+ return func.apply(context, args);+ };+};++// ------------------------------------------------------------------------------+function UUIDcreatePart (length) {+ var uuidpart = '';+ for (var i = 0; i < length; i++) {+ var uuidchar = parseInt((Math.random() * 256), 10).toString(16);+ if (uuidchar.length === 1) {+ uuidchar = '0' + uuidchar;+ }+ uuidpart += uuidchar;+ }+ return uuidpart;+}++/**+ * Create a UUID+ */+utils.createUUID = function () {+ return UUIDcreatePart(4) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(6);+};++/**+ * Extends a child object from a parent object using classical inheritance+ * pattern.+ */+utils.extend = (function () {+ // proxy used to establish prototype chain+ var F = function () {};+ // extend Child from Parent+ return function (Child, Parent) {++ F.prototype = Parent.prototype;+ Child.prototype = new F();+ Child.__super__ = Parent.prototype;+ Child.prototype.constructor = Child;+ };+}());++/**+ * Alerts a message in any available way: alert or console.log.+ */+utils.alert = function (msg) {+ if (window.alert) {+ window.alert(msg);+ } else if (console && console.log) {+ console.log(msg);+ }+};++});++window.cordova = require('cordova');+// file: src/scripts/bootstrap.js++require('cordova/init');++})();diff --git a/cordova/platforms/android/app/src/main/assets/www/index.html b/cordova/platforms/android/app/src/main/assets/www/index.htmlnew file mode 100644index 000000000..fa2f903ee--- /dev/null+++ b/cordova/platforms/android/app/src/main/assets/www/index.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<html>+ <head>+ <meta http-equiv="Content-Security-Policy" content="connect-src *; default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">+ <meta name="format-detection" content="telephone=no">+ <meta name="msapplication-tap-highlight" content="no">+ <meta charset="utf-8">+ <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">+ <link rel="stylesheet" type="text/css" href="dist/style.css">+ <title>TagSpaces App</title>+ </head>+ <body class="default-background">+ <div id="root"></div>+ <script type="text/javascript" src="cordova.js"></script>+ <script type="text/javascript" src="dist/bundle.js"></script>+ </body>+</html>diff --git a/cordova/platforms/android/src/org/tagspaces/mobile/MainActivity.java b/cordova/platforms/android/app/src/main/java/org/tagspaces/mobile/MainActivity.javasimilarity index 100%rename from cordova/platforms/android/src/org/tagspaces/mobile/MainActivity.javarename to cordova/platforms/android/app/src/main/java/org/tagspaces/mobile/MainActivity.javadiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.pngnew file mode 100644index 000000000..2d564f49cBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.pngnew file mode 100644index 000000000..c7eae7edeBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.pngnew file mode 100644index 000000000..3bf1ec2e9Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.pngnew file mode 100644index 000000000..987a92462Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.pngnew file mode 100644index 000000000..ef9fc7400Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.pngnew file mode 100644index 000000000..8f9a458e1Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.pngnew file mode 100644index 000000000..5875561d3Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.pngnew file mode 100644index 000000000..725420620Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.pngnew file mode 100644index 000000000..9034b68fdBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.pngnew file mode 100644index 000000000..95dc8d849Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.pngnew file mode 100644index 000000000..9b6bfe4a8Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.pngnew file mode 100644index 000000000..ec655cde1Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.pngnew file mode 100644index 000000000..538426124Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-ldpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-ldpi/icon.pngnew file mode 100644index 000000000..c5fcaeb64Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-ldpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.pngnew file mode 100644index 000000000..a18167be1Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.pngnew file mode 100644index 000000000..9e3eec364Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.pngnew file mode 100644index 000000000..a56928965Binary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.pngnew file mode 100644index 000000000..3c322f2eaBinary files /dev/null and b/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.png differdiff --git a/cordova/platforms/android/res/values/strings.xml b/cordova/platforms/android/app/src/main/res/values/strings.xmlsimilarity index 100%rename from cordova/platforms/android/res/values/strings.xmlrename to cordova/platforms/android/app/src/main/res/values/strings.xmldiff --git a/cordova/platforms/android/res/xml/config.xml b/cordova/platforms/android/app/src/main/res/xml/config.xmlsimilarity index 55%rename from cordova/platforms/android/res/xml/config.xmlrename to cordova/platforms/android/app/src/main/res/xml/config.xmlindex ba1fb29b0..7fa24b04e 100644--- a/cordova/platforms/android/res/xml/config.xml+++ b/cordova/platforms/android/app/src/main/res/xml/config.xml@@ -1,9 +1,5 @@<?xml version='1.0' encoding='utf-8'?><widget id="org.tagspaces.mobile" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">- <feature name="Whitelist">- <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" />- <param name="onload" value="true" />- </feature><name>TagSpaces</name><description>A sample Apache Cordova application that responds to the deviceready event.@@ -21,11 +17,4 @@<allow-intent href="geo:*" /><allow-intent href="market:*" /><preference name="loglevel" value="DEBUG" />- <preference name="webView" value="org.crosswalk.engine.XWalkWebViewEngine" />- <preference name="xwalkVersion" value="23+" />- <preference name="xwalkLiteVersion" value="xwalk_core_library_canary:17+" />- <preference name="xwalkCommandLine" value="--disable-pull-to-refresh-effect" />- <preference name="xwalkMode" value="embedded" />- <preference name="xwalkMultipleApk" value="true" />- <preference name="android-minSdkVersion" value="16" /></widget>diff --git a/cordova/platforms/android/build.gradle b/cordova/platforms/android/build.gradleindex 7294944e2..569004f45 100644--- a/cordova/platforms/android/build.gradle+++ b/cordova/platforms/android/build.gradle@@ -1,314 +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.+/* 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.*/-apply plugin: 'com.android.application'+// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {repositories {- mavenCentral()+ maven {+ url "https://maven.google.com"+ }jcenter()}-- // Switch the Android Gradle plugin version requirement depending on the- // installed version of Gradle. This dependency is documented at- // http://tools.android.com/tech-docs/new-build-system/version-compatibility- // and https://issues.apache.org/jira/browse/CB-8143dependencies {- classpath 'com.android.tools.build:gradle:2.2.3'++ // NOTE: Do not place your application dependencies here; they belong+ // in the individual module build.gradle files+ classpath 'com.android.tools.build:gradle:3.0.1'}}-// Allow plugins to declare Maven dependencies via build-extras.gradle.allprojects {repositories {- mavenCentral();- jcenter()- }-}--task wrapper(type: Wrapper) {- gradleVersion = '2.14.1'-}--// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.-// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html-ext {- apply from: 'CordovaLib/cordova.gradle'- // The value for android.compileSdkVersion.- if (!project.hasProperty('cdvCompileSdkVersion')) {- cdvCompileSdkVersion = null;- }- // The value for android.buildToolsVersion.- if (!project.hasProperty('cdvBuildToolsVersion')) {- cdvBuildToolsVersion = null;- }- // Sets the versionCode to the given value.- if (!project.hasProperty('cdvVersionCode')) {- cdvVersionCode = null- }- // Sets the minSdkVersion to the given value.- if (!project.hasProperty('cdvMinSdkVersion')) {- cdvMinSdkVersion = null- }- // Whether to build architecture-specific APKs.- if (!project.hasProperty('cdvBuildMultipleApks')) {- cdvBuildMultipleApks = null- }- // .properties files to use for release signing.- if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {- cdvReleaseSigningPropertiesFile = null- }- // .properties files to use for debug signing.- if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {- cdvDebugSigningPropertiesFile = null- }- // Set by build.js script.- if (!project.hasProperty('cdvBuildArch')) {- cdvBuildArch = null- }-- // Plugin gradle extensions can append to this to have code run at the end.- cdvPluginPostBuildExtras = []-}--// PLUGIN GRADLE EXTENSIONS START-apply from: "cordova-plugin-crosswalk-webview/mobile-xwalk.gradle"-// PLUGIN GRADLE EXTENSIONS END--def hasBuildExtras = file('build-extras.gradle').exists()-if (hasBuildExtras) {- apply from: 'build-extras.gradle'-}--// Set property defaults after extension .gradle files.-if (ext.cdvCompileSdkVersion == null) {- ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()-}-if (ext.cdvBuildToolsVersion == null) {- ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()-}-if (ext.cdvDebugSigningPropertiesFile == null && file('debug-signing.properties').exists()) {- ext.cdvDebugSigningPropertiesFile = 'debug-signing.properties'-}-if (ext.cdvReleaseSigningPropertiesFile == null && file('release-signing.properties').exists()) {- ext.cdvReleaseSigningPropertiesFile = 'release-signing.properties'-}--// Cast to appropriate types.-ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();-ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : Integer.parseInt('' + cdvMinSdkVersion)-ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)--def computeBuildTargetName(debugBuild) {- def ret = 'assemble'- if (cdvBuildMultipleApks && cdvBuildArch) {- def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch- ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);- }- return ret + (debugBuild ? 'Debug' : 'Release')-}--// Make cdvBuild a task that depends on the debug/arch-sepecific task.-task cdvBuildDebug-cdvBuildDebug.dependsOn {- return computeBuildTargetName(true)-}--task cdvBuildRelease-cdvBuildRelease.dependsOn {- return computeBuildTargetName(false)-}--task cdvPrintProps << {- println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)- println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)- println('cdvVersionCode=' + cdvVersionCode)- println('cdvMinSdkVersion=' + cdvMinSdkVersion)- println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)- println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)- println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)- println('cdvBuildArch=' + cdvBuildArch)- println('computedVersionCode=' + android.defaultConfig.versionCode)- android.productFlavors.each { flavor ->- println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)- }-}--android {- sourceSets {- main {- manifest.srcFile 'AndroidManifest.xml'- java.srcDirs = ['src']- resources.srcDirs = ['src']- aidl.srcDirs = ['src']- renderscript.srcDirs = ['src']- res.srcDirs = ['res']- assets.srcDirs = ['assets']- jniLibs.srcDirs = ['libs']+ maven {+ url "https://maven.google.com"}+ jcenter()}-- defaultConfig {- versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))- applicationId privateHelpers.extractStringFromManifest("package")-- if (cdvMinSdkVersion != null) {- minSdkVersion cdvMinSdkVersion- }- }-- lintOptions {- abortOnError false;- }-- compileSdkVersion cdvCompileSdkVersion- buildToolsVersion cdvBuildToolsVersion-- if (Boolean.valueOf(cdvBuildMultipleApks)) {- productFlavors {- armv7 {- versionCode defaultConfig.versionCode*10 + 2- ndk {- abiFilters "armeabi-v7a", ""- }- }- x86 {- versionCode defaultConfig.versionCode*10 + 4- ndk {- abiFilters "x86", ""- }- }- all {- ndk {- abiFilters "all", ""- }- }- }- }- /*-- ELSE NOTHING! DON'T MESS WITH THE VERSION CODE IF YOU DON'T HAVE TO!-- else if (!cdvVersionCode) {- def minSdkVersion = cdvMinSdkVersion ?: privateHelpers.extractIntFromManifest("minSdkVersion")- // Vary versionCode by the two most common API levels:- // 14 is ICS, which is the lowest API level for many apps.- // 20 is Lollipop, which is the lowest API level for the updatable system webview.- if (minSdkVersion >= 20) {- defaultConfig.versionCode += 9- } else if (minSdkVersion >= 14) {- defaultConfig.versionCode += 8- }- }- */-- compileOptions {- sourceCompatibility JavaVersion.VERSION_1_6- targetCompatibility JavaVersion.VERSION_1_6- }-- if (cdvReleaseSigningPropertiesFile) {- signingConfigs {- release {- // These must be set or Gradle will complain (even if they are overridden).- keyAlias = ""- keyPassword = "__unset" // And these must be set to non-empty in order to have the signing step added to the task graph.- storeFile = null- storePassword = "__unset"- }- }- buildTypes {- release {- signingConfig signingConfigs.release- }- }- addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)- }- if (cdvDebugSigningPropertiesFile) {- addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)- }-}--dependencies {- compile fileTree(dir: 'libs', include: '*.jar')- // SUB-PROJECT DEPENDENCIES START- debugCompile(project(path: "CordovaLib", configuration: "debug"))- releaseCompile(project(path: "CordovaLib", configuration: "release"))- // SUB-PROJECT DEPENDENCIES END-}--def promptForReleaseKeyPassword() {- if (!cdvReleaseSigningPropertiesFile) {- return;- }- if ('__unset'.equals(android.signingConfigs.release.storePassword)) {- android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')- }- if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {- android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');- }-}--gradle.taskGraph.whenReady { taskGraph ->- taskGraph.getAllTasks().each() { task ->- if (task.name == 'validateReleaseSigning' || task.name == 'validateSigningRelease') {- promptForReleaseKeyPassword()- }- }-}--def addSigningProps(propsFilePath, signingConfig) {- def propsFile = file(propsFilePath)- def props = new Properties()- propsFile.withReader { reader ->- props.load(reader)- }-- def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))- if (!storeFile.isAbsolute()) {- storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())- }- if (!storeFile.exists()) {- throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())- }- signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')- signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))- signingConfig.storeFile = storeFile- signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))- def storeType = props.get('storeType', props.get('key.store.type', ''))- if (!storeType) {- def filename = storeFile.getName().toLowerCase();- if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {- storeType = 'pkcs12'- } else {- storeType = signingConfig.storeType // "jks"- }+ //This replaces project.properties w.r.t. build settings+ project.ext {+ defaultBuildToolsVersion="27.0.1" //String+ defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4+ defaultTargetSdkVersion=27 //Integer - We ALWAYS target the latest by default+ defaultCompileSdkVersion=27 //Integer - We ALWAYS compile with the latest by default}- signingConfig.storeType = storeType-}--for (def func : cdvPluginPostBuildExtras) {- func()}-// This can be defined within build-extras.gradle as:-// ext.postBuildExtras = { ... code here ... }-if (hasProperty('postBuildExtras')) {- postBuildExtras()+task clean(type: Delete) {+ delete rootProject.buildDir}diff --git a/cordova/platforms/android/cordova-plugin-crosswalk-webview/mobile-xwalk.gradle b/cordova/platforms/android/cordova-plugin-crosswalk-webview/mobile-xwalk.gradledeleted file mode 100644index 635925ae3..000000000--- a/cordova/platforms/android/cordova-plugin-crosswalk-webview/mobile-xwalk.gradle+++ /dev/null@@ -1,170 +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.-*/--def EMBEDDED_MODE = "embedded"-def SHARED_MODE = "shared"-def LITE_MODE = "lite"-def DEFAULT_GROUP_ID = "org.xwalk:"-def SHARED_ARTIFACT_ID = "xwalk_shared_library:"-def EMBEDD_ARTIFACT_ID = "xwalk_core_library:"-def CANARY_ARTIFACT_ID = "xwalk_core_library_canary:"-def BIT_64 = ":64bit@aar"-def DEFAULT_MIN_SDK_VERSION = 14--def getConfigPreference(name) {- name = name.toLowerCase()- def xml = file("res/xml/config.xml").getText()- // Disable namespace awareness since Cordova doesn't use them properly- def root = new XmlParser(false, false).parseText(xml)-- def ret, defaultValue- root.preference.each { it ->- def attrName = it.attribute("name")- if (attrName && attrName.toLowerCase() == name) {- if (it.attribute('default') != null) {- defaultValue = it.attribute('default');- } else {- ret = it.attribute("value")- }- }- }- return ret ? ret : defaultValue-}--if (!project.hasProperty('xwalk64bit')) {- ext.xwalk64bit = getConfigPreference("xwalk64bit");- println xwalk64bit-}-if (cdvBuildMultipleApks == null) {- ext.xwalkMultipleApk = getConfigPreference("xwalkMultipleApk").toBoolean();-} else {- ext.xwalkMultipleApk = cdvBuildMultipleApks.toBoolean();-}--def minSdk = getConfigPreference("android-minSdkVersion");-if (cdvMinSdkVersion == null) {- ext.cdvMinSdkVersion = minSdk && Integer.parseInt(minSdk) > DEFAULT_MIN_SDK_VERSION ? minSdk : DEFAULT_MIN_SDK_VERSION;-} else if (Integer.parseInt('' + cdvMinSdkVersion) < Integer.parseInt(minSdk)) {- ext.cdvMinSdkVersion = minSdk;-}--if (!project.hasProperty('xwalkMode')) {- ext.xwalkMode = getConfigPreference("xwalkMode");-}---if (ext.xwalkMode == SHARED_MODE) {- // Build one apk at shared mode because the value of- // ext.cdvBuildMultipleApks is false by default.- xwalk64bit = null;-} else if (xwalk64bit == null) {- // Build embedded 32 bit crosswalk will generate two apks by default.- ext.cdvBuildMultipleApks = xwalkMultipleApk;-}--// Set defaults before project's build-extras.gradle-if (!project.hasProperty('xwalkVersion')) {- ext.xwalkVersion = getConfigPreference("xwalkVersion")-}--// Set defaults before project's build-extras.gradle-if (!project.hasProperty('xwalkLiteVersion')) {- ext.xwalkLiteVersion = getConfigPreference("xwalkLiteVersion")-}--if (!project.hasProperty('xwalkCommandLine')) {- ext.xwalkCommandLine = getConfigPreference("xwalkCommandLine")-}-// Apply values after project's build-extras.gradle-cdvPluginPostBuildExtras.add({- def xwalkMavenRepo = 'https://download.01.org/crosswalk/releases/crosswalk/android/maven2';- if (xwalkMode == LITE_MODE) {- xwalkMavenRepo = 'https://download.01.org/crosswalk/releases/crosswalk-lite/android/maven2';- }- repositories {- maven {- url xwalkMavenRepo- }- }-- android {- if (xwalk64bit != null) {- productFlavors {- x86_64 {- versionCode defaultConfig.versionCode + 6- ndk {- abiFilters "x86_64", ""- }- }- arm64 {- versionCode defaultConfig.versionCode + 9- ndk {- abiFilters "arm64-v8a", ""- }- }- }- }- }-- def xwalkSpec = xwalkVersion- if (ext.xwalkMode == LITE_MODE) {- xwalkSpec = xwalkLiteVersion;- }-- if ((xwalkSpec =~ /:/).count == 1) {- xwalkSpec = DEFAULT_GROUP_ID + xwalkSpec- } else if ((xwalkSpec =~ /:/).count == 0) {- if (xwalkSpec ==~ /\d+/) {- xwalkSpec = "${xwalkSpec}+"- }-- def artifactid = EMBEDD_ARTIFACT_ID;- if (ext.xwalkMode == SHARED_MODE) {- artifactid = SHARED_ARTIFACT_ID;- } else if (ext.xwalkMode == LITE_MODE) {- artifactid = CANARY_ARTIFACT_ID;- }- xwalkSpec = DEFAULT_GROUP_ID + artifactid + xwalkSpec- }- if (xwalk64bit != null) {- xwalkSpec = xwalkSpec + BIT_64- }- println xwalkSpec-- dependencies {- compile xwalkSpec- }-- if (file('assets/xwalk-command-line').exists()) {- println('Not writing assets/xwalk-command-line since file already exists.')- return- }- android.applicationVariants.all { variant ->- def variantName = variant.name.capitalize()- def mergeTask = tasks["merge${variantName}Assets"]- def processTask = tasks["process${variantName}Resources"]- def outFile = new File (mergeTask.outputDir, "xwalk-command-line")- def newTask = project.task("createXwalkCommandLineFile${variantName}") << {- mergeTask.outputDir.mkdirs()- outFile.write("xwalk ${xwalkCommandLine}\n")- }- newTask.dependsOn(mergeTask)- processTask.dependsOn(newTask)- }-})diff --git a/cordova/platforms/android/cordova/.jshintrc b/cordova/platforms/android/cordova/.jshintrcdeleted file mode 100644index 89a121cf1..000000000--- a/cordova/platforms/android/cordova/.jshintrc+++ /dev/null@@ -1,10 +0,0 @@-{- "node": true- , "bitwise": true- , "undef": true- , "trailing": true- , "quotmark": true- , "indent": 4- , "unused": "vars"- , "latedef": "nofunc"-}diff --git a/cordova/platforms/android/cordova/Api.js b/cordova/platforms/android/cordova/Api.jsindex 8e4711cb8..ae4d17bdd 100644--- a/cordova/platforms/android/cordova/Api.js+++ b/cordova/platforms/android/cordova/Api.js@@ -29,8 +29,7 @@ var selfEvents = require('cordova-common').events;var PLATFORM = 'android';--function setupEvents(externalEventEmitter) {+function setupEvents (externalEventEmitter) {if (externalEventEmitter) {// This will make the platform internal events visible outsideselfEvents.forwardEventsTo(externalEventEmitter);@@ -43,7 +42,6 @@ function setupEvents(externalEventEmitter) {return selfEvents;}-/*** Class, that acts as abstraction over particular platform. Encapsulates the* platform's properties and methods.@@ -55,9 +53,10 @@ function setupEvents(externalEventEmitter) {** * platform: String that defines a platform name.*/-function Api(platform, platformRootDir, events) {+function Api (platform, platformRootDir, events) {this.platform = PLATFORM;this.root = path.resolve(__dirname, '..');+ this.builder = 'gradle';setupEvents(events);@@ -73,20 +72,24 @@ function Api(platform, platformRootDir, events) {strings: path.join(self.root, 'res/values/strings.xml'),manifest: path.join(self.root, 'AndroidManifest.xml'),build: path.join(self.root, 'build'),+ javaSrc: path.join(self.root, 'src'),// NOTE: Due to platformApi spec we need to return relative paths herecordovaJs: 'bin/templates/project/assets/www/cordova.js',cordovaJsSrc: 'cordova-js-src'};// XXX Override some locations for Android Studio projects- if(AndroidStudio.isAndroidStudioProject(self.root) === true) {- selfEvents.emit('log', 'Android Studio project detected');- this.android_studio = true;- this.locations.configXml = path.join(self.root, 'app/src/main/res/xml/config.xml');- this.locations.strings = path.join(self.root, 'app/src/main/res/xml/strings.xml');- this.locations.manifest = path.join(self.root, 'app/src/main/AndroidManifest.xml');- this.locations.www = path.join(self.root, 'app/src/main/assets/www');- this.locations.res = path.join(self.root, 'app/src/main/res');+ if (AndroidStudio.isAndroidStudioProject(self.root) === true) {+ selfEvents.emit('log', 'Android Studio project detected');+ this.builder = 'studio';+ this.android_studio = true;+ this.locations.configXml = path.join(self.root, 'app/src/main/res/xml/config.xml');+ this.locations.strings = path.join(self.root, 'app/src/main/res/values/strings.xml');+ this.locations.manifest = path.join(self.root, 'app/src/main/AndroidManifest.xml');+ // We could have Java Source, we could have other languages+ this.locations.javaSrc = path.join(self.root, 'app/src/main/java/');+ this.locations.www = path.join(self.root, 'app/src/main/assets/www');+ this.locations.res = path.join(self.root, 'app/src/main/res');}}@@ -112,16 +115,13 @@ Api.createPlatform = function (destination, config, options, events) {events = setupEvents(events);var result;try {- result = require('../../lib/create')- .create(destination, config, options, events)- .then(function (destination) {+ result = require('../../lib/create').create(destination, config, options, events).then(function (destination) {var PlatformApi = require(path.resolve(destination, 'cordova/Api'));return new PlatformApi(PLATFORM, destination, events);});- }- catch (e) {- events.emit('error','createPlatform is not callable from the android project API.');- throw(e);+ } catch (e) {+ events.emit('error', 'createPlatform is not callable from the android project API.');+ throw (e);}return result;};@@ -146,16 +146,13 @@ Api.updatePlatform = function (destination, options, events) {events = setupEvents(events);var result;try {- result = require('../../lib/create')- .update(destination, options, events)- .then(function (destination) {+ result = require('../../lib/create').update(destination, options, events).then(function (destination) {var PlatformApi = require(path.resolve(destination, 'cordova/Api'));return new PlatformApi('android', destination, events);});- }- catch (e) {- events.emit('error','updatePlatform is not callable from the android project API, you will need to do this manually.');- throw(e);+ } catch (e) {+ events.emit('error', 'updatePlatform is not callable from the android project API, you will need to do this manually.');+ throw (e);}return result;};@@ -226,40 +223,35 @@ Api.prototype.addPlugin = function (plugin, installOptions) {installOptions.variables.PACKAGE_NAME = project.getPackageName();}- if(this.android_studio === true) {- installOptions.android_studio = true;+ if (this.android_studio === true) {+ installOptions.android_studio = true;}- return Q()- .then(function () {- //CB-11964: Do a clean when installing the plugin code to get around- //the Gradle bug introduced by the Android Gradle Plugin Version 2.2- //TODO: Delete when the next version of Android Gradle plugin comes out-- // Since clean doesn't just clean the build, it also wipes out www, we need- // to pass additional options.-- // Do some basic argument parsing- var opts = {};-- // Skip cleaning prepared files when not invoking via cordova CLI.- opts.noPrepare = true;-- if(!AndroidStudio.isAndroidStudioProject(self.root) && !project.isClean()) {- return self.clean(opts);- }- })- .then(function () {- return PluginManager.get(self.platform, self.locations, project)- .addPlugin(plugin, installOptions);- })- .then(function () {- if (plugin.getFrameworks(this.platform).length === 0) return;-- selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');- require('./lib/builders/builders').getBuilder('gradle').prepBuildFiles();- }.bind(this))- // CB-11022 Return truthy value to prevent running prepare after+ return Q().then(function () {+ // CB-11964: Do a clean when installing the plugin code to get around+ // the Gradle bug introduced by the Android Gradle Plugin Version 2.2+ // TODO: Delete when the next version of Android Gradle plugin comes out+ // Since clean doesn't just clean the build, it also wipes out www, we need+ // to pass additional options.++ // Do some basic argument parsing+ var opts = {};++ // Skip cleaning prepared files when not invoking via cordova CLI.+ opts.noPrepare = true;++ if (!AndroidStudio.isAndroidStudioProject(self.root) && !project.isClean()) {+ return self.clean(opts);+ }+ }).then(function () {+ return PluginManager.get(self.platform, self.locations, project).addPlugin(plugin, installOptions);+ }).then(function () {+ if (plugin.getFrameworks(this.platform).length === 0) return;+ selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');+ // This should pick the correct builder, not just get gradle+ require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();+ }.bind(this))+ // CB-11022 Return truthy value to prevent running prepare after.thenResolve(true);};@@ -279,9 +271,9 @@ Api.prototype.addPlugin = function (plugin, installOptions) {Api.prototype.removePlugin = function (plugin, uninstallOptions) {var project = AndroidProject.getProjectFile(this.root);- if(uninstallOptions && uninstallOptions.usePlatformWww === true && this.android_studio === true) {- uninstallOptions.usePlatformWww = false;- uninstallOptions.android_studio = true;+ if (uninstallOptions && uninstallOptions.usePlatformWww === true && this.android_studio === true) {+ uninstallOptions.usePlatformWww = false;+ uninstallOptions.android_studio = true;}return PluginManager.get(this.platform, this.locations, project)@@ -290,7 +282,7 @@ Api.prototype.removePlugin = function (plugin, uninstallOptions) {if (plugin.getFrameworks(this.platform).length === 0) return;selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');- require('./lib/builders/builders').getBuilder('gradle').prepBuildFiles();+ require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();}.bind(this))// CB-11022 Return truthy value to prevent running prepare after.thenResolve(true);@@ -343,11 +335,12 @@ Api.prototype.removePlugin = function (plugin, uninstallOptions) {*/Api.prototype.build = function (buildOptions) {var self = this;- return require('./lib/check_reqs').run()- .then(function () {+ if (this.android_studio) {+ buildOptions.studio = true;+ }+ return require('./lib/check_reqs').run().then(function () {return require('./lib/build').run.call(self, buildOptions);- })- .then(function (buildResults) {+ }).then(function (buildResults) {// Cast build result to array of build artifactsreturn buildResults.apkPaths.map(function (apkPath) {return {@@ -372,10 +365,9 @@ Api.prototype.build = function (buildOptions) {* @return {Promise} A promise either fulfilled if package was built and ran* successfully, or rejected with CordovaError.*/-Api.prototype.run = function(runOptions) {+Api.prototype.run = function (runOptions) {var self = this;- return require('./lib/check_reqs').run()- .then(function () {+ return require('./lib/check_reqs').run().then(function () {return require('./lib/run').run.call(self, runOptions);});};@@ -387,18 +379,22 @@ Api.prototype.run = function(runOptions) {* @return {Promise} Return a promise either fulfilled, or rejected with* CordovaError.*/-Api.prototype.clean = function(cleanOptions) {+Api.prototype.clean = function (cleanOptions) {var self = this;- return require('./lib/check_reqs').run()- .then(function () {- return require('./lib/build').runClean.call(self, cleanOptions);- })- .then(function () {- return require('./lib/prepare').clean.call(self, cleanOptions);- });-};-+ if (this.android_studio) {+ // This will lint, checking for null won't+ if (typeof cleanOptions === 'undefined') {+ cleanOptions = {};+ }+ cleanOptions.studio = true;+ }+ return require('./lib/check_reqs').run().then(function () {+ return require('./lib/build').runClean.call(self, cleanOptions);+ }).then(function () {+ return require('./lib/prepare').clean.call(self, cleanOptions);+ });+};/*** Performs a requirements check for current platform. Each platform defines its@@ -408,7 +404,7 @@ Api.prototype.clean = function(cleanOptions) {* @return {Promise<Requirement[]>} Promise, resolved with set of Requirement* objects for current platform.*/-Api.prototype.requirements = function() {+Api.prototype.requirements = function () {return require('./lib/check_reqs').check_all();};diff --git a/cordova/platforms/android/cordova/android_sdk_version.bat b/cordova/platforms/android/cordova/android_sdk_version.batindex 33a1fa251..a6bc10435 100644--- a/cordova/platforms/android/cordova/android_sdk_version.bat+++ b/cordova/platforms/android/cordova/android_sdk_version.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0android_sdk_version"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'android_sdk_version' script in 'bin' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/check_reqs.bat b/cordova/platforms/android/cordova/check_reqs.batindex cb2c6f541..846dfa1f4 100644--- a/cordova/platforms/android/cordova/check_reqs.bat+++ b/cordova/platforms/android/cordova/check_reqs.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0check_reqs"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'check_reqs' script in 'bin' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/lib/Adb.js b/cordova/platforms/android/cordova/lib/Adb.jsindex 84ae707e1..038c67c09 100644--- a/cordova/platforms/android/cordova/lib/Adb.js+++ b/cordova/platforms/android/cordova/lib/Adb.js@@ -25,11 +25,11 @@ var CordovaError = require('cordova-common').CordovaError;var Adb = {};-function isDevice(line) {+function isDevice (line) {return line.match(/\w+\tdevice/) && !line.match(/emulator/);}-function isEmulator(line) {+function isEmulator (line) {return line.match(/device/) && line.match(/emulator/);}@@ -44,8 +44,7 @@ function isEmulator(line) {* devices/emulators*/Adb.devices = function (opts) {- return spawn('adb', ['devices'], {cwd: os.tmpdir()})- .then(function(output) {+ return spawn('adb', ['devices'], {cwd: os.tmpdir()}).then(function (output) {return output.split('\n').filter(function (line) {// Filter out either real devices or emulators, depending on optionsreturn (line && opts && opts.emulators) ? isEmulator(line) : isDevice(line);@@ -59,8 +58,7 @@ Adb.install = function (target, packagePath, opts) {events.emit('verbose', 'Installing apk ' + packagePath + ' on target ' + target + '...');var args = ['-s', target, 'install'];if (opts && opts.replace) args.push('-r');- return spawn('adb', args.concat(packagePath), {cwd: os.tmpdir()})- .then(function(output) {+ return spawn('adb', args.concat(packagePath), {cwd: os.tmpdir()}).then(function (output) {// 'adb install' seems to always returns no error, even if installation fails// so we catching output to detect installation failureif (output.match(/Failure/)) {@@ -86,8 +84,7 @@ Adb.shell = function (target, shellCommand) {events.emit('verbose', 'Running adb shell command "' + shellCommand + '" on target ' + target + '...');var args = ['-s', target, 'shell'];shellCommand = shellCommand.split(/\s+/);- return spawn('adb', args.concat(shellCommand), {cwd: os.tmpdir()})- .catch(function (output) {+ return spawn('adb', args.concat(shellCommand), {cwd: os.tmpdir()}).catch(function (output) {return Q.reject(new CordovaError('Failed to execute shell command "' +shellCommand + '"" on device: ' + output));});@@ -95,8 +92,7 @@ Adb.shell = function (target, shellCommand) {Adb.start = function (target, activityName) {events.emit('verbose', 'Starting application "' + activityName + '" on target ' + target + '...');- return Adb.shell(target, 'am start -W -a android.intent.action.MAIN -n' + activityName)- .catch(function (output) {+ return Adb.shell(target, 'am start -W -a android.intent.action.MAIN -n' + activityName).catch(function (output) {return Q.reject(new CordovaError('Failed to start application "' +activityName + '"" on device: ' + output));});diff --git a/cordova/platforms/android/cordova/lib/AndroidManifest.js b/cordova/platforms/android/cordova/lib/AndroidManifest.jsindex 8248f5938..5b7077ae5 100644--- a/cordova/platforms/android/cordova/lib/AndroidManifest.js+++ b/cordova/platforms/android/cordova/lib/AndroidManifest.js@@ -19,12 +19,12 @@var fs = require('fs');var et = require('elementtree');-var xml= require('cordova-common').xmlHelpers;+var xml = require('cordova-common').xmlHelpers;var DEFAULT_ORIENTATION = 'default';/** Wraps an AndroidManifest file */-function AndroidManifest(path) {+function AndroidManifest (path) {this.path = path;this.doc = xml.parseElementtreeSync(path);if (this.doc.getroot().tag !== 'manifest') {@@ -32,38 +32,38 @@ function AndroidManifest(path) {}}-AndroidManifest.prototype.getVersionName = function() {+AndroidManifest.prototype.getVersionName = function () {return this.doc.getroot().attrib['android:versionName'];};-AndroidManifest.prototype.setVersionName = function(versionName) {+AndroidManifest.prototype.setVersionName = function (versionName) {this.doc.getroot().attrib['android:versionName'] = versionName;return this;};-AndroidManifest.prototype.getVersionCode = function() {+AndroidManifest.prototype.getVersionCode = function () {return this.doc.getroot().attrib['android:versionCode'];};-AndroidManifest.prototype.setVersionCode = function(versionCode) {+AndroidManifest.prototype.setVersionCode = function (versionCode) {this.doc.getroot().attrib['android:versionCode'] = versionCode;return this;};-AndroidManifest.prototype.getPackageId = function() {- /*jshint -W069 */+AndroidManifest.prototype.getPackageId = function () {+ /* jshint -W069 */return this.doc.getroot().attrib['package'];- /*jshint +W069 */+ /* jshint +W069 */};-AndroidManifest.prototype.setPackageId = function(pkgId) {- /*jshint -W069 */+AndroidManifest.prototype.setPackageId = function (pkgId) {+ /* jshint -W069 */this.doc.getroot().attrib['package'] = pkgId;- /*jshint +W069 */+ /* jshint +W069 */return this;};-AndroidManifest.prototype.getActivity = function() {+AndroidManifest.prototype.getActivity = function () {var activity = this.doc.getroot().find('./application/activity');return {getName: function () {@@ -102,17 +102,16 @@ AndroidManifest.prototype.getActivity = function() {};};-['minSdkVersion', 'maxSdkVersion', 'targetSdkVersion']-.forEach(function(sdkPrefName) {+['minSdkVersion', 'maxSdkVersion', 'targetSdkVersion'].forEach(function (sdkPrefName) {// Copy variable reference to avoid closure issuesvar prefName = sdkPrefName;- AndroidManifest.prototype['get' + capitalize(prefName)] = function() {+ AndroidManifest.prototype['get' + capitalize(prefName)] = function () {var usesSdk = this.doc.getroot().find('./uses-sdk');return usesSdk && usesSdk.attrib['android:' + prefName];};- AndroidManifest.prototype['set' + capitalize(prefName)] = function(prefValue) {+ AndroidManifest.prototype['set' + capitalize(prefName)] = function (prefValue) {var usesSdk = this.doc.getroot().find('./uses-sdk');if (!usesSdk && prefValue) { // if there is no required uses-sdk element, we should create it first@@ -128,11 +127,11 @@ AndroidManifest.prototype.getActivity = function() {};});-AndroidManifest.prototype.getDebuggable = function() {+AndroidManifest.prototype.getDebuggable = function () {return this.doc.getroot().find('./application').attrib['android:debuggable'] === 'true';};-AndroidManifest.prototype.setDebuggable = function(value) {+AndroidManifest.prototype.setDebuggable = function (value) {var application = this.doc.getroot().find('./application');if (value) {application.attrib['android:debuggable'] = 'true';@@ -150,7 +149,7 @@ AndroidManifest.prototype.setDebuggable = function(value) {* @param {String} [destPath] File to write manifest to. If omitted,* manifest will be written to file it has been read from.*/-AndroidManifest.prototype.write = function(destPath) {+AndroidManifest.prototype.write = function (destPath) {fs.writeFileSync(destPath || this.path, this.doc.write({indent: 4}), 'utf-8');};diff --git a/cordova/platforms/android/cordova/lib/AndroidProject.js b/cordova/platforms/android/cordova/lib/AndroidProject.jsindex fa1c6129f..bf55cad1c 100644--- a/cordova/platforms/android/cordova/lib/AndroidProject.js+++ b/cordova/platforms/android/cordova/lib/AndroidProject.js@@ -26,16 +26,15 @@ var pluginHandlers = require('./pluginHandlers');var projectFileCache = {};-function addToPropertyList(projectProperties, key, value) {+function addToPropertyList (projectProperties, key, value) {var i = 1;- while (projectProperties.get(key + '.' + i))- i++;+ while (projectProperties.get(key + '.' + i)) { i++; }projectProperties.set(key + '.' + i, value);projectProperties.dirty = true;}-function removeFromPropertyList(projectProperties, key, value) {+function removeFromPropertyList (projectProperties, key, value) {var i = 1;var currentValue;while ((currentValue = projectProperties.get(key + '.' + i))) {@@ -54,18 +53,18 @@ function removeFromPropertyList(projectProperties, key, value) {function getRelativeLibraryPath (parentDir, subDir) {var libraryPath = path.relative(parentDir, subDir);- return (path.sep == '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath;+ return (path.sep === '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath;}-function AndroidProject(projectDir) {+function AndroidProject (projectDir) {this._propertiesEditors = {};this._subProjectDirs = {};this._dirty = false;this.projectDir = projectDir;this.platformWww = path.join(this.projectDir, 'platform_www');this.www = path.join(this.projectDir, 'assets/www');- if(AndroidStudio.isAndroidStudioProject(projectDir) === true) {- this.www = path.join(this.projectDir, 'app/src/main/assets/www');+ if (AndroidStudio.isAndroidStudioProject(projectDir) === true) {+ this.www = path.join(this.projectDir, 'app/src/main/assets/www');}}@@ -92,15 +91,15 @@ AndroidProject.purgeCache = function (projectDir) {** @return {String} The name of the package*/-AndroidProject.prototype.getPackageName = function() {+AndroidProject.prototype.getPackageName = function () {var manifestPath = path.join(this.projectDir, 'AndroidManifest.xml');- if(AndroidStudio.isAndroidStudioProject(this.projectDir) === true) {- manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');+ if (AndroidStudio.isAndroidStudioProject(this.projectDir) === true) {+ manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');}return new AndroidManifest(manifestPath).getPackageId();};-AndroidProject.prototype.getCustomSubprojectRelativeDir = function(plugin_id, src) {+AndroidProject.prototype.getCustomSubprojectRelativeDir = function (plugin_id, src) {// All custom subprojects are prefixed with the last portion of the package id.// This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name.var packageName = this.getPackageName();@@ -110,7 +109,7 @@ AndroidProject.prototype.getCustomSubprojectRelativeDir = function(plugin_id, srreturn subRelativeDir;};-AndroidProject.prototype.addSubProject = function(parentDir, subDir) {+AndroidProject.prototype.addSubProject = function (parentDir, subDir) {var parentProjectFile = path.resolve(parentDir, 'project.properties');var subProjectFile = path.resolve(subDir, 'project.properties');var parentProperties = this._getPropertiesFile(parentProjectFile);@@ -126,7 +125,7 @@ AndroidProject.prototype.addSubProject = function(parentDir, subDir) {this._dirty = true;};-AndroidProject.prototype.removeSubProject = function(parentDir, subDir) {+AndroidProject.prototype.removeSubProject = function (parentDir, subDir) {var parentProjectFile = path.resolve(parentDir, 'project.properties');var parentProperties = this._getPropertiesFile(parentProjectFile);removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));@@ -134,35 +133,35 @@ AndroidProject.prototype.removeSubProject = function(parentDir, subDir) {this._dirty = true;};-AndroidProject.prototype.addGradleReference = function(parentDir, subDir) {+AndroidProject.prototype.addGradleReference = function (parentDir, subDir) {var parentProjectFile = path.resolve(parentDir, 'project.properties');var parentProperties = this._getPropertiesFile(parentProjectFile);addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));this._dirty = true;};-AndroidProject.prototype.removeGradleReference = function(parentDir, subDir) {+AndroidProject.prototype.removeGradleReference = function (parentDir, subDir) {var parentProjectFile = path.resolve(parentDir, 'project.properties');var parentProperties = this._getPropertiesFile(parentProjectFile);removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));this._dirty = true;};-AndroidProject.prototype.addSystemLibrary = function(parentDir, value) {+AndroidProject.prototype.addSystemLibrary = function (parentDir, value) {var parentProjectFile = path.resolve(parentDir, 'project.properties');var parentProperties = this._getPropertiesFile(parentProjectFile);addToPropertyList(parentProperties, 'cordova.system.library', value);this._dirty = true;};-AndroidProject.prototype.removeSystemLibrary = function(parentDir, value) {+AndroidProject.prototype.removeSystemLibrary = function (parentDir, value) {var parentProjectFile = path.resolve(parentDir, 'project.properties');var parentProperties = this._getPropertiesFile(parentProjectFile);removeFromPropertyList(parentProperties, 'cordova.system.library', value);this._dirty = true;};-AndroidProject.prototype.write = function() {+AndroidProject.prototype.write = function () {if (!this._dirty) {return;}@@ -201,9 +200,9 @@ AndroidProject.prototype.getUninstaller = function (type) {* This checks if an Android project is clean or has old build artifacts*/-AndroidProject.prototype.isClean = function() {+AndroidProject.prototype.isClean = function () {var build_path = path.join(this.projectDir, 'build');- //If the build directory doesn't exist, it's clean+ // If the build directory doesn't exist, it's cleanreturn !(fs.existsSync(build_path));};diff --git a/cordova/platforms/android/cordova/lib/AndroidStudio.js b/cordova/platforms/android/cordova/lib/AndroidStudio.jsindex 335b334b6..68d4d8f6c 100644--- a/cordova/platforms/android/cordova/lib/AndroidStudio.js+++ b/cordova/platforms/android/cordova/lib/AndroidStudio.js@@ -4,39 +4,8 @@* @param {String} root Root folder of the project*/-/*jshint esnext: false */+/* jshint esnext: false */-var path = require('path');-var fs = require('fs');-var CordovaError = require('cordova-common').CordovaError;--module.exports.isAndroidStudioProject = function isAndroidStudioProject(root) {- var eclipseFiles = ['AndroidManifest.xml', 'libs', 'res', 'project.properties', 'platform_www'];- var androidStudioFiles = ['app', 'gradle', 'app/src/main/res'];-- // assume it is an AS project and not an Eclipse project- var isEclipse = false;- var isAS = true;-- if(!fs.existsSync(root)) {- throw new CordovaError('AndroidStudio.js:inAndroidStudioProject root does not exist: ' + root);- }-- // if any of the following exists, then we are not an ASProj- eclipseFiles.forEach(function(file) {- if(fs.existsSync(path.join(root, file))) {- isEclipse = true;- }- });-- // if it is NOT an eclipse project, check that all required files exist- if(!isEclipse) {- androidStudioFiles.forEach(function(file){- if(!fs.existsSync(path.join(root, file))) {- console.log('missing file :: ' + file);- isAS = false;- }- });- }- return (!isEclipse && isAS);+module.exports.isAndroidStudioProject = function isAndroidStudioProject (root) {+ return true;};diff --git a/cordova/platforms/android/cordova/lib/android_sdk.js b/cordova/platforms/android/cordova/lib/android_sdk.jsindex a1a806a63..148f9f3db 100755--- a/cordova/platforms/android/cordova/lib/android_sdk.js+++ b/cordova/platforms/android/cordova/lib/android_sdk.js@@ -17,8 +17,8 @@under the License.*/-var Q = require('q'),- superspawn = require('cordova-common').superspawn;+var Q = require('q');+var superspawn = require('cordova-common').superspawn;var suffix_number_regex = /(\d+)$/;// Used for sorting Android targets, example strings to sort:@@ -29,7 +29,7 @@ var suffix_number_regex = /(\d+)$/;// The idea is to sort based on largest "suffix" number - meaning the bigger// the number at the end, the more recent the target, the closer to the// start of the array.-function sort_by_largest_numerical_suffix(a, b) {+function sort_by_largest_numerical_suffix (a, b) {var suffix_a = a.match(suffix_number_regex);var suffix_b = b.match(suffix_number_regex);if (suffix_a && suffix_b) {@@ -43,9 +43,8 @@ function sort_by_largest_numerical_suffix(a, b) {}}-module.exports.print_newest_available_sdk_target = function() {- return module.exports.list_targets()- .then(function(targets) {+module.exports.print_newest_available_sdk_target = function () {+ return module.exports.list_targets().then(function (targets) {targets.sort(sort_by_largest_numerical_suffix);console.log(targets[0]);});@@ -63,41 +62,38 @@ module.exports.version_string_to_api_level = {'5.1': 22,'6.0': 23,'7.0': 24,- '7.1.1': 25+ '7.1.1': 25,+ '8.0': 26};-function parse_targets(output) {+function parse_targets (output) {var target_out = output.split('\n');var targets = [];for (var i = target_out.length - 1; i >= 0; i--) {- if(target_out[i].match(/id:/)) { // if "id:" is in the line...- targets.push(target_out[i].match(/"(.+)"/)[1]); //.. match whatever is in quotes.+ if (target_out[i].match(/id:/)) { // if "id:" is in the line...+ targets.push(target_out[i].match(/"(.+)"/)[1]); // .. match whatever is in quotes.}}return targets;}-module.exports.list_targets_with_android = function() {- return superspawn.spawn('android', ['list', 'target'])- .then(parse_targets);+module.exports.list_targets_with_android = function () {+ return superspawn.spawn('android', ['list', 'target']).then(parse_targets);};-module.exports.list_targets_with_avdmanager = function() {- return superspawn.spawn('avdmanager', ['list', 'target'])- .then(parse_targets);+module.exports.list_targets_with_avdmanager = function () {+ return superspawn.spawn('avdmanager', ['list', 'target']).then(parse_targets);};-module.exports.list_targets = function() {- return module.exports.list_targets_with_avdmanager()- .catch(function(err) {+module.exports.list_targets = function () {+ return module.exports.list_targets_with_avdmanager().catch(function (err) {// If there's an error, like avdmanager could not be found, we can try// as a last resort, to run `android`, in case this is a super old// SDK installation.- if (err && (err.code == 'ENOENT' || (err.stderr && err.stderr.match(/not recognized/)))) {+ if (err && (err.code === 'ENOENT' || (err.stderr && err.stderr.match(/not recognized/)))) {return module.exports.list_targets_with_android();} else throw err;- })- .then(function(targets) {+ }).then(function (targets) {if (targets.length === 0) {return Q.reject(new Error('No android targets (SDKs) installed!'));}diff --git a/cordova/platforms/android/cordova/lib/build.js b/cordova/platforms/android/cordova/lib/build.jsindex bd613da2f..e33cfae08 100644--- a/cordova/platforms/android/cordova/lib/build.js+++ b/cordova/platforms/android/cordova/lib/build.js@@ -19,10 +19,10 @@under the License.*/-var Q = require('q'),- path = require('path'),- fs = require('fs'),- nopt = require('nopt');+var Q = require('q');+var path = require('path');+var fs = require('fs');+var nopt = require('nopt');var Adb = require('./Adb');@@ -31,11 +31,11 @@ var events = require('cordova-common').events;var spawn = require('cordova-common').superspawn.spawn;var CordovaError = require('cordova-common').CordovaError;-function parseOpts(options, resolvedTarget, projectRoot) {+function parseOpts (options, resolvedTarget, projectRoot) {options = options || {};options.argv = nopt({gradle: Boolean,- ant: Boolean,+ studio: Boolean,prepenv: Boolean,versionCode: String,minSdkVersion: String,@@ -47,24 +47,28 @@ function parseOpts(options, resolvedTarget, projectRoot) {keystoreType: String}, {}, options.argv, 0);+ // Android Studio Build method is the defaultvar ret = {buildType: options.release ? 'release' : 'debug',- buildMethod: process.env.ANDROID_BUILD || 'gradle',+ buildMethod: process.env.ANDROID_BUILD || 'studio',prepEnv: options.argv.prepenv,arch: resolvedTarget && resolvedTarget.arch,extraArgs: []};- if (options.argv.ant || options.argv.gradle)- ret.buildMethod = options.argv.ant ? 'ant' : 'gradle';+ if (options.argv.gradle || options.argv.studio) {+ ret.buildMethod = options.argv.studio ? 'studio' : 'gradle';+ }++ // This comes from cordova/run+ if (options.studio) ret.buildMethod = 'studio';+ if (options.gradle) ret.buildMethod = 'gradle';if (options.nobuild) ret.buildMethod = 'none';- if (options.argv.versionCode)- ret.extraArgs.push('-PcdvVersionCode=' + options.argv.versionCode);+ if (options.argv.versionCode) { ret.extraArgs.push('-PcdvVersionCode=' + options.argv.versionCode); }- if (options.argv.minSdkVersion)- ret.extraArgs.push('-PcdvMinSdkVersion=' + options.argv.minSdkVersion);+ if (options.argv.minSdkVersion) { ret.extraArgs.push('-PcdvMinSdkVersion=' + options.argv.minSdkVersion); }if (options.argv.gradleArg) {ret.extraArgs = ret.extraArgs.concat(options.argv.gradleArg);@@ -72,12 +76,10 @@ function parseOpts(options, resolvedTarget, projectRoot) {var packageArgs = {};- if (options.argv.keystore)- packageArgs.keystore = path.relative(projectRoot, path.resolve(options.argv.keystore));+ if (options.argv.keystore) { packageArgs.keystore = path.relative(projectRoot, path.resolve(options.argv.keystore)); }- ['alias','storePassword','password','keystoreType'].forEach(function (flagName) {- if (options.argv[flagName])- packageArgs[flagName] = options.argv[flagName];+ ['alias', 'storePassword', 'password', 'keystoreType'].forEach(function (flagName) {+ if (options.argv[flagName]) { packageArgs[flagName] = options.argv[flagName]; }});var buildConfig = options.buildConfig;@@ -88,20 +90,20 @@ function parseOpts(options, resolvedTarget, projectRoot) {if (!fs.existsSync(buildConfig)) {throw new Error('Specified build config file does not exist: ' + buildConfig);}- events.emit('log', 'Reading build config file: '+ path.resolve(buildConfig));+ events.emit('log', 'Reading build config file: ' + path.resolve(buildConfig));var buildjson = fs.readFileSync(buildConfig, 'utf8');var config = JSON.parse(buildjson.replace(/^\ufeff/, '')); // Remove BOMif (config.android && config.android[ret.buildType]) {var androidInfo = config.android[ret.buildType];- if(androidInfo.keystore && !packageArgs.keystore) {- if(androidInfo.keystore.substr(0,1) === '~') {+ if (androidInfo.keystore && !packageArgs.keystore) {+ if (androidInfo.keystore.substr(0, 1) === '~') {androidInfo.keystore = process.env.HOME + androidInfo.keystore.substr(1);}packageArgs.keystore = path.resolve(path.dirname(buildConfig), androidInfo.keystore);events.emit('log', 'Reading the keystore from: ' + packageArgs.keystore);}- ['alias', 'storePassword', 'password','keystoreType'].forEach(function (key){+ ['alias', 'storePassword', 'password', 'keystoreType'].forEach(function (key) {packageArgs[key] = packageArgs[key] || androidInfo[key];});}@@ -112,8 +114,8 @@ function parseOpts(options, resolvedTarget, projectRoot) {packageArgs.password, packageArgs.keystoreType);}- if(!ret.packageInfo) {- if(Object.keys(packageArgs).length > 0) {+ if (!ret.packageInfo) {+ if (Object.keys(packageArgs).length > 0) {events.emit('warn', '\'keystore\' and \'alias\' need to be specified to generate a signed archive.');}}@@ -125,11 +127,10 @@ function parseOpts(options, resolvedTarget, projectRoot) {* Builds the project with the specifed options* Returns a promise.*/-module.exports.runClean = function(options) {+module.exports.runClean = function (options) {var opts = parseOpts(options, null, this.root);var builder = builders.getBuilder(opts.buildMethod);- return builder.prepEnv(opts)- .then(function() {+ return builder.prepEnv(opts).then(function () {return builder.clean(opts);});};@@ -146,17 +147,16 @@ module.exports.runClean = function(options) {* @return {Promise<Object>} Promise, resolved with built packages* information.*/-module.exports.run = function(options, optResolvedTarget) {+module.exports.run = function (options, optResolvedTarget) {var opts = parseOpts(options, optResolvedTarget, this.root);+ console.log(opts.buildMethod);var builder = builders.getBuilder(opts.buildMethod);- return builder.prepEnv(opts)- .then(function() {+ return builder.prepEnv(opts).then(function () {if (opts.prepEnv) {events.emit('verbose', 'Build file successfully prepared.');return;}- return builder.build(opts)- .then(function() {+ return builder.build(opts).then(function () {var apkPaths = builder.findOutputApks(opts.buildType, opts.arch);events.emit('log', 'Built the following apk(s): \n\t' + apkPaths.join('\n\t'));return {@@ -172,38 +172,31 @@ module.exports.run = function(options, optResolvedTarget) {* Detects the architecture of a device/emulator* Returns "arm" or "x86".*/-module.exports.detectArchitecture = function(target) {- function helper() {- return Adb.shell(target, 'cat /proc/cpuinfo')- .then(function(output) {+module.exports.detectArchitecture = function (target) {+ function helper () {+ return Adb.shell(target, 'cat /proc/cpuinfo').then(function (output) {return /intel/i.exec(output) ? 'x86' : 'arm';});}// It sometimes happens (at least on OS X), that this command will hang forever.// To fix it, either unplug & replug device, or restart adb server.- return helper()- .timeout(1000, new CordovaError('Device communication timed out. Try unplugging & replugging the device.'))- .then(null, function(err) {+ return helper().timeout(1000, new CordovaError('Device communication timed out. Try unplugging & replugging the device.')).then(null, function (err) {if (/timed out/.exec('' + err)) {// adb kill-server doesn't seem to do the trick.// Could probably find a x-platform version of killall, but I'm not actually// sure that this scenario even happens on non-OSX machines.events.emit('verbose', 'adb timed out while detecting device/emulator architecture. Killing adb and trying again.');- return spawn('killall', ['adb'])- .then(function() {- return helper()- .then(null, function() {+ return spawn('killall', ['adb']).then(function () {+ return helper().then(null, function () {// The double kill is sadly often necessary, at least on mac.events.emit('warn', 'adb timed out a second time while detecting device/emulator architecture. Killing adb and trying again.');- return spawn('killall', ['adb'])- .then(function() {- return helper()- .then(null, function() {+ return spawn('killall', ['adb']).then(function () {+ return helper().then(null, function () {return Q.reject(new CordovaError('adb timed out a third time while detecting device/emulator architecture. Try unplugging & replugging the device.'));});});});- }, function() {+ }, function () {// For non-killall OS's.return Q.reject(err);});@@ -212,10 +205,10 @@ module.exports.detectArchitecture = function(target) {});};-module.exports.findBestApkForArchitecture = function(buildResults, arch) {- var paths = buildResults.apkPaths.filter(function(p) {+module.exports.findBestApkForArchitecture = function (buildResults, arch) {+ var paths = buildResults.apkPaths.filter(function (p) {var apkName = path.basename(p);- if (buildResults.buildType == 'debug') {+ if (buildResults.buildType === 'debug') {return /-debug/.exec(apkName);}return !/-debug/.exec(apkName);@@ -235,7 +228,7 @@ module.exports.findBestApkForArchitecture = function(buildResults, arch) {throw new Error('Could not find apk architecture: ' + arch + ' build-type: ' + buildResults.buildType);};-function PackageInfo(keystore, alias, storePassword, password, keystoreType) {+function PackageInfo (keystore, alias, storePassword, password, keystoreType) {this.keystore = {'name': 'key.store','value': keystore@@ -265,10 +258,10 @@ function PackageInfo(keystore, alias, storePassword, password, keystoreType) {}PackageInfo.prototype = {- toProperties: function() {+ toProperties: function () {var self = this;var result = '';- Object.keys(self).forEach(function(key) {+ Object.keys(self).forEach(function (key) {result += self[key].name;result += '=';result += self[key].value.replace(/\\/g, '\\\\');@@ -278,7 +271,7 @@ PackageInfo.prototype = {}};-module.exports.help = function() {+module.exports.help = function () {console.log('Usage: ' + path.relative(process.cwd(), path.join('../build')) + ' [flags] [Signed APK flags]');console.log('Flags:');console.log(' \'--debug\': will build project in debug mode (default)');diff --git a/cordova/platforms/android/cordova/lib/builders/AntBuilder.js b/cordova/platforms/android/cordova/lib/builders/AntBuilder.jsdeleted file mode 100644index 4e0f71ab0..000000000--- a/cordova/platforms/android/cordova/lib/builders/AntBuilder.js+++ /dev/null@@ -1,156 +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 Q = require('q');-var fs = require('fs');-var path = require('path');-var util = require('util');-var shell = require('shelljs');-var spawn = require('cordova-common').superspawn.spawn;-var CordovaError = require('cordova-common').CordovaError;-var check_reqs = require('../check_reqs');--var SIGNING_PROPERTIES = '-signing.properties';-var MARKER = 'YOUR CHANGES WILL BE ERASED!';-var TEMPLATE =- '# This file is automatically generated.\n' +- '# Do not modify this file -- ' + MARKER + '\n';--var GenericBuilder = require('./GenericBuilder');--function AntBuilder (projectRoot) {- GenericBuilder.call(this, projectRoot);-- this.binDirs = {ant: this.binDirs.ant};-}--util.inherits(AntBuilder, GenericBuilder);--AntBuilder.prototype.getArgs = function(cmd, opts) {- var args = [cmd, '-f', path.join(this.root, 'build.xml')];- // custom_rules.xml is required for incremental builds.- if (hasCustomRules(this.root)) {- args.push('-Dout.dir=ant-build', '-Dgen.absolute.dir=ant-gen');- }- if(opts.packageInfo) {- args.push('-propertyfile=' + path.join(this.root, opts.buildType + SIGNING_PROPERTIES));- }- return args;-};--AntBuilder.prototype.prepEnv = function(opts) {- var self = this;- return check_reqs.check_ant()- .then(function() {- // Copy in build.xml on each build so that:- // A) we don't require the Android SDK at project creation time, and- // B) we always use the SDK's latest version of it.- /*jshint -W069 */- var sdkDir = process.env['ANDROID_HOME'];- /*jshint +W069 */- var buildTemplate = fs.readFileSync(path.join(sdkDir, 'tools', 'lib', 'build.template'), 'utf8');- function writeBuildXml(projectPath) {- var newData = buildTemplate.replace('PROJECT_NAME', self.extractRealProjectNameFromManifest());- fs.writeFileSync(path.join(projectPath, 'build.xml'), newData);- if (!fs.existsSync(path.join(projectPath, 'local.properties'))) {- fs.writeFileSync(path.join(projectPath, 'local.properties'), TEMPLATE);- }- }- writeBuildXml(self.root);- var propertiesObj = self.readProjectProperties();- var subProjects = propertiesObj.libs;- for (var i = 0; i < subProjects.length; ++i) {- writeBuildXml(path.join(self.root, subProjects[i]));- }- if (propertiesObj.systemLibs.length > 0) {- throw new CordovaError('Project contains at least one plugin that requires a system library. This is not supported with ANT. Use gradle instead.');- }-- var propertiesFile = opts.buildType + SIGNING_PROPERTIES;- var propertiesFilePath = path.join(self.root, propertiesFile);- if (opts.packageInfo) {- fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());- } else if(isAutoGenerated(propertiesFilePath)) {- shell.rm('-f', propertiesFilePath);- }- });-};--/*- * Builds the project with ant.- * Returns a promise.- */-AntBuilder.prototype.build = function(opts) {- // Without our custom_rules.xml, we need to clean before building.- var ret = Q();- if (!hasCustomRules(this.root)) {- // clean will call check_ant() for us.- ret = this.clean(opts);- }-- var args = this.getArgs(opts.buildType == 'debug' ? 'debug' : 'release', opts);- return check_reqs.check_ant()- .then(function() {- return spawn('ant', args, {stdio: 'pipe'});- }).progress(function (stdio){- if (stdio.stderr) {- process.stderr.write(stdio.stderr);- } else {- process.stdout.write(stdio.stdout);- }- }).catch(function (error) {- if (error.toString().indexOf('Unable to resolve project target') >= 0) {- return check_reqs.check_android_target(error).then(function() {- // If due to some odd reason - check_android_target succeeds- // we should still fail here.- return Q.reject(error);- });- }- return Q.reject(error);- });-};--AntBuilder.prototype.clean = function(opts) {- var args = this.getArgs('clean', opts);- var self = this;- return check_reqs.check_ant()- .then(function() {- return spawn('ant', args, {stdio: 'inherit'});- })- .then(function () {- shell.rm('-rf', path.join(self.root, 'out'));-- ['debug', 'release'].forEach(function(config) {- var propertiesFilePath = path.join(self.root, config + SIGNING_PROPERTIES);- if(isAutoGenerated(propertiesFilePath)){- shell.rm('-f', propertiesFilePath);- }- });- });-};--module.exports = AntBuilder;--function hasCustomRules(projectRoot) {- return fs.existsSync(path.join(projectRoot, 'custom_rules.xml'));-}--function isAutoGenerated(file) {- return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;-}diff --git a/cordova/platforms/android/cordova/lib/builders/GenericBuilder.js b/cordova/platforms/android/cordova/lib/builders/GenericBuilder.jsindex 362da4312..892aa38f4 100644--- a/cordova/platforms/android/cordova/lib/builders/GenericBuilder.js+++ b/cordova/platforms/android/cordova/lib/builders/GenericBuilder.js@@ -16,83 +16,55 @@specific language governing permissions and limitationsunder the License.*/+/* eslint no-self-assign: 0 */+/* eslint no-unused-vars: 0 */var Q = require('q');var fs = require('fs');var path = require('path');var shell = require('shelljs');var events = require('cordova-common').events;-var CordovaError = require('cordova-common').CordovaError;function GenericBuilder (projectDir) {this.root = projectDir || path.resolve(__dirname, '../../..');this.binDirs = {- ant: path.join(this.root, hasCustomRules(this.root) ? 'ant-build' : 'bin'),+ studio: path.join(this.root, 'app', 'build', 'outputs', 'apk'),gradle: path.join(this.root, 'build', 'outputs', 'apk')};}-function hasCustomRules(projectRoot) {- return fs.existsSync(path.join(projectRoot, 'custom_rules.xml'));-}--GenericBuilder.prototype.prepEnv = function() {+GenericBuilder.prototype.prepEnv = function () {return Q();};-GenericBuilder.prototype.build = function() {+GenericBuilder.prototype.build = function () {events.emit('log', 'Skipping build...');return Q(null);};-GenericBuilder.prototype.clean = function() {+GenericBuilder.prototype.clean = function () {return Q();};-GenericBuilder.prototype.findOutputApks = function(build_type, arch) {+GenericBuilder.prototype.findOutputApks = function (build_type, arch) {var self = this;- return Object.keys(this.binDirs)- .reduce(function (result, builderName) {+ return Object.keys(this.binDirs).reduce(function (result, builderName) {var binDir = self.binDirs[builderName];return result.concat(findOutputApksHelper(binDir, build_type, builderName === 'ant' ? null : arch));- }, [])- .sort(apkSorter);+ }, []).sort(apkSorter);};-GenericBuilder.prototype.readProjectProperties = function () {- function findAllUniq(data, r) {- var s = {};- var m;- while ((m = r.exec(data))) {- s[m[1]] = 1;- }- return Object.keys(s);- }-- var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');- return {- libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),- gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),- systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)- };-};+module.exports = GenericBuilder;-GenericBuilder.prototype.extractRealProjectNameFromManifest = function () {- var manifestPath = path.join(this.root, 'AndroidManifest.xml');- var manifestData = fs.readFileSync(manifestPath, 'utf8');- var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);- if (!m) {- throw new CordovaError('Could not find package name in ' + manifestPath);+function apkSorter (fileA, fileB) {+ // De-prioritize arch specific builds+ var archSpecificRE = /-x86|-arm/;+ if (archSpecificRE.exec(fileA)) {+ return 1;+ } else if (archSpecificRE.exec(fileB)) {+ return -1;}- var packageName=m[1];- var lastDotIndex = packageName.lastIndexOf('.');- return packageName.substring(lastDotIndex + 1);-};--module.exports = GenericBuilder;--function apkSorter(fileA, fileB) {// De-prioritize unsigned buildsvar unsignedRE = /-unsigned/;if (unsignedRE.exec(fileA)) {@@ -101,16 +73,22 @@ function apkSorter(fileA, fileB) {return -1;}- var timeDiff = fs.statSync(fileA).mtime - fs.statSync(fileB).mtime;+ var timeDiff = fs.statSync(fileB).mtime - fs.statSync(fileA).mtime;return timeDiff === 0 ? fileA.length - fileB.length : timeDiff;}-function findOutputApksHelper(dir, build_type, arch) {+function findOutputApksHelper (dir, build_type, arch) {var shellSilent = shell.config.silent;shell.config.silent = true;- var ret = shell.ls(path.join(dir, '*.apk'))- .filter(function(candidate) {+ // list directory recursively+ var ret = shell.ls('-R', dir).map(function (file) {+ // ls does not include base directory+ return path.join(dir, file);+ }).filter(function (file) {+ // find all APKs+ return file.match(/\.apk?$/i);+ }).filter(function (candidate) {var apkName = path.basename(candidate);// Need to choose between release and debug .apk.if (build_type === 'debug') {@@ -120,8 +98,7 @@ function findOutputApksHelper(dir, build_type, arch) {return /-release/.exec(apkName) && !/-unaligned/.exec(apkName);}return true;- })- .sort(apkSorter);+ }).sort(apkSorter);shellSilent = shellSilent;@@ -131,15 +108,15 @@ function findOutputApksHelper(dir, build_type, arch) {// Assume arch-specific build if newest apk has -x86 or -arm.var archSpecific = !!/-x86|-arm/.exec(path.basename(ret[0]));// And show only arch-specific ones (or non-arch-specific)- ret = ret.filter(function(p) {- /*jshint -W018 */- return !!/-x86|-arm/.exec(path.basename(p)) == archSpecific;- /*jshint +W018 */+ ret = ret.filter(function (p) {+ /* jshint -W018 */+ return !!/-x86|-arm/.exec(path.basename(p)) === archSpecific;+ /* jshint +W018 */});if (archSpecific && ret.length > 1 && arch) {- ret = ret.filter(function(p) {- return path.basename(p).indexOf('-' + arch) != -1;+ ret = ret.filter(function (p) {+ return path.basename(p).indexOf('-' + arch) !== -1;});}diff --git a/cordova/platforms/android/cordova/lib/builders/GradleBuilder.js b/cordova/platforms/android/cordova/lib/builders/GradleBuilder.jsindex 5b5ce13de..b955db18b 100644--- a/cordova/platforms/android/cordova/lib/builders/GradleBuilder.js+++ b/cordova/platforms/android/cordova/lib/builders/GradleBuilder.js@@ -22,8 +22,9 @@ var fs = require('fs');var util = require('util');var path = require('path');var shell = require('shelljs');-var spawn = require('cordova-common').superspawn.spawn;+var superspawn = require('cordova-common').superspawn;var CordovaError = require('cordova-common').CordovaError;+var events = require('cordova-common').events;var check_reqs = require('../check_reqs');var GenericBuilder = require('./GenericBuilder');@@ -37,15 +38,15 @@ var TEMPLATE =function GradleBuilder (projectRoot) {GenericBuilder.call(this, projectRoot);- this.binDirs = {gradle: this.binDirs.gradle};+ this.binDirs = { gradle: this.binDirs.gradle };}util.inherits(GradleBuilder, GenericBuilder);-GradleBuilder.prototype.getArgs = function(cmd, opts) {- if (cmd == 'release') {+GradleBuilder.prototype.getArgs = function (cmd, opts) {+ if (cmd === 'release') {cmd = 'cdvBuildRelease';- } else if (cmd == 'debug') {+ } else if (cmd === 'debug') {cmd = 'cdvBuildDebug';}var args = [cmd, '-b', path.join(this.root, 'build.gradle')];@@ -69,46 +70,89 @@ GradleBuilder.prototype.getArgs = function(cmd, opts) {* This returns a promise*/-GradleBuilder.prototype.runGradleWrapper = function(gradle_cmd) {+GradleBuilder.prototype.runGradleWrapper = function (gradle_cmd, gradle_file) {var gradlePath = path.join(this.root, 'gradlew');- var wrapperGradle = path.join(this.root, 'wrapper.gradle');- if(fs.existsSync(gradlePath)) {- //Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows+ gradle_file = path.join(this.root, (gradle_file || 'wrapper.gradle'));+ if (fs.existsSync(gradlePath)) {+ // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows} else {- return spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', wrapperGradle], {stdio: 'inherit'});+ return superspawn.spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', gradle_file], { stdio: 'pipe' })+ .progress(function (stdio) {+ suppressJavaOptionsInfo(stdio);+ });}};+/*+ * We need to kill this in a fire.+ */++GradleBuilder.prototype.readProjectProperties = function () {+ function findAllUniq (data, r) {+ var s = {};+ var m;+ while ((m = r.exec(data))) {+ s[m[1]] = 1;+ }+ return Object.keys(s);+ }++ var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');+ return {+ libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),+ gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),+ systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)+ };+};++GradleBuilder.prototype.extractRealProjectNameFromManifest = function () {+ var manifestPath = path.join(this.root, 'AndroidManifest.xml');+ var manifestData = fs.readFileSync(manifestPath, 'utf8');+ var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);+ if (!m) {+ throw new CordovaError('Could not find package name in ' + manifestPath);+ }++ var packageName = m[1];+ var lastDotIndex = packageName.lastIndexOf('.');+ return packageName.substring(lastDotIndex + 1);+};// Makes the project buildable, minus the gradle wrapper.-GradleBuilder.prototype.prepBuildFiles = function() {+GradleBuilder.prototype.prepBuildFiles = function () {// Update the version of build.gradle in each dependent library.var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');var propertiesObj = this.readProjectProperties();var subProjects = propertiesObj.libs;- var checkAndCopy = function(subProject, root) {- var subProjectGradle = path.join(root, subProject, 'build.gradle');- // This is the future-proof way of checking if a file exists- // This must be synchronous to satisfy a Travis test- try {- fs.accessSync(subProjectGradle, fs.F_OK);- } catch (e) {- shell.cp('-f', pluginBuildGradle, subProjectGradle);- }++ // Check and copy the gradle file into the subproject.+ // Called by the loop below this function def.+ var checkAndCopy = function (subProject, root) {+ var subProjectGradle = path.join(root, subProject, 'build.gradle');+ // This is the future-proof way of checking if a file exists+ // This must be synchronous to satisfy a Travis test+ try {+ fs.accessSync(subProjectGradle, fs.F_OK);+ } catch (e) {+ shell.cp('-f', pluginBuildGradle, subProjectGradle);+ }};++ // Some dependencies on Android don't use gradle, or don't have default+ // gradle files. This copies a dummy gradle file into themfor (var i = 0; i < subProjects.length; ++i) {- if (subProjects[i] !== 'CordovaLib') {- checkAndCopy(subProjects[i], this.root);+ if (subProjects[i] !== 'CordovaLib' && subProjects[i] !== 'app') {+ checkAndCopy(subProjects[i], this.root);}}+var name = this.extractRealProjectNameFromManifest();- //Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149- var settingsGradlePaths = subProjects.map(function(p){- var realDir=p.replace(/[/\\]/g, ':');- var libName=realDir.replace(name+'-','');- var str='include ":'+libName+'"\n';- if(realDir.indexOf(name+'-')!==-1)- str+='project(":'+libName+'").projectDir = new File("'+p+'")\n';+ // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149+ var settingsGradlePaths = subProjects.map(function (p) {+ var realDir = p.replace(/[/\\]/g, ':');+ var libName = realDir.replace(name + '-', '');+ var str = 'include ":' + libName + '"\n';+ if (realDir.indexOf(name + '-') !== -1) { str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n'; }return str;});@@ -120,30 +164,33 @@ GradleBuilder.prototype.prepBuildFiles = function() {var buildGradle = fs.readFileSync(path.join(this.root, 'build.gradle'), 'utf8');var depsList = '';var root = this.root;- var insertExclude = function(p) {- var gradlePath = path.join(root, p, 'build.gradle');- var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');- if(projectGradleFile.indexOf('CordovaLib') != -1) {++ // Cordova Plugins can be written as library modules that would use Cordova as a+ // dependency. Because we need to make sure that Cordova is compiled only once for+ // dexing, we make sure to exclude CordovaLib from these modules+ var insertExclude = function (p) {+ var gradlePath = path.join(root, p, 'build.gradle');+ var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');+ if (projectGradleFile.indexOf('CordovaLib') !== -1) {depsList += '{\n exclude module:("CordovaLib")\n }\n';- }- else {- depsList +='\n';- }+ } else {+ depsList += '\n';+ }};- subProjects.forEach(function(p) {- console.log('Subproject Path: ' + p);- var libName=p.replace(/[/\\]/g, ':').replace(name+'-','');- depsList += ' debugCompile(project(path: "' + libName + '", configuration: "debug"))';- insertExclude(p);- depsList += ' releaseCompile(project(path: "' + libName + '", configuration: "release"))';++ subProjects.forEach(function (p) {+ events.emit('log', 'Subproject Path: ' + p);+ var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');+ depsList += ' implementation(project(path: "' + libName + '"))';insertExclude(p);});+// For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390var SYSTEM_LIBRARY_MAPPINGS = [[/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],[/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']];- propertiesObj.systemLibs.forEach(function(p) {+ propertiesObj.systemLibs.forEach(function (p) {var mavenRef;// It's already in gradle form if it has two ':'sif (/:.*:/.exec(p)) {@@ -162,23 +209,25 @@ GradleBuilder.prototype.prepBuildFiles = function() {}depsList += ' compile "' + mavenRef + '"\n';});++ // This code is dangerous and actually writes gradle declarations directly into the build.gradle+ // Try not to mess with this if possiblebuildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');var includeList = '';- propertiesObj.gradleIncludes.forEach(function(includePath) {+ propertiesObj.gradleIncludes.forEach(function (includePath) {includeList += 'apply from: "' + includePath + '"\n';});buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');fs.writeFileSync(path.join(this.root, 'build.gradle'), buildGradle);};-GradleBuilder.prototype.prepEnv = function(opts) {+GradleBuilder.prototype.prepEnv = function (opts) {var self = this;- return check_reqs.check_gradle()- .then(function(gradlePath) {+ return check_reqs.check_gradle().then(function (gradlePath) {return self.runGradleWrapper(gradlePath);- }).then(function() {- return self.prepBuildFiles();- }).then(function() {+ }).then(function () {+ return self.prepBuildFiles();+ }).then(function () {// We now copy the gradle out of the framework// This is a dirty patch to get the build working/*@@ -198,12 +247,12 @@ GradleBuilder.prototype.prepEnv = function(opts) {// If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.// For some reason, using ^ and $ don't work. This does the job, though.var distributionUrlRegex = /distributionUrl.*zip/;- /*jshint -W069 */- var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-3.3-all.zip';- /*jshint +W069 */+ /* jshint -W069 */+ var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-4.1-all.zip';+ /* jshint +W069 */var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');shell.chmod('u+w', gradleWrapperPropertiesPath);- shell.sed('-i', distributionUrlRegex, 'distributionUrl='+distributionUrl, gradleWrapperPropertiesPath);+ shell.sed('-i', distributionUrlRegex, 'distributionUrl=' + distributionUrl, gradleWrapperPropertiesPath);var propertiesFile = opts.buildType + SIGNING_PROPERTIES;var propertiesFilePath = path.join(self.root, propertiesFile);@@ -219,53 +268,37 @@ GradleBuilder.prototype.prepEnv = function(opts) {* Builds the project with gradle.* Returns a promise.*/-GradleBuilder.prototype.build = function(opts) {+GradleBuilder.prototype.build = function (opts) {var wrapper = path.join(this.root, 'gradlew');- var args = this.getArgs(opts.buildType == 'debug' ? 'debug' : 'release', opts);-- return spawn(wrapper, args, {stdio: 'pipe'})- .progress(function (stdio){- if (stdio.stderr) {- /*- * Workaround for the issue with Java printing some unwanted information to- * stderr instead of stdout.- * This function suppresses 'Picked up _JAVA_OPTIONS' message from being- * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for- * explanation.- */- var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());- if (suppressThisLine) {- return;+ var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);++ return superspawn.spawn(wrapper, args, { stdio: 'pipe' })+ .progress(function (stdio) {+ suppressJavaOptionsInfo(stdio);+ }).catch(function (error) {+ if (error.toString().indexOf('failed to find target with hash string') >= 0) {+ return check_reqs.check_android_target(error).then(function () {+ // If due to some odd reason - check_android_target succeeds+ // we should still fail here.+ return Q.reject(error);+ });}- process.stderr.write(stdio.stderr);- } else {- process.stdout.write(stdio.stdout);- }- }).catch(function (error) {- if (error.toString().indexOf('failed to find target with hash string') >= 0) {- return check_reqs.check_android_target(error).then(function() {- // If due to some odd reason - check_android_target succeeds- // we should still fail here.- return Q.reject(error);- });- }- return Q.reject(error);- });+ return Q.reject(error);+ });};-GradleBuilder.prototype.clean = function(opts) {+GradleBuilder.prototype.clean = function (opts) {var builder = this;var wrapper = path.join(this.root, 'gradlew');var args = builder.getArgs('clean', opts);- return Q().then(function() {- return spawn(wrapper, args, {stdio: 'inherit'});- })- .then(function () {+ return Q().then(function () {+ return superspawn.spawn(wrapper, args, { stdio: 'inherit' });+ }).then(function () {shell.rm('-rf', path.join(builder.root, 'out'));- ['debug', 'release'].forEach(function(config) {+ ['debug', 'release'].forEach(function (config) {var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);- if(isAutoGenerated(propertiesFilePath)){+ if (isAutoGenerated(propertiesFilePath)) {shell.rm('-f', propertiesFilePath);}});@@ -274,6 +307,25 @@ GradleBuilder.prototype.clean = function(opts) {module.exports = GradleBuilder;-function isAutoGenerated(file) {+function suppressJavaOptionsInfo (stdio) {+ if (stdio.stderr) {+ /*+ * Workaround for the issue with Java printing some unwanted information to+ * stderr instead of stdout.+ * This function suppresses 'Picked up _JAVA_OPTIONS' message from being+ * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for+ * explanation.+ */+ var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());+ if (suppressThisLine) {+ return;+ }+ process.stderr.write(stdio.stderr);+ } else {+ process.stdout.write(stdio.stdout);+ }+}++function isAutoGenerated (file) {return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;}diff --git a/cordova/platforms/android/cordova/lib/builders/StudioBuilder.js b/cordova/platforms/android/cordova/lib/builders/StudioBuilder.jsnew file mode 100644index 000000000..1689e16c5--- /dev/null+++ b/cordova/platforms/android/cordova/lib/builders/StudioBuilder.js@@ -0,0 +1,303 @@+/*+ 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 Q = require('q');+var fs = require('fs');+var util = require('util');+var path = require('path');+var shell = require('shelljs');+var spawn = require('cordova-common').superspawn.spawn;+var events = require('cordova-common').events;+var CordovaError = require('cordova-common').CordovaError;+var check_reqs = require('../check_reqs');++var GenericBuilder = require('./GenericBuilder');++var MARKER = 'YOUR CHANGES WILL BE ERASED!';+var SIGNING_PROPERTIES = '-signing.properties';+var TEMPLATE =+ '# This file is automatically generated.\n' ++ '# Do not modify this file -- ' + MARKER + '\n';++function StudioBuilder (projectRoot) {+ GenericBuilder.call(this, projectRoot);++ this.binDirs = {gradle: this.binDirs.studio};+}++util.inherits(StudioBuilder, GenericBuilder);++StudioBuilder.prototype.getArgs = function (cmd, opts) {+ if (cmd === 'release') {+ cmd = 'cdvBuildRelease';+ } else if (cmd === 'debug') {+ cmd = 'cdvBuildDebug';+ }+ var args = [cmd, '-b', path.join(this.root, 'build.gradle')];+ if (opts.arch) {+ args.push('-PcdvBuildArch=' + opts.arch);+ }++ // 10 seconds -> 6 seconds+ args.push('-Dorg.gradle.daemon=true');+ // to allow dex in process+ args.push('-Dorg.gradle.jvmargs=-Xmx2048m');+ // allow NDK to be used - required by Gradle 1.5 plugin+ // args.push('-Pandroid.useDeprecatedNdk=true');+ args.push.apply(args, opts.extraArgs);+ // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):+ // args.push('-Dorg.gradle.parallel=true');+ return args;+};++/*+ * This returns a promise+ */++StudioBuilder.prototype.runGradleWrapper = function (gradle_cmd) {+ var gradlePath = path.join(this.root, 'gradlew');+ var wrapperGradle = path.join(this.root, 'wrapper.gradle');+ if (fs.existsSync(gradlePath)) {+ // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows+ } else {+ return spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', wrapperGradle], {stdio: 'inherit'});+ }+};++StudioBuilder.prototype.readProjectProperties = function () {++ function findAllUniq (data, r) {+ var s = {};+ var m;+ while ((m = r.exec(data))) {+ s[m[1]] = 1;+ }+ return Object.keys(s);+ }++ var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');+ return {+ libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),+ gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),+ systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)+ };+};++StudioBuilder.prototype.extractRealProjectNameFromManifest = function () {+ var manifestPath = path.join(this.root, 'app', 'src', 'main', 'AndroidManifest.xml');+ var manifestData = fs.readFileSync(manifestPath, 'utf8');+ var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);+ if (!m) {+ throw new CordovaError('Could not find package name in ' + manifestPath);+ }++ var packageName = m[1];+ var lastDotIndex = packageName.lastIndexOf('.');+ return packageName.substring(lastDotIndex + 1);+};++// Makes the project buildable, minus the gradle wrapper.+StudioBuilder.prototype.prepBuildFiles = function () {+ // Update the version of build.gradle in each dependent library.+ var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');+ var propertiesObj = this.readProjectProperties();+ var subProjects = propertiesObj.libs;++ // Check and copy the gradle file into the subproject+ // Called by the loop before this function def++ var checkAndCopy = function (subProject, root) {+ var subProjectGradle = path.join(root, subProject, 'build.gradle');+ // This is the future-proof way of checking if a file exists+ // This must be synchronous to satisfy a Travis test+ try {+ fs.accessSync(subProjectGradle, fs.F_OK);+ } catch (e) {+ shell.cp('-f', pluginBuildGradle, subProjectGradle);+ }+ };++ for (var i = 0; i < subProjects.length; ++i) {+ if (subProjects[i] !== 'CordovaLib') {+ checkAndCopy(subProjects[i], this.root);+ }+ }+ var name = this.extractRealProjectNameFromManifest();+ // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149+ var settingsGradlePaths = subProjects.map(function (p) {+ var realDir = p.replace(/[/\\]/g, ':');+ var libName = realDir.replace(name + '-', '');+ var str = 'include ":' + libName + '"\n';+ if (realDir.indexOf(name + '-') !== -1) {+ str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n';+ }+ return str;+ });++ fs.writeFileSync(path.join(this.root, 'settings.gradle'),+ '// GENERATED FILE - DO NOT EDIT\n' ++ 'include ":"\n' + settingsGradlePaths.join(''));++ // Update dependencies within build.gradle.+ var buildGradle = fs.readFileSync(path.join(this.root, 'app', 'build.gradle'), 'utf8');+ var depsList = '';+ var root = this.root;+ var insertExclude = function (p) {+ var gradlePath = path.join(root, p, 'build.gradle');+ var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');+ if (projectGradleFile.indexOf('CordovaLib') !== -1) {+ depsList += '{\n exclude module:("CordovaLib")\n }\n';+ } else {+ depsList += '\n';+ }+ };+ subProjects.forEach(function (p) {+ events.emit('log', 'Subproject Path: ' + p);+ var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');+ if (libName !== 'app') {+ depsList += ' implementation(project(path: ":' + libName + '"))';+ insertExclude(p);+ }+ });+ // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390+ var SYSTEM_LIBRARY_MAPPINGS = [+ [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],+ [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']+ ];++ propertiesObj.systemLibs.forEach(function (p) {+ var mavenRef;+ // It's already in gradle form if it has two ':'s+ if (/:.*:/.exec(p)) {+ mavenRef = p;+ } else {+ for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {+ var pair = SYSTEM_LIBRARY_MAPPINGS[i];+ if (pair[0].exec(p)) {+ mavenRef = p.replace(pair[0], pair[1]);+ break;+ }+ }+ if (!mavenRef) {+ throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);+ }+ }+ depsList += ' compile "' + mavenRef + '"\n';+ });++ buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');+ var includeList = '';++ propertiesObj.gradleIncludes.forEach(function (includePath) {+ includeList += 'apply from: "../' + includePath + '"\n';+ });+ buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');+ // This needs to be stored in the app gradle, not the root grade+ fs.writeFileSync(path.join(this.root, 'app', 'build.gradle'), buildGradle);+};++StudioBuilder.prototype.prepEnv = function (opts) {+ var self = this;+ return check_reqs.check_gradle()+ .then(function (gradlePath) {+ return self.runGradleWrapper(gradlePath);+ }).then(function () {+ return self.prepBuildFiles();+ }).then(function () {+ // If the gradle distribution URL is set, make sure it points to version we want.+ // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.+ // For some reason, using ^ and $ don't work. This does the job, though.+ var distributionUrlRegex = /distributionUrl.*zip/;+ var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-4.1-all.zip';+ var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');+ shell.chmod('u+w', gradleWrapperPropertiesPath);+ shell.sed('-i', distributionUrlRegex, 'distributionUrl=' + distributionUrl, gradleWrapperPropertiesPath);++ var propertiesFile = opts.buildType + SIGNING_PROPERTIES;+ var propertiesFilePath = path.join(self.root, propertiesFile);+ if (opts.packageInfo) {+ fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());+ } else if (isAutoGenerated(propertiesFilePath)) {+ shell.rm('-f', propertiesFilePath);+ }+ });+};++/*+ * Builds the project with gradle.+ * Returns a promise.+ */+StudioBuilder.prototype.build = function (opts) {+ var wrapper = path.join(this.root, 'gradlew');+ var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);++ return spawn(wrapper, args, {stdio: 'pipe'})+ .progress(function (stdio) {+ if (stdio.stderr) {+ /*+ * Workaround for the issue with Java printing some unwanted information to+ * stderr instead of stdout.+ * This function suppresses 'Picked up _JAVA_OPTIONS' message from being+ * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for+ * explanation.+ */+ var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());+ if (suppressThisLine) {+ return;+ }+ process.stderr.write(stdio.stderr);+ } else {+ process.stdout.write(stdio.stdout);+ }+ }).catch(function (error) {+ if (error.toString().indexOf('failed to find target with hash string') >= 0) {+ return check_reqs.check_android_target(error).then(function () {+ // If due to some odd reason - check_android_target succeeds+ // we should still fail here.+ return Q.reject(error);+ });+ }+ return Q.reject(error);+ });+};++StudioBuilder.prototype.clean = function (opts) {+ var builder = this;+ var wrapper = path.join(this.root, 'gradlew');+ var args = builder.getArgs('clean', opts);+ return Q().then(function () {+ return spawn(wrapper, args, {stdio: 'inherit'});+ })+ .then(function () {+ shell.rm('-rf', path.join(builder.root, 'out'));++ ['debug', 'release'].forEach(function (config) {+ var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);+ if (isAutoGenerated(propertiesFilePath)) {+ shell.rm('-f', propertiesFilePath);+ }+ });+ });+};++module.exports = StudioBuilder;++function isAutoGenerated (file) {+ return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;+}diff --git a/cordova/platforms/android/cordova/lib/builders/builders.js b/cordova/platforms/android/cordova/lib/builders/builders.jsindex 4921c49aa..aedf9be52 100644--- a/cordova/platforms/android/cordova/lib/builders/builders.js+++ b/cordova/platforms/android/cordova/lib/builders/builders.js@@ -20,8 +20,8 @@var CordovaError = require('cordova-common').CordovaError;var knownBuilders = {- ant: 'AntBuilder',gradle: 'GradleBuilder',+ studio: 'StudioBuilder',none: 'GenericBuilder'};@@ -35,8 +35,7 @@ var knownBuilders = {* @return {Builder} A builder instance for specified build type.*/module.exports.getBuilder = function (builderType, projectRoot) {- if (!knownBuilders[builderType])- throw new CordovaError('Builder ' + builderType + ' is not supported.');+ if (!knownBuilders[builderType]) { throw new CordovaError('Builder ' + builderType + ' is not supported.'); }try {var Builder = require('./' + knownBuilders[builderType]);diff --git a/cordova/platforms/android/cordova/lib/check_reqs.js b/cordova/platforms/android/cordova/lib/check_reqs.jsindex 1fd397ad3..d9c5f99d5 100644--- a/cordova/platforms/android/cordova/lib/check_reqs.js+++ b/cordova/platforms/android/cordova/lib/check_reqs.js@@ -21,19 +21,19 @@/* jshint sub:true */-var shelljs = require('shelljs'),- child_process = require('child_process'),- Q = require('q'),- path = require('path'),- fs = require('fs'),- os = require('os'),- REPO_ROOT = path.join(__dirname, '..', '..', '..', '..'),- PROJECT_ROOT = path.join(__dirname, '..', '..');+var shelljs = require('shelljs');+var child_process = require('child_process');+var Q = require('q');+var path = require('path');+var fs = require('fs');+var os = require('os');+var REPO_ROOT = path.join(__dirname, '..', '..', '..', '..');+var PROJECT_ROOT = path.join(__dirname, '..', '..');var CordovaError = require('cordova-common').CordovaError;var superspawn = require('cordova-common').superspawn;var android_sdk = require('./android_sdk');-function forgivingWhichSync(cmd) {+function forgivingWhichSync (cmd) {try {return fs.realpathSync(shelljs.which(cmd));} catch (e) {@@ -41,29 +41,18 @@ function forgivingWhichSync(cmd) {}}-function tryCommand(cmd, errMsg, catchStderr) {- var d = Q.defer();- child_process.exec(cmd, function(err, stdout, stderr) {- if (err) d.reject(new CordovaError(errMsg));- // Sometimes it is necessary to return an stderr instead of stdout in case of success, since- // some commands prints theirs output to stderr instead of stdout. 'javac' is the example- else d.resolve((catchStderr ? stderr : stdout).trim());- });- return d.promise;-}--module.exports.isWindows = function() {- return (os.platform() == 'win32');+module.exports.isWindows = function () {+ return (os.platform() === 'win32');};-module.exports.isDarwin = function() {- return (os.platform() == 'darwin');+module.exports.isDarwin = function () {+ return (os.platform() === 'darwin');};// Get valid target from framework/project.properties if run from this repo// Otherwise get target from project.properties file within a generated cordova-android project-module.exports.get_target = function() {- function extractFromFile(filePath) {+module.exports.get_target = function () {+ function extractFromFile (filePath) {var target = shelljs.grep(/\btarget=/, filePath);if (!target) {throw new Error('Could not find android target within: ' + filePath);@@ -83,77 +72,82 @@ module.exports.get_target = function() {};// Returns a promise. Called only by build and clean commands.-module.exports.check_ant = function() {- return superspawn.spawn('ant', ['-version'])- .then(function(output) {+module.exports.check_ant = function () {+ return superspawn.spawn('ant', ['-version']).then(function (output) {// Parse Ant version from command outputreturn /version ((?:\d+\.)+(?:\d+))/i.exec(output)[1];- }).catch(function(err) {- throw new CordovaError('Failed to run `ant -version`. Make sure you have `ant` on your $PATH.');+ }).catch(function (err) {+ if (err) {+ throw new CordovaError('Failed to run `ant -version`. Make sure you have `ant` on your $PATH.');+ }});};-module.exports.get_gradle_wrapper = function() {+module.exports.get_gradle_wrapper = function () {var androidStudioPath;var i = 0;var foundStudio = false;var program_dir;- if (module.exports.isDarwin()) {- program_dir = fs.readdirSync('/Applications');- while (i < program_dir.length && !foundStudio) {- if (program_dir[i].startsWith('Android Studio')) {- //TODO: Check for a specific Android Studio version, make sure it's not Canary- androidStudioPath = path.join('/Applications', program_dir[i], 'Contents', 'gradle');- foundStudio = true;- } else { ++i; }- }- } else if (module.exports.isWindows()) {- var androidPath = path.join(process.env['ProgramFiles'], 'Android') + '/';- if (fs.existsSync(androidPath)) {- program_dir = fs.readdirSync(androidPath);- while (i < program_dir.length && !foundStudio) {- if (program_dir[i].startsWith('Android Studio')) {- foundStudio = true;- androidStudioPath = path.join(process.env['ProgramFiles'], 'Android', program_dir[i], 'gradle');- } else { ++i; }+ // OK, This hack only works on Windows, not on Mac OS or Linux. We will be deleting this eventually!+ if (module.exports.isWindows()) {++ var result = child_process.spawnSync(path.join(__dirname, 'getASPath.bat'));+ // console.log('result.stdout =' + result.stdout.toString());+ // console.log('result.stderr =' + result.stderr.toString());++ if (result.stderr.toString().length > 0) {+ var androidPath = path.join(process.env['ProgramFiles'], 'Android') + '/';+ if (fs.existsSync(androidPath)) {+ program_dir = fs.readdirSync(androidPath);+ while (i < program_dir.length && !foundStudio) {+ if (program_dir[i].startsWith('Android Studio')) {+ foundStudio = true;+ androidStudioPath = path.join(process.env['ProgramFiles'], 'Android', program_dir[i], 'gradle');+ } else { ++i; }+ }}+ } else {+ // console.log('got android studio path from registry');+ // remove the (os independent) new line char at the end of stdout+ // add gradle to match the above.+ androidStudioPath = path.join(result.stdout.toString().split('\r\n')[0], 'gradle');}}if (androidStudioPath !== null && fs.existsSync(androidStudioPath)) {var dirs = fs.readdirSync(androidStudioPath);- if(dirs[0].split('-')[0] == 'gradle') {+ if (dirs[0].split('-')[0] === 'gradle') {return path.join(androidStudioPath, dirs[0], 'bin', 'gradle');}} else {- //OK, let's try to check for Gradle!+ // OK, let's try to check for Gradle!return forgivingWhichSync('gradle');}};// Returns a promise. Called only by build and clean commands.-module.exports.check_gradle = function() {+module.exports.check_gradle = function () {var sdkDir = process.env['ANDROID_HOME'];var d = Q.defer();- if (!sdkDir)+ if (!sdkDir) {return Q.reject(new CordovaError('Could not find gradle wrapper within Android SDK. Could not find Android SDK directory.\n' +'Might need to install Android SDK or set up \'ANDROID_HOME\' env variable.'));+ }var gradlePath = module.exports.get_gradle_wrapper();- if (gradlePath.length !== 0)- d.resolve(gradlePath);- else+ if (gradlePath.length !== 0) { d.resolve(gradlePath); } else {d.reject(new CordovaError('Could not find an installed version of Gradle either in Android Studio,\n' +'or on your system to install the gradle wrapper. Please include gradle \n' +'in your path, or install Android Studio'));+ }return d.promise;};// Returns a promise.-module.exports.check_java = function() {+module.exports.check_java = function () {var javacPath = forgivingWhichSync('javac');var hasJavaHome = !!process.env['JAVA_HOME'];- return Q().then(function() {+ return Q().then(function () {if (hasJavaHome) {// Windows java installer doesn't add javac to PATH, nor set JAVA_HOME (ugh).if (!javacPath) {@@ -163,13 +157,14 @@ module.exports.check_java = function() {if (javacPath) {// OS X has a command for finding JAVA_HOME.var find_java = '/usr/libexec/java_home';- var default_java_error_msg = 'Failed to find \'JAVA_HOME\' environment variable. Try setting setting it manually.';+ var default_java_error_msg = 'Failed to find \'JAVA_HOME\' environment variable. Try setting it manually.';if (fs.existsSync(find_java)) {- return superspawn.spawn(find_java)- .then(function(stdout) {+ return superspawn.spawn(find_java).then(function (stdout) {process.env['JAVA_HOME'] = stdout.trim();- }).catch(function(err) {- throw new CordovaError(default_java_error_msg);+ }).catch(function (err) {+ if (err) {+ throw new CordovaError(default_java_error_msg);+ }});} else {// See if we can derive it from javac's location.@@ -200,32 +195,34 @@ module.exports.check_java = function() {}}}- }).then(function() {- var msg =- 'Failed to run "javac -version", make sure that you have a JDK installed.\n' +- 'You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.\n';- if (process.env['JAVA_HOME']) {- msg += 'Your JAVA_HOME is invalid: ' + process.env['JAVA_HOME'] + '\n';- }- // We use tryCommand with catchStderr = true, because- // javac writes version info to stderr instead of stdout- return tryCommand('javac -version', msg, true)- .then(function (output) {- //Let's check for at least Java 8, and keep it future proof so we can support Java 10- var match = /javac ((?:1\.)(?:[8-9]\.)(?:\d+))|((?:1\.)(?:[1-9]\d+\.)(?:\d+))/i.exec(output);- return match && match[1];- });+ }).then(function () {+ return Q.denodeify(child_process.exec)('javac -version')+ .then(outputs => {+ // outputs contains two entries: stdout and stderr+ // Java <= 8 writes version info to stderr, Java >= 9 to stdout+ const output = outputs.join('').trim();+ const match = /javac\s+([\d.]+)/i.exec(output);+ return match && match[1];+ }, () => {+ var msg =+ 'Failed to run "javac -version", make sure that you have a JDK installed.\n' ++ 'You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.\n';+ if (process.env['JAVA_HOME']) {+ msg += 'Your JAVA_HOME is invalid: ' + process.env['JAVA_HOME'] + '\n';+ }+ throw new CordovaError(msg);+ });});};// Returns a promise.-module.exports.check_android = function() {- return Q().then(function() {+module.exports.check_android = function () {+ return Q().then(function () {var androidCmdPath = forgivingWhichSync('android');var adbInPath = forgivingWhichSync('adb');var avdmanagerInPath = forgivingWhichSync('avdmanager');var hasAndroidHome = !!process.env['ANDROID_HOME'] && fs.existsSync(process.env['ANDROID_HOME']);- function maybeSetAndroidHome(value) {+ function maybeSetAndroidHome (value) {if (!hasAndroidHome && fs.existsSync(value)) {hasAndroidHome = true;process.env['ANDROID_HOME'] = value;@@ -265,10 +262,10 @@ module.exports.check_android = function() {if (androidCmdPath) {parentDir = path.dirname(androidCmdPath);grandParentDir = path.dirname(parentDir);- if (path.basename(parentDir) == 'tools' || fs.existsSync(path.join(grandParentDir, 'tools', 'android'))) {+ if (path.basename(parentDir) === 'tools' || fs.existsSync(path.join(grandParentDir, 'tools', 'android'))) {maybeSetAndroidHome(grandParentDir);} else {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' ++ throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' +'Detected \'android\' command at ' + parentDir + ' but no \'tools\' directory found near.\n' +'Try reinstall Android SDK or update your PATH to include valid path to SDK' + path.sep + 'tools directory.');}@@ -276,10 +273,10 @@ module.exports.check_android = function() {if (adbInPath) {parentDir = path.dirname(adbInPath);grandParentDir = path.dirname(parentDir);- if (path.basename(parentDir) == 'platform-tools') {+ if (path.basename(parentDir) === 'platform-tools') {maybeSetAndroidHome(grandParentDir);} else {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' ++ throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' +'Detected \'adb\' command at ' + parentDir + ' but no \'platform-tools\' directory found near.\n' +'Try reinstall Android SDK or update your PATH to include valid path to SDK' + path.sep + 'platform-tools directory.');}@@ -287,17 +284,17 @@ module.exports.check_android = function() {if (avdmanagerInPath) {parentDir = path.dirname(avdmanagerInPath);grandParentDir = path.dirname(parentDir);- if (path.basename(parentDir) == 'bin' && path.basename(grandParentDir) == 'tools') {+ if (path.basename(parentDir) === 'bin' && path.basename(grandParentDir) === 'tools') {maybeSetAndroidHome(path.dirname(grandParentDir));} else {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' ++ throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' +'Detected \'avdmanager\' command at ' + parentDir + ' but no \'tools' + path.sep + 'bin\' directory found near.\n' +'Try reinstall Android SDK or update your PATH to include valid path to SDK' + path.sep + 'tools' + path.sep + 'bin directory.');}}}if (!process.env['ANDROID_HOME']) {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' ++ throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' +'Failed to find \'android\' command in your \'PATH\'. Try update your \'PATH\' to include path to valid SDK directory.');}if (!fs.existsSync(process.env['ANDROID_HOME'])) {@@ -330,20 +327,19 @@ module.exports.getAbsoluteAndroidCmd = function () {return cmd.replace(/(\s)/g, '\\$1');};-module.exports.check_android_target = function(originalError) {+module.exports.check_android_target = function (originalError) {// valid_target can look like:// android-19// android-L// Google Inc.:Google APIs:20// Google Inc.:Glass Development Kit Preview:20var desired_api_level = module.exports.get_target();- return android_sdk.list_targets()- .then(function(targets) {+ return android_sdk.list_targets().then(function (targets) {if (targets.indexOf(desired_api_level) >= 0) {return targets;}var androidCmd = module.exports.getAbsoluteAndroidCmd();- var msg = 'Please install Android target / API level: "' + desired_api_level + '".\n\n' ++ var msg = 'Please install Android target / API level: "' + desired_api_level + '".\n\n' +'Hint: Open the SDK manager by running: ' + androidCmd + '\n' +'You will require:\n' +'1. "SDK Platform" for API level ' + desired_api_level + '\n' +@@ -357,23 +353,21 @@ module.exports.check_android_target = function(originalError) {};// Returns a promise.-module.exports.run = function() {- return Q.all([this.check_java(), this.check_android()])- .then(function(values) {- console.log('ANDROID_HOME=' + process.env['ANDROID_HOME']);- console.log('JAVA_HOME=' + process.env['JAVA_HOME']);+module.exports.run = function () {+ return Q.all([this.check_java(), this.check_android()]).then(function (values) {+ console.log('ANDROID_HOME=' + process.env['ANDROID_HOME']);+ console.log('JAVA_HOME=' + process.env['JAVA_HOME']);- if (!values[0]) {- throw new CordovaError('Requirements check failed for JDK 1.8 or greater');- }+ if (!String(values[0]).startsWith('1.8.')) {+ throw new CordovaError('Requirements check failed for JDK 1.8');+ }- if (!values[1]) {+ if (!values[1]) {throw new CordovaError('Requirements check failed for Android SDK');- }- });+ }+ });};-/*** Object thar represents one of requirements for current platform.* @param {String} id The unique identifier for this requirements.@@ -387,7 +381,7 @@ var Requirement = function (id, name, version, installed) {this.name = name;this.installed = installed || false;this.metadata = {- version: version,+ version: version};};@@ -397,7 +391,7 @@ var Requirement = function (id, name, version, installed) {** @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.*/-module.exports.check_all = function() {+module.exports.check_all = function () {var requirements = [new Requirement('java', 'Java JDK'),@@ -417,15 +411,13 @@ module.exports.check_all = function() {return checkFns.reduce(function (promise, checkFn, idx) {// Update each requirement with resultsvar requirement = requirements[idx];- return promise.then(checkFn)- .then(function (version) {+ return promise.then(checkFn).then(function (version) {requirement.installed = true;requirement.metadata.version = version;}, function (err) {requirement.metadata.reason = err instanceof Error ? err.message : err;});- }, Q())- .then(function () {+ }, Q()).then(function () {// When chain is completed, return requirements array to upstream APIreturn requirements;});diff --git a/cordova/platforms/android/cordova/lib/device.js b/cordova/platforms/android/cordova/lib/device.jsindex 4b171db67..84b509479 100644--- a/cordova/platforms/android/cordova/lib/device.js+++ b/cordova/platforms/android/cordova/lib/device.js@@ -19,8 +19,8 @@under the License.*/-var Q = require('q'),- build = require('./build');+var Q = require('q');+var build = require('./build');var path = require('path');var Adb = require('./Adb');var AndroidManifest = require('./AndroidManifest');@@ -32,18 +32,16 @@ var events = require('cordova-common').events;* Returns a promise for the list of the device ID's found* @param lookHarder When true, try restarting adb if no devices are found.*/-module.exports.list = function(lookHarder) {- return Adb.devices()- .then(function(list) {+module.exports.list = function (lookHarder) {+ return Adb.devices().then(function (list) {if (list.length === 0 && lookHarder) {// adb kill-server doesn't seem to do the trick.// Could probably find a x-platform version of killall, but I'm not actually// sure that this scenario even happens on non-OSX machines.- return spawn('killall', ['adb'])- .then(function() {+ return spawn('killall', ['adb']).then(function () {events.emit('verbose', 'Restarting adb to see if more devices are detected.');return Adb.devices();- }, function() {+ }, function () {// For non-killall OS's.return list;});@@ -52,9 +50,8 @@ module.exports.list = function(lookHarder) {});};-module.exports.resolveTarget = function(target) {- return this.list(true)- .then(function(device_list) {+module.exports.resolveTarget = function (target) {+ return this.list(true).then(function (device_list) {if (!device_list || !device_list.length) {return Q.reject(new CordovaError('Failed to deploy to device, no devices found.'));}@@ -65,8 +62,7 @@ module.exports.resolveTarget = function(target) {return Q.reject('ERROR: Unable to find target \'' + target + '\'.');}- return build.detectArchitecture(target)- .then(function(arch) {+ return build.detectArchitecture(target).then(function (arch) {return { target: target, arch: arch, isEmulator: false };});});@@ -77,43 +73,39 @@ module.exports.resolveTarget = function(target) {* and launches it.* Returns a promise.*/-module.exports.install = function(target, buildResults) {- return Q().then(function() {- if (target && typeof target == 'object') {+module.exports.install = function (target, buildResults) {+ return Q().then(function () {+ if (target && typeof target === 'object') {return target;}return module.exports.resolveTarget(target);- }).then(function(resolvedTarget) {+ }).then(function (resolvedTarget) {var apk_path = build.findBestApkForArchitecture(buildResults, resolvedTarget.arch);- var manifest = new AndroidManifest(path.join(__dirname, '../../AndroidManifest.xml'));+ var manifest = new AndroidManifest(path.join(__dirname, '../../app/src/main/AndroidManifest.xml'));var pkgName = manifest.getPackageId();var launchName = pkgName + '/.' + manifest.getActivity().getName();events.emit('log', 'Using apk: ' + apk_path);events.emit('log', 'Package name: ' + pkgName);- return Adb.install(resolvedTarget.target, apk_path, {replace: true})- .catch(function (error) {+ return Adb.install(resolvedTarget.target, apk_path, {replace: true}).catch(function (error) {// CB-9557 CB-10157 only uninstall and reinstall app if the one that// is already installed on device was signed w/different certificate- if (!/INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES/.test(error.toString()))- throw error;+ if (!/INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES/.test(error.toString())) { throw error; }events.emit('warn', 'Uninstalling app from device and reinstalling it again because the ' +'installed app already signed with different key');// This promise is always resolved, even if 'adb uninstall' fails to uninstall app// or the app doesn't installed at all, so no error catching needed.- return Adb.uninstall(resolvedTarget.target, pkgName)- .then(function() {+ return Adb.uninstall(resolvedTarget.target, pkgName).then(function () {return Adb.install(resolvedTarget.target, apk_path, {replace: true});});- })- .then(function() {- //unlock screen+ }).then(function () {+ // unlock screenreturn Adb.shell(resolvedTarget.target, 'input keyevent 82');- }).then(function() {+ }).then(function () {return Adb.start(resolvedTarget.target, launchName);- }).then(function() {+ }).then(function () {events.emit('log', 'LAUNCH SUCCESS');});});diff --git a/cordova/platforms/android/cordova/lib/emulator.js b/cordova/platforms/android/cordova/lib/emulator.jsindex 22209aa0c..63ed302fe 100644--- a/cordova/platforms/android/cordova/lib/emulator.js+++ b/cordova/platforms/android/cordova/lib/emulator.js@@ -21,8 +21,9 @@/* jshint sub:true */-var retry = require('./retry');-var build = require('./build');+var android_versions = require('android-versions');+var retry = require('./retry');+var build = require('./build');var path = require('path');var Adb = require('./Adb');var AndroidManifest = require('./AndroidManifest');@@ -33,20 +34,20 @@ var shelljs = require('shelljs');var android_sdk = require('./android_sdk');var check_reqs = require('./check_reqs');-var Q = require('q');-var os = require('os');-var fs = require('fs');+var Q = require('q');+var os = require('os');+var fs = require('fs');var child_process = require('child_process');// constants-var ONE_SECOND = 1000; // in milliseconds-var ONE_MINUTE = 60 * ONE_SECOND; // in milliseconds+var ONE_SECOND = 1000; // in milliseconds+var ONE_MINUTE = 60 * ONE_SECOND; // in millisecondsvar INSTALL_COMMAND_TIMEOUT = 5 * ONE_MINUTE; // in milliseconds-var NUM_INSTALL_RETRIES = 3;-var CHECK_BOOTED_INTERVAL = 3 * ONE_SECOND; // in milliseconds-var EXEC_KILL_SIGNAL = 'SIGKILL';+var NUM_INSTALL_RETRIES = 3;+var CHECK_BOOTED_INTERVAL = 3 * ONE_SECOND; // in milliseconds+var EXEC_KILL_SIGNAL = 'SIGKILL';-function forgivingWhichSync(cmd) {+function forgivingWhichSync (cmd) {try {return fs.realpathSync(shelljs.which(cmd));} catch (e) {@@ -55,8 +56,7 @@ function forgivingWhichSync(cmd) {}module.exports.list_images_using_avdmanager = function () {- return superspawn.spawn('avdmanager', ['list', 'avd'])- .then(function(output) {+ return superspawn.spawn('avdmanager', ['list', 'avd']).then(function (output) {var response = output.split('\n');var emulator_list = [];for (var i = 1; i < response.length; i++) {@@ -108,16 +108,15 @@ module.exports.list_images_using_avdmanager = function () {/* To just return a list of names use thisif (response[i].match(/Name:\s/)) {emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');- }*/+ } */}return emulator_list;});};-module.exports.list_images_using_android = function() {- return superspawn.spawn('android', ['list', 'avd'])- .then(function(output) {+module.exports.list_images_using_android = function () {+ return superspawn.spawn('android', ['list', 'avd']).then(function (output) {var response = output.split('\n');var emulator_list = [];for (var i = 1; i < response.length; i++) {@@ -152,7 +151,7 @@ module.exports.list_images_using_android = function() {/* To just return a list of names use thisif (response[i].match(/Name:\s/)) {emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');- }*/+ } */}return emulator_list;@@ -170,16 +169,32 @@ module.exports.list_images_using_android = function() {skin : <skin>}*/-module.exports.list_images = function() {- if (forgivingWhichSync('avdmanager')) {- return module.exports.list_images_using_avdmanager();- } else if (forgivingWhichSync('android')) {- return module.exports.list_images_using_android();- } else {- return Q().then(function() {- throw new CordovaError('Could not find either `android` or `avdmanager` on your $PATH! Are you sure the Android SDK is installed and available?');+module.exports.list_images = function () {+ return Q.fcall(function () {+ if (forgivingWhichSync('avdmanager')) {+ return module.exports.list_images_using_avdmanager();+ } else if (forgivingWhichSync('android')) {+ return module.exports.list_images_using_android();+ } else {+ return Q().then(function () {+ throw new CordovaError('Could not find either `android` or `avdmanager` on your $PATH! Are you sure the Android SDK is installed and available?');+ });+ }+ }).then(function (avds) {+ // In case we're missing the Android OS version string from the target description, add it.+ return avds.map(function (avd) {+ if (avd.target && avd.target.indexOf('Android API') > -1 && avd.target.indexOf('API level') < 0) {+ var api_level = avd.target.match(/\d+/);+ if (api_level) {+ var level = android_versions.get(api_level);+ if (level) {+ avd.target = 'Android ' + level.semver + ' (API level ' + api_level + ')';+ }+ }+ }+ return avd;});- }+ });};/**@@ -187,20 +202,19 @@ module.exports.list_images = function() {* or undefined if no avds exist.* Returns a promise.*/-module.exports.best_image = function() {- return this.list_images()- .then(function(images) {+module.exports.best_image = function () {+ return this.list_images().then(function (images) {// Just return undefined if there is no imagesif (images.length === 0) return;var closest = 9999;var best = images[0];- var project_target = check_reqs.get_target().replace('android-', '');+ var project_target = parseInt(check_reqs.get_target().replace('android-', ''));for (var i in images) {var target = images[i].target;- if(target) {- var num = target.split('(API level ')[1].replace(')', '');- if (num == project_target) {+ if (target && target.indexOf('API level') > -1) {+ var num = parseInt(target.split('(API level ')[1].replace(')', ''));+ if (num === project_target) {return images[i];} else if (project_target - num < closest && project_target > num) {closest = project_target - num;@@ -213,19 +227,18 @@ module.exports.best_image = function() {};// Returns a promise.-module.exports.list_started = function() {+module.exports.list_started = function () {return Adb.devices({emulators: true});};// Returns a promise.// TODO: we should remove this, there's a more robust method under android_sdk.js-module.exports.list_targets = function() {- return superspawn.spawn('android', ['list', 'targets'], {cwd: os.tmpdir()})- .then(function(output) {+module.exports.list_targets = function () {+ return superspawn.spawn('android', ['list', 'targets'], {cwd: os.tmpdir()}).then(function (output) {var target_out = output.split('\n');var targets = [];for (var i = target_out.length; i >= 0; i--) {- if(target_out[i].match(/id:/)) {+ if (target_out[i].match(/id:/)) {targets.push(targets[i].split(' ')[1]);}}@@ -240,9 +253,8 @@ module.exports.list_targets = function() {module.exports.get_available_port = function () {var self = this;- return self.list_started()- .then(function (emulators) {- for (var p = 5584; p >= 5554; p-=2) {+ return self.list_started().then(function (emulators) {+ for (var p = 5584; p >= 5554; p -= 2) {if (emulators.indexOf('emulator-' + p) === -1) {events.emit('verbose', 'Found available port: ' + p);return p;@@ -262,14 +274,13 @@ module.exports.get_available_port = function () {** Returns a promise.*/-module.exports.start = function(emulator_ID, boot_timeout) {+module.exports.start = function (emulator_ID, boot_timeout) {var self = this;- return Q().then(function() {+ return Q().then(function () {if (emulator_ID) return Q(emulator_ID);- return self.best_image()- .then(function(best) {+ return self.best_image().then(function (best) {if (best && best.name) {events.emit('warn', 'No emulator specified, defaulting to ' + best.name);return best.name;@@ -281,9 +292,8 @@ module.exports.start = function(emulator_ID, boot_timeout) {'2. Create an AVD by running: ' + androidCmd + ' avd\n' +'HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver\n'));});- }).then(function(emulatorId) {- return self.get_available_port()- .then(function (port) {+ }).then(function (emulatorId) {+ return self.get_available_port().then(function (port) {// Figure out the directory the emulator binary runs in, and set the cwd to that directory.// Workaround for https://code.google.com/p/android/issues/detail?id=235461var emulator_dir = path.dirname(shelljs.which('emulator'));@@ -297,20 +307,17 @@ module.exports.start = function(emulator_ID, boot_timeout) {events.emit('log', 'Waiting for emulator to start...');return self.wait_for_emulator(port);});- }).then(function(emulatorId) {- if (!emulatorId)- return Q.reject(new CordovaError('Failed to start emulator'));+ }).then(function (emulatorId) {+ if (!emulatorId) { return Q.reject(new CordovaError('Failed to start emulator')); }- //wait for emulator to boot up+ // wait for emulator to boot upprocess.stdout.write('Waiting for emulator to boot (this may take a while)...');- return self.wait_for_boot(emulatorId, boot_timeout)- .then(function(success) {+ return self.wait_for_boot(emulatorId, boot_timeout).then(function (success) {if (success) {- events.emit('log','BOOT COMPLETE');- //unlock screen- return Adb.shell(emulatorId, 'input keyevent 82')- .then(function() {- //return the new emulator id for the started emulators+ events.emit('log', 'BOOT COMPLETE');+ // unlock screen+ return Adb.shell(emulatorId, 'input keyevent 82').then(function () {+ // return the new emulator id for the started emulatorsreturn emulatorId;});} else {@@ -325,20 +332,20 @@ module.exports.start = function(emulator_ID, boot_timeout) {* Waits for an emulator to boot on a given port.* Returns this emulator's ID in a promise.*/-module.exports.wait_for_emulator = function(port) {+module.exports.wait_for_emulator = function (port) {var self = this;- return Q().then(function() {+ return Q().then(function () {var emulator_id = 'emulator-' + port;- return Adb.shell(emulator_id, 'getprop dev.bootcomplete')- .then(function (output) {+ return Adb.shell(emulator_id, 'getprop dev.bootcomplete').then(function (output) {if (output.indexOf('1') >= 0) {return emulator_id;}return self.wait_for_emulator(port);}, function (error) {- if (error && error.message &&- (error.message.indexOf('not found') > -1) ||- error.message.indexOf('device offline') > -1) {+ if ((error && error.message &&+ (error.message.indexOf('not found') > -1)) ||+ (error.message.indexOf('device offline') > -1) ||+ (error.message.indexOf('device still connecting') > -1)) {// emulator not yet started, continue waitingreturn self.wait_for_emulator(port);} else {@@ -346,7 +353,7 @@ module.exports.wait_for_emulator = function(port) {throw error;}});- });+ });};/*@@ -354,10 +361,9 @@ module.exports.wait_for_emulator = function(port) {* promise that resolves to a boolean indicating success. Not specifying a* time_remaining or passing a negative value will cause it to wait forever*/-module.exports.wait_for_boot = function(emulator_id, time_remaining) {+module.exports.wait_for_boot = function (emulator_id, time_remaining) {var self = this;- return Adb.shell(emulator_id, 'ps')- .then(function(output) {+ return Adb.shell(emulator_id, 'ps').then(function (output) {if (output.match(/android\.process\.acore/)) {return true;} else if (time_remaining === 0) {@@ -366,7 +372,7 @@ module.exports.wait_for_boot = function(emulator_id, time_remaining) {process.stdout.write('.');// Check at regular intervals- return Q.delay(time_remaining < CHECK_BOOTED_INTERVAL ? time_remaining : CHECK_BOOTED_INTERVAL).then(function() {+ return Q.delay(time_remaining < CHECK_BOOTED_INTERVAL ? time_remaining : CHECK_BOOTED_INTERVAL).then(function () {var updated_time = time_remaining >= 0 ? Math.max(time_remaining - CHECK_BOOTED_INTERVAL, 0) : time_remaining;return self.wait_for_boot(emulator_id, updated_time);});@@ -379,11 +385,10 @@ module.exports.wait_for_boot = function(emulator_id, time_remaining) {* TODO : Enter the stdin input required to complete the creation of an avd.* Returns a promise.*/-module.exports.create_image = function(name, target) {+module.exports.create_image = function (name, target) {console.log('Creating new avd named ' + name);if (target) {- return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', target])- .then(null, function(error) {+ return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', target]).then(null, function (error) {console.error('ERROR : Failed to create emulator image : ');console.error(' Do you have the latest android targets including ' + target + '?');console.error(error);@@ -391,22 +396,20 @@ module.exports.create_image = function(name, target) {} else {console.log('WARNING : Project target not found, creating avd with a different target but the project may fail to install.');// TODO: there's a more robust method for finding targets in android_sdk.js- return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', this.list_targets()[0]])- .then(function() {+ return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', this.list_targets()[0]]).then(function () {// TODO: This seems like another error case, even though it always happens.console.error('ERROR : Unable to create an avd emulator, no targets found.');console.error('Ensure you have targets available by running the "android" command');return Q.reject();- }, function(error) {+ }, function (error) {console.error('ERROR : Failed to create emulator image : ');console.error(error);});}};-module.exports.resolveTarget = function(target) {- return this.list_started()- .then(function(emulator_list) {+module.exports.resolveTarget = function (target) {+ return this.list_started().then(function (emulator_list) {if (emulator_list.length < 1) {return Q.reject('No running Android emulators found, please start an emulator before deploying your project.');}@@ -417,9 +420,8 @@ module.exports.resolveTarget = function(target) {return Q.reject('Unable to find target \'' + target + '\'. Failed to deploy to emulator.');}- return build.detectArchitecture(target)- .then(function(arch) {- return {target:target, arch:arch, isEmulator:true};+ return build.detectArchitecture(target).then(function (arch) {+ return {target: target, arch: arch, isEmulator: true};});});};@@ -430,15 +432,20 @@ module.exports.resolveTarget = function(target) {* If no started emulators are found, error out.* Returns a promise.*/-module.exports.install = function(givenTarget, buildResults) {+module.exports.install = function (givenTarget, buildResults) {var target;- var manifest = new AndroidManifest(path.join(__dirname, '../../AndroidManifest.xml'));+ // We need to find the proper path to the Android Manifest+ var manifestPath = path.join(__dirname, '..', '..', 'app', 'src', 'main', 'AndroidManifest.xml');+ if (buildResults.buildMethod === 'gradle') {+ manifestPath = path.join(__dirname, '../../AndroidManifest.xml');+ }+ var manifest = new AndroidManifest(manifestPath);var pkgName = manifest.getPackageId();// resolve the target emulatorreturn Q().then(function () {- if (givenTarget && typeof givenTarget == 'object') {+ if (givenTarget && typeof givenTarget === 'object') {return givenTarget;} else {return module.exports.resolveTarget(givenTarget);@@ -452,13 +459,12 @@ module.exports.install = function(givenTarget, buildResults) {}).then(function () {// This promise is always resolved, even if 'adb uninstall' fails to uninstall app// or the app doesn't installed at all, so no error catching needed.- return Q.when()- .then(function() {+ return Q.when().then(function () {var apk_path = build.findBestApkForArchitecture(buildResults, target.arch);var execOptions = {cwd: os.tmpdir(),- timeout: INSTALL_COMMAND_TIMEOUT, // in milliseconds+ timeout: INSTALL_COMMAND_TIMEOUT, // in millisecondskillSignal: EXEC_KILL_SIGNAL};@@ -469,12 +475,12 @@ module.exports.install = function(givenTarget, buildResults) {// A special function to call adb install in specific environment w/ specific options.// Introduced as a part of fix for http://issues.apache.org/jira/browse/CB-9119// to workaround sporadic emulator hangs- function adbInstallWithOptions(target, apk, opts) {+ function adbInstallWithOptions (target, apk, opts) {events.emit('verbose', 'Installing apk ' + apk + ' on ' + target + '...');var command = 'adb -s ' + target + ' install -r "' + apk + '"';return Q.promise(function (resolve, reject) {- child_process.exec(command, opts, function(err, stdout, stderr) {+ child_process.exec(command, opts, function (err, stdout, stderr) {if (err) reject(new CordovaError('Error executing "' + command + '": ' + stderr));// adb does not return an error code even if installation fails. Instead it puts a specific// message to stdout, so we have to use RegExp matching to detect installation failure.@@ -494,27 +500,23 @@ module.exports.install = function(givenTarget, buildResults) {}function installPromise () {- return adbInstallWithOptions(target.target, apk_path, execOptions)- .catch(function (error) {+ return adbInstallWithOptions(target.target, apk_path, execOptions).catch(function (error) {// CB-9557 CB-10157 only uninstall and reinstall app if the one that// is already installed on device was signed w/different certificate- if (!/INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES/.test(error.toString()))- throw error;+ if (!/INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES/.test(error.toString())) { throw error; }events.emit('warn', 'Uninstalling app from device and reinstalling it because the ' +'currently installed app was signed with different key');// This promise is always resolved, even if 'adb uninstall' fails to uninstall app// or the app doesn't installed at all, so no error catching needed.- return Adb.uninstall(target.target, pkgName)- .then(function() {+ return Adb.uninstall(target.target, pkgName).then(function () {return adbInstallWithOptions(target.target, apk_path, execOptions);});});}- return retry.retryPromise(NUM_INSTALL_RETRIES, installPromise)- .then(function (output) {+ return retry.retryPromise(NUM_INSTALL_RETRIES, installPromise).then(function (output) {events.emit('log', 'INSTALL SUCCESS');});});diff --git a/cordova/platforms/android/cordova/lib/getASPath.bat b/cordova/platforms/android/cordova/lib/getASPath.batnew file mode 100644index 000000000..14dad4394--- /dev/null+++ b/cordova/platforms/android/cordova/lib/getASPath.bat@@ -0,0 +1,3 @@+@ECHO OFF+for /f "tokens=2*" %%a in ('REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Android Studio" /v Path') do set "ASPath=%%~b"+ECHO %ASPath%\ No newline at end of filediff --git a/cordova/platforms/android/cordova/lib/install-device.bat b/cordova/platforms/android/cordova/lib/install-device.batindex ac7214aca..109b470eb 100644--- a/cordova/platforms/android/cordova/lib/install-device.bat+++ b/cordova/platforms/android/cordova/lib/install-device.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0install-device"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'install-device' script in 'cordova\lib' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/lib/install-emulator.bat b/cordova/platforms/android/cordova/lib/install-emulator.batindex 1ec677905..a28c23a18 100644--- a/cordova/platforms/android/cordova/lib/install-emulator.bat+++ b/cordova/platforms/android/cordova/lib/install-emulator.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0install-emulator"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'install-emulator' script in 'cordova\lib' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/lib/list-devices.bat b/cordova/platforms/android/cordova/lib/list-devices.batindex c0bcdd9a4..ad5f03ed0 100644--- a/cordova/platforms/android/cordova/lib/list-devices.bat+++ b/cordova/platforms/android/cordova/lib/list-devices.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0list-devices"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'list-devices' script in 'cordova\lib' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/lib/list-emulator-images.bat b/cordova/platforms/android/cordova/lib/list-emulator-images.batindex 661cbf950..616ffb751 100644--- a/cordova/platforms/android/cordova/lib/list-emulator-images.bat+++ b/cordova/platforms/android/cordova/lib/list-emulator-images.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0list-emulator-images"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'list-emulator-images' script in 'cordova\lib' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/lib/list-started-emulators.bat b/cordova/platforms/android/cordova/lib/list-started-emulators.batindex a4e88f7d2..eed02a5c5 100644--- a/cordova/platforms/android/cordova/lib/list-started-emulators.bat+++ b/cordova/platforms/android/cordova/lib/list-started-emulators.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0list-started-emulators"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'list-started-emulators' script in 'cordova\lib' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/lib/log.js b/cordova/platforms/android/cordova/lib/log.jsindex ebf836d54..ef2dd5cb0 100644--- a/cordova/platforms/android/cordova/lib/log.js+++ b/cordova/platforms/android/cordova/lib/log.js@@ -19,28 +19,28 @@under the License.*/-var path = require('path'),- os = require('os'),- Q = require('q'),- child_process = require('child_process'),- ROOT = path.join(__dirname, '..', '..');+var path = require('path');+var os = require('os');+var Q = require('q');+var child_process = require('child_process');+var ROOT = path.join(__dirname, '..', '..');/** Starts running logcat in the shell.* Returns a promise.*/-module.exports.run = function() {+module.exports.run = function () {var d = Q.defer();var adb = child_process.spawn('adb', ['logcat'], {cwd: os.tmpdir()});- adb.stdout.on('data', function(data) {+ adb.stdout.on('data', function (data) {var lines = data ? data.toString().split('\n') : [];- var out = lines.filter(function(x) { return x.indexOf('nativeGetEnabledTags') < 0; });+ var out = lines.filter(function (x) { return x.indexOf('nativeGetEnabledTags') < 0; });console.log(out.join('\n'));});adb.stderr.on('data', console.error);- adb.on('close', function(code) {+ adb.on('close', function (code) {if (code > 0) {d.reject('Failed to run logcat command.');} else d.resolve();@@ -49,7 +49,7 @@ module.exports.run = function() {return d.promise;};-module.exports.help = function() {+module.exports.help = function () {console.log('Usage: ' + path.relative(process.cwd(), path.join(ROOT, 'cordova', 'log')));console.log('Gives the logcat output on the command line.');process.exit(0);diff --git a/cordova/platforms/android/cordova/lib/plugin-build.gradle b/cordova/platforms/android/cordova/lib/plugin-build.gradleindex d1c633650..fdef1f73f 100644--- a/cordova/platforms/android/cordova/lib/plugin-build.gradle+++ b/cordova/platforms/android/cordova/lib/plugin-build.gradle@@ -20,7 +20,9 @@buildscript {repositories {- mavenCentral()+ maven {+ url "https://maven.google.com"+ }jcenter()}diff --git a/cordova/platforms/android/cordova/lib/pluginHandlers.js b/cordova/platforms/android/cordova/lib/pluginHandlers.jsindex 5e745fd52..a3ebed0eb 100644--- a/cordova/platforms/android/cordova/lib/pluginHandlers.js+++ b/cordova/platforms/android/cordova/lib/pluginHandlers.js@@ -1,7 +1,4 @@/*- *- * Copyright 2013 Anis Kadri- ** Licensed 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@@ -26,15 +23,18 @@ var events = require('cordova-common').events;var CordovaError = require('cordova-common').CordovaError;var handlers = {- 'source-file':{- install:function(obj, plugin, project, options) {+ 'source-file': {+ install: function (obj, plugin, project, options) {if (!obj.src) throw new CordovaError(generateAttributeError('src', 'source-file', plugin.id));if (!obj.targetDir) throw new CordovaError(generateAttributeError('target-dir', 'source-file', plugin.id));var dest = path.join(obj.targetDir, path.basename(obj.src));- if(options && options.android_studio === true) {- dest = path.join('app/src/main/java', obj.targetDir.substring(4), path.basename(obj.src));+ // TODO: This code needs to be replaced, since the core plugins need to be re-mapped to a different location in+ // a later plugins release. This is for legacy plugins to work with Cordova.++ if (options && options.android_studio === true) {+ dest = studioPathRemap(obj);}if (options && options.force) {@@ -43,42 +43,56 @@ var handlers = {copyNewFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));}},- uninstall:function(obj, plugin, project, options) {+ uninstall: function (obj, plugin, project, options) {var dest = path.join(obj.targetDir, path.basename(obj.src));-- if(options && options.android_studio === true) {- dest = path.join('app/src/main/java', obj.targetDir.substring(4), path.basename(obj.src));++ if (options && options.android_studio === true) {+ dest = studioPathRemap(obj);}- deleteJava(project.projectDir, dest);+ // TODO: Add Koltin extension to uninstall, since they are handled like Java files+ if (obj.src.endsWith('java')) {+ deleteJava(project.projectDir, dest);+ } else {+ // Just remove the file, not the whole parent directory+ removeFile(project.projectDir, dest);+ }}},- 'lib-file':{- install:function(obj, plugin, project, options) {+ 'lib-file': {+ install: function (obj, plugin, project, options) {var dest = path.join('libs', path.basename(obj.src));- if(options && options.android_studio === true) {- dest = path.join('app/libs', path.basename(obj.src));+ if (options && options.android_studio === true) {+ dest = path.join('app/libs', path.basename(obj.src));}copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));},- uninstall:function(obj, plugin, project, options) {+ uninstall: function (obj, plugin, project, options) {var dest = path.join('libs', path.basename(obj.src));- if(options && options.android_studio === true) {- dest = path.join('app/libs', path.basename(obj.src));+ if (options && options.android_studio === true) {+ dest = path.join('app/libs', path.basename(obj.src));}removeFile(project.projectDir, dest);}},- 'resource-file':{- install:function(obj, plugin, project, options) {- copyFile(plugin.dir, obj.src, project.projectDir, path.normalize(obj.target), !!(options && options.link));+ 'resource-file': {+ install: function (obj, plugin, project, options) {+ var dest = path.normalize(obj.target);+ if (options && options.android_studio === true) {+ dest = path.join('app/src/main', dest);+ }+ copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));},- uninstall:function(obj, plugin, project, options) {- removeFile(project.projectDir, path.normalize(obj.target));+ uninstall: function (obj, plugin, project, options) {+ var dest = path.normalize(obj.target);+ if (options && options.android_studio === true) {+ dest = path.join('app/src/main', dest);+ }+ removeFile(project.projectDir, dest);}},'framework': {- install:function(obj, plugin, project, options) {+ install: function (obj, plugin, project, options) {var src = obj.src;if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id));@@ -95,15 +109,15 @@ var handlers = {subDir = src;}- if (obj.type == 'gradleReference') {+ if (obj.type === 'gradleReference') {project.addGradleReference(parentDir, subDir);- } else if (obj.type == 'sys') {+ } else if (obj.type === 'sys') {project.addSystemLibrary(parentDir, subDir);} else {project.addSubProject(parentDir, subDir);}},- uninstall:function(obj, plugin, project, options) {+ uninstall: function (obj, plugin, project, options) {var src = obj.src;if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id));@@ -125,17 +139,17 @@ var handlers = {subDir = src;}- if (obj.type == 'gradleReference') {+ if (obj.type === 'gradleReference') {project.removeGradleReference(parentDir, subDir);- } else if (obj.type == 'sys') {+ } else if (obj.type === 'sys') {project.removeSystemLibrary(parentDir, subDir);} else {project.removeSubProject(parentDir, subDir);}}},- asset:{- install:function(obj, plugin, project, options) {+ asset: {+ install: function (obj, plugin, project, options) {if (!obj.src) {throw new CordovaError(generateAttributeError('src', 'asset', plugin.id));}@@ -149,7 +163,7 @@ var handlers = {copyFile(plugin.dir, obj.src, project.platformWww, obj.target);}},- uninstall:function(obj, plugin, project, options) {+ uninstall: function (obj, plugin, project, options) {var target = obj.target || obj.src;if (!target) throw new CordovaError(generateAttributeError('target', 'asset', plugin.id));@@ -167,7 +181,7 @@ var handlers = {install: function (obj, plugin, project, options) {// Copy the plugin's files into the www directory.var moduleSource = path.resolve(plugin.dir, obj.src);- var moduleName = plugin.id + '.' + (obj.name || path.basename(obj.src, path.extname (obj.src)));+ var moduleName = plugin.id + '.' + (obj.name || path.basename(obj.src, path.extname(obj.src)));// Read in the file, prepend the cordova.define, and write it back out.var scriptContent = fs.readFileSync(moduleSource, 'utf-8').replace(/^\ufeff/, ''); // Window BOM@@ -206,7 +220,7 @@ module.exports.getInstaller = function (type) {events.emit('verbose', '<' + type + '> is not supported for android plugins');};-module.exports.getUninstaller = function(type) {+module.exports.getUninstaller = function (type) {if (handlers[type] && handlers[type].uninstall) {return handlers[type].uninstall;}@@ -221,21 +235,19 @@ function copyFile (plugin_dir, src, project_dir, dest, link) {// check that src path is inside plugin directoryvar real_path = fs.realpathSync(src);var real_plugin_path = fs.realpathSync(plugin_dir);- if (real_path.indexOf(real_plugin_path) !== 0)- throw new CordovaError('File "' + src + '" is located outside the plugin directory "' + plugin_dir + '"');+ if (real_path.indexOf(real_plugin_path) !== 0) { throw new CordovaError('File "' + src + '" is located outside the plugin directory "' + plugin_dir + '"'); }dest = path.resolve(project_dir, dest);// check that dest path is located in project directory- if (dest.indexOf(project_dir) !== 0)- throw new CordovaError('Destination "' + dest + '" for source file "' + src + '" is located outside the project');+ if (dest.indexOf(project_dir) !== 0) { throw new CordovaError('Destination "' + dest + '" for source file "' + src + '" is located outside the project'); }shell.mkdir('-p', path.dirname(dest));if (link) {symlinkFileOrDirTree(src, dest);} else if (fs.statSync(src).isDirectory()) {// XXX shelljs decides to create a directory when -R|-r is used which sucks. http://goo.gl/nbsjq- shell.cp('-Rf', src+'/*', dest);+ shell.cp('-Rf', src + '/*', dest);} else {shell.cp('-f', src, dest);}@@ -244,24 +256,22 @@ function copyFile (plugin_dir, src, project_dir, dest, link) {// Same as copy file but throws error if target existsfunction copyNewFile (plugin_dir, src, project_dir, dest, link) {var target_path = path.resolve(project_dir, dest);- if (fs.existsSync(target_path))- throw new CordovaError('"' + target_path + '" already exists!');+ if (fs.existsSync(target_path)) { throw new CordovaError('"' + target_path + '" already exists!'); }copyFile(plugin_dir, src, project_dir, dest, !!link);}-function symlinkFileOrDirTree(src, dest) {+function symlinkFileOrDirTree (src, dest) {if (fs.existsSync(dest)) {shell.rm('-Rf', dest);}if (fs.statSync(src).isDirectory()) {shell.mkdir('-p', dest);- fs.readdirSync(src).forEach(function(entry) {+ fs.readdirSync(src).forEach(function (entry) {symlinkFileOrDirTree(path.join(src, entry), path.join(dest, entry));});- }- else {+ } else {fs.symlinkSync(path.relative(fs.realpathSync(path.dirname(dest)), src), dest);}}@@ -292,8 +302,8 @@ function removeFileAndParents (baseDir, destFile, stopper) {// check if directory is emptyvar curDir = path.dirname(file);- while(curDir !== path.resolve(baseDir, stopper)) {- if(fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) {+ while (curDir !== path.resolve(baseDir, stopper)) {+ if (fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) {fs.rmdirSync(curDir);curDir = path.resolve(curDir, '..');} else {@@ -303,6 +313,19 @@ function removeFileAndParents (baseDir, destFile, stopper) {}}-function generateAttributeError(attribute, element, id) {+function generateAttributeError (attribute, element, id) {return 'Required attribute "' + attribute + '" not specified in <' + element + '> element from plugin: ' + id;}++function studioPathRemap (obj) {+ // If a Java file is using the new directory structure, don't penalize it+ if (!obj.targetDir.includes('app/src/main')) {+ if (obj.src.endsWith('.java')) {+ return path.join('app/src/main/java', obj.targetDir.substring(4), path.basename(obj.src));+ } else {+ // For all other files, add 'app/src/main' to the targetDir if it didn't have it already+ return path.join('app/src/main', obj.targetDir, path.basename(obj.src));+ }+ }++}diff --git a/cordova/platforms/android/cordova/lib/prepare.js b/cordova/platforms/android/cordova/lib/prepare.jsindex 504eb6123..ac63f8a68 100644--- a/cordova/platforms/android/cordova/lib/prepare.js+++ b/cordova/platforms/android/cordova/lib/prepare.js@@ -16,6 +16,7 @@specific language governing permissions and limitationsunder the License.*/+/* eslint no-useless-escape: 0 */var Q = require('q');var fs = require('fs');@@ -23,6 +24,7 @@ var path = require('path');var shell = require('shelljs');var events = require('cordova-common').events;var AndroidManifest = require('./AndroidManifest');+var checkReqs = require('./check_reqs');var xmlHelpers = require('cordova-common').xmlHelpers;var CordovaError = require('cordova-common').CordovaError;var ConfigParser = require('cordova-common').ConfigParser;@@ -40,17 +42,14 @@ module.exports.prepare = function (cordovaProject, options) {this._config = updateConfigFilesFrom(cordovaProject.projectConfig, munger, this.locations);// Update own www dir with project's www assets and plugins' assets and js-files- return Q.when(updateWww(cordovaProject, this.locations))- .then(function () {+ return Q.when(updateWww(cordovaProject, this.locations)).then(function () {// update project according to config.xml changes.return updateProjectAccordingTo(self._config, self.locations);- })- .then(function () {+ }).then(function () {updateIcons(cordovaProject, path.relative(cordovaProject.root, self.locations.res));updateSplashes(cordovaProject, path.relative(cordovaProject.root, self.locations.res));updateFileResources(cordovaProject, path.relative(cordovaProject.root, self.locations.root));- })- .then(function () {+ }).then(function () {events.emit('verbose', 'Prepared android project successfully');});};@@ -91,7 +90,7 @@ module.exports.clean = function (options) {* represents current project's configuration. When returned, the* configuration is already dumped to appropriate config.xml file.*/-function updateConfigFilesFrom(sourceConfig, configMunger, locations) {+function updateConfigFilesFrom (sourceConfig, configMunger, locations) {events.emit('verbose', 'Generating platform-specific config.xml from defaults for android at ' + locations.configXml);// First cleanup current config and merge project's one into own@@ -106,7 +105,7 @@ function updateConfigFilesFrom(sourceConfig, configMunger, locations) {// Merge changes from app's config.xml into platform's onevar config = new ConfigParser(locations.configXml);xmlHelpers.mergeXml(sourceConfig.doc.getroot(),- config.doc.getroot(), 'android', /*clobber=*/true);+ config.doc.getroot(), 'android', /* clobber= */true);config.write();return config;@@ -115,7 +114,7 @@ function updateConfigFilesFrom(sourceConfig, configMunger, locations) {/*** Logs all file operations via the verbose event stream, indented.*/-function logFileOp(message) {+function logFileOp (message) {events.emit('verbose', ' ' + message);}@@ -128,7 +127,7 @@ function logFileOp(message) {* @param {Object} destinations An object that contains destination* paths for www files.*/-function updateWww(cordovaProject, destinations) {+function updateWww (cordovaProject, destinations) {var sourceDirs = [path.relative(cordovaProject.root, cordovaProject.locations.www),path.relative(cordovaProject.root, destinations.platformWww)@@ -151,7 +150,7 @@ function updateWww(cordovaProject, destinations) {/*** Cleans all files from the platform 'www' directory.*/-function cleanWww(projectRoot, locations) {+function cleanWww (projectRoot, locations) {var targetDir = path.relative(projectRoot, locations.www);events.emit('verbose', 'Cleaning ' + targetDir);@@ -167,19 +166,26 @@ function cleanWww(projectRoot, locations) {* be used to update project* @param {Object} locations A map of locations for this platform*/-function updateProjectAccordingTo(platformConfig, locations) {+function updateProjectAccordingTo (platformConfig, locations) {// Update app name by editing res/values/strings.xml- var name = platformConfig.name();var strings = xmlHelpers.parseElementtreeSync(locations.strings);++ var name = platformConfig.name();strings.find('string[@name="app_name"]').text = name.replace(/\'/g, '\\\'');++ var shortName = platformConfig.shortName && platformConfig.shortName();+ if (shortName && shortName !== name) {+ strings.find('string[@name="launcher_name"]').text = shortName.replace(/\'/g, '\\\'');+ }+fs.writeFileSync(locations.strings, strings.write({indent: 4}), 'utf-8');events.emit('verbose', 'Wrote out android application name "' + name + '" to ' + locations.strings);// Java packages cannot support dashes- var pkg = (platformConfig.android_packageName() || platformConfig.packageName()).replace(/-/g, '_');+ var androidPkgName = (platformConfig.android_packageName() || platformConfig.packageName()).replace(/-/g, '_');var manifest = new AndroidManifest(locations.manifest);- var orig_pkg = manifest.getPackageId();+ var manifestId = manifest.getPackageId();manifest.getActivity().setOrientation(platformConfig.getPreference('orientation'))@@ -187,36 +193,41 @@ function updateProjectAccordingTo(platformConfig, locations) {manifest.setVersionName(platformConfig.version()).setVersionCode(platformConfig.android_versionCode() || default_versionCode(platformConfig.version()))- .setPackageId(pkg)+ .setPackageId(androidPkgName).setMinSdkVersion(platformConfig.getPreference('android-minSdkVersion', 'android')).setMaxSdkVersion(platformConfig.getPreference('android-maxSdkVersion', 'android')).setTargetSdkVersion(platformConfig.getPreference('android-targetSdkVersion', 'android')).write();- var javaPattern = path.join(locations.root, 'src', orig_pkg.replace(/\./g, '/'), '*.java');- var java_files = shell.ls(javaPattern).filter(function(f) {+ // Java file paths shouldn't be hard coded+ var javaPattern = path.join(locations.javaSrc, manifestId.replace(/\./g, '/'), '*.java');+ var java_files = shell.ls(javaPattern).filter(function (f) {return shell.grep(/extends\s+CordovaActivity/g, f);});if (java_files.length === 0) {throw new CordovaError('No Java files found that extend CordovaActivity.');- } else if(java_files.length > 1) {+ } else if (java_files.length > 1) {events.emit('log', 'Multiple candidate Java files that extend CordovaActivity found. Guessing at the first one, ' + java_files[0]);}- var destFile = path.join(locations.root, 'src', pkg.replace(/\./g, '/'), path.basename(java_files[0]));+ var destFile = path.join(locations.root, 'app', 'src', 'main', 'java', androidPkgName.replace(/\./g, '/'), path.basename(java_files[0]));shell.mkdir('-p', path.dirname(destFile));- shell.sed(/package [\w\.]*;/, 'package ' + pkg + ';', java_files[0]).to(destFile);- events.emit('verbose', 'Wrote out Android package name "' + pkg + '" to ' + destFile);+ shell.sed(/package [\w\.]*;/, 'package ' + androidPkgName + ';', java_files[0]).to(destFile);+ events.emit('verbose', 'Wrote out Android package name "' + androidPkgName + '" to ' + destFile);++ var removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin() ?+ manifestId.toUpperCase() !== androidPkgName.toUpperCase() :+ manifestId !== androidPkgName;- if (orig_pkg !== pkg) {+ if (removeOrigPkg) {// If package was name changed we need to remove old java with main activity- shell.rm('-Rf',java_files[0]);+ shell.rm('-Rf', java_files[0]);// remove any empty directoriesvar currentDir = path.dirname(java_files[0]);var sourcesRoot = path.resolve(locations.root, 'src');- while(currentDir !== sourcesRoot) {- if(fs.existsSync(currentDir) && fs.readdirSync(currentDir).length === 0) {+ while (currentDir !== sourcesRoot) {+ if (fs.existsSync(currentDir) && fs.readdirSync(currentDir).length === 0) {fs.rmdirSync(currentDir);currentDir = path.resolve(currentDir, '..');} else {@@ -229,7 +240,7 @@ function updateProjectAccordingTo(platformConfig, locations) {// Consturct the default value for versionCode as// PATCH + MINOR * 100 + MAJOR * 10000// see http://developer.android.com/tools/publishing/versioning.html-function default_versionCode(version) {+function default_versionCode (version) {var nums = version.split('-')[0].split('.');var versionCode = 0;if (+nums[0]) {@@ -246,7 +257,7 @@ function default_versionCode(version) {return versionCode;}-function getImageResourcePath(resourcesDir, type, density, name, sourceName) {+function getImageResourcePath (resourcesDir, type, density, name, sourceName) {if (/\.9\.png$/.test(sourceName)) {name = name.replace(/\.png$/, '.9.png');}@@ -254,7 +265,7 @@ function getImageResourcePath(resourcesDir, type, density, name, sourceName) {return resourcePath;}-function updateSplashes(cordovaProject, platformResourcesDir) {+function updateSplashes (cordovaProject, platformResourcesDir) {var resources = cordovaProject.projectConfig.getSplashScreens('android');// if there are "splash" elements in config.xml@@ -270,7 +281,7 @@ function updateSplashes(cordovaProject, platformResourcesDir) {if (!resource.density) {return;}- if (resource.density == 'mdpi') {+ if (resource.density === 'mdpi') {hadMdpi = true;}var targetPath = getImageResourcePath(@@ -290,7 +301,7 @@ function updateSplashes(cordovaProject, platformResourcesDir) {resourceMap, { rootDir: cordovaProject.root }, logFileOp);}-function cleanSplashes(projectRoot, projectConfig, platformResourcesDir) {+function cleanSplashes (projectRoot, projectConfig, platformResourcesDir) {var resources = projectConfig.getSplashScreens('android');if (resources.length > 0) {var resourceMap = mapImageResources(projectRoot, platformResourcesDir, 'drawable', 'screen.png');@@ -302,7 +313,7 @@ function cleanSplashes(projectRoot, projectConfig, platformResourcesDir) {}}-function updateIcons(cordovaProject, platformResourcesDir) {+function updateIcons (cordovaProject, platformResourcesDir) {var icons = cordovaProject.projectConfig.getIcons('android');// if there are icon elements in config.xml@@ -326,7 +337,7 @@ function updateIcons(cordovaProject, platformResourcesDir) {};// find the best matching icon for a given density or size// @output android_icons- var parseIcon = function(icon, icon_size) {+ var parseIcon = function (icon, icon_size) {// do I have a platform icon for that density alreadyvar density = icon.density || sizeToDensityMap[icon_size];if (!density) {@@ -341,7 +352,7 @@ function updateIcons(cordovaProject, platformResourcesDir) {};// iterate over all icon elements to find the default icon and call parseIcon- for (var i=0; i<icons.length; i++) {+ for (var i = 0; i < icons.length; i++) {var icon = icons[i];var size = icon.width;if (!size) {@@ -378,7 +389,7 @@ function updateIcons(cordovaProject, platformResourcesDir) {resourceMap, { rootDir: cordovaProject.root }, logFileOp);}-function cleanIcons(projectRoot, projectConfig, platformResourcesDir) {+function cleanIcons (projectRoot, projectConfig, platformResourcesDir) {var icons = projectConfig.getIcons('android');if (icons.length > 0) {var resourceMap = mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'icon.png');@@ -393,18 +404,16 @@ function cleanIcons(projectRoot, projectConfig, platformResourcesDir) {/*** Gets a map containing resources of a specified name from all drawable folders in a directory.*/-function mapImageResources(rootDir, subDir, type, resourceName) {+function mapImageResources (rootDir, subDir, type, resourceName) {var pathMap = {};- shell.ls(path.join(rootDir, subDir, type + '-*'))- .forEach(function (drawableFolder) {+ shell.ls(path.join(rootDir, subDir, type + '-*')).forEach(function (drawableFolder) {var imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);pathMap[imagePath] = null;});return pathMap;}--function updateFileResources(cordovaProject, platformDir) {+function updateFileResources (cordovaProject, platformDir) {var files = cordovaProject.projectConfig.getFileResources('android');// if there are resource-file elements in config.xml@@ -414,7 +423,7 @@ function updateFileResources(cordovaProject, platformDir) {}var resourceMap = {};- files.forEach(function(res) {+ files.forEach(function (res) {var targetPath = path.join(platformDir, res.target);resourceMap[targetPath] = res.src;});@@ -424,20 +433,20 @@ function updateFileResources(cordovaProject, platformDir) {resourceMap, { rootDir: cordovaProject.root }, logFileOp);}--function cleanFileResources(projectRoot, projectConfig, platformDir) {- var files = projectConfig.getFileResources('android');+function cleanFileResources (projectRoot, projectConfig, platformDir) {+ var files = projectConfig.getFileResources('android', true);if (files.length > 0) {events.emit('verbose', 'Cleaning resource files at ' + platformDir);var resourceMap = {};- files.forEach(function(res) {+ files.forEach(function (res) {var filePath = path.join(platformDir, res.target);resourceMap[filePath] = null;});FileUpdater.updatePaths(- resourceMap, { rootDir: projectRoot, all: true}, logFileOp);+ resourceMap, {+ rootDir: projectRoot, all: true}, logFileOp);}}@@ -452,7 +461,7 @@ function cleanFileResources(projectRoot, projectConfig, platformDir) {* default value, if there is no such preference. The default value is* 'singleTop'*/-function findAndroidLaunchModePreference(platformConfig) {+function findAndroidLaunchModePreference (platformConfig) {var launchMode = platformConfig.getPreference('AndroidLaunchMode');if (!launchMode) {// Return a default valuediff --git a/cordova/platforms/android/cordova/lib/retry.js b/cordova/platforms/android/cordova/lib/retry.jsindex 3cb492744..c464b9d5f 100644--- a/cordova/platforms/android/cordova/lib/retry.js+++ b/cordova/platforms/android/cordova/lib/retry.js@@ -45,12 +45,12 @@ module.exports.retryPromise = function (attemts_left, promiseFunction) {return promiseFunction.apply(undefined, promiseFunctionArguments).then(// on success pass results through- function onFulfilled(value) {+ function onFulfilled (value) {return value;},// on rejection either retry, or throw the error- function onRejected(error) {+ function onRejected (error) {attemts_left -= 1;diff --git a/cordova/platforms/android/cordova/lib/run.js b/cordova/platforms/android/cordova/lib/run.jsindex 214a1e199..4d7927ced 100644--- a/cordova/platforms/android/cordova/lib/run.js+++ b/cordova/platforms/android/cordova/lib/run.js@@ -21,14 +21,14 @@/* jshint loopfunc:true */-var path = require('path'),- build = require('./build'),- emulator = require('./emulator'),- device = require('./device'),- Q = require('q'),- events = require('cordova-common').events;+var path = require('path');+var build = require('./build');+var emulator = require('./emulator');+var device = require('./device');+var Q = require('q');+var events = require('cordova-common').events;-function getInstallTarget(runOptions) {+function getInstallTarget (runOptions) {var install_target;if (runOptions.target) {install_target = runOptions.target;@@ -51,17 +51,15 @@ function getInstallTarget(runOptions) {** @return {Promise}*/- module.exports.run = function(runOptions) {+module.exports.run = function (runOptions) {var self = this;var install_target = getInstallTarget(runOptions);- return Q()- .then(function() {+ return Q().then(function () {if (!install_target) {// no target given, deploy to device if available, otherwise use the emulator.- return device.list()- .then(function(device_list) {+ return device.list().then(function (device_list) {if (device_list.length > 0) {events.emit('warn', 'No target specified, deploying to device \'' + device_list[0] + '\'.');install_target = device_list[0];@@ -71,36 +69,31 @@ function getInstallTarget(runOptions) {}});}- }).then(function() {- if (install_target == '--device') {+ }).then(function () {+ if (install_target === '--device') {return device.resolveTarget(null);- } else if (install_target == '--emulator') {+ } else if (install_target === '--emulator') {// Give preference to any already started emulators. Else, start one.- return emulator.list_started()- .then(function(started) {+ return emulator.list_started().then(function (started) {return started && started.length > 0 ? started[0] : emulator.start();- }).then(function(emulatorId) {+ }).then(function (emulatorId) {return emulator.resolveTarget(emulatorId);});}// They specified a specific device/emulator ID.- return device.list()- .then(function(devices) {+ return device.list().then(function (devices) {if (devices.indexOf(install_target) > -1) {return device.resolveTarget(install_target);}- return emulator.list_started()- .then(function(started_emulators) {+ return emulator.list_started().then(function (started_emulators) {if (started_emulators.indexOf(install_target) > -1) {return emulator.resolveTarget(install_target);}- return emulator.list_images()- .then(function(avds) {+ return emulator.list_images().then(function (avds) {// if target emulator isn't started, then start it.for (var avd in avds) {- if (avds[avd].name == install_target) {- return emulator.start(install_target)- .then(function(emulatorId) {+ if (avds[avd].name === install_target) {+ return emulator.start(install_target).then(function (emulatorId) {return emulator.resolveTarget(emulatorId);});}@@ -109,16 +102,14 @@ function getInstallTarget(runOptions) {});});});- }).then(function(resolvedTarget) {+ }).then(function (resolvedTarget) {// Better just call self.build, but we're doing some processing of// build results (according to platformApi spec) so they are in different// format than emulator.install expects.// TODO: Update emulator/device.install to handle this change- return build.run.call(self, runOptions, resolvedTarget)- .then(function(buildResults) {- if (resolvedTarget.isEmulator) {- return emulator.wait_for_boot(resolvedTarget.target)- .then(function () {+ return build.run.call(self, runOptions, resolvedTarget).then(function (buildResults) {+ if (resolvedTarget && resolvedTarget.isEmulator) {+ return emulator.wait_for_boot(resolvedTarget.target).then(function () {return emulator.install(resolvedTarget, buildResults);});}@@ -127,7 +118,7 @@ function getInstallTarget(runOptions) {});};-module.exports.help = function() {+module.exports.help = function () {console.log('Usage: ' + path.relative(process.cwd(), process.argv[1]) + ' [options]');console.log('Build options :');console.log(' --debug : Builds project in debug mode');diff --git a/cordova/platforms/android/cordova/lib/start-emulator.bat b/cordova/platforms/android/cordova/lib/start-emulator.batindex 9329d9517..6c237ea2a 100644--- a/cordova/platforms/android/cordova/lib/start-emulator.bat+++ b/cordova/platforms/android/cordova/lib/start-emulator.bat@@ -18,7 +18,7 @@@ECHO OFFSET script_path="%~dp0start-emulator"IF EXIST %script_path% (- node "%script_path%" %*+ node %script_path% %*) ELSE (ECHO.ECHO ERROR: Could not find 'start-emulator' script in 'cordova\lib' folder, aborting...>&2diff --git a/cordova/platforms/android/cordova/version b/cordova/platforms/android/cordova/versionindex cdc2e80ab..6f490b8db 100755--- a/cordova/platforms/android/cordova/version+++ b/cordova/platforms/android/cordova/version@@ -20,7 +20,7 @@*/// Coho updates this line:-var VERSION = "6.2.3";+var VERSION = "7.1.2";module.exports.version = VERSION;diff --git a/cordova/platforms/android/platform_www/cordova.js b/cordova/platforms/android/platform_www/cordova.jsindex bda7c3e57..a9f8bb0dd 100644--- a/cordova/platforms/android/platform_www/cordova.js+++ b/cordova/platforms/android/platform_www/cordova.js@@ -1,5 +1,5 @@// Platform: android-// 7ef9f9c03167a4dde4372d869472241b6816fee9+// 9e8e1b716252c4a08abcd31a13013b868d6f4141/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,35 +19,33 @@under the License.*/;(function() {-var PLATFORM_VERSION_BUILD_LABEL = '6.2.3';+var PLATFORM_VERSION_BUILD_LABEL = '7.1.2';// file: src/scripts/require.js-/*jshint -W079 */-/*jshint -W020 */+/* jshint -W079 */+/* jshint -W020 */-var require,- define;+var require;+var define;(function () {- var modules = {},+ var modules = {};// Stack of moduleIds currently being built.- requireStack = [],+ var requireStack = [];// Map of module ID -> index into requireStack of modules currently being built.- inProgressModules = {},- SEPARATOR = ".";---- function build(module) {- var factory = module.factory,- localRequire = function (id) {- var resultantId = id;- //Its a relative path, so lop off the last portion and add the id (minus "./")- if (id.charAt(0) === ".") {- resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2);- }- return require(resultantId);- };+ var inProgressModules = {};+ var SEPARATOR = '.';++ function build (module) {+ var factory = module.factory;+ var localRequire = function (id) {+ var resultantId = id;+ // Its a relative path, so lop off the last portion and add the id (minus "./")+ if (id.charAt(0) === '.') {+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2);+ }+ return require(resultantId);+ };module.exports = {};delete module.factory;factory(localRequire, module.exports, module);@@ -56,10 +54,10 @@ var require,require = function (id) {if (!modules[id]) {- throw "module " + id + " not found";+ throw 'module ' + id + ' not found';} else if (id in inProgressModules) {var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;- throw "Cycle in require graph: " + cycle;+ throw 'Cycle in require graph: ' + cycle;}if (modules[id].factory) {try {@@ -76,7 +74,7 @@ var require,define = function (id, factory) {if (modules[id]) {- throw "module " + id + " already defined";+ throw 'module ' + id + ' already defined';}modules[id] = {@@ -92,8 +90,8 @@ var require,define.moduleMap = modules;})();-//Export for use in node-if (typeof module === "object" && typeof require === "function") {+// Export for use in node+if (typeof module === 'object' && typeof require === 'function') {module.exports.require = require;module.exports.define = define;}@@ -103,15 +101,13 @@ define("cordova", function(require, exports, module) {// Workaround for Windows 10 in hosted environment case// http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object-if (window.cordova && !(window.cordova instanceof HTMLElement)) {- throw new Error("cordova already defined");+if (window.cordova && !(window.cordova instanceof HTMLElement)) { // eslint-disable-line no-undef+ throw new Error('cordova already defined');}-var channel = require('cordova/channel');var platform = require('cordova/platform');-/*** Intercept calls to addEventListener + removeEventListener and handle deviceready,* resume, and pause events.@@ -124,48 +120,48 @@ var m_window_removeEventListener = window.removeEventListener;/*** Houses custom event handlers to intercept on document + window event listeners.*/-var documentEventHandlers = {},- windowEventHandlers = {};+var documentEventHandlers = {};+var windowEventHandlers = {};-document.addEventListener = function(evt, handler, capture) {+document.addEventListener = function (evt, handler, capture) {var e = evt.toLowerCase();- if (typeof documentEventHandlers[e] != 'undefined') {+ if (typeof documentEventHandlers[e] !== 'undefined') {documentEventHandlers[e].subscribe(handler);} else {m_document_addEventListener.call(document, evt, handler, capture);}};-window.addEventListener = function(evt, handler, capture) {+window.addEventListener = function (evt, handler, capture) {var e = evt.toLowerCase();- if (typeof windowEventHandlers[e] != 'undefined') {+ if (typeof windowEventHandlers[e] !== 'undefined') {windowEventHandlers[e].subscribe(handler);} else {m_window_addEventListener.call(window, evt, handler, capture);}};-document.removeEventListener = function(evt, handler, capture) {+document.removeEventListener = function (evt, handler, capture) {var e = evt.toLowerCase();// If unsubscribing from an event that is handled by a plugin- if (typeof documentEventHandlers[e] != "undefined") {+ if (typeof documentEventHandlers[e] !== 'undefined') {documentEventHandlers[e].unsubscribe(handler);} else {m_document_removeEventListener.call(document, evt, handler, capture);}};-window.removeEventListener = function(evt, handler, capture) {+window.removeEventListener = function (evt, handler, capture) {var e = evt.toLowerCase();// If unsubscribing from an event that is handled by a plugin- if (typeof windowEventHandlers[e] != "undefined") {+ if (typeof windowEventHandlers[e] !== 'undefined') {windowEventHandlers[e].unsubscribe(handler);} else {m_window_removeEventListener.call(window, evt, handler, capture);}};-function createEvent(type, data) {+function createEvent (type, data) {var event = document.createEvent('Events');event.initEvent(type, false, false);if (data) {@@ -178,29 +174,32 @@ function createEvent(type, data) {return event;}-+/* eslint-disable no-undef */var cordova = {- define:define,- require:require,- version:PLATFORM_VERSION_BUILD_LABEL,- platformVersion:PLATFORM_VERSION_BUILD_LABEL,- platformId:platform.id,+ define: define,+ require: require,+ version: PLATFORM_VERSION_BUILD_LABEL,+ platformVersion: PLATFORM_VERSION_BUILD_LABEL,+ platformId: platform.id,++ /* eslint-enable no-undef */+/*** Methods to add/remove your own addEventListener hijacking on document + window.*/- addWindowEventHandler:function(event) {+ addWindowEventHandler: function (event) {return (windowEventHandlers[event] = channel.create(event));},- addStickyDocumentEventHandler:function(event) {+ addStickyDocumentEventHandler: function (event) {return (documentEventHandlers[event] = channel.createSticky(event));},- addDocumentEventHandler:function(event) {+ addDocumentEventHandler: function (event) {return (documentEventHandlers[event] = channel.create(event));},- removeWindowEventHandler:function(event) {+ removeWindowEventHandler: function (event) {delete windowEventHandlers[event];},- removeDocumentEventHandler:function(event) {+ removeDocumentEventHandler: function (event) {delete documentEventHandlers[event];},/**@@ -208,24 +207,23 @@ var cordova = {** @return object*/- getOriginalHandlers: function() {+ getOriginalHandlers: function () {return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},- 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};+ 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};},/*** Method to fire event from native code* bNoDetach is required for events which cause an exception which needs to be caught in native code*/- fireDocumentEvent: function(type, data, bNoDetach) {+ fireDocumentEvent: function (type, data, bNoDetach) {var evt = createEvent(type, data);- if (typeof documentEventHandlers[type] != 'undefined') {- if( bNoDetach ) {+ if (typeof documentEventHandlers[type] !== 'undefined') {+ if (bNoDetach) {documentEventHandlers[type].fire(evt);- }- else {- setTimeout(function() {+ } else {+ setTimeout(function () {// Fire deviceready on listeners that were registered before cordova.js was loaded.- if (type == 'deviceready') {+ if (type === 'deviceready') {document.dispatchEvent(evt);}documentEventHandlers[type].fire(evt);@@ -235,10 +233,10 @@ var cordova = {document.dispatchEvent(evt);}},- fireWindowEvent: function(type, data) {- var evt = createEvent(type,data);- if (typeof windowEventHandlers[type] != 'undefined') {- setTimeout(function() {+ fireWindowEvent: function (type, data) {+ var evt = createEvent(type, data);+ if (typeof windowEventHandlers[type] !== 'undefined') {+ setTimeout(function () {windowEventHandlers[type].fire(evt);}, 0);} else {@@ -252,7 +250,7 @@ var cordova = {// Randomize the starting callbackId to avoid collisions after refreshing or navigating.// This way, it's very unlikely that any new callback would get the same callbackId as an old callback.callbackId: Math.floor(Math.random() * 2000000000),- callbacks: {},+ callbacks: {},callbackStatus: {NO_RESULT: 0,OK: 1,@@ -269,14 +267,14 @@ var cordova = {/*** Called by native code when returning successful result from an action.*/- callbackSuccess: function(callbackId, args) {+ callbackSuccess: function (callbackId, args) {cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);},/*** Called by native code when returning error result from an action.*/- callbackError: function(callbackId, args) {+ callbackError: function (callbackId, args) {// TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.// Derive success from status.cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);@@ -285,11 +283,11 @@ var cordova = {/*** Called by native code when returning the result from an action.*/- callbackFromNative: function(callbackId, isSuccess, status, args, keepCallback) {+ callbackFromNative: function (callbackId, isSuccess, status, args, keepCallback) {try {var callback = cordova.callbacks[callbackId];if (callback) {- if (isSuccess && status == cordova.callbackStatus.OK) {+ if (isSuccess && status === cordova.callbackStatus.OK) {callback.success && callback.success.apply(null, args);} else if (!isSuccess) {callback.fail && callback.fail.apply(null, args);@@ -306,31 +304,30 @@ var cordova = {delete cordova.callbacks[callbackId];}}- }- catch (err) {- var msg = "Error in " + (isSuccess ? "Success" : "Error") + " callbackId: " + callbackId + " : " + err;+ } catch (err) {+ var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;console && console.log && console.log(msg);- cordova.fireWindowEvent("cordovacallbackerror", { 'message': msg });+ console && console.log && err.stack && console.log(err.stack);+ cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });throw err;}},- addConstructor: function(func) {- channel.onCordovaReady.subscribe(function() {+ addConstructor: function (func) {+ channel.onCordovaReady.subscribe(function () {try {func();- } catch(e) {- console.log("Failed to run constructor: " + e);+ } catch (e) {+ console.log('Failed to run constructor: ' + e);}});}};-module.exports = cordova;});-// file: /Users/maj/src/cordova-android/cordova-js-src/android/nativeapiprovider.js+// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/android/nativeapiprovider.jsdefine("cordova/android/nativeapiprovider", function(require, exports, module) {/**@@ -353,7 +350,7 @@ module.exports = {});-// file: /Users/maj/src/cordova-android/cordova-js-src/android/promptbasednativeapi.js+// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/android/promptbasednativeapi.jsdefine("cordova/android/promptbasednativeapi", function(require, exports, module) {/**@@ -391,29 +388,29 @@ var typeMap = {'O': 'Object'};-function extractParamName(callee, argIndex) {+function extractParamName (callee, argIndex) {return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];}-function checkArgs(spec, functionName, args, opt_callee) {+function checkArgs (spec, functionName, args, opt_callee) {if (!moduleExports.enableChecks) {return;}var errMsg = null;var typeName;for (var i = 0; i < spec.length; ++i) {- var c = spec.charAt(i),- cUpper = c.toUpperCase(),- arg = args[i];+ var c = spec.charAt(i);+ var cUpper = c.toUpperCase();+ var arg = args[i];// Asterix means allow anything.- if (c == '*') {+ if (c === '*') {continue;}typeName = utils.typeName(arg);- if ((arg === null || arg === undefined) && c == cUpper) {+ if ((arg === null || arg === undefined) && c === cUpper) {continue;}- if (typeName != typeMap[cUpper]) {+ if (typeName !== typeMap[cUpper]) {errMsg = 'Expected ' + typeMap[cUpper];break;}@@ -422,14 +419,14 @@ function checkArgs(spec, functionName, args, opt_callee) {errMsg += ', but got ' + typeName + '.';errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;// Don't log when running unit tests.- if (typeof jasmine == 'undefined') {+ if (typeof jasmine === 'undefined') {console.error(errMsg);}throw TypeError(errMsg);}}-function getValue(value, defaultValue) {+function getValue (value, defaultValue) {return value === undefined ? defaultValue : value;}@@ -437,7 +434,6 @@ moduleExports.checkArgs = checkArgs;moduleExports.getValue = getValue;moduleExports.enableChecks = true;-});// file: src/common/base64.js@@ -445,58 +441,58 @@ define("cordova/base64", function(require, exports, module) {var base64 = exports;-base64.fromArrayBuffer = function(arrayBuffer) {+base64.fromArrayBuffer = function (arrayBuffer) {var array = new Uint8Array(arrayBuffer);return uint8ToBase64(array);};-base64.toArrayBuffer = function(str) {- var decodedStr = typeof atob != 'undefined' ? atob(str) : new Buffer(str,'base64').toString('binary');+base64.toArrayBuffer = function (str) {+ var decodedStr = typeof atob !== 'undefined' ? atob(str) : Buffer.from(str, 'base64').toString('binary'); // eslint-disable-line no-undefvar arrayBuffer = new ArrayBuffer(decodedStr.length);var array = new Uint8Array(arrayBuffer);- for (var i=0, len=decodedStr.length; i < len; i++) {+ for (var i = 0, len = decodedStr.length; i < len; i++) {array[i] = decodedStr.charCodeAt(i);}return arrayBuffer;};-//------------------------------------------------------------------------------+// ------------------------------------------------------------------------------/* This code is based on the performance tests at http://jsperf.com/b64tests* This 12-bit-at-a-time algorithm was the best performing version on all* platforms tested.*/-var b64_6bit = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+var b64_6bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';var b64_12bit;-var b64_12bitTable = function() {+var b64_12bitTable = function () {b64_12bit = [];- for (var i=0; i<64; i++) {- for (var j=0; j<64; j++) {- b64_12bit[i*64+j] = b64_6bit[i] + b64_6bit[j];+ for (var i = 0; i < 64; i++) {+ for (var j = 0; j < 64; j++) {+ b64_12bit[i * 64 + j] = b64_6bit[i] + b64_6bit[j];}}- b64_12bitTable = function() { return b64_12bit; };+ b64_12bitTable = function () { return b64_12bit; };return b64_12bit;};-function uint8ToBase64(rawData) {+function uint8ToBase64 (rawData) {var numBytes = rawData.byteLength;- var output="";+ var output = '';var segment;var table = b64_12bitTable();- for (var i=0;i<numBytes-2;i+=3) {- segment = (rawData[i] << 16) + (rawData[i+1] << 8) + rawData[i+2];+ for (var i = 0; i < numBytes - 2; i += 3) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8) + rawData[i + 2];output += table[segment >> 12];output += table[segment & 0xfff];}- if (numBytes - i == 2) {- segment = (rawData[i] << 16) + (rawData[i+1] << 8);+ if (numBytes - i === 2) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8);output += table[segment >> 12];output += b64_6bit[(segment & 0xfff) >> 6];output += '=';- } else if (numBytes - i == 1) {+ } else if (numBytes - i === 1) {segment = (rawData[i] << 16);output += table[segment >> 12];output += '==';@@ -511,7 +507,7 @@ define("cordova/builder", function(require, exports, module) {var utils = require('cordova/utils');-function each(objects, func, context) {+function each (objects, func, context) {for (var prop in objects) {if (objects.hasOwnProperty(prop)) {func.apply(context, [objects[prop], prop]);@@ -519,7 +515,7 @@ function each(objects, func, context) {}}-function clobber(obj, key, value) {+function clobber (obj, key, value) {exports.replaceHookForTesting(obj, key);var needsProperty = false;try {@@ -529,15 +525,15 @@ function clobber(obj, key, value) {}// Getters can only be overridden by getters.if (needsProperty || obj[key] !== value) {- utils.defineGetter(obj, key, function() {+ utils.defineGetter(obj, key, function () {return value;});}}-function assignOrWrapInDeprecateGetter(obj, key, value, message) {+function assignOrWrapInDeprecateGetter (obj, key, value, message) {if (message) {- utils.defineGetter(obj, key, function() {+ utils.defineGetter(obj, key, function () {console.log(message);delete obj[key];clobber(obj, key, value);@@ -548,7 +544,7 @@ function assignOrWrapInDeprecateGetter(obj, key, value, message) {}}-function include(parent, objects, clobber, merge) {+function include (parent, objects, clobber, merge) {each(objects, function (obj, key) {try {var result = obj.path ? require(obj.path) : {};@@ -568,7 +564,7 @@ function include(parent, objects, clobber, merge) {result = parent[key];} else {// Overwrite if not currently defined.- if (typeof parent[key] == 'undefined') {+ if (typeof parent[key] === 'undefined') {assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);} else {// Set result to what already exists, so we can build children into it if they exist.@@ -579,7 +575,7 @@ function include(parent, objects, clobber, merge) {if (obj.children) {include(result, obj.children, clobber, merge);}- } catch(e) {+ } catch (e) {utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');}});@@ -592,7 +588,7 @@ function include(parent, objects, clobber, merge) {* @param target Object to merge properties into.* @param src Object to merge properties from.*/-function recursiveMerge(target, src) {+function recursiveMerge (target, src) {for (var prop in src) {if (src.hasOwnProperty(prop)) {if (target.prototype && target.prototype.constructor === target) {@@ -609,26 +605,26 @@ function recursiveMerge(target, src) {}}-exports.buildIntoButDoNotClobber = function(objects, target) {+exports.buildIntoButDoNotClobber = function (objects, target) {include(target, objects, false, false);};-exports.buildIntoAndClobber = function(objects, target) {+exports.buildIntoAndClobber = function (objects, target) {include(target, objects, true, false);};-exports.buildIntoAndMerge = function(objects, target) {+exports.buildIntoAndMerge = function (objects, target) {include(target, objects, true, true);};exports.recursiveMerge = recursiveMerge;exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;-exports.replaceHookForTesting = function() {};+exports.replaceHookForTesting = function () {};});// file: src/common/channel.jsdefine("cordova/channel", function(require, exports, module) {-var utils = require('cordova/utils'),- nextGuid = 1;+var utils = require('cordova/utils');+var nextGuid = 1;/*** Custom pub-sub "channel" that can have functions subscribed to it@@ -668,7 +664,7 @@ var utils = require('cordova/utils'),* @constructor* @param type String the channel name*/-var Channel = function(type, sticky) {+var Channel = function (type, sticky) {this.type = type;// Map of guid -> function.this.handlers = {};@@ -681,72 +677,73 @@ var Channel = function(type, sticky) {// Function that is called when the first listener is subscribed, or when// the last listener is unsubscribed.this.onHasSubscribersChange = null;-},- channel = {- /**- * Calls the provided function only after all of the channels specified- * have been fired. All channels must be sticky channels.- */- join: function(h, c) {- var len = c.length,- i = len,- f = function() {- if (!(--i)) h();- };- for (var j=0; j<len; j++) {- if (c[j].state === 0) {- throw Error('Can only use join with sticky channels.');- }- c[j].subscribe(f);- }- if (!len) h();- },- create: function(type) {- return channel[type] = new Channel(type, false);- },- createSticky: function(type) {- return channel[type] = new Channel(type, true);- },-- /**- * cordova Channels that must fire before "deviceready" is fired.- */- deviceReadyChannelsArray: [],- deviceReadyChannelsMap: {},-- /**- * Indicate that a feature needs to be initialized before it is ready to be used.- * This holds up Cordova's "deviceready" event until the feature has been initialized- * and Cordova.initComplete(feature) is called.- *- * @param feature {String} The unique feature name- */- waitForInitialization: function(feature) {- if (feature) {- var c = channel[feature] || this.createSticky(feature);- this.deviceReadyChannelsMap[feature] = c;- this.deviceReadyChannelsArray.push(c);- }- },-- /**- * Indicate that initialization code has completed and the feature is ready to be used.- *- * @param feature {String} The unique feature name- */- initializationComplete: function(feature) {- var c = this.deviceReadyChannelsMap[feature];- if (c) {- c.fire();+};+var channel = {+ /**+ * Calls the provided function only after all of the channels specified+ * have been fired. All channels must be sticky channels.+ */+ join: function (h, c) {+ var len = c.length;+ var i = len;+ var f = function () {+ if (!(--i)) h();+ };+ for (var j = 0; j < len; j++) {+ if (c[j].state === 0) {+ throw Error('Can only use join with sticky channels.');}+ c[j].subscribe(f);}- };+ if (!len) h();+ },+ /* eslint-disable no-return-assign */+ create: function (type) {+ return channel[type] = new Channel(type, false);+ },+ createSticky: function (type) {+ return channel[type] = new Channel(type, true);+ },+ /* eslint-enable no-return-assign */+ /**+ * cordova Channels that must fire before "deviceready" is fired.+ */+ deviceReadyChannelsArray: [],+ deviceReadyChannelsMap: {},-function checkSubscriptionArgument(argument) {- if (typeof argument !== "function" && typeof argument.handleEvent !== "function") {+ /**+ * Indicate that a feature needs to be initialized before it is ready to be used.+ * This holds up Cordova's "deviceready" event until the feature has been initialized+ * and Cordova.initComplete(feature) is called.+ *+ * @param feature {String} The unique feature name+ */+ waitForInitialization: function (feature) {+ if (feature) {+ var c = channel[feature] || this.createSticky(feature);+ this.deviceReadyChannelsMap[feature] = c;+ this.deviceReadyChannelsArray.push(c);+ }+ },++ /**+ * Indicate that initialization code has completed and the feature is ready to be used.+ *+ * @param feature {String} The unique feature name+ */+ initializationComplete: function (feature) {+ var c = this.deviceReadyChannelsMap[feature];+ if (c) {+ c.fire();+ }+ }+};++function checkSubscriptionArgument (argument) {+ if (typeof argument !== 'function' && typeof argument.handleEvent !== 'function') {throw new Error(- "Must provide a function or an EventListener object " +- "implementing the handleEvent interface."+ 'Must provide a function or an EventListener object ' ++ 'implementing the handleEvent interface.');}}@@ -758,11 +755,11 @@ function checkSubscriptionArgument(argument) {* and a guid that can be used to stop subscribing to the channel.* Returns the guid.*/-Channel.prototype.subscribe = function(eventListenerOrFunction, eventListener) {+Channel.prototype.subscribe = function (eventListenerOrFunction, eventListener) {checkSubscriptionArgument(eventListenerOrFunction);var handleEvent, guid;- if (eventListenerOrFunction && typeof eventListenerOrFunction === "object") {+ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {// Received an EventListener object implementing the handleEvent interfacehandleEvent = eventListenerOrFunction.handleEvent;eventListener = eventListenerOrFunction;@@ -771,13 +768,13 @@ Channel.prototype.subscribe = function(eventListenerOrFunction, eventListener) {handleEvent = eventListenerOrFunction;}- if (this.state == 2) {+ if (this.state === 2) {handleEvent.apply(eventListener || this, this.fireArgs);return;}guid = eventListenerOrFunction.observer_guid;- if (typeof eventListener === "object") {+ if (typeof eventListener === 'object') {handleEvent = utils.close(eventListener, handleEvent);}@@ -792,7 +789,7 @@ Channel.prototype.subscribe = function(eventListenerOrFunction, eventListener) {if (!this.handlers[guid]) {this.handlers[guid] = handleEvent;this.numHandlers++;- if (this.numHandlers == 1) {+ if (this.numHandlers === 1) {this.onHasSubscribersChange && this.onHasSubscribersChange();}}@@ -801,11 +798,11 @@ Channel.prototype.subscribe = function(eventListenerOrFunction, eventListener) {/*** Unsubscribes the function with the given guid from the channel.*/-Channel.prototype.unsubscribe = function(eventListenerOrFunction) {+Channel.prototype.unsubscribe = function (eventListenerOrFunction) {checkSubscriptionArgument(eventListenerOrFunction);var handleEvent, guid, handler;- if (eventListenerOrFunction && typeof eventListenerOrFunction === "object") {+ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {// Received an EventListener object implementing the handleEvent interfacehandleEvent = eventListenerOrFunction.handleEvent;} else {@@ -827,11 +824,11 @@ Channel.prototype.unsubscribe = function(eventListenerOrFunction) {/*** Calls all functions subscribed to this channel.*/-Channel.prototype.fire = function(e) {- var fail = false,- fireArgs = Array.prototype.slice.call(arguments);+Channel.prototype.fire = function (e) {+ var fail = false; // eslint-disable-line no-unused-vars+ var fireArgs = Array.prototype.slice.call(arguments);// Apply stickiness.- if (this.state == 1) {+ if (this.state === 1) {this.state = 2;this.fireArgs = fireArgs;}@@ -845,7 +842,7 @@ Channel.prototype.fire = function(e) {for (var i = 0; i < toCall.length; ++i) {toCall[i].apply(this, fireArgs);}- if (this.state == 2 && this.numHandlers) {+ if (this.state === 2 && this.numHandlers) {this.numHandlers = 0;this.handlers = {};this.onHasSubscribersChange && this.onHasSubscribersChange();@@ -853,7 +850,6 @@ Channel.prototype.fire = function(e) {}};-// defining them here so they are ready super fast!// DOM event that is received when the web page is loaded and parsed.channel.createSticky('onDOMContentLoaded');@@ -886,7 +882,7 @@ module.exports = channel;});-// file: /Users/maj/src/cordova-android/cordova-js-src/exec.js+// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/exec.jsdefine("cordova/exec", function(require, exports, module) {/**@@ -1171,31 +1167,31 @@ module.exports = androidExec;// file: src/common/exec/proxy.jsdefine("cordova/exec/proxy", function(require, exports, module) {-// internal map of proxy functionvar CommandProxyMap = {};module.exports = {// example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);- add:function(id,proxyObj) {- console.log("adding proxy for " + id);+ add: function (id, proxyObj) {+ console.log('adding proxy for ' + id);CommandProxyMap[id] = proxyObj;return proxyObj;},// cordova.commandProxy.remove("Accelerometer");- remove:function(id) {+ remove: function (id) {var proxy = CommandProxyMap[id];delete CommandProxyMap[id];CommandProxyMap[id] = null;return proxy;},- get:function(service,action) {- return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null );+ get: function (service, action) {+ return (CommandProxyMap[service] ? CommandProxyMap[service][action] : null);}};+});// file: src/common/init.js@@ -1210,16 +1206,16 @@ var utils = require('cordova/utils');var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];-function logUnfiredChannels(arr) {+function logUnfiredChannels (arr) {for (var i = 0; i < arr.length; ++i) {- if (arr[i].state != 2) {+ if (arr[i].state !== 2) {console.log('Channel not fired: ' + arr[i].type);}}}-window.setTimeout(function() {- if (channel.onDeviceReady.state != 2) {+window.setTimeout(function () {+ if (channel.onDeviceReady.state !== 2) {console.log('deviceready has not fired after 5 seconds.');logUnfiredChannels(platformInitChannelsArray);logUnfiredChannels(channel.deviceReadyChannelsArray);@@ -1228,20 +1224,19 @@ window.setTimeout(function() {// Replace navigator before any modules are required(), to ensure it happens as soon as possible.// We replace it so that properties that can't be clobbered can instead be overridden.-function replaceNavigator(origNavigator) {- var CordovaNavigator = function() {};+function replaceNavigator (origNavigator) {+ var CordovaNavigator = function () {};CordovaNavigator.prototype = origNavigator;var newNavigator = new CordovaNavigator();// This work-around really only applies to new APIs that are newer than Function.bind.// Without it, APIs such as getGamepads() break.if (CordovaNavigator.bind) {for (var key in origNavigator) {- if (typeof origNavigator[key] == 'function') {+ if (typeof origNavigator[key] === 'function') {newNavigator[key] = origNavigator[key].bind(origNavigator);- }- else {- (function(k) {- utils.defineGetterSetter(newNavigator,key,function() {+ } else {+ (function (k) {+ utils.defineGetterSetter(newNavigator, key, function () {return origNavigator[k];});})(key);@@ -1257,12 +1252,12 @@ if (window.navigator) {if (!window.console) {window.console = {- log: function(){}+ log: function () {}};}if (!window.console.warn) {- window.console.warn = function(msg) {- this.log("warn: " + msg);+ window.console.warn = function (msg) {+ this.log('warn: ' + msg);};}@@ -1273,10 +1268,10 @@ channel.onActivated = cordova.addDocumentEventHandler('activated');channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');// Listen for DOMContentLoaded and notify our channel subscribers.-if (document.readyState == 'complete' || document.readyState == 'interactive') {+if (document.readyState === 'complete' || document.readyState === 'interactive') {channel.onDOMContentLoaded.fire();} else {- document.addEventListener('DOMContentLoaded', function() {+ document.addEventListener('DOMContentLoaded', function () {channel.onDOMContentLoaded.fire();}, false);}@@ -1297,8 +1292,8 @@ platform.bootstrap && platform.bootstrap();// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.// The delay allows the attached modules to be defined before the plugin loader looks for them.-setTimeout(function() {- pluginloader.load(function() {+setTimeout(function () {+ pluginloader.load(function () {channel.onPluginsReady.fire();});}, 0);@@ -1306,7 +1301,7 @@ setTimeout(function() {/*** Create all cordova objects once native side is ready.*/-channel.join(function() {+channel.join(function () {modulemapper.mapModules(window);platform.initialize && platform.initialize();@@ -1317,13 +1312,12 @@ channel.join(function() {// Fire onDeviceReady event once page has fully loaded, all// constructors have run and cordova info has been received from native// side.- channel.join(function() {+ channel.join(function () {require('cordova').fireDocumentEvent('deviceready');}, channel.deviceReadyChannelsArray);}, platformInitChannelsArray);-});// file: src/common/init_b.js@@ -1341,16 +1335,16 @@ var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeRea// setting execcordova.exec = require('cordova/exec');-function logUnfiredChannels(arr) {+function logUnfiredChannels (arr) {for (var i = 0; i < arr.length; ++i) {- if (arr[i].state != 2) {+ if (arr[i].state !== 2) {console.log('Channel not fired: ' + arr[i].type);}}}-window.setTimeout(function() {- if (channel.onDeviceReady.state != 2) {+window.setTimeout(function () {+ if (channel.onDeviceReady.state !== 2) {console.log('deviceready has not fired after 5 seconds.');logUnfiredChannels(platformInitChannelsArray);logUnfiredChannels(channel.deviceReadyChannelsArray);@@ -1359,20 +1353,19 @@ window.setTimeout(function() {// Replace navigator before any modules are required(), to ensure it happens as soon as possible.// We replace it so that properties that can't be clobbered can instead be overridden.-function replaceNavigator(origNavigator) {- var CordovaNavigator = function() {};+function replaceNavigator (origNavigator) {+ var CordovaNavigator = function () {};CordovaNavigator.prototype = origNavigator;var newNavigator = new CordovaNavigator();// This work-around really only applies to new APIs that are newer than Function.bind.// Without it, APIs such as getGamepads() break.if (CordovaNavigator.bind) {for (var key in origNavigator) {- if (typeof origNavigator[key] == 'function') {+ if (typeof origNavigator[key] === 'function') {newNavigator[key] = origNavigator[key].bind(origNavigator);- }- else {- (function(k) {- utils.defineGetterSetter(newNavigator,key,function() {+ } else {+ (function (k) {+ utils.defineGetterSetter(newNavigator, key, function () {return origNavigator[k];});})(key);@@ -1387,12 +1380,12 @@ if (window.navigator) {if (!window.console) {window.console = {- log: function(){}+ log: function () {}};}if (!window.console.warn) {- window.console.warn = function(msg) {- this.log("warn: " + msg);+ window.console.warn = function (msg) {+ this.log('warn: ' + msg);};}@@ -1403,10 +1396,10 @@ channel.onActivated = cordova.addDocumentEventHandler('activated');channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');// Listen for DOMContentLoaded and notify our channel subscribers.-if (document.readyState == 'complete' || document.readyState == 'interactive') {+if (document.readyState === 'complete' || document.readyState === 'interactive') {channel.onDOMContentLoaded.fire();} else {- document.addEventListener('DOMContentLoaded', function() {+ document.addEventListener('DOMContentLoaded', function () {channel.onDOMContentLoaded.fire();}, false);}@@ -1423,8 +1416,8 @@ platform.bootstrap && platform.bootstrap();// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.// The delay allows the attached modules to be defined before the plugin loader looks for them.-setTimeout(function() {- pluginloader.load(function() {+setTimeout(function () {+ pluginloader.load(function () {channel.onPluginsReady.fire();});}, 0);@@ -1432,7 +1425,7 @@ setTimeout(function() {/*** Create all cordova objects once native side is ready.*/-channel.join(function() {+channel.join(function () {modulemapper.mapModules(window);platform.initialize && platform.initialize();@@ -1443,7 +1436,7 @@ channel.join(function() {// Fire onDeviceReady event once page has fully loaded, all// constructors have run and cordova info has been received from native// side.- channel.join(function() {+ channel.join(function () {require('cordova').fireDocumentEvent('deviceready');}, channel.deviceReadyChannelsArray);@@ -1454,17 +1447,17 @@ channel.join(function() {// file: src/common/modulemapper.jsdefine("cordova/modulemapper", function(require, exports, module) {-var builder = require('cordova/builder'),- moduleMap = define.moduleMap,- symbolList,- deprecationMap;+var builder = require('cordova/builder');+var moduleMap = define.moduleMap; // eslint-disable-line no-undef+var symbolList;+var deprecationMap;-exports.reset = function() {+exports.reset = function () {symbolList = [];deprecationMap = {};};-function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {+function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {if (!(moduleName in moduleMap)) {throw new Error('Module ' + moduleName + ' does not exist.');}@@ -1475,35 +1468,35 @@ function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {}// Note: Android 2.3 does have Function.bind().-exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) {+exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {addEntry('c', moduleName, symbolPath, opt_deprecationMessage);};-exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) {+exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {addEntry('m', moduleName, symbolPath, opt_deprecationMessage);};-exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) {+exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {addEntry('d', moduleName, symbolPath, opt_deprecationMessage);};-exports.runs = function(moduleName) {+exports.runs = function (moduleName) {addEntry('r', moduleName, null);};-function prepareNamespace(symbolPath, context) {+function prepareNamespace (symbolPath, context) {if (!symbolPath) {return context;}var parts = symbolPath.split('.');var cur = context;- for (var i = 0, part; part = parts[i]; ++i) {+ for (var i = 0, part; part = parts[i]; ++i) { // eslint-disable-line no-cond-assigncur = cur[part] = cur[part] || {};}return cur;}-exports.mapModules = function(context) {+exports.mapModules = function (context) {var origSymbols = {};context.CDV_origSymbols = origSymbols;for (var i = 0, len = symbolList.length; i < len; i += 3) {@@ -1511,7 +1504,7 @@ exports.mapModules = function(context) {var moduleName = symbolList[i + 1];var module = require(moduleName);// <runs/>- if (strategy == 'r') {+ if (strategy === 'r') {continue;}var symbolPath = symbolList[i + 2];@@ -1523,9 +1516,9 @@ exports.mapModules = function(context) {var parentObj = prepareNamespace(namespace, context);var target = parentObj[lastName];- if (strategy == 'm' && target) {+ if (strategy === 'm' && target) {builder.recursiveMerge(target, module);- } else if ((strategy == 'd' && !target) || (strategy != 'd')) {+ } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {if (!(symbolPath in origSymbols)) {origSymbols[symbolPath] = target;}@@ -1534,7 +1527,7 @@ exports.mapModules = function(context) {}};-exports.getOriginalSymbol = function(context, symbolPath) {+exports.getOriginalSymbol = function (context, symbolPath) {var origSymbols = context.CDV_origSymbols;if (origSymbols && (symbolPath in origSymbols)) {return origSymbols[symbolPath];@@ -1549,22 +1542,21 @@ exports.getOriginalSymbol = function(context, symbolPath) {exports.reset();-});// file: src/common/modulemapper_b.jsdefine("cordova/modulemapper_b", function(require, exports, module) {-var builder = require('cordova/builder'),- symbolList = [],- deprecationMap;+var builder = require('cordova/builder');+var symbolList = [];+var deprecationMap;-exports.reset = function() {+exports.reset = function () {symbolList = [];deprecationMap = {};};-function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {+function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {symbolList.push(strategy, moduleName, symbolPath);if (opt_deprecationMessage) {deprecationMap[symbolPath] = opt_deprecationMessage;@@ -1572,35 +1564,35 @@ function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) {}// Note: Android 2.3 does have Function.bind().-exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) {+exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {addEntry('c', moduleName, symbolPath, opt_deprecationMessage);};-exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) {+exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {addEntry('m', moduleName, symbolPath, opt_deprecationMessage);};-exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) {+exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {addEntry('d', moduleName, symbolPath, opt_deprecationMessage);};-exports.runs = function(moduleName) {+exports.runs = function (moduleName) {addEntry('r', moduleName, null);};-function prepareNamespace(symbolPath, context) {+function prepareNamespace (symbolPath, context) {if (!symbolPath) {return context;}var parts = symbolPath.split('.');var cur = context;- for (var i = 0, part; part = parts[i]; ++i) {+ for (var i = 0, part; part = parts[i]; ++i) { // eslint-disable-line no-cond-assigncur = cur[part] = cur[part] || {};}return cur;}-exports.mapModules = function(context) {+exports.mapModules = function (context) {var origSymbols = {};context.CDV_origSymbols = origSymbols;for (var i = 0, len = symbolList.length; i < len; i += 3) {@@ -1608,7 +1600,7 @@ exports.mapModules = function(context) {var moduleName = symbolList[i + 1];var module = require(moduleName);// <runs/>- if (strategy == 'r') {+ if (strategy === 'r') {continue;}var symbolPath = symbolList[i + 2];@@ -1620,9 +1612,9 @@ exports.mapModules = function(context) {var parentObj = prepareNamespace(namespace, context);var target = parentObj[lastName];- if (strategy == 'm' && target) {+ if (strategy === 'm' && target) {builder.recursiveMerge(target, module);- } else if ((strategy == 'd' && !target) || (strategy != 'd')) {+ } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {if (!(symbolPath in origSymbols)) {origSymbols[symbolPath] = target;}@@ -1631,7 +1623,7 @@ exports.mapModules = function(context) {}};-exports.getOriginalSymbol = function(context, symbolPath) {+exports.getOriginalSymbol = function (context, symbolPath) {var origSymbols = context.CDV_origSymbols;if (origSymbols && (symbolPath in origSymbols)) {return origSymbols[symbolPath];@@ -1646,10 +1638,9 @@ exports.getOriginalSymbol = function(context, symbolPath) {exports.reset();-});-// file: /Users/maj/src/cordova-android/cordova-js-src/platform.js+// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/platform.jsdefine("cordova/platform", function(require, exports, module) {// The last resume event that was received that had the result of a plugin call.@@ -1759,7 +1750,7 @@ function onMessageFromNative(msg) {});-// file: /Users/maj/src/cordova-android/cordova-js-src/plugin/android/app.js+// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/plugin/android/app.jsdefine("cordova/plugin/android/app", function(require, exports, module) {var exec = require('cordova/exec');@@ -1856,12 +1847,11 @@ module.exports = {define("cordova/pluginloader", function(require, exports, module) {var modulemapper = require('cordova/modulemapper');-var urlutil = require('cordova/urlutil');// Helper function to inject a <script> tag.// Exported for testing.-exports.injectScript = function(url, onload, onerror) {- var script = document.createElement("script");+exports.injectScript = function (url, onload, onerror) {+ var script = document.createElement('script');// onload fires even when script fails loads with an error.script.onload = onload;// onerror fires for malformed URLs.@@ -1870,13 +1860,13 @@ exports.injectScript = function(url, onload, onerror) {document.head.appendChild(script);};-function injectIfNecessary(id, url, onload, onerror) {+function injectIfNecessary (id, url, onload, onerror) {onerror = onerror || onload;- if (id in define.moduleMap) {+ if (id in define.moduleMap) { // eslint-disable-line no-undefonload();} else {- exports.injectScript(url, function() {- if (id in define.moduleMap) {+ exports.injectScript(url, function () {+ if (id in define.moduleMap) { // eslint-disable-line no-undefonload();} else {onerror();@@ -1885,9 +1875,9 @@ function injectIfNecessary(id, url, onload, onerror) {}}-function onScriptLoadingComplete(moduleList, finishPluginLoading) {+function onScriptLoadingComplete (moduleList, finishPluginLoading) {// Loop through all the plugins and then through their clobbers and merges.- for (var i = 0, module; module = moduleList[i]; i++) {+ for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assignif (module.clobbers && module.clobbers.length) {for (var j = 0; j < module.clobbers.length; j++) {modulemapper.clobbers(module.id, module.clobbers[j]);@@ -1913,7 +1903,7 @@ function onScriptLoadingComplete(moduleList, finishPluginLoading) {// See plugman's plugin_loader.js for the details of this object.// This function is only called if the really is a plugins array that isn't empty.// Otherwise the onerror response handler will just call finishPluginLoading().-function handlePluginsObject(path, moduleList, finishPluginLoading) {+function handlePluginsObject (path, moduleList, finishPluginLoading) {// Now inject the scripts.var scriptCounter = moduleList.length;@@ -1921,7 +1911,7 @@ function handlePluginsObject(path, moduleList, finishPluginLoading) {finishPluginLoading();return;}- function scriptLoadedCallback() {+ function scriptLoadedCallback () {if (!--scriptCounter) {onScriptLoadingComplete(moduleList, finishPluginLoading);}@@ -1932,13 +1922,13 @@ function handlePluginsObject(path, moduleList, finishPluginLoading) {}}-function findCordovaPath() {+function findCordovaPath () {var path = null;var scripts = document.getElementsByTagName('script');var term = '/cordova.js';- for (var n = scripts.length-1; n>-1; n--) {+ for (var n = scripts.length - 1; n > -1; n--) {var src = scripts[n].src.replace(/\?.*$/, ''); // Strip any query param (CB-6007).- if (src.indexOf(term) == (src.length - term.length)) {+ if (src.indexOf(term) === (src.length - term.length)) {path = src.substring(0, src.length - term.length) + '/';break;}@@ -1949,19 +1939,18 @@ function findCordovaPath() {// Tries to load all plugins' js-modules.// This is an async process, but onDeviceReady is blocked on onPluginsReady.// onPluginsReady is fired when there are no plugins to load, or they are all done.-exports.load = function(callback) {+exports.load = function (callback) {var pathPrefix = findCordovaPath();if (pathPrefix === null) {console.log('Could not find cordova.js script tag. Plugin loading may fail.');pathPrefix = '';}- injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function() {- var moduleList = require("cordova/plugin_list");+ injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function () {+ var moduleList = require('cordova/plugin_list');handlePluginsObject(pathPrefix, moduleList, callback);}, callback);};-});// file: src/common/pluginloader_b.js@@ -1971,14 +1960,14 @@ var modulemapper = require('cordova/modulemapper');// Handler for the cordova_plugins.js content.// See plugman's plugin_loader.js for the details of this object.-function handlePluginsObject(moduleList) {+function handlePluginsObject (moduleList) {// if moduleList is not defined or empty, we've nothing to doif (!moduleList || !moduleList.length) {return;}// Loop through all the modules and then through their clobbers and merges.- for (var i = 0, module; module = moduleList[i]; i++) {+ for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assignif (module.clobbers && module.clobbers.length) {for (var j = 0; j < module.clobbers.length; j++) {modulemapper.clobbers(module.id, module.clobbers[j]);@@ -2002,31 +1991,28 @@ function handlePluginsObject(moduleList) {// but the method accepts callback to be compatible with non-browserify flow.// onDeviceReady is blocked on onPluginsReady. onPluginsReady is fired when there are// no plugins to load, or they are all done.-exports.load = function(callback) {- var moduleList = require("cordova/plugin_list");+exports.load = function (callback) {+ var moduleList = require('cordova/plugin_list');handlePluginsObject(moduleList);callback();};-});// file: src/common/urlutil.jsdefine("cordova/urlutil", function(require, exports, module) {-/*** For already absolute URLs, returns what is passed in.* For relative URLs, converts them to absolute ones.*/-exports.makeAbsolute = function makeAbsolute(url) {+exports.makeAbsolute = function makeAbsolute (url) {var anchorEl = document.createElement('a');anchorEl.href = url;return anchorEl.href;};-});// file: src/common/utils.js@@ -2037,7 +2023,7 @@ var utils = exports;/*** Defines a property getter / setter for obj[key].*/-utils.defineGetterSetter = function(obj, key, getFunc, opt_setFunc) {+utils.defineGetterSetter = function (obj, key, getFunc, opt_setFunc) {if (Object.defineProperty) {var desc = {get: getFunc,@@ -2060,13 +2046,13 @@ utils.defineGetterSetter = function(obj, key, getFunc, opt_setFunc) {*/utils.defineGetter = utils.defineGetterSetter;-utils.arrayIndexOf = function(a, item) {+utils.arrayIndexOf = function (a, item) {if (a.indexOf) {return a.indexOf(item);}var len = a.length;for (var i = 0; i < len; ++i) {- if (a[i] == item) {+ if (a[i] === item) {return i;}}@@ -2076,15 +2062,15 @@ utils.arrayIndexOf = function(a, item) {/*** Returns whether the item was found in the array.*/-utils.arrayRemove = function(a, item) {+utils.arrayRemove = function (a, item) {var index = utils.arrayIndexOf(a, item);- if (index != -1) {+ if (index !== -1) {a.splice(index, 1);}- return index != -1;+ return index !== -1;};-utils.typeName = function(val) {+utils.typeName = function (val) {return Object.prototype.toString.call(val).slice(8, -1);};@@ -2092,39 +2078,39 @@ utils.typeName = function(val) {* Returns an indication of whether the argument is an array or not*/utils.isArray = Array.isArray ||- function(a) {return utils.typeName(a) == 'Array';};+ function (a) { return utils.typeName(a) === 'Array'; };/*** Returns an indication of whether the argument is a Date or not*/-utils.isDate = function(d) {+utils.isDate = function (d) {return (d instanceof Date);};/*** Does a deep clone of the object.*/-utils.clone = function(obj) {- if(!obj || typeof obj == 'function' || utils.isDate(obj) || typeof obj != 'object') {+utils.clone = function (obj) {+ if (!obj || typeof obj === 'function' || utils.isDate(obj) || typeof obj !== 'object') {return obj;}var retVal, i;- if(utils.isArray(obj)){+ if (utils.isArray(obj)) {retVal = [];- for(i = 0; i < obj.length; ++i){+ for (i = 0; i < obj.length; ++i) {retVal.push(utils.clone(obj[i]));}return retVal;}retVal = {};- for(i in obj){+ for (i in obj) {// https://issues.apache.org/jira/browse/CB-11522 'unknown' type may be returned in// custom protocol activation case on Windows Phone 8.1 causing "No such interface supported" exception// on cloning.- if((!(i in retVal) || retVal[i] != obj[i]) && typeof obj[i] != 'undefined' && typeof obj[i] != 'unknown') {+ if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') { // eslint-disable-line valid-typeofretVal[i] = utils.clone(obj[i]);}}@@ -2134,20 +2120,20 @@ utils.clone = function(obj) {/*** Returns a wrapped version of the function*/-utils.close = function(context, func, params) {- return function() {+utils.close = function (context, func, params) {+ return function () {var args = params || arguments;return func.apply(context, args);};};-//-------------------------------------------------------------------------------function UUIDcreatePart(length) {- var uuidpart = "";- for (var i=0; i<length; i++) {+// ------------------------------------------------------------------------------+function UUIDcreatePart (length) {+ var uuidpart = '';+ for (var i = 0; i < length; i++) {var uuidchar = parseInt((Math.random() * 256), 10).toString(16);- if (uuidchar.length == 1) {- uuidchar = "0" + uuidchar;+ if (uuidchar.length === 1) {+ uuidchar = '0' + uuidchar;}uuidpart += uuidchar;}@@ -2157,7 +2143,7 @@ function UUIDcreatePart(length) {/*** Create a UUID*/-utils.createUUID = function() {+utils.createUUID = function () {return UUIDcreatePart(4) + '-' +UUIDcreatePart(2) + '-' +UUIDcreatePart(2) + '-' +@@ -2165,16 +2151,15 @@ utils.createUUID = function() {UUIDcreatePart(6);};-/*** Extends a child object from a parent object using classical inheritance* pattern.*/-utils.extend = (function() {+utils.extend = (function () {// proxy used to establish prototype chain- var F = function() {};+ var F = function () {};// extend Child from Parent- return function(Child, Parent) {+ return function (Child, Parent) {F.prototype = Parent.prototype;Child.prototype = new F();@@ -2186,7 +2171,7 @@ utils.extend = (function() {/*** Alerts a message in any available way: alert or console.log.*/-utils.alert = function(msg) {+utils.alert = function (msg) {if (window.alert) {window.alert(msg);} else if (console && console.log) {@@ -2194,10 +2179,6 @@ utils.alert = function(msg) {}};----});window.cordova = require('cordova');@@ -2205,4 +2186,4 @@ window.cordova = require('cordova');require('cordova/init');-})();\ No newline at end of file+})();diff --git a/cordova/platforms/android/platform_www/cordova_plugins.js b/cordova/platforms/android/platform_www/cordova_plugins.jsdeleted file mode 100644index 38bda0cc8..000000000--- a/cordova/platforms/android/platform_www/cordova_plugins.js+++ /dev/null@@ -1,10 +0,0 @@-cordova.define('cordova/plugin_list', function(require, exports, module) {-module.exports = [];-module.exports.metadata =-// TOP OF METADATA-{- "cordova-plugin-whitelist": "1.3.2",- "cordova-plugin-crosswalk-webview": "2.3.0"-};-// BOTTOM OF METADATA-});\ No newline at end of filediff --git a/cordova/platforms/android/project.properties b/cordova/platforms/android/project.propertiesindex 3fbee8fea..1b79a1e37 100644--- a/cordova/platforms/android/project.properties+++ b/cordova/platforms/android/project.properties@@ -1,15 +1,13 @@-# This file is automatically generated by Android Tools.-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!-#-# This file must be checked in Version Control Systems.-#-# To customize properties used by the Ant build system edit-# "ant.properties", and override values to adapt the script to your-# project structure.-#-# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):-#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt+# This file was originally created by the Android Tools, but is now+# used by cordova-android to manage the state of the various third party+# libraries used in your application++# This is the Library Module that contains the Cordova Library, this is not+# required when using an AAR++# This is the application project. This is only required for Android Studio Gradle projects+# Project target.-target=android-25+target=android-27android.library.reference.1=CordovaLib-cordova.gradle.include.1=cordova-plugin-crosswalk-webview/mobile-xwalk.gradle\ No newline at end of file+android.library.reference.2=appdiff --git a/cordova/platforms/android/res/drawable-land-hdpi/screen.png b/cordova/platforms/android/res/drawable-land-hdpi/screen.pngdeleted file mode 100644index a61e2b1a3..000000000Binary files a/cordova/platforms/android/res/drawable-land-hdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-land-ldpi/screen.png b/cordova/platforms/android/res/drawable-land-ldpi/screen.pngdeleted file mode 100644index f3934cdcc..000000000Binary files a/cordova/platforms/android/res/drawable-land-ldpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-land-mdpi/screen.png b/cordova/platforms/android/res/drawable-land-mdpi/screen.pngdeleted file mode 100644index a1b697c53..000000000Binary files a/cordova/platforms/android/res/drawable-land-mdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-land-xhdpi/screen.png b/cordova/platforms/android/res/drawable-land-xhdpi/screen.pngdeleted file mode 100644index 79f2f0945..000000000Binary files a/cordova/platforms/android/res/drawable-land-xhdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-land-xxhdpi/screen.png b/cordova/platforms/android/res/drawable-land-xxhdpi/screen.pngdeleted file mode 100644index 2f5683808..000000000Binary files a/cordova/platforms/android/res/drawable-land-xxhdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-land-xxxhdpi/screen.png b/cordova/platforms/android/res/drawable-land-xxxhdpi/screen.pngdeleted file mode 100644index ff6c13c28..000000000Binary files a/cordova/platforms/android/res/drawable-land-xxxhdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-port-hdpi/screen.png b/cordova/platforms/android/res/drawable-port-hdpi/screen.pngdeleted file mode 100644index 5d6a28a82..000000000Binary files a/cordova/platforms/android/res/drawable-port-hdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-port-ldpi/screen.png b/cordova/platforms/android/res/drawable-port-ldpi/screen.pngdeleted file mode 100644index 65ad163ab..000000000Binary files a/cordova/platforms/android/res/drawable-port-ldpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-port-mdpi/screen.png b/cordova/platforms/android/res/drawable-port-mdpi/screen.pngdeleted file mode 100644index ea1569359..000000000Binary files a/cordova/platforms/android/res/drawable-port-mdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-port-xhdpi/screen.png b/cordova/platforms/android/res/drawable-port-xhdpi/screen.pngdeleted file mode 100644index c2e804217..000000000Binary files a/cordova/platforms/android/res/drawable-port-xhdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-port-xxhdpi/screen.png b/cordova/platforms/android/res/drawable-port-xxhdpi/screen.pngdeleted file mode 100644index 9c7df083d..000000000Binary files a/cordova/platforms/android/res/drawable-port-xxhdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/drawable-port-xxxhdpi/screen.png b/cordova/platforms/android/res/drawable-port-xxxhdpi/screen.pngdeleted file mode 100644index 68c799896..000000000Binary files a/cordova/platforms/android/res/drawable-port-xxxhdpi/screen.png and /dev/null differdiff --git a/cordova/platforms/android/res/mipmap-hdpi/icon.png b/cordova/platforms/android/res/mipmap-hdpi/icon.pngdeleted file mode 100644index 4d2763448..000000000Binary files a/cordova/platforms/android/res/mipmap-hdpi/icon.png and /dev/null differdiff --git a/cordova/platforms/android/res/mipmap-ldpi/icon.png b/cordova/platforms/android/res/mipmap-ldpi/icon.pngdeleted file mode 100644index cd5032a4f..000000000Binary files a/cordova/platforms/android/res/mipmap-ldpi/icon.png and /dev/null differdiff --git a/cordova/platforms/android/res/mipmap-mdpi/icon.png b/cordova/platforms/android/res/mipmap-mdpi/icon.pngdeleted file mode 100644index e79c6062c..000000000Binary files a/cordova/platforms/android/res/mipmap-mdpi/icon.png and /dev/null differdiff --git a/cordova/platforms/android/res/mipmap-xhdpi/icon.png b/cordova/platforms/android/res/mipmap-xhdpi/icon.pngdeleted file mode 100644index ec7ffbfbd..000000000Binary files a/cordova/platforms/android/res/mipmap-xhdpi/icon.png and /dev/null differdiff --git a/cordova/platforms/android/res/mipmap-xxhdpi/icon.png b/cordova/platforms/android/res/mipmap-xxhdpi/icon.pngdeleted file mode 100644index 38c2bf5e1..000000000Binary files a/cordova/platforms/android/res/mipmap-xxhdpi/icon.png and /dev/null differdiff --git a/cordova/platforms/android/res/mipmap-xxxhdpi/icon.png b/cordova/platforms/android/res/mipmap-xxxhdpi/icon.pngdeleted file mode 100644index 53e57538d..000000000Binary files a/cordova/platforms/android/res/mipmap-xxxhdpi/icon.png and /dev/null differdiff --git a/cordova/platforms/android/settings.gradle b/cordova/platforms/android/settings.gradleindex 8a39471fc..dfb85579d 100644--- a/cordova/platforms/android/settings.gradle+++ b/cordova/platforms/android/settings.gradle@@ -1,3 +1,4 @@// GENERATED FILE - DO NOT EDITinclude ":"include ":CordovaLib"+include ":app"diff --git a/cordova/platforms/android/src/org/apache/cordova/whitelist/WhitelistPlugin.java b/cordova/platforms/android/src/org/apache/cordova/whitelist/WhitelistPlugin.javadeleted file mode 100644index 365678864..000000000--- a/cordova/platforms/android/src/org/apache/cordova/whitelist/WhitelistPlugin.java+++ /dev/null@@ -1,161 +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.-*/--package org.apache.cordova.whitelist;--import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.ConfigXmlParser;-import org.apache.cordova.LOG;-import org.apache.cordova.Whitelist;-import org.xmlpull.v1.XmlPullParser;--import android.content.Context;--public class WhitelistPlugin extends CordovaPlugin {- private static final String LOG_TAG = "WhitelistPlugin";- private Whitelist allowedNavigations;- private Whitelist allowedIntents;- private Whitelist allowedRequests;-- // Used when instantiated via reflection by PluginManager- public WhitelistPlugin() {- }- // These can be used by embedders to allow Java-configuration of whitelists.- public WhitelistPlugin(Context context) {- this(new Whitelist(), new Whitelist(), null);- new CustomConfigXmlParser().parse(context);- }- public WhitelistPlugin(XmlPullParser xmlParser) {- this(new Whitelist(), new Whitelist(), null);- new CustomConfigXmlParser().parse(xmlParser);- }- public WhitelistPlugin(Whitelist allowedNavigations, Whitelist allowedIntents, Whitelist allowedRequests) {- if (allowedRequests == null) {- allowedRequests = new Whitelist();- allowedRequests.addWhiteListEntry("file:///*", false);- allowedRequests.addWhiteListEntry("data:*", false);- }- this.allowedNavigations = allowedNavigations;- this.allowedIntents = allowedIntents;- this.allowedRequests = allowedRequests;- }- @Override- public void pluginInitialize() {- if (allowedNavigations == null) {- allowedNavigations = new Whitelist();- allowedIntents = new Whitelist();- allowedRequests = new Whitelist();- new CustomConfigXmlParser().parse(webView.getContext());- }- }-- private class CustomConfigXmlParser extends ConfigXmlParser {- @Override- public void handleStartTag(XmlPullParser xml) {- String strNode = xml.getName();- if (strNode.equals("content")) {- String startPage = xml.getAttributeValue(null, "src");- allowedNavigations.addWhiteListEntry(startPage, false);- } else if (strNode.equals("allow-navigation")) {- String origin = xml.getAttributeValue(null, "href");- if ("*".equals(origin)) {- allowedNavigations.addWhiteListEntry("http://*/*", false);- allowedNavigations.addWhiteListEntry("https://*/*", false);- allowedNavigations.addWhiteListEntry("data:*", false);- } else {- allowedNavigations.addWhiteListEntry(origin, false);- }- } else if (strNode.equals("allow-intent")) {- String origin = xml.getAttributeValue(null, "href");- allowedIntents.addWhiteListEntry(origin, false);- } else if (strNode.equals("access")) {- String origin = xml.getAttributeValue(null, "origin");- String subdomains = xml.getAttributeValue(null, "subdomains");- boolean external = (xml.getAttributeValue(null, "launch-external") != null);- if (origin != null) {- if (external) {- LOG.w(LOG_TAG, "Found <access launch-external> within config.xml. Please use <allow-intent> instead.");- allowedIntents.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));- } else {- if ("*".equals(origin)) {- allowedRequests.addWhiteListEntry("http://*/*", false);- allowedRequests.addWhiteListEntry("https://*/*", false);- } else {- allowedRequests.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));- }- }- }- }- }- @Override- public void handleEndTag(XmlPullParser xml) {- }- }-- @Override- public Boolean shouldAllowNavigation(String url) {- if (allowedNavigations.isUrlWhiteListed(url)) {- return true;- }- return null; // Default policy- }-- @Override- public Boolean shouldAllowRequest(String url) {- if (Boolean.TRUE == shouldAllowNavigation(url)) {- return true;- }- if (allowedRequests.isUrlWhiteListed(url)) {- return true;- }- return null; // Default policy- }-- @Override- public Boolean shouldOpenExternalUrl(String url) {- if (allowedIntents.isUrlWhiteListed(url)) {- return true;- }- return null; // Default policy- }-- public Whitelist getAllowedNavigations() {- return allowedNavigations;- }-- public void setAllowedNavigations(Whitelist allowedNavigations) {- this.allowedNavigations = allowedNavigations;- }-- public Whitelist getAllowedIntents() {- return allowedIntents;- }-- public void setAllowedIntents(Whitelist allowedIntents) {- this.allowedIntents = allowedIntents;- }-- public Whitelist getAllowedRequests() {- return allowedRequests;- }-- public void setAllowedRequests(Whitelist allowedRequests) {- this.allowedRequests = allowedRequests;- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaClientCertRequest.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaClientCertRequest.javadeleted file mode 100644index ea1b95f22..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaClientCertRequest.java+++ /dev/null@@ -1,90 +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.-*/-package org.crosswalk.engine;--import org.apache.cordova.ICordovaClientCertRequest;-import org.xwalk.core.ClientCertRequest;--import java.security.cert.X509Certificate;-import java.security.Principal;-import java.security.PrivateKey;-import java.util.Arrays;--public class XWalkCordovaClientCertRequest implements ICordovaClientCertRequest {-- private final ClientCertRequest request;-- public XWalkCordovaClientCertRequest(ClientCertRequest request) {- this.request = request;- }-- /**- * Cancel this request- */- public void cancel() {- request.cancel();- }-- /*- * Returns the host name of the server requesting the certificate.- */- public String getHost() {- return request.getHost();- }-- /*- * Returns the acceptable types of asymmetric keys (can be null).- */- public String[] getKeyTypes() {- return request.getKeyTypes();- }-- /*- * Returns the port number of the server requesting the certificate.- */- public int getPort() {- return request.getPort();- }-- /*- * Returns the acceptable certificate issuers for the certificate matching the private- * key (can be null).- */- public Principal[] getPrincipals() {- return request.getPrincipals();- }-- /*- * Ignore the request for now. Do not remember user's choice.- */- public void ignore() {- request.ignore();- }-- /*- * Proceed with the specified private key and client certificate chain. Remember the user's- * positive choice and use it for future requests.- *- * @param privateKey The privateKey- * @param chain The certificate chain- */- public void proceed(PrivateKey privateKey, X509Certificate[] chain) {- request.proceed(privateKey, Arrays.asList(chain));- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaCookieManager.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaCookieManager.javadeleted file mode 100644index ddf1127e4..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaCookieManager.java+++ /dev/null@@ -1,53 +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.-*/-package org.crosswalk.engine;--import org.apache.cordova.ICordovaCookieManager;-import org.xwalk.core.XWalkCookieManager;--class XWalkCordovaCookieManager implements ICordovaCookieManager {-- protected XWalkCookieManager cookieManager = null;-- public XWalkCordovaCookieManager() {- cookieManager = new XWalkCookieManager();- }-- public void setCookiesEnabled(boolean accept) {- cookieManager.setAcceptCookie(accept);- }-- public void setCookie(final String url, final String value) {- cookieManager.setCookie(url, value);- }-- public String getCookie(final String url) {- return cookieManager.getCookie(url);- }-- public void clearCookies() {- cookieManager.removeAllCookie();- }-- public void flush() {- cookieManager.flushCookieStore();- }-};--diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaHttpAuthHandler.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaHttpAuthHandler.javadeleted file mode 100644index c1e9dd4f7..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaHttpAuthHandler.java+++ /dev/null@@ -1,52 +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.-*/-package org.crosswalk.engine;--import org.apache.cordova.ICordovaHttpAuthHandler;-import org.xwalk.core.XWalkHttpAuthHandler;--/**- * Specifies interface for HTTP auth handler object which is used to handle auth requests and- * specifying user credentials.- */-public class XWalkCordovaHttpAuthHandler implements ICordovaHttpAuthHandler {-- private final XWalkHttpAuthHandler handler;-- public XWalkCordovaHttpAuthHandler(XWalkHttpAuthHandler handler) {- this.handler = handler;- }-- /**- * Instructs the XWalkView to cancel the authentication request.- */- public void cancel() {- handler.cancel();- }-- /**- * Instructs the XWalkView to proceed with the authentication with the given credentials.- *- * @param username- * @param password- */- public void proceed(String username, String password) {- handler.proceed(username, password);- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaResourceClient.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaResourceClient.javadeleted file mode 100644index e37d780bb..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaResourceClient.java+++ /dev/null@@ -1,159 +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.-*/-package org.crosswalk.engine;--import android.content.pm.ApplicationInfo;-import android.content.pm.PackageManager;-import android.net.Uri;-import android.net.http.SslError;-import android.webkit.ValueCallback;-import android.webkit.WebResourceResponse;--import org.apache.cordova.CordovaResourceApi;-import org.apache.cordova.CordovaResourceApi.OpenForReadResult;-import org.apache.cordova.LOG;-import org.apache.cordova.PluginManager;-import org.xwalk.core.ClientCertRequest;-import org.xwalk.core.XWalkHttpAuthHandler;-import org.xwalk.core.XWalkResourceClient;-import org.xwalk.core.XWalkView;--import java.io.FileNotFoundException;-import java.io.IOException;--public class XWalkCordovaResourceClient extends XWalkResourceClient {-- private static final String TAG = "XWalkCordovaResourceClient";- protected XWalkWebViewEngine parentEngine;-- public XWalkCordovaResourceClient(XWalkWebViewEngine parentEngine) {- super(parentEngine.webView);- this.parentEngine = parentEngine;- }-- /**- * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).- * The errorCode parameter corresponds to one of the ERROR_* constants.- *- * @param view The WebView that is initiating the callback.- * @param errorCode The error code corresponding to an ERROR_* value.- * @param description A String describing the error.- * @param failingUrl The url that failed to load.- */- @Override- public void onReceivedLoadError(XWalkView view, int errorCode, String description,- String failingUrl) {- LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);-- parentEngine.client.onReceivedError(errorCode, description, failingUrl);- }-- @Override- public WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) {- try {- // Check the against the white-list.- if (!parentEngine.pluginManager.shouldAllowRequest(url)) {- LOG.w(TAG, "URL blocked by whitelist: " + url);- // Results in a 404.- return new WebResourceResponse("text/plain", "UTF-8", null);- }-- CordovaResourceApi resourceApi = parentEngine.resourceApi;- Uri origUri = Uri.parse(url);- // Allow plugins to intercept WebView requests.- Uri remappedUri = resourceApi.remapUri(origUri);-- if (!origUri.equals(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) {- if (!(e instanceof FileNotFoundException)) {- LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);- }- // Results in a 404.- return new WebResourceResponse("text/plain", "UTF-8", null);- }- }-- @Override- public boolean shouldOverrideUrlLoading(XWalkView view, String url) {- return parentEngine.client.onNavigationAttempt(url);- }--- /**- * Notify the host application that an SSL error occurred while loading a- * resource. The host application must call either callback.onReceiveValue(true)- * or callback.onReceiveValue(false). Note that the decision may be- * retained for use in response to future SSL errors. The default behavior- * is to pop up a dialog.- */- @Override- public void onReceivedSslError(XWalkView view, ValueCallback<Boolean> callback, SslError error) {- final String packageName = parentEngine.cordova.getActivity().getPackageName();- final PackageManager pm = parentEngine.cordova.getActivity().getPackageManager();-- ApplicationInfo appInfo;- try {- appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);- if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {- // debug = true- callback.onReceiveValue(true);- } else {- // debug = false- callback.onReceiveValue(false);- }- } catch (PackageManager.NameNotFoundException e) {- // When it doubt, lock it out!- callback.onReceiveValue(false);- }- }-- @Override- public void onReceivedHttpAuthRequest(XWalkView view, XWalkHttpAuthHandler handler,- String host, String realm) {- // Check if there is some plugin which can resolve this auth challenge- PluginManager pluginManager = parentEngine.pluginManager;- if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(- parentEngine.parentWebView,- new XWalkCordovaHttpAuthHandler(handler), host, realm)) {- parentEngine.client.clearLoadTimeoutTimer();- return;- }-- // By default handle 401 like we'd normally do!- super.onReceivedHttpAuthRequest(view, handler, host, realm);- }-- @Override- public void onReceivedClientCertRequest(XWalkView view, ClientCertRequest request) {- // Check if there is some plugin which can resolve this certificate request- PluginManager pluginManager = parentEngine.pluginManager;- if (pluginManager != null && pluginManager.onReceivedClientCertRequest(- parentEngine.parentWebView, new XWalkCordovaClientCertRequest(request))) {- parentEngine.client.clearLoadTimeoutTimer();- return;- }-- super.onReceivedClientCertRequest(view, request);- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaUiClient.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaUiClient.javadeleted file mode 100644index e996f8328..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaUiClient.java+++ /dev/null@@ -1,208 +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.-*/-package org.crosswalk.engine;--import android.app.Activity;-import android.content.ActivityNotFoundException;-import android.content.Intent;-import android.net.Uri;-import android.util.Log;-import android.webkit.ValueCallback;--import org.apache.cordova.CordovaDialogsHelper;-import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.LOG;-import org.xwalk.core.XWalkJavascriptResult;-import org.xwalk.core.XWalkUIClient;-import org.xwalk.core.XWalkView;--import org.crosswalk.engine.XWalkWebViewEngine.PermissionRequestListener;--public class XWalkCordovaUiClient extends XWalkUIClient {- private static final String TAG = "XWalkCordovaUiClient";- protected final CordovaDialogsHelper dialogsHelper;- protected final XWalkWebViewEngine parentEngine;-- private XWalkFileChooser mFileChooser;- private CordovaPlugin mFileChooserResultPlugin;-- private static final int FILECHOOSER_RESULTCODE = 5173;-- public XWalkCordovaUiClient(XWalkWebViewEngine parentEngine) {- super(parentEngine.webView);- this.parentEngine = parentEngine;- dialogsHelper = new CordovaDialogsHelper(parentEngine.webView.getContext());- }-- @Override- public boolean onJavascriptModalDialog(XWalkView view, JavascriptMessageType type, String url,- String message, String defaultValue, XWalkJavascriptResult result) {- switch (type) {- case JAVASCRIPT_ALERT:- return onJsAlert(view, url, message, result);- case JAVASCRIPT_CONFIRM:- return onJsConfirm(view, url, message, result);- case JAVASCRIPT_PROMPT:- return onJsPrompt(view, url, message, defaultValue, result);- case JAVASCRIPT_BEFOREUNLOAD:- // Reuse onJsConfirm to show the dialog.- return onJsConfirm(view, url, message, result);- default:- break;- }- assert (false);- return false;- }-- /**- * Tell the client to display a javascript alert dialog.- */- public boolean onJsAlert(XWalkView view, String url, String message,- final XWalkJavascriptResult result) {- dialogsHelper.showAlert(message, new CordovaDialogsHelper.Result() {- @Override- public void gotResult(boolean success, String value) {- if (success) {- result.confirm();- } else {- result.cancel();- }- }- });- return true;- }-- /**- * Tell the client to display a confirm dialog to the user.- */- public boolean onJsConfirm(XWalkView view, String url, String message,- final XWalkJavascriptResult result) {- dialogsHelper.showConfirm(message, new CordovaDialogsHelper.Result() {- @Override- public void gotResult(boolean success, String value) {- if (success) {- result.confirm();- } else {- result.cancel();- }- }- });- return true;- }-- /**- * Tell the client to display a prompt dialog to the user.- * If the client returns true, WebView will assume that the client will- * handle the prompt dialog and call the appropriate JsPromptResult method.- * <p/>- * Since we are hacking prompts for our own purposes, we should not be using them for- * this purpose, perhaps we should hack console.log to do this instead!- */- public boolean onJsPrompt(XWalkView view, String origin, String message, String defaultValue,- final XWalkJavascriptResult result) {- // Unlike the @JavascriptInterface bridge, this method is always called on the UI thread.- String handledRet = parentEngine.bridge.promptOnJsPrompt(origin, message, defaultValue);- if (handledRet != null) {- result.confirmWithResult(handledRet);- } else {- dialogsHelper.showPrompt(message, defaultValue, new CordovaDialogsHelper.Result() {- @Override- public void gotResult(boolean success, String value) {- if (success) {- result.confirmWithResult(value);- } else {- result.cancel();- }- }- });-- }- return true;- }-- /**- * Notify the host application that a page has started loading.- * This method is called once for each main frame load so a page with iframes or framesets will call onPageLoadStarted- * one time for the main frame. This also means that onPageLoadStarted will not be called when the contents of an- * embedded frame changes, i.e. clicking a link whose target is an iframe.- *- * @param view The webView initiating the callback.- * @param url The url of the page.- */- @Override- public void onPageLoadStarted(XWalkView view, String url) {- LOG.d(TAG, "onPageLoadStarted(" + url + ")");- if (view.getUrl() != null) {- // Flush stale messages.- parentEngine.client.onPageStarted(url);- parentEngine.bridge.reset();- }- }-- /**- * Notify the host application that a page has stopped loading.- * This method is called only for main frame. When onPageLoadStopped() is called, the rendering picture may not be updated yet.- *- * @param view The webView initiating the callback.- * @param url The url of the page.- * @param status The load status of the webView, can be FINISHED, CANCELLED or FAILED.- */- @Override- public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) {- LOG.d(TAG, "onPageLoadStopped(" + url + ")");- if (status == LoadStatus.FINISHED) {- parentEngine.client.onPageFinishedLoading(url);- } else if (status == LoadStatus.FAILED) {- // TODO: Should this call parentEngine.client.onReceivedError()?- // Right now we call this from ResourceClient, but maybe that is just for sub-resources?- }- }-- // File Chooser- @Override- public void openFileChooser(XWalkView view, final ValueCallback<Uri> uploadFile,- final String acceptType, final String capture) {- if (mFileChooser == null) {- mFileChooser = new XWalkFileChooser(parentEngine.cordova.getActivity());- mFileChooserResultPlugin = new CordovaPlugin() {- @Override- public void onActivityResult(int requestCode, int resultCode, Intent intent) {- mFileChooser.onActivityResult(requestCode, resultCode, intent);- }- };- }-- PermissionRequestListener listener = new PermissionRequestListener() {- @Override- public void onRequestPermissionResult(int requestCode, String[] permissions,- int[] grantResults) {- for (int i = 0; i < permissions.length; ++i) {- Log.d(TAG, "permission:" + permissions[i] + " result:" + grantResults[i]);- }- parentEngine.cordova.setActivityResultCallback(mFileChooserResultPlugin);- mFileChooser.showFileChooser(uploadFile, acceptType, capture);- }- };-- if (!parentEngine.requestPermissionsForFileChooser(listener)) {- parentEngine.cordova.setActivityResultCallback(mFileChooserResultPlugin);- mFileChooser.showFileChooser(uploadFile, acceptType, capture);- }- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaView.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaView.javadeleted file mode 100644index bc0353c83..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkCordovaView.java+++ /dev/null@@ -1,135 +0,0 @@-package org.crosswalk.engine;--import org.apache.cordova.CordovaPreferences;-import org.xwalk.core.XWalkPreferences;-import org.xwalk.core.XWalkResourceClient;-import org.xwalk.core.XWalkUIClient;-import org.xwalk.core.XWalkView;--import android.content.Context;-import android.content.Intent;-import android.content.pm.ApplicationInfo;-import android.content.pm.PackageManager;-import android.os.Bundle;-import android.util.AttributeSet;-import android.util.Log;-import android.view.KeyEvent;--import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.CordovaWebView;-import org.apache.cordova.CordovaWebViewEngine;--public class XWalkCordovaView extends XWalkView implements CordovaWebViewEngine.EngineView {-- public static final String TAG = "XWalkCordovaView";-- protected XWalkCordovaResourceClient resourceClient;- protected XWalkCordovaUiClient uiClient;- protected XWalkWebViewEngine parentEngine;-- private static boolean hasSetStaticPref;- // This needs to run before the super's constructor.- private static Context setGlobalPrefs(Context context, CordovaPreferences preferences) {- if (!hasSetStaticPref) {- hasSetStaticPref = true;- ApplicationInfo ai = null;- try {- ai = context.getPackageManager().getApplicationInfo(context.getApplicationContext().getPackageName(), PackageManager.GET_META_DATA);- } catch (PackageManager.NameNotFoundException e) {- throw new RuntimeException(e);- }- boolean prefAnimatable = preferences == null ? false : preferences.getBoolean("CrosswalkAnimatable", false);- boolean manifestAnimatable = ai.metaData == null ? false : ai.metaData.getBoolean("CrosswalkAnimatable");- // Selects between a TextureView (obeys framework transforms applied to view) or a SurfaceView (better performance).- XWalkPreferences.setValue(XWalkPreferences.ANIMATABLE_XWALK_VIEW, prefAnimatable || manifestAnimatable);- if ((ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {- XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);- }- XWalkPreferences.setValue(XWalkPreferences.JAVASCRIPT_CAN_OPEN_WINDOW, true);- XWalkPreferences.setValue(XWalkPreferences.ALLOW_UNIVERSAL_ACCESS_FROM_FILE, true);- }- return context;- }-- public XWalkCordovaView(Context context, CordovaPreferences preferences) {- super(setGlobalPrefs(context, preferences), (AttributeSet)null);- }-- public XWalkCordovaView(Context context, AttributeSet attrs) {- super(setGlobalPrefs(context, null), attrs);- }-- void init(XWalkWebViewEngine parentEngine) {- this.parentEngine = parentEngine;- if (resourceClient == null) {- setResourceClient(new XWalkCordovaResourceClient(parentEngine));- }- if (uiClient == null) {- setUIClient(new XWalkCordovaUiClient(parentEngine));- }- }-- @Override- public void setResourceClient(XWalkResourceClient client) {- // XWalk calls this method from its constructor.- if (client instanceof XWalkCordovaResourceClient) {- this.resourceClient = (XWalkCordovaResourceClient)client;- }- super.setResourceClient(client);- }-- @Override- public void setUIClient(XWalkUIClient client) {- // XWalk calls this method from its constructor.- if (client instanceof XWalkCordovaUiClient) {- this.uiClient = (XWalkCordovaUiClient)client;- }- super.setUIClient(client);- }-- // Call CordovaInterface to start activity for result to make sure- // onActivityResult() callback will be triggered from CordovaActivity correctly.- // Todo(leonhsl) How to handle |options|?- @Override- public void startActivityForResult(Intent intent, int requestCode, Bundle options) {- parentEngine.cordova.startActivityForResult(new CordovaPlugin() {- @Override- public void onActivityResult(int requestCode, int resultCode, Intent intent) {- // Route to XWalkView.- Log.i(TAG, "Route onActivityResult() to XWalkView");- XWalkCordovaView.this.onActivityResult(requestCode, resultCode, intent);- }- }, intent, requestCode);- }-- @Override- public boolean dispatchKeyEvent(KeyEvent event) {- Boolean ret = parentEngine.client.onDispatchKeyEvent(event);- if (ret != null) {- return ret.booleanValue();- }- return super.dispatchKeyEvent(event);- }-- @Override- public void pauseTimers() {- // This is called by XWalkViewInternal.onActivityStateChange().- // We don't want them paused by default though.- }-- public void pauseTimersForReal() {- super.pauseTimers();- }-- @Override- public CordovaWebView getCordovaWebView() {- return parentEngine == null ? null : parentEngine.getCordovaWebView();- }-- @Override- public void setBackgroundColor(int color) {- if (parentEngine != null && parentEngine.isXWalkReady()) {- super.setBackgroundColor(color);- }- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkExposedJsApi.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkExposedJsApi.javadeleted file mode 100644index 257152162..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkExposedJsApi.java+++ /dev/null@@ -1,52 +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.-*/-package org.crosswalk.engine;--import android.os.Looper;--import org.apache.cordova.CordovaBridge;-import org.apache.cordova.ExposedJsApi;-import org.json.JSONException;-import org.xwalk.core.JavascriptInterface;--class XWalkExposedJsApi implements ExposedJsApi {- private final CordovaBridge bridge;-- XWalkExposedJsApi(CordovaBridge bridge) {- this.bridge = bridge;- }-- @JavascriptInterface- public String exec(int bridgeSecret, String service, String action, String callbackId, String arguments) throws JSONException, IllegalAccessException {- if (Looper.myLooper() == null) {- Looper.prepare();- }- return bridge.jsExec(bridgeSecret, service, action, callbackId, arguments);- }-- @JavascriptInterface- public void setNativeToJsBridgeMode(int bridgeSecret, int value) throws IllegalAccessException {- bridge.jsSetNativeToJsBridgeMode(bridgeSecret, value);- }-- @JavascriptInterface- public String retrieveJsMessages(int bridgeSecret, boolean fromOnlineEvent) throws IllegalAccessException {- return bridge.jsRetrieveJsMessages(bridgeSecret, fromOnlineEvent);- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkFileChooser.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkFileChooser.javadeleted file mode 100644index a70a8bf11..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkFileChooser.java+++ /dev/null@@ -1,229 +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.-*/---package org.crosswalk.engine;--import android.app.Activity;-import android.content.Intent;-import android.content.pm.PackageInfo;-import android.content.pm.PackageManager;-import android.content.pm.PackageManager.NameNotFoundException;-import android.Manifest;-import android.net.Uri;-import android.os.Environment;-import android.provider.MediaStore;-import android.util.Log;-import android.webkit.ValueCallback;--import java.io.File;-import java.io.IOException;-import java.text.SimpleDateFormat;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.Date;--public class XWalkFileChooser {- private static final String IMAGE_TYPE = "image/";- private static final String VIDEO_TYPE = "video/";- private static final String AUDIO_TYPE = "audio/";- private static final String ALL_IMAGE_TYPES = IMAGE_TYPE + "*";- private static final String ALL_VIDEO_TYPES = VIDEO_TYPE + "*";- private static final String ALL_AUDIO_TYPES = AUDIO_TYPE + "*";- private static final String ANY_TYPES = "*/*";- private static final String SPLIT_EXPRESSION = ",";- private static final String PATH_PREFIX = "file:";- private static final String WRITE_EXTERNAL_STORAGE= "android.permission.WRITE_EXTERNAL_STORAGE";-- public static final int INPUT_FILE_REQUEST_CODE = 1;-- private static final String TAG = "XWalkFileChooser";-- private Activity mActivity;- private ValueCallback<Uri> mFilePathCallback;- private String mCameraPhotoPath;-- public XWalkFileChooser(Activity activity) {- mActivity = activity;- }-- public boolean showFileChooser(ValueCallback<Uri> uploadFile, String acceptType,- String capture) {- mFilePathCallback = uploadFile;-- Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);- if (takePictureIntent.resolveActivity(mActivity.getPackageManager()) != null) {- // Create the File where the photo should go- File photoFile = createImageFile();- // Continue only if the File was successfully created- if (photoFile != null) {- mCameraPhotoPath = PATH_PREFIX + photoFile.getAbsolutePath();- takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);- takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));- } else {- takePictureIntent = null;- }- }-- Intent camcorder = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);- Intent soundRecorder = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);- Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);- contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);- ArrayList<Intent> extraIntents = new ArrayList<Intent>();-- // A single mime type.- if (!(acceptType.contains(SPLIT_EXPRESSION) || acceptType.contains(ANY_TYPES))) {- if (capture.equals("true")) {- if (acceptType.startsWith(IMAGE_TYPE)) {- if (takePictureIntent != null) {- mActivity.startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);- Log.d(TAG, "Started taking picture");- return true;- }- } else if (acceptType.startsWith(VIDEO_TYPE)) {- mActivity.startActivityForResult(camcorder, INPUT_FILE_REQUEST_CODE);- Log.d(TAG, "Started camcorder");- return true;- } else if (acceptType.startsWith(AUDIO_TYPE)) {- mActivity.startActivityForResult(soundRecorder, INPUT_FILE_REQUEST_CODE);- Log.d(TAG, "Started sound recorder");- return true;- }- } else {- if (acceptType.startsWith(IMAGE_TYPE)) {- if (takePictureIntent != null) {- extraIntents.add(takePictureIntent);- }- contentSelectionIntent.setType(ALL_IMAGE_TYPES);- } else if (acceptType.startsWith(VIDEO_TYPE)) {- extraIntents.add(camcorder);- contentSelectionIntent.setType(ALL_VIDEO_TYPES);- } else if (acceptType.startsWith(AUDIO_TYPE)) {- extraIntents.add(soundRecorder);- contentSelectionIntent.setType(ALL_AUDIO_TYPES);- }- }- }-- // Couldn't resolve an accept type.- if (extraIntents.isEmpty() && canWriteExternalStorage()) {- if (takePictureIntent != null) {- extraIntents.add(takePictureIntent);- }- extraIntents.add(camcorder);- extraIntents.add(soundRecorder);- contentSelectionIntent.setType(ANY_TYPES);- }-- Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);- chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);- if (!extraIntents.isEmpty()) {- chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,- extraIntents.toArray(new Intent[] { }));- }- mActivity.startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);- Log.d(TAG, "Started chooser");- return true;- }-- public void onActivityResult(int requestCode, int resultCode, Intent data) {- if(requestCode == INPUT_FILE_REQUEST_CODE && mFilePathCallback != null) {- Log.d(TAG, "Activity result: " + resultCode);- Uri results = null;-- // Check that the response is a good one- if(Activity.RESULT_OK == resultCode) {- // In Android M, camera results return an empty Intent rather than null.- if(data == null || (data.getAction() == null && data.getData() == null)) {- // If there is not data, then we may have taken a photo- if(mCameraPhotoPath != null) {- results = Uri.parse(mCameraPhotoPath);- }- } else {- String dataString = data.getDataString();- if (dataString != null) {- results = Uri.parse(dataString);- }- deleteImageFile();- }- } else if (Activity.RESULT_CANCELED == resultCode) {- deleteImageFile();- }-- if (results != null) {- Log.d(TAG, "Received file: " + results.toString());- }- mFilePathCallback.onReceiveValue(results);- mFilePathCallback = null;- }- }-- private boolean canWriteExternalStorage() {- try {- PackageManager packageManager = mActivity.getPackageManager();- PackageInfo packageInfo = packageManager.getPackageInfo(- mActivity.getPackageName(), PackageManager.GET_PERMISSIONS);- return Arrays.asList(packageInfo.requestedPermissions).contains(WRITE_EXTERNAL_STORAGE);- } catch (NameNotFoundException e) {- return false;- } catch (NullPointerException e) {- return false;- }- }-- private File createImageFile() {- // FIXME: If the external storage state is not "MEDIA_MOUNTED", we need to get- // other volume paths by "getVolumePaths()" when it was exposed.- String state = Environment.getExternalStorageState();- if (!state.equals(Environment.MEDIA_MOUNTED)) {- Log.e(TAG, "External storage is not mounted.");- return null;- }-- // Create an image file name- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());- String imageFileName = "JPEG_" + timeStamp + "_";- File storageDir = Environment.getExternalStoragePublicDirectory(- Environment.DIRECTORY_PICTURES);- if (!storageDir.exists()) {- storageDir.mkdirs();- }-- try {- File file = File.createTempFile(imageFileName, ".jpg", storageDir);- Log.d(TAG, "Created image file: " + file.getAbsolutePath());- return file;- } catch (IOException e) {- // Error occurred while creating the File- Log.e(TAG, "Unable to create Image File, " +- "please make sure permission 'WRITE_EXTERNAL_STORAGE' was added.");- return null;- }- }-- private boolean deleteImageFile() {- if (mCameraPhotoPath == null || !mCameraPhotoPath.contains(PATH_PREFIX)) {- return false;- }- String filePath = mCameraPhotoPath.split(PATH_PREFIX)[1];- boolean result = new File(filePath).delete();- Log.d(TAG, "Delete image file: " + filePath + " result: " + result);- return result;- }-}diff --git a/cordova/platforms/android/src/org/crosswalk/engine/XWalkWebViewEngine.java b/cordova/platforms/android/src/org/crosswalk/engine/XWalkWebViewEngine.javadeleted file mode 100644index d39a1273e..000000000--- a/cordova/platforms/android/src/org/crosswalk/engine/XWalkWebViewEngine.java+++ /dev/null@@ -1,366 +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.-*/--package org.crosswalk.engine;--import android.app.Activity;-import android.content.Context;-import android.content.Intent;-import android.content.pm.PackageInfo;-import android.content.pm.PackageManager;-import android.content.pm.PackageManager.NameNotFoundException;-import android.content.res.AssetManager;-import android.graphics.Bitmap;-import android.graphics.Color;-import android.Manifest;-import android.util.Log;-import android.view.View;-import android.webkit.ValueCallback;--import java.io.File;-import java.io.IOException;-import java.util.ArrayList;--import org.apache.cordova.CordovaBridge;-import org.apache.cordova.CordovaInterface;-import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.CordovaPreferences;-import org.apache.cordova.CordovaResourceApi;-import org.apache.cordova.CordovaWebView;-import org.apache.cordova.CordovaWebViewEngine;-import org.apache.cordova.ICordovaCookieManager;-import org.apache.cordova.NativeToJsMessageQueue;-import org.apache.cordova.PluginEntry;-import org.apache.cordova.PluginManager;-import org.xwalk.core.XWalkActivityDelegate;-import org.xwalk.core.XWalkNavigationHistory;-import org.xwalk.core.XWalkView;-import org.xwalk.core.XWalkGetBitmapCallback;--/**- * Glue class between CordovaWebView (main Cordova logic) and XWalkCordovaView (the actual View).- */-public class XWalkWebViewEngine implements CordovaWebViewEngine {-- public static final String TAG = "XWalkWebViewEngine";- public static final String XWALK_USER_AGENT = "xwalkUserAgent";- public static final String XWALK_Z_ORDER_ON_TOP = "xwalkZOrderOnTop";-- private static final String XWALK_EXTENSIONS_FOLDER = "xwalk-extensions";-- private static final int PERMISSION_REQUEST_CODE = 100;-- protected final XWalkCordovaView webView;- protected XWalkCordovaCookieManager cookieManager;- protected CordovaBridge bridge;- protected CordovaWebViewEngine.Client client;- protected CordovaWebView parentWebView;- protected CordovaInterface cordova;- protected PluginManager pluginManager;- protected CordovaResourceApi resourceApi;- protected NativeToJsMessageQueue nativeToJsMessageQueue;- protected XWalkActivityDelegate activityDelegate;- protected String startUrl;- protected CordovaPreferences preferences;-- /** Used when created via reflection. */- public XWalkWebViewEngine(Context context, CordovaPreferences preferences) {- this.preferences = preferences;- Runnable cancelCommand = new Runnable() {- @Override- public void run() {- cordova.getActivity().finish();- }- };- Runnable completeCommand = new Runnable() {- @Override- public void run() {- cookieManager = new XWalkCordovaCookieManager();-- initWebViewSettings();- exposeJsInterface(webView, bridge);- loadExtensions();-- CordovaPlugin notifPlugin = new CordovaPlugin() {- @Override- public void onNewIntent(Intent intent) {- Log.i(TAG, "notifPlugin route onNewIntent() to XWalkView: " + intent.toString());- XWalkWebViewEngine.this.webView.onNewIntent(intent);- }-- @Override- public Object onMessage(String id, Object data) {- if (id.equals("captureXWalkBitmap")) {- // Capture bitmap on UI thread.- XWalkWebViewEngine.this.cordova.getActivity().runOnUiThread(new Runnable() {- public void run() {- XWalkWebViewEngine.this.webView.captureBitmapAsync(- new XWalkGetBitmapCallback() {- @Override- public void onFinishGetBitmap(Bitmap bitmap,- int response) {- pluginManager.postMessage(- "onGotXWalkBitmap", bitmap);- }- });- }- });- }- return null;- }- };- pluginManager.addService(new PluginEntry("XWalkNotif", notifPlugin));-- // Send the massage of xwalk's ready to plugin.- if (pluginManager != null) {- pluginManager.postMessage("onXWalkReady", this);- }-- if (startUrl != null) {- webView.load(startUrl, null);- }- }- };- activityDelegate = new XWalkActivityDelegate((Activity) context, cancelCommand, completeCommand);-- webView = new XWalkCordovaView(context, preferences);- }-- // Use two-phase init so that the control will work with XML layouts.-- @Override- public void init(CordovaWebView parentWebView, CordovaInterface cordova, CordovaWebViewEngine.Client client,- CordovaResourceApi resourceApi, PluginManager pluginManager,- NativeToJsMessageQueue nativeToJsMessageQueue) {- if (this.cordova != null) {- throw new IllegalStateException();- }- this.parentWebView = parentWebView;- this.cordova = cordova;- this.client = client;- this.resourceApi = resourceApi;- this.pluginManager = pluginManager;- this.nativeToJsMessageQueue = nativeToJsMessageQueue;-- CordovaPlugin activityDelegatePlugin = new CordovaPlugin() {- @Override- public void onResume(boolean multitasking) {- activityDelegate.onResume();- }- };- pluginManager.addService(new PluginEntry("XWalkActivityDelegate", activityDelegatePlugin));-- webView.init(this);-- nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.OnlineEventsBridgeMode(- new NativeToJsMessageQueue.OnlineEventsBridgeMode.OnlineEventsBridgeModeDelegate() {- @Override- public void setNetworkAvailable(boolean value) {- webView.setNetworkAvailable(value);- }- @Override- public void runOnUiThread(Runnable r) {- XWalkWebViewEngine.this.cordova.getActivity().runOnUiThread(r);- }- }));- nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.EvalBridgeMode(this, cordova));- bridge = new CordovaBridge(pluginManager, nativeToJsMessageQueue);- }-- @Override- public CordovaWebView getCordovaWebView() {- return parentWebView;- }-- @Override- public View getView() {- return webView;- }-- private void initWebViewSettings() {- webView.setVerticalScrollBarEnabled(false);-- boolean zOrderOnTop = preferences == null ? false : preferences.getBoolean(XWALK_Z_ORDER_ON_TOP, false);- webView.setZOrderOnTop(zOrderOnTop);-- // Set xwalk webview settings by Cordova preferences.- String xwalkUserAgent = preferences == null ? "" : preferences.getString(XWALK_USER_AGENT, "");- if (!xwalkUserAgent.isEmpty()) {- webView.setUserAgentString(xwalkUserAgent);- }-- String appendUserAgent = preferences.getString("AppendUserAgent", "");- if (!appendUserAgent.isEmpty()) {- webView.setUserAgentString(webView.getUserAgentString() + " " + appendUserAgent);- }-- if (preferences.contains("BackgroundColor")) {- int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);- webView.setBackgroundColor(backgroundColor);- }- }-- private static void exposeJsInterface(XWalkView webView, CordovaBridge bridge) {- XWalkExposedJsApi exposedJsApi = new XWalkExposedJsApi(bridge);- webView.addJavascriptInterface(exposedJsApi, "_cordovaNative");- }-- private void loadExtensions() {- AssetManager assetManager = cordova.getActivity().getAssets();- String[] extList;- try {- Log.i(TAG, "Iterate assets/xwalk-extensions folder");- extList = assetManager.list(XWALK_EXTENSIONS_FOLDER);- } catch (IOException e) {- Log.w(TAG, "Failed to iterate assets/xwalk-extensions folder");- return;- }-- for (String path : extList) {- // Load the extension.- Log.i(TAG, "Start to load extension: " + path);- webView.getExtensionManager().loadExtension(XWALK_EXTENSIONS_FOLDER + File.separator + path);- }- }-- @Override- public boolean canGoBack() {- if (!activityDelegate.isXWalkReady()) return false;- return this.webView.getNavigationHistory().canGoBack();- }-- @Override- public boolean goBack() {- if (this.webView.getNavigationHistory().canGoBack()) {- this.webView.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);- return true;- }- return false;- }-- @Override- public void setPaused(boolean value) {- if (!activityDelegate.isXWalkReady()) return;- if (value) {- // TODO: I think this has been fixed upstream and we don't need to override pauseTimers() anymore.- webView.pauseTimersForReal();- } else {- webView.resumeTimers();- }- }-- @Override- public void destroy() {- if (!activityDelegate.isXWalkReady()) return;- webView.onDestroy();- }-- @Override- public void clearHistory() {- if (!activityDelegate.isXWalkReady()) return;- this.webView.getNavigationHistory().clear();- }-- @Override- public void stopLoading() {- if (!activityDelegate.isXWalkReady()) return;- this.webView.stopLoading();- }-- @Override- public void clearCache() {- if (!activityDelegate.isXWalkReady()) return;- webView.clearCache(true);- }-- @Override- public String getUrl() {- if (!activityDelegate.isXWalkReady()) return null;- return this.webView.getUrl();- }-- @Override- public ICordovaCookieManager getCookieManager() {- return cookieManager;- }-- @Override- public void loadUrl(String url, boolean clearNavigationStack) {- if (!activityDelegate.isXWalkReady()) {- startUrl = url;- return;- }- webView.load(url, null);- }-- /**- * This API is used in Cordova-Android 6.0.0 override from- *- * CordovaWebViewEngine.java- * @since Cordova 6.0- */- public void evaluateJavascript(String js, ValueCallback<String> callback) {- webView.evaluateJavascript(js, callback);- }-- public boolean isXWalkReady() {- return activityDelegate.isXWalkReady();- }-- public interface PermissionRequestListener {- public void onRequestPermissionResult(int requestCode, String[] permissions,- int[] grantResults);- }-- public boolean requestPermissionsForFileChooser(final PermissionRequestListener listener) {- ArrayList<String> dangerous_permissions = new ArrayList<String>();- try {- PackageManager packageManager = cordova.getActivity().getPackageManager();- PackageInfo packageInfo = packageManager.getPackageInfo(- cordova.getActivity().getPackageName(), PackageManager.GET_PERMISSIONS);- for (String permission : packageInfo.requestedPermissions) {- if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)- || permission.equals(Manifest.permission.CAMERA)) {- dangerous_permissions.add(permission);- }- }- } catch (NameNotFoundException e) {- }-- if (dangerous_permissions.isEmpty()) {- return false;- }-- CordovaPlugin permissionRequestPlugin = new CordovaPlugin() {- @Override- public void onRequestPermissionResult(int requestCode, String[] permissions,- int[] grantResults) {- if (requestCode != PERMISSION_REQUEST_CODE) return;- listener.onRequestPermissionResult(requestCode, permissions, grantResults);- }- };- try {- cordova.requestPermissions(permissionRequestPlugin, PERMISSION_REQUEST_CODE,- dangerous_permissions.toArray(new String[dangerous_permissions.size()]));- } catch (NoSuchMethodError e) {- return false;- }- return true;- }-}diff --git a/cordova/yarn.lock b/cordova/yarn.locknew file mode 100644index 000000000..acb34704a--- /dev/null+++ b/cordova/yarn.lock@@ -0,0 +1,211 @@+# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.+# yarn lockfile v1+++abbrev@1:+ version "1.1.1"+ resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"+ integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==++android-versions@^1.2.1:+ version "1.4.0"+ resolved "https://registry.yarnpkg.com/android-versions/-/android-versions-1.4.0.tgz#807ea2941d7e5780e6dd61c5d9b7b6f3c0706e09"+ integrity sha512-GnomfYsBq+nZh3c3UH/4r9Jt6FuTxdhUJbeHIdYOH5xBhQ8I0ZzC2/RM5IFFIjrzuNWSHb8JWP1lPK0/a26jrg==+ dependencies:+ semver "^5.4.1"++ansi@^0.3.1:+ version "0.3.1"+ resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21"+ integrity sha1-DELU+xcWDVqa8eSEus4cZpIsGyE=++balanced-match@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"+ integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c=++ version "1.2.0"+ resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.0.tgz#a39992d723584811982be5e290bb6a53d86700f1"+ integrity sha1-o5mS1yNYSBGYK+XikLtqU9hnAPE=++big-integer@^1.6.7:+ version "1.6.36"+ resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.36.tgz#78631076265d4ae3555c04f85e7d9d2f3a071a36"+ integrity sha512-t70bfa7HYEA1D9idDbmuv7YbsbVkQ+Hp+8KFSul4aE5e/i1bjCNIRYJZlA8Q8p0r9T8cF/RVvwUgRA//FydEyg==++bplist-parser@^0.1.0:+ version "0.1.1"+ resolved "https://registry.yarnpkg.com/bplist-parser/-/bplist-parser-0.1.1.tgz#d60d5dcc20cba6dc7e1f299b35d3e1f95dafbae6"+ integrity sha1-1g1dzCDLptx+HymbNdPh+V2vuuY=+ dependencies:+ big-integer "^1.6.7"++brace-expansion@^1.1.7:+ version "1.1.11"+ resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"+ integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==+ dependencies:+ balanced-match "^1.0.0"+ concat-map "0.0.1"++ version "0.0.1"+ resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"+ integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=++cordova-android@^6.4.0:+ version "6.4.0"+ resolved "https://registry.yarnpkg.com/cordova-android/-/cordova-android-6.4.0.tgz#54ae8da5728a8d7e5efcc6172d3dcca17bc7fe7d"+ integrity sha1-VK6NpXKKjX5e/MYXLT3MoXvH/n0=+ dependencies:+ android-versions "^1.2.1"+ cordova-common "^2.1.0"+ elementtree "0.1.6"+ nopt "^3.0.1"+ properties-parser "^0.2.3"+ q "^1.4.1"+ shelljs "^0.5.3"++cordova-common@^2.1.0:+ version "2.2.5"+ resolved "https://registry.yarnpkg.com/cordova-common/-/cordova-common-2.2.5.tgz#f93cef2ad494cfcbf56c46e3d612aaa9cb5fcc32"+ integrity sha1-+TzvKtSUz8v1bEbj1hKqqctfzDI=+ dependencies:+ ansi "^0.3.1"+ bplist-parser "^0.1.0"+ cordova-registry-mapper "^1.1.8"+ elementtree "0.1.6"+ glob "^5.0.13"+ minimatch "^3.0.0"+ plist "^2.1.0"+ q "^1.4.1"+ shelljs "^0.5.3"+ underscore "^1.8.3"+ unorm "^1.3.3"++cordova-plugin-whitelist@^1.3.2:+ version "1.3.3"+ resolved "https://registry.yarnpkg.com/cordova-plugin-whitelist/-/cordova-plugin-whitelist-1.3.3.tgz#b5e85ecdbbfe5aeded40a1bf4ee2372e67d96fb4"+ integrity sha1-tehezbv+Wu3tQKG/TuI3LmfZb7Q=++cordova-registry-mapper@^1.1.8:+ version "1.1.15"+ resolved "https://registry.yarnpkg.com/cordova-registry-mapper/-/cordova-registry-mapper-1.1.15.tgz#e244b9185b8175473bff6079324905115f83dc7c"+ integrity sha1-4kS5GFuBdUc7/2B5MkkFEV+D3Hw=++ version "0.1.6"+ resolved "https://registry.yarnpkg.com/elementtree/-/elementtree-0.1.6.tgz#2ac4c46ea30516c8c4cbdb5e3ac7418e592de20c"+ integrity sha1-KsTEbqMFFsjEy9teOsdBjlkt4gw=+ dependencies:+ sax "0.3.5"++glob@^5.0.13:+ version "5.0.15"+ resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1"+ integrity sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=+ dependencies:+ inflight "^1.0.4"+ inherits "2"+ minimatch "2 || 3"+ once "^1.3.0"+ path-is-absolute "^1.0.0"++inflight@^1.0.4:+ version "1.0.6"+ resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"+ integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=+ dependencies:+ once "^1.3.0"+ wrappy "1"++inherits@2:+ version "2.0.3"+ resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"+ integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=++"minimatch@2 || 3", minimatch@^3.0.0:+ version "3.0.4"+ resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"+ integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==+ dependencies:+ brace-expansion "^1.1.7"++nopt@^3.0.1:+ version "3.0.6"+ resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9"+ integrity sha1-xkZdvwirzU2zWTF/eaxopkayj/k=+ dependencies:+ abbrev "1"++once@^1.3.0:+ version "1.4.0"+ resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"+ integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=+ dependencies:+ wrappy "1"++path-is-absolute@^1.0.0:+ version "1.0.1"+ resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"+ integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18=++plist@^2.1.0:+ version "2.1.0"+ resolved "https://registry.yarnpkg.com/plist/-/plist-2.1.0.tgz#57ccdb7a0821df21831217a3cad54e3e146a1025"+ integrity sha1-V8zbeggh3yGDEhejytVOPhRqECU=+ dependencies:+ base64-js "1.2.0"+ xmlbuilder "8.2.2"+ xmldom "0.1.x"++properties-parser@^0.2.3:+ version "0.2.3"+ resolved "https://registry.yarnpkg.com/properties-parser/-/properties-parser-0.2.3.tgz#f7591255f707abbff227c7b56b637dbb0373a10f"+ integrity sha1-91kSVfcHq7/yJ8e1a2N9uwNzoQ8=++q@^1.4.1:+ version "1.5.1"+ resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7"+ integrity sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=++ version "0.3.5"+ resolved "https://registry.yarnpkg.com/sax/-/sax-0.3.5.tgz#88fcfc1f73c0c8bbd5b7c776b6d3f3501eed073d"+ integrity sha1-iPz8H3PAyLvVt8d2ttPzUB7tBz0=++semver@^5.4.1:+ version "5.6.0"+ resolved "https://registry.yarnpkg.com/semver/-/semver-5.6.0.tgz#7e74256fbaa49c75aa7c7a205cc22799cac80004"+ integrity sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==++shelljs@^0.5.3:+ version "0.5.3"+ resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.5.3.tgz#c54982b996c76ef0c1e6b59fbdc5825f5b713113"+ integrity sha1-xUmCuZbHbvDB5rWfvcWCX1txMRM=++underscore@^1.8.3:+ version "1.9.1"+ resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.9.1.tgz#06dce34a0e68a7babc29b365b8e74b8925203961"+ integrity sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg==++unorm@^1.3.3:+ version "1.4.1"+ resolved "https://registry.yarnpkg.com/unorm/-/unorm-1.4.1.tgz#364200d5f13646ca8bcd44490271335614792300"+ integrity sha1-NkIA1fE2RsqLzURJAnEzVhR5IwA=++wrappy@1:+ version "1.0.2"+ resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"+ integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=++ version "8.2.2"+ resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-8.2.2.tgz#69248673410b4ba42e1a6136551d2922335aa773"+ integrity sha1-aSSGc0ELS6QuGmE2VR0pIjNap3M=++ version "0.1.27"+ resolved "https://registry.yarnpkg.com/xmldom/-/xmldom-0.1.27.tgz#d501f97b3bdb403af8ef9ecc20573187aadac0e9"+ integrity sha1-1QH5ezvbQDr4757MIFcxh6rawOk=