You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by fi...@apache.org on 2017/06/27 21:21:52 UTC
[11/51] [partial] cordova-lib git commit: Reorganized unit test
directory. Changes include: - consolidate spec-cordova/ and spec-plugman/
into a single spec/ dir. - put jasmine config and helper modules in top-level
spec dir. - changed package.json npm r
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java b/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java
deleted file mode 100755
index 3ea5e57..0000000
--- a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java
+++ /dev/null
@@ -1,292 +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.engine;
-
-import java.util.Arrays;
-import android.annotation.TargetApi;
-import android.app.Activity;
-import android.content.Context;
-import android.content.ActivityNotFoundException;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Build;
-import android.view.Gravity;
-import android.view.View;
-import android.view.ViewGroup.LayoutParams;
-import android.webkit.ConsoleMessage;
-import android.webkit.GeolocationPermissions.Callback;
-import android.webkit.JsPromptResult;
-import android.webkit.JsResult;
-import android.webkit.ValueCallback;
-import android.webkit.WebChromeClient;
-import android.webkit.WebStorage;
-import android.webkit.WebView;
-import android.webkit.PermissionRequest;
-import android.widget.LinearLayout;
-import android.widget.ProgressBar;
-import android.widget.RelativeLayout;
-
-import org.apache.cordova.CordovaDialogsHelper;
-import org.apache.cordova.CordovaPlugin;
-import org.apache.cordova.LOG;
-
-/**
- * This class is the WebChromeClient that implements callbacks for our web view.
- * The kind of callbacks that happen here are on the chrome outside the document,
- * such as onCreateWindow(), onConsoleMessage(), onProgressChanged(), etc. Related
- * to but different than CordovaWebViewClient.
- */
-public class SystemWebChromeClient extends WebChromeClient {
-
- private static final int FILECHOOSER_RESULTCODE = 5173;
- private static final String LOG_TAG = "SystemWebChromeClient";
- private long MAX_QUOTA = 100 * 1024 * 1024;
- protected final SystemWebViewEngine parentEngine;
-
- // the video progress view
- private View mVideoProgressView;
-
- private CordovaDialogsHelper dialogsHelper;
- private Context appContext;
-
- private WebChromeClient.CustomViewCallback mCustomViewCallback;
- private View mCustomView;
-
- public SystemWebChromeClient(SystemWebViewEngine parentEngine) {
- this.parentEngine = parentEngine;
- appContext = parentEngine.webView.getContext();
- dialogsHelper = new CordovaDialogsHelper(appContext);
- }
-
- /**
- * Tell the client to display a javascript alert dialog.
- */
- @Override
- public boolean onJsAlert(WebView view, String url, String message, final JsResult 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.
- */
- @Override
- public boolean onJsConfirm(WebView view, String url, String message, final JsResult 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.
- *
- * 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!
- */
- @Override
- public boolean onJsPrompt(WebView view, String origin, String message, String defaultValue, final JsPromptResult 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.confirm(handledRet);
- } else {
- dialogsHelper.showPrompt(message, defaultValue, new CordovaDialogsHelper.Result() {
- @Override
- public void gotResult(boolean success, String value) {
- if (success) {
- result.confirm(value);
- } else {
- result.cancel();
- }
- }
- });
- }
- return true;
- }
-
- /**
- * Handle database quota exceeded notification.
- */
- @Override
- public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
- long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
- {
- LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
- 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)
- @Override
- public boolean onConsoleMessage(ConsoleMessage consoleMessage)
- {
- if (consoleMessage.message() != null)
- LOG.d(LOG_TAG, "%s: Line %d : %s" , consoleMessage.sourceId() , consoleMessage.lineNumber(), consoleMessage.message());
- return super.onConsoleMessage(consoleMessage);
- }
-
- @Override
- /**
- * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
- *
- * This also checks for the Geolocation Plugin and requests permission from the application to use Geolocation.
- *
- * @param origin
- * @param callback
- */
- public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
- super.onGeolocationPermissionsShowPrompt(origin, callback);
- callback.invoke(origin, true, false);
- //Get the plugin, it should be loaded
- CordovaPlugin geolocation = parentEngine.pluginManager.getPlugin("Geolocation");
- if(geolocation != null && !geolocation.hasPermisssion())
- {
- geolocation.requestPermissions(0);
- }
-
- }
-
- // API level 7 is required for this, see if we could lower this using something else
- @Override
- public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
- parentEngine.getCordovaWebView().showCustomView(view, callback);
- }
-
- @Override
- public void onHideCustomView() {
- parentEngine.getCordovaWebView().hideCustomView();
- }
-
- @Override
- /**
- * Ask the host application for a custom progress view to show while
- * a <video> is loading.
- * @return View The progress view.
- */
- public View getVideoLoadingProgressView() {
-
- if (mVideoProgressView == null) {
- // Create a new Loading view programmatically.
-
- // create the linear layout
- LinearLayout layout = new LinearLayout(parentEngine.getView().getContext());
- layout.setOrientation(LinearLayout.VERTICAL);
- RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
- layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
- layout.setLayoutParams(layoutParams);
- // the proress bar
- ProgressBar bar = new ProgressBar(parentEngine.getView().getContext());
- LinearLayout.LayoutParams barLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
- barLayoutParams.gravity = Gravity.CENTER;
- bar.setLayoutParams(barLayoutParams);
- layout.addView(bar);
-
- mVideoProgressView = layout;
- }
- return mVideoProgressView;
- }
-
- // <input type=file> support:
- // openFileChooser() is for pre KitKat and in KitKat mr1 (it's known broken in KitKat).
- // For Lollipop, we use onShowFileChooser().
- public void openFileChooser(ValueCallback<Uri> uploadMsg) {
- this.openFileChooser(uploadMsg, "*/*");
- }
-
- public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {
- this.openFileChooser(uploadMsg, acceptType, null);
- }
-
- public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType, String capture)
- {
- Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
- intent.addCategory(Intent.CATEGORY_OPENABLE);
- intent.setType("*/*");
- parentEngine.cordova.startActivityForResult(new CordovaPlugin() {
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent intent) {
- Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
- LOG.d(LOG_TAG, "Receive file chooser URL: " + result);
- uploadMsg.onReceiveValue(result);
- }
- }, intent, FILECHOOSER_RESULTCODE);
- }
-
- @TargetApi(Build.VERSION_CODES.LOLLIPOP)
- @Override
- public boolean onShowFileChooser(WebView webView, final ValueCallback<Uri[]> filePathsCallback, final WebChromeClient.FileChooserParams fileChooserParams) {
- Intent intent = fileChooserParams.createIntent();
- try {
- parentEngine.cordova.startActivityForResult(new CordovaPlugin() {
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent intent) {
- Uri[] result = WebChromeClient.FileChooserParams.parseResult(resultCode, intent);
- LOG.d(LOG_TAG, "Receive file chooser URL: " + result);
- filePathsCallback.onReceiveValue(result);
- }
- }, intent, FILECHOOSER_RESULTCODE);
- } catch (ActivityNotFoundException e) {
- LOG.w("No activity found to handle file chooser intent.", e);
- filePathsCallback.onReceiveValue(null);
- }
- return true;
- }
-
- @TargetApi(Build.VERSION_CODES.LOLLIPOP)
- @Override
- public void onPermissionRequest(final PermissionRequest request) {
- LOG.d(LOG_TAG, "onPermissionRequest: " + Arrays.toString(request.getResources()));
- request.grant(request.getResources());
- }
-
- public void destroyLastDialog(){
- dialogsHelper.destroyLastDialog();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebView.java
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebView.java b/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebView.java
deleted file mode 100644
index 01c2f00..0000000
--- a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebView.java
+++ /dev/null
@@ -1,88 +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.engine;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.KeyEvent;
-import android.webkit.WebChromeClient;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-
-import org.apache.cordova.CordovaInterface;
-import org.apache.cordova.CordovaWebView;
-import org.apache.cordova.CordovaWebViewEngine;
-
-/**
- * Custom WebView subclass that enables us to capture events needed for Cordova.
- */
-public class SystemWebView extends WebView implements CordovaWebViewEngine.EngineView {
- private SystemWebViewClient viewClient;
- SystemWebChromeClient chromeClient;
- private SystemWebViewEngine parentEngine;
- private CordovaInterface cordova;
-
- public SystemWebView(Context context) {
- this(context, null);
- }
-
- public SystemWebView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- // Package visibility to enforce that only SystemWebViewEngine should call this method.
- void init(SystemWebViewEngine parentEngine, CordovaInterface cordova) {
- this.cordova = cordova;
- this.parentEngine = parentEngine;
- if (this.viewClient == null) {
- setWebViewClient(new SystemWebViewClient(parentEngine));
- }
-
- if (this.chromeClient == null) {
- setWebChromeClient(new SystemWebChromeClient(parentEngine));
- }
- }
-
- @Override
- public CordovaWebView getCordovaWebView() {
- return parentEngine != null ? parentEngine.getCordovaWebView() : null;
- }
-
- @Override
- public void setWebViewClient(WebViewClient client) {
- viewClient = (SystemWebViewClient)client;
- super.setWebViewClient(client);
- }
-
- @Override
- public void setWebChromeClient(WebChromeClient client) {
- chromeClient = (SystemWebChromeClient)client;
- super.setWebChromeClient(client);
- }
-
- @Override
- public boolean dispatchKeyEvent(KeyEvent event) {
- Boolean ret = parentEngine.client.onDispatchKeyEvent(event);
- if (ret != null) {
- return ret.booleanValue();
- }
- return super.dispatchKeyEvent(event);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java b/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java
deleted file mode 100755
index d176502..0000000
--- a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java
+++ /dev/null
@@ -1,374 +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.engine;
-
-import android.annotation.TargetApi;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.graphics.Bitmap;
-import android.net.Uri;
-import android.net.http.SslError;
-import android.os.Build;
-import android.webkit.ClientCertRequest;
-import android.webkit.HttpAuthHandler;
-import android.webkit.SslErrorHandler;
-import android.webkit.WebResourceResponse;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-
-import org.apache.cordova.AuthenticationToken;
-import org.apache.cordova.CordovaClientCertRequest;
-import org.apache.cordova.CordovaHttpAuthHandler;
-import org.apache.cordova.CordovaResourceApi;
-import org.apache.cordova.LOG;
-import org.apache.cordova.PluginManager;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Hashtable;
-
-
-/**
- * This class is the WebViewClient that implements callbacks for our web view.
- * The kind of callbacks that happen here are regarding the rendering of the
- * document instead of the chrome surrounding it, such as onPageStarted(),
- * shouldOverrideUrlLoading(), etc. Related to but different than
- * CordovaChromeClient.
- */
-public class SystemWebViewClient extends WebViewClient {
-
- private static final String TAG = "SystemWebViewClient";
- protected final SystemWebViewEngine parentEngine;
- private boolean doClearHistory = false;
- boolean isCurrentlyLoading;
-
- /** The authorization tokens. */
- private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();
-
- public SystemWebViewClient(SystemWebViewEngine parentEngine) {
- this.parentEngine = parentEngine;
- }
-
- /**
- * Give the host application a chance to take over the control when a new url
- * is about to be loaded in the current WebView.
- *
- * @param view The WebView that is initiating the callback.
- * @param url The url to be loaded.
- * @return true to override, false for default behavior
- */
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- return parentEngine.client.onNavigationAttempt(url);
- }
-
- /**
- * On received http auth request.
- * The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
- */
- @Override
- public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
-
- // Get the authentication token (if specified)
- AuthenticationToken token = this.getAuthenticationToken(host, realm);
- if (token != null) {
- handler.proceed(token.getUserName(), token.getPassword());
- return;
- }
-
- // Check if there is some plugin which can resolve this auth challenge
- PluginManager pluginManager = this.parentEngine.pluginManager;
- if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(null, new CordovaHttpAuthHandler(handler), host, realm)) {
- parentEngine.client.clearLoadTimeoutTimer();
- return;
- }
-
- // By default handle 401 like we'd normally do!
- super.onReceivedHttpAuthRequest(view, handler, host, realm);
- }
-
- /**
- * On received client cert request.
- * The method forwards the request to any running plugins before using the default implementation.
- *
- * @param view
- * @param request
- */
- @Override
- @TargetApi(21)
- public void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
- {
-
- // Check if there is some plugin which can resolve this certificate request
- PluginManager pluginManager = this.parentEngine.pluginManager;
- if (pluginManager != null && pluginManager.onReceivedClientCertRequest(null, new CordovaClientCertRequest(request))) {
- parentEngine.client.clearLoadTimeoutTimer();
- return;
- }
-
- // By default pass to WebViewClient
- super.onReceivedClientCertRequest(view, request);
- }
-
- /**
- * 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 onPageStarted
- * one time for the main frame. This also means that onPageStarted 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 onPageStarted(WebView view, String url, Bitmap favicon) {
- super.onPageStarted(view, url, favicon);
- isCurrentlyLoading = true;
- // Flush stale messages & reset plugins.
- parentEngine.bridge.reset();
- parentEngine.client.onPageStarted(url);
- }
-
- /**
- * Notify the host application that a page has finished loading.
- * This method is called only for main frame. When onPageFinished() is called, the rendering picture may not be updated yet.
- *
- *
- * @param view The webview initiating the callback.
- * @param url The url of the page.
- */
- @Override
- public void onPageFinished(WebView view, String url) {
- super.onPageFinished(view, url);
- // Ignore excessive calls, if url is not about:blank (CB-8317).
- if (!isCurrentlyLoading && !url.startsWith("about:")) {
- return;
- }
- isCurrentlyLoading = false;
-
- /**
- * Because of a timing issue we need to clear this history in onPageFinished as well as
- * onPageStarted. However we only want to do this if the doClearHistory boolean is set to
- * true. You see when you load a url with a # in it which is common in jQuery applications
- * onPageStared is not called. Clearing the history at that point would break jQuery apps.
- */
- if (this.doClearHistory) {
- view.clearHistory();
- this.doClearHistory = false;
- }
- parentEngine.client.onPageFinishedLoading(url);
-
- }
-
- /**
- * 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 onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
- // Ignore error due to stopLoading().
- if (!isCurrentlyLoading) {
- return;
- }
- LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
-
- // If this is a "Protocol Not Supported" error, then revert to the previous
- // page. If there was no previous page, then punt. The application's config
- // is likely incorrect (start page set to sms: or something like that)
- if (errorCode == WebViewClient.ERROR_UNSUPPORTED_SCHEME) {
- parentEngine.client.clearLoadTimeoutTimer();
-
- if (view.canGoBack()) {
- view.goBack();
- return;
- } else {
- super.onReceivedError(view, errorCode, description, failingUrl);
- }
- }
- parentEngine.client.onReceivedError(errorCode, description, failingUrl);
- }
-
- /**
- * Notify the host application that an SSL error occurred while loading a resource.
- * The host application must call either handler.cancel() or handler.proceed().
- * Note that the decision may be retained for use in response to future SSL errors.
- * The default behavior is to cancel the load.
- *
- * @param view The WebView that is initiating the callback.
- * @param handler An SslErrorHandler object that will handle the user's response.
- * @param error The SSL error object.
- */
- @TargetApi(8)
- @Override
- public void onReceivedSslError(WebView view, SslErrorHandler handler, 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
- handler.proceed();
- return;
- } else {
- // debug = false
- super.onReceivedSslError(view, handler, error);
- }
- } catch (NameNotFoundException e) {
- // When it doubt, lock it out!
- super.onReceivedSslError(view, handler, error);
- }
- }
-
-
- /**
- * Sets the authentication token.
- *
- * @param authenticationToken
- * @param host
- * @param realm
- */
- public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
- if (host == null) {
- host = "";
- }
- if (realm == null) {
- realm = "";
- }
- this.authenticationTokens.put(host.concat(realm), authenticationToken);
- }
-
- /**
- * Removes the authentication token.
- *
- * @param host
- * @param realm
- *
- * @return the authentication token or null if did not exist
- */
- public AuthenticationToken removeAuthenticationToken(String host, String realm) {
- return this.authenticationTokens.remove(host.concat(realm));
- }
-
- /**
- * Gets the authentication token.
- *
- * In order it tries:
- * 1- host + realm
- * 2- host
- * 3- realm
- * 4- no host, no realm
- *
- * @param host
- * @param realm
- *
- * @return the authentication token
- */
- public AuthenticationToken getAuthenticationToken(String host, String realm) {
- AuthenticationToken token = null;
- token = this.authenticationTokens.get(host.concat(realm));
-
- if (token == null) {
- // try with just the host
- token = this.authenticationTokens.get(host);
-
- // Try the realm
- if (token == null) {
- token = this.authenticationTokens.get(realm);
- }
-
- // if no host found, just query for default
- if (token == null) {
- token = this.authenticationTokens.get("");
- }
- }
-
- return token;
- }
-
- /**
- * Clear all authentication tokens.
- */
- public void clearAuthenticationTokens() {
- this.authenticationTokens.clear();
- }
-
- @TargetApi(Build.VERSION_CODES.HONEYCOMB)
- @Override
- public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
- try {
- // Check the against the whitelist and lock out access to the WebView directory
- // Changing this will cause problems for your application
- 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) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
- CordovaResourceApi.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);
- }
- }
-
- private static boolean needsKitKatContentUrlFix(Uri uri) {
- return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && "content".equals(uri.getScheme());
- }
-
- private static boolean needsSpecialsInAssetUrlFix(Uri uri) {
- if (CordovaResourceApi.getUriType(uri) != CordovaResourceApi.URI_TYPE_ASSET) {
- return false;
- }
- if (uri.getQuery() != null || uri.getFragment() != null) {
- return true;
- }
-
- if (!uri.toString().contains("%")) {
- 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;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java b/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java
deleted file mode 100755
index 0fa0276..0000000
--- a/spec-plugman/projects/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java
+++ /dev/null
@@ -1,350 +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.engine;
-
-import android.annotation.SuppressLint;
-import android.annotation.TargetApi;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ApplicationInfo;
-import android.os.Build;
-import android.view.View;
-import android.webkit.ValueCallback;
-import android.webkit.WebSettings;
-import android.webkit.WebSettings.LayoutAlgorithm;
-import android.webkit.WebView;
-
-import org.apache.cordova.CordovaBridge;
-import org.apache.cordova.CordovaInterface;
-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.LOG;
-import org.apache.cordova.NativeToJsMessageQueue;
-import org.apache.cordova.PluginManager;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-
-/**
- * Glue class between CordovaWebView (main Cordova logic) and SystemWebView (the actual View).
- * We make the Engine separate from the actual View so that:
- * A) We don't need to worry about WebView methods clashing with CordovaWebViewEngine methods
- * (e.g.: goBack() is void for WebView, and boolean for CordovaWebViewEngine)
- * B) Separating the actual View from the Engine makes API surfaces smaller.
- * Class uses two-phase initialization. However, CordovaWebView is responsible for calling .init().
- */
-public class SystemWebViewEngine implements CordovaWebViewEngine {
- public static final String TAG = "SystemWebViewEngine";
-
- protected final SystemWebView webView;
- protected final SystemCookieManager cookieManager;
- protected CordovaPreferences preferences;
- protected CordovaBridge bridge;
- protected CordovaWebViewEngine.Client client;
- protected CordovaWebView parentWebView;
- protected CordovaInterface cordova;
- protected PluginManager pluginManager;
- protected CordovaResourceApi resourceApi;
- protected NativeToJsMessageQueue nativeToJsMessageQueue;
- private BroadcastReceiver receiver;
-
- /** Used when created via reflection. */
- public SystemWebViewEngine(Context context, CordovaPreferences preferences) {
- this(new SystemWebView(context), preferences);
- }
-
- public SystemWebViewEngine(SystemWebView webView) {
- this(webView, null);
- }
-
- public SystemWebViewEngine(SystemWebView webView, CordovaPreferences preferences) {
- this.preferences = preferences;
- this.webView = webView;
- cookieManager = new SystemCookieManager(webView);
- }
-
- @Override
- public void init(CordovaWebView parentWebView, CordovaInterface cordova, CordovaWebViewEngine.Client client,
- CordovaResourceApi resourceApi, PluginManager pluginManager,
- NativeToJsMessageQueue nativeToJsMessageQueue) {
- if (this.cordova != null) {
- throw new IllegalStateException();
- }
- // Needed when prefs are not passed by the constructor
- if (preferences == null) {
- preferences = parentWebView.getPreferences();
- }
- this.parentWebView = parentWebView;
- this.cordova = cordova;
- this.client = client;
- this.resourceApi = resourceApi;
- this.pluginManager = pluginManager;
- this.nativeToJsMessageQueue = nativeToJsMessageQueue;
- webView.init(this, cordova);
-
- initWebViewSettings();
-
- nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.OnlineEventsBridgeMode(new NativeToJsMessageQueue.OnlineEventsBridgeMode.OnlineEventsBridgeModeDelegate() {
- @Override
- public void setNetworkAvailable(boolean value) {
- webView.setNetworkAvailable(value);
- }
- @Override
- public 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);
- exposeJsInterface(webView, bridge);
- }
-
- @Override
- public CordovaWebView getCordovaWebView() {
- return parentWebView;
- }
-
- @Override
- public ICordovaCookieManager getCookieManager() {
- return cookieManager;
- }
-
- @Override
- public View getView() {
- return webView;
- }
-
- @SuppressLint({"NewApi", "SetJavaScriptEnabled"})
- @SuppressWarnings("deprecation")
- private void initWebViewSettings() {
- webView.setInitialScale(0);
- webView.setVerticalScrollBarEnabled(false);
- // Enable JavaScript
- final WebSettings settings = webView.getSettings();
- settings.setJavaScriptEnabled(true);
- 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.");
- }
-
- //We don't save any form data in the application
- settings.setSaveFormData(false);
- settings.setSavePassword(false);
-
- // 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);
- }
- // Enable database
- // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16
- String databasePath = webView.getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
- settings.setDatabaseEnabled(true);
- settings.setDatabasePath(databasePath);
-
-
- //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) {
- enableRemoteDebugging();
- }
-
- settings.setGeolocationDatabasePath(databasePath);
-
- // Enable DOM storage
- settings.setDomStorageEnabled(true);
-
- // Enable built-in geolocation
- settings.setGeolocationEnabled(true);
-
- // Enable AppCache
- // Fix for CB-2282
- settings.setAppCacheMaxSize(5 * 1048576);
- settings.setAppCachePath(databasePath);
- settings.setAppCacheEnabled(true);
-
- // Fix for CB-1405
- // Google issue 4641
- String defaultUserAgent = settings.getUserAgentString();
-
- // Fix for CB-3360
- String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
- if (overrideUserAgent != null) {
- settings.setUserAgentString(overrideUserAgent);
- } else {
- String appendUserAgent = preferences.getString("AppendUserAgent", null);
- if (appendUserAgent != null) {
- settings.setUserAgentString(defaultUserAgent + " " + appendUserAgent);
- }
- }
- // End CB-3360
-
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
- if (this.receiver == null) {
- this.receiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- settings.getUserAgentString();
- }
- };
- webView.getContext().registerReceiver(this.receiver, intentFilter);
- }
- // end CB-1405
- }
-
- @TargetApi(Build.VERSION_CODES.KITKAT)
- private void enableRemoteDebugging() {
- try {
- WebView.setWebContentsDebuggingEnabled(true);
- } catch (IllegalArgumentException e) {
- LOG.d(TAG, "You have one job! To turn on Remote Web Debugging! YOU HAVE FAILED! ");
- e.printStackTrace();
- }
- }
-
- 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");
- }
-
-
- /**
- * Load the url into the webview.
- */
- @Override
- public void loadUrl(final String url, boolean clearNavigationStack) {
- webView.loadUrl(url);
- }
-
- @Override
- public String getUrl() {
- return webView.getUrl();
- }
-
- @Override
- public void stopLoading() {
- webView.stopLoading();
- }
-
- @Override
- public void clearCache() {
- webView.clearCache(true);
- }
-
- @Override
- public void clearHistory() {
- webView.clearHistory();
- }
-
- @Override
- public boolean canGoBack() {
- return webView.canGoBack();
- }
-
- /**
- * Go to previous page in history. (We manage our own history)
- *
- * @return true if we went back, false if we are already at top
- */
- @Override
- public boolean goBack() {
- // Check webview first to see if there is a history
- // This is needed to support curPage#diffLink, since they are added to parentEngine's history, but not our history url array (JQMobile behavior)
- if (webView.canGoBack()) {
- webView.goBack();
- return true;
- }
- return false;
- }
-
- @Override
- public void setPaused(boolean value) {
- if (value) {
- webView.onPause();
- webView.pauseTimers();
- } else {
- webView.onResume();
- webView.resumeTimers();
- }
- }
-
- @Override
- public void destroy() {
- webView.chromeClient.destroyLastDialog();
- webView.destroy();
- // unregister the receiver
- if (receiver != null) {
- try {
- webView.getContext().unregisterReceiver(receiver);
- } catch (Exception e) {
- LOG.e(TAG, "Error unregistering configuration receiver: " + e.getMessage(), e);
- }
- }
- }
-
- @Override
- public 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");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/android.json
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/android.json b/spec-plugman/projects/android/android.json
deleted file mode 100644
index b48014e..0000000
--- a/spec-plugman/projects/android/android.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "prepare_queue": {
- "installed": [],
- "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
- }
- ]
- }
- }
- }
- },
- "installed_plugins": {
- "cordova-plugin-whitelist": {
- "PACKAGE_NAME": "io.cordova.hellocordova"
- }
- },
- "dependent_plugins": {},
- "modules": [],
- "plugin_metadata": {
- "cordova-plugin-whitelist": "1.3.2"
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/assets/www/cordova-js-src/android/nativeapiprovider.js
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/assets/www/cordova-js-src/android/nativeapiprovider.js b/spec-plugman/projects/android/assets/www/cordova-js-src/android/nativeapiprovider.js
deleted file mode 100644
index 2e9aa67..0000000
--- a/spec-plugman/projects/android/assets/www/cordova-js-src/android/nativeapiprovider.js
+++ /dev/null
@@ -1,36 +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.
-*/
-
-/**
- * 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;
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/assets/www/cordova-js-src/android/promptbasednativeapi.js
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/assets/www/cordova-js-src/android/promptbasednativeapi.js b/spec-plugman/projects/android/assets/www/cordova-js-src/android/promptbasednativeapi.js
deleted file mode 100644
index f7fb6bc..0000000
--- a/spec-plugman/projects/android/assets/www/cordova-js-src/android/promptbasednativeapi.js
+++ /dev/null
@@ -1,35 +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.
-*/
-
-/**
- * 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);
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/assets/www/cordova-js-src/exec.js
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/assets/www/cordova-js-src/exec.js b/spec-plugman/projects/android/assets/www/cordova-js-src/exec.js
deleted file mode 100644
index f73d87a..0000000
--- a/spec-plugman/projects/android/assets/www/cordova-js-src/exec.js
+++ /dev/null
@@ -1,297 +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.
- *
-*/
-
-/**
- * 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;
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/assets/www/cordova-js-src/platform.js
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/assets/www/cordova-js-src/platform.js b/spec-plugman/projects/android/assets/www/cordova-js-src/platform.js
deleted file mode 100644
index 2bfd024..0000000
--- a/spec-plugman/projects/android/assets/www/cordova-js-src/platform.js
+++ /dev/null
@@ -1,125 +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.
- *
-*/
-
-// 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);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/d164a88f/spec-plugman/projects/android/assets/www/cordova-js-src/plugin/android/app.js
----------------------------------------------------------------------
diff --git a/spec-plugman/projects/android/assets/www/cordova-js-src/plugin/android/app.js b/spec-plugman/projects/android/assets/www/cordova-js-src/plugin/android/app.js
deleted file mode 100644
index 22cf96e..0000000
--- a/spec-plugman/projects/android/assets/www/cordova-js-src/plugin/android/app.js
+++ /dev/null
@@ -1,108 +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 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", []);
- }
-};
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cordova.apache.org
For additional commands, e-mail: commits-help@cordova.apache.org