/* * Copyright (C) 2006 The Android Open Source Project * * 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 * * 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 android.webkit; import android.annotation.Widget; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ClipboardManager; import android.content.ComponentCallbacks2; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DrawFilter; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Picture; import android.graphics.Point; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.graphics.RegionIterator; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.net.Proxy; import android.net.ProxyProperties; import android.net.Uri; import android.net.http.SslCertificate; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.StrictMode; import android.provider.Settings; import android.speech.tts.TextToSpeech; import android.util.AttributeSet; import android.util.EventLog; import android.util.Log; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.HardwareCanvas; import android.view.InputDevice; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.webkit.WebTextView.AutoCompleteAdapter; import android.webkit.WebViewCore.DrawData; import android.webkit.WebViewCore.EventHub; import android.webkit.WebViewCore.TouchEventData; import android.webkit.WebViewCore.TouchHighlightData; import android.widget.AbsoluteLayout; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.CheckedTextView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.OverScroller; import android.widget.Toast; import junit.framework.Assert; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

A View that displays web pages. This class is the basis upon which you * can roll your own web browser or simply display some online content within your Activity. * It uses the WebKit rendering engine to display * web pages and includes methods to navigate forward and backward * through a history, zoom in and out, perform text searches and more.

*

To enable the built-in zoom, set * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} * (introduced in API version 3). *

Note that, in order for your Activity to access the Internet and load web pages * in a WebView, you must add the {@code INTERNET} permissions to your * Android Manifest file:

*
<uses-permission android:name="android.permission.INTERNET" />
* *

This must be a child of the {@code } * element.

* *

See the Web View * tutorial.

* *

Basic usage

* *

By default, a WebView provides no browser-like widgets, does not * enable JavaScript and web page errors are ignored. If your goal is only * to display some HTML as a part of your UI, this is probably fine; * the user won't need to interact with the web page beyond reading * it, and the web page won't need to interact with the user. If you * actually want a full-blown web browser, then you probably want to * invoke the Browser application with a URL Intent rather than show it * with a WebView. For example: *

 * Uri uri = Uri.parse("http://www.example.com");
 * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 * startActivity(intent);
 * 
*

See {@link android.content.Intent} for more information.

* *

To provide a WebView in your own Activity, include a {@code } in your layout, * or set the entire Activity window as a WebView during {@link * android.app.Activity#onCreate(Bundle) onCreate()}:

*
 * WebView webview = new WebView(this);
 * setContentView(webview);
 * 
* *

Then load the desired web page:

*
 * // Simplest usage: note that an exception will NOT be thrown
 * // if there is an error loading this page (see below).
 * webview.loadUrl("http://slashdot.org/");
 *
 * // OR, you can also load from an HTML string:
 * String summary = "<html><body>You scored <b>192</b> points.</body></html>";
 * webview.loadData(summary, "text/html", null);
 * // ... although note that there are restrictions on what this HTML can do.
 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
 * 
* *

A WebView has several customization points where you can add your * own behavior. These are:

* * * *

Here's a more complicated example, showing error handling, * settings, and progress notification:

* *
 * // Let's display the progress in the activity title bar, like the
 * // browser app does.
 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
 *
 * webview.getSettings().setJavaScriptEnabled(true);
 *
 * final Activity activity = this;
 * webview.setWebChromeClient(new WebChromeClient() {
 *   public void onProgressChanged(WebView view, int progress) {
 *     // Activities and WebViews measure progress with different scales.
 *     // The progress meter will automatically disappear when we reach 100%
 *     activity.setProgress(progress * 1000);
 *   }
 * });
 * webview.setWebViewClient(new WebViewClient() {
 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
 *   }
 * });
 *
 * webview.loadUrl("http://slashdot.org/");
 * 
* *

Cookie and window management

* *

For obvious security reasons, your application has its own * cache, cookie store etc.—it does not share the Browser * application's data. Cookies are managed on a separate thread, so * operations like index building don't block the UI * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} * if you want to use cookies in your application. *

* *

By default, requests by the HTML to open new windows are * ignored. This is true whether they be opened by JavaScript or by * the target attribute on a link. You can customize your * {@link WebChromeClient} to provide your own behaviour for opening multiple windows, * and render them in whatever manner you want.

* *

The standard behavior for an Activity is to be destroyed and * recreated when the device orientation or any other configuration changes. This will cause * the WebView to reload the current page. If you don't want that, you * can set your Activity to handle the {@code orientation} and {@code keyboardHidden} * changes, and then just leave the WebView alone. It'll automatically * re-orient itself as appropriate. Read Handling Runtime Changes for * more information about how to handle configuration changes during runtime.

* * *

Building web pages to support different screen densities

* *

The screen density of a device is based on the screen resolution. A screen with low density * has fewer available pixels per inch, where a screen with high density * has more — sometimes significantly more — pixels per inch. The density of a * screen is important because, other things being equal, a UI element (such as a button) whose * height and width are defined in terms of screen pixels will appear larger on the lower density * screen and smaller on the higher density screen. * For simplicity, Android collapses all actual screen densities into three generalized densities: * high, medium, and low.

*

By default, WebView scales a web page so that it is drawn at a size that matches the default * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels * are bigger). * Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help * you (as a web developer) target screens with different screen densities.

*

Here's a summary of the features you can use to handle different screen densities:

* *

If you want to modify your web page for different densities, by using the {@code * -webkit-device-pixel-ratio} CSS media query and/or the {@code * window.devicePixelRatio} DOM property, then you should set the {@code target-densitydpi} meta * property to {@code device-dpi}. This stops Android from performing scaling in your web page and * allows you to make the necessary adjustments for each density via CSS and JavaScript.

* * */ @Widget public class WebView extends AbsoluteLayout implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListener { private class InnerGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener { public void onGlobalLayout() { if (isShown()) { setGLRectViewport(); } } } private class InnerScrollChangedListener implements ViewTreeObserver.OnScrollChangedListener { public void onScrollChanged() { if (isShown()) { setGLRectViewport(); } } } // The listener to capture global layout change event. private InnerGlobalLayoutListener mGlobalLayoutListener = null; // The listener to capture scroll event. private InnerScrollChangedListener mScrollChangedListener = null; // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing // the screen all-the-time. Good for profiling our drawing code static private final boolean AUTO_REDRAW_HACK = false; // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK private boolean mAutoRedraw; // Reference to the AlertDialog displayed by InvokeListBox. // It's used to dismiss the dialog in destroy if not done before. private AlertDialog mListBoxDialog = null; static final String LOGTAG = "webview"; private ZoomManager mZoomManager; private final Rect mGLRectViewport = new Rect(); private final Rect mViewRectViewport = new Rect(); private boolean mGLViewportEmpty = false; /** * Transportation object for returning WebView across thread boundaries. */ public class WebViewTransport { private WebView mWebview; /** * Set the WebView to the transportation object. * @param webview The WebView to transport. */ public synchronized void setWebView(WebView webview) { mWebview = webview; } /** * Return the WebView object. * @return WebView The transported WebView object. */ public synchronized WebView getWebView() { return mWebview; } } private static class OnTrimMemoryListener implements ComponentCallbacks2 { private static OnTrimMemoryListener sInstance = null; static void init(Context c) { if (sInstance == null) { sInstance = new OnTrimMemoryListener(c.getApplicationContext()); } } private OnTrimMemoryListener(Context c) { c.registerComponentCallbacks(this); } @Override public void onConfigurationChanged(Configuration newConfig) { // Ignore } @Override public void onLowMemory() { // Ignore } @Override public void onTrimMemory(int level) { if (DebugFlags.WEB_VIEW) { Log.d("WebView", "onTrimMemory: " + level); } WebView.nativeOnTrimMemory(level); } } // A final CallbackProxy shared by WebViewCore and BrowserFrame. private final CallbackProxy mCallbackProxy; private final WebViewDatabase mDatabase; // SSL certificate for the main top-level page (if secure) private SslCertificate mCertificate; // Native WebView pointer that is 0 until the native object has been // created. private int mNativeClass; // This would be final but it needs to be set to null when the WebView is // destroyed. private WebViewCore mWebViewCore; // Handler for dispatching UI messages. /* package */ final Handler mPrivateHandler = new PrivateHandler(); private WebTextView mWebTextView; // Used to ignore changes to webkit text that arrives to the UI side after // more key events. private int mTextGeneration; /* package */ void incrementTextGeneration() { mTextGeneration++; } // Used by WebViewCore to create child views. /* package */ final ViewManager mViewManager; // Used to display in full screen mode PluginFullScreenHolder mFullScreenHolder; /** * Position of the last touch event in pixels. * Use integer to prevent loss of dragging delta calculation accuracy; * which was done in float and converted to integer, and resulted in gradual * and compounding touch position and view dragging mismatch. */ private int mLastTouchX; private int mLastTouchY; private int mStartTouchX; private int mStartTouchY; private float mAverageAngle; /** * Time of the last touch event. */ private long mLastTouchTime; /** * Time of the last time sending touch event to WebViewCore */ private long mLastSentTouchTime; /** * The minimum elapsed time before sending another ACTION_MOVE event to * WebViewCore. This really should be tuned for each type of the devices. * For example in Google Map api test case, it takes Dream device at least * 150ms to do a full cycle in the WebViewCore by processing a touch event, * triggering the layout and drawing the picture. While the same process * takes 60+ms on the current high speed device. If we make * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent * to WebViewCore queue and the real layout and draw events will be pushed * to further, which slows down the refresh rate. Choose 50 to favor the * current high speed devices. For Dream like devices, 100 is a better * choice. Maybe make this in the buildspec later. * (Update 12/14/2010: changed to 0 since current device should be able to * handle the raw events and Map team voted to have the raw events too. */ private static final int TOUCH_SENT_INTERVAL = 0; private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL; /** * Helper class to get velocity for fling */ VelocityTracker mVelocityTracker; private int mMaximumFling; private float mLastVelocity; private float mLastVelX; private float mLastVelY; // The id of the native layer being scrolled. private int mScrollingLayer; private Rect mScrollingLayerRect = new Rect(); // only trigger accelerated fling if the new velocity is at least // MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION times of the previous velocity private static final float MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION = 0.2f; /** * Touch mode */ private int mTouchMode = TOUCH_DONE_MODE; private static final int TOUCH_INIT_MODE = 1; private static final int TOUCH_DRAG_START_MODE = 2; private static final int TOUCH_DRAG_MODE = 3; private static final int TOUCH_SHORTPRESS_START_MODE = 4; private static final int TOUCH_SHORTPRESS_MODE = 5; private static final int TOUCH_DOUBLE_TAP_MODE = 6; private static final int TOUCH_DONE_MODE = 7; private static final int TOUCH_PINCH_DRAG = 8; private static final int TOUCH_DRAG_LAYER_MODE = 9; // Whether to forward the touch events to WebCore // Can only be set by WebKit via JNI. private boolean mForwardTouchEvents = false; // Whether to prevent default during touch. The initial value depends on // mForwardTouchEvents. If WebCore wants all the touch events, it says yes // for touch down. Otherwise UI will wait for the answer of the first // confirmed move before taking over the control. private static final int PREVENT_DEFAULT_NO = 0; private static final int PREVENT_DEFAULT_MAYBE_YES = 1; private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2; private static final int PREVENT_DEFAULT_YES = 3; private static final int PREVENT_DEFAULT_IGNORE = 4; private int mPreventDefault = PREVENT_DEFAULT_IGNORE; // true when the touch movement exceeds the slop private boolean mConfirmMove; // if true, touch events will be first processed by WebCore, if prevent // default is not set, the UI will continue handle them. private boolean mDeferTouchProcess; // to avoid interfering with the current touch events, track them // separately. Currently no snapping or fling in the deferred process mode private int mDeferTouchMode = TOUCH_DONE_MODE; private float mLastDeferTouchX; private float mLastDeferTouchY; // To keep track of whether the current drag was initiated by a WebTextView, // so that we know not to hide the cursor boolean mDragFromTextInput; // Whether or not to draw the cursor ring. private boolean mDrawCursorRing = true; // true if onPause has been called (and not onResume) private boolean mIsPaused; private HitTestResult mInitialHitTestResult; /** * Customizable constant */ // pre-computed square of ViewConfiguration.getScaledTouchSlop() private int mTouchSlopSquare; // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop() private int mDoubleTapSlopSquare; // pre-computed density adjusted navigation slop private int mNavSlop; // This should be ViewConfiguration.getTapTimeout() // But system time out is 100ms, which is too short for the browser. // In the browser, if it switches out of tap too soon, jump tap won't work. // In addition, a double tap on a trackpad will always have a duration of // 300ms, so this value must be at least that (otherwise we will timeout the // first tap and convert it to a long press). private static final int TAP_TIMEOUT = 300; // This should be ViewConfiguration.getLongPressTimeout() // But system time out is 500ms, which is too short for the browser. // With a short timeout, it's difficult to treat trigger a short press. private static final int LONG_PRESS_TIMEOUT = 1000; // needed to avoid flinging after a pause of no movement private static final int MIN_FLING_TIME = 250; // draw unfiltered after drag is held without movement private static final int MOTIONLESS_TIME = 100; // The amount of content to overlap between two screens when going through // pages with the space bar, in pixels. private static final int PAGE_SCROLL_OVERLAP = 24; /** * These prevent calling requestLayout if either dimension is fixed. This * depends on the layout parameters and the measure specs. */ boolean mWidthCanMeasure; boolean mHeightCanMeasure; // Remember the last dimensions we sent to the native side so we can avoid // sending the same dimensions more than once. int mLastWidthSent; int mLastHeightSent; // Since view height sent to webkit could be fixed to avoid relayout, this // value records the last sent actual view height. int mLastActualHeightSent; private int mContentWidth; // cache of value from WebViewCore private int mContentHeight; // cache of value from WebViewCore // Need to have the separate control for horizontal and vertical scrollbar // style than the View's single scrollbar style private boolean mOverlayHorizontalScrollbar = true; private boolean mOverlayVerticalScrollbar = false; // our standard speed. this way small distances will be traversed in less // time than large distances, but we cap the duration, so that very large // distances won't take too long to get there. private static final int STD_SPEED = 480; // pixels per second // time for the longest scroll animation private static final int MAX_DURATION = 750; // milliseconds private static final int SLIDE_TITLE_DURATION = 500; // milliseconds // Used by OverScrollGlow OverScroller mScroller; private boolean mInOverScrollMode = false; private static Paint mOverScrollBackground; private static Paint mOverScrollBorder; private boolean mWrapContent; private static final int MOTIONLESS_FALSE = 0; private static final int MOTIONLESS_PENDING = 1; private static final int MOTIONLESS_TRUE = 2; private static final int MOTIONLESS_IGNORE = 3; private int mHeldMotionless; // An instance for injecting accessibility in WebViews with disabled // JavaScript or ones for which no accessibility script exists private AccessibilityInjector mAccessibilityInjector; // flag indicating if accessibility script is injected so we // know to handle Shift and arrows natively first private boolean mAccessibilityScriptInjected; static final boolean USE_JAVA_TEXT_SELECTION = true; private Region mTextSelectionRegion = new Region(); private Paint mTextSelectionPaint; private Drawable mSelectHandleLeft; private Drawable mSelectHandleRight; static final boolean USE_WEBKIT_RINGS = false; // the color used to highlight the touch rectangles private static final int HIGHLIGHT_COLOR = 0x6633b5e5; // the round corner for the highlight path private static final float TOUCH_HIGHLIGHT_ARC = 5.0f; // the region indicating where the user touched on the screen private Region mTouchHighlightRegion = new Region(); // the paint for the touch highlight private Paint mTouchHightlightPaint; // debug only private static final boolean DEBUG_TOUCH_HIGHLIGHT = true; private static final int TOUCH_HIGHLIGHT_ELAPSE_TIME = 2000; private Paint mTouchCrossHairColor; private int mTouchHighlightX; private int mTouchHighlightY; private long mTouchHighlightRequested; // Basically this proxy is used to tell the Video to update layer tree at // SetBaseLayer time and to pause when WebView paused. private HTML5VideoViewProxy mHTML5VideoViewProxy; // If we are using a set picture, don't send view updates to webkit private boolean mBlockWebkitViewMessages = false; // cached value used to determine if we need to switch drawing models private boolean mHardwareAccelSkia = false; /* * Private message ids */ private static final int REMEMBER_PASSWORD = 1; private static final int NEVER_REMEMBER_PASSWORD = 2; private static final int SWITCH_TO_SHORTPRESS = 3; private static final int SWITCH_TO_LONGPRESS = 4; private static final int RELEASE_SINGLE_TAP = 5; private static final int REQUEST_FORM_DATA = 6; private static final int RESUME_WEBCORE_PRIORITY = 7; private static final int DRAG_HELD_MOTIONLESS = 8; private static final int AWAKEN_SCROLL_BARS = 9; private static final int PREVENT_DEFAULT_TIMEOUT = 10; private static final int SCROLL_SELECT_TEXT = 11; private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD; private static final int LAST_PRIVATE_MSG_ID = SCROLL_SELECT_TEXT; /* * Package message ids */ static final int SCROLL_TO_MSG_ID = 101; static final int NEW_PICTURE_MSG_ID = 105; static final int UPDATE_TEXT_ENTRY_MSG_ID = 106; static final int WEBCORE_INITIALIZED_MSG_ID = 107; static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 108; static final int UPDATE_ZOOM_RANGE = 109; static final int UNHANDLED_NAV_KEY = 110; static final int CLEAR_TEXT_ENTRY = 111; static final int UPDATE_TEXT_SELECTION_MSG_ID = 112; static final int SHOW_RECT_MSG_ID = 113; static final int LONG_PRESS_CENTER = 114; static final int PREVENT_TOUCH_ID = 115; static final int WEBCORE_NEED_TOUCH_EVENTS = 116; // obj=Rect in doc coordinates static final int INVAL_RECT_MSG_ID = 117; static final int REQUEST_KEYBOARD = 118; static final int DO_MOTION_UP = 119; static final int SHOW_FULLSCREEN = 120; static final int HIDE_FULLSCREEN = 121; static final int DOM_FOCUS_CHANGED = 122; static final int REPLACE_BASE_CONTENT = 123; static final int FORM_DID_BLUR = 124; static final int RETURN_LABEL = 125; static final int FIND_AGAIN = 126; static final int CENTER_FIT_RECT = 127; static final int REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID = 128; static final int SET_SCROLLBAR_MODES = 129; static final int SELECTION_STRING_CHANGED = 130; static final int SET_TOUCH_HIGHLIGHT_RECTS = 131; static final int SAVE_WEBARCHIVE_FINISHED = 132; static final int SET_AUTOFILLABLE = 133; static final int AUTOFILL_COMPLETE = 134; static final int SELECT_AT = 135; static final int SCREEN_ON = 136; static final int ENTER_FULLSCREEN_VIDEO = 137; static final int UPDATE_SELECTION = 138; private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID; private static final int LAST_PACKAGE_MSG_ID = SET_TOUCH_HIGHLIGHT_RECTS; static final String[] HandlerPrivateDebugString = { "REMEMBER_PASSWORD", // = 1; "NEVER_REMEMBER_PASSWORD", // = 2; "SWITCH_TO_SHORTPRESS", // = 3; "SWITCH_TO_LONGPRESS", // = 4; "RELEASE_SINGLE_TAP", // = 5; "REQUEST_FORM_DATA", // = 6; "RESUME_WEBCORE_PRIORITY", // = 7; "DRAG_HELD_MOTIONLESS", // = 8; "AWAKEN_SCROLL_BARS", // = 9; "PREVENT_DEFAULT_TIMEOUT", // = 10; "SCROLL_SELECT_TEXT" // = 11; }; static final String[] HandlerPackageDebugString = { "SCROLL_TO_MSG_ID", // = 101; "102", // = 102; "103", // = 103; "104", // = 104; "NEW_PICTURE_MSG_ID", // = 105; "UPDATE_TEXT_ENTRY_MSG_ID", // = 106; "WEBCORE_INITIALIZED_MSG_ID", // = 107; "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 108; "UPDATE_ZOOM_RANGE", // = 109; "UNHANDLED_NAV_KEY", // = 110; "CLEAR_TEXT_ENTRY", // = 111; "UPDATE_TEXT_SELECTION_MSG_ID", // = 112; "SHOW_RECT_MSG_ID", // = 113; "LONG_PRESS_CENTER", // = 114; "PREVENT_TOUCH_ID", // = 115; "WEBCORE_NEED_TOUCH_EVENTS", // = 116; "INVAL_RECT_MSG_ID", // = 117; "REQUEST_KEYBOARD", // = 118; "DO_MOTION_UP", // = 119; "SHOW_FULLSCREEN", // = 120; "HIDE_FULLSCREEN", // = 121; "DOM_FOCUS_CHANGED", // = 122; "REPLACE_BASE_CONTENT", // = 123; "FORM_DID_BLUR", // = 124; "RETURN_LABEL", // = 125; "FIND_AGAIN", // = 126; "CENTER_FIT_RECT", // = 127; "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128; "SET_SCROLLBAR_MODES", // = 129; "SELECTION_STRING_CHANGED", // = 130; "SET_TOUCH_HIGHLIGHT_RECTS", // = 131; "SAVE_WEBARCHIVE_FINISHED", // = 132; "SET_AUTOFILLABLE", // = 133; "AUTOFILL_COMPLETE", // = 134; "SELECT_AT", // = 135; "SCREEN_ON", // = 136; "ENTER_FULLSCREEN_VIDEO" // = 137; }; // If the site doesn't use the viewport meta tag to specify the viewport, // use DEFAULT_VIEWPORT_WIDTH as the default viewport width static final int DEFAULT_VIEWPORT_WIDTH = 980; // normally we try to fit the content to the minimum preferred width // calculated by the Webkit. To avoid the bad behavior when some site's // minimum preferred width keeps growing when changing the viewport width or // the minimum preferred width is huge, an upper limit is needed. static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH; // initial scale in percent. 0 means using default. private int mInitialScaleInPercent = 0; // Whether or not a scroll event should be sent to webkit. This is only set // to false when restoring the scroll position. private boolean mSendScrollEvent = true; private int mSnapScrollMode = SNAP_NONE; private static final int SNAP_NONE = 0; private static final int SNAP_LOCK = 1; // not a separate state private static final int SNAP_X = 2; // may be combined with SNAP_LOCK private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK private boolean mSnapPositive; // keep these in sync with their counterparts in WebView.cpp private static final int DRAW_EXTRAS_NONE = 0; private static final int DRAW_EXTRAS_FIND = 1; private static final int DRAW_EXTRAS_SELECTION = 2; private static final int DRAW_EXTRAS_CURSOR_RING = 3; // keep this in sync with WebCore:ScrollbarMode in WebKit private static final int SCROLLBAR_AUTO = 0; private static final int SCROLLBAR_ALWAYSOFF = 1; // as we auto fade scrollbar, this is ignored. private static final int SCROLLBAR_ALWAYSON = 2; private int mHorizontalScrollBarMode = SCROLLBAR_AUTO; private int mVerticalScrollBarMode = SCROLLBAR_AUTO; // constants for determining script injection strategy private static final int ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED = -1; private static final int ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT = 0; private static final int ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED = 1; // the alias via which accessibility JavaScript interface is exposed private static final String ALIAS_ACCESSIBILITY_JS_INTERFACE = "accessibility"; // JavaScript to inject the script chooser which will // pick the right script for the current URL private static final String ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT = "javascript:(function() {" + " var chooser = document.createElement('script');" + " chooser.type = 'text/javascript';" + " chooser.src = 'https://ssl.gstatic.com/accessibility/javascript/android/AndroidScriptChooser.user.js';" + " document.getElementsByTagName('head')[0].appendChild(chooser);" + " })();"; // Regular expression that matches the "axs" URL parameter. // The value of 0 means the accessibility script is opted out // The value of 1 means the accessibility script is already injected private static final String PATTERN_MATCH_AXS_URL_PARAMETER = "(\\?axs=(0|1))|(&axs=(0|1))"; // TextToSpeech instance exposed to JavaScript to the injected screenreader. private TextToSpeech mTextToSpeech; // variable to cache the above pattern in case accessibility is enabled. private Pattern mMatchAxsUrlParameterPattern; /** * Max distance to overscroll by in pixels. * This how far content can be pulled beyond its normal bounds by the user. */ private int mOverscrollDistance; /** * Max distance to overfling by in pixels. * This is how far flinged content can move beyond the end of its normal bounds. */ private int mOverflingDistance; private OverScrollGlow mOverScrollGlow; // Used to match key downs and key ups private Vector mKeysPressed; /* package */ static boolean mLogEvent = true; // for event log private long mLastTouchUpTime = 0; private WebViewCore.AutoFillData mAutoFillData; private static boolean sNotificationsEnabled = true; /** * URI scheme for telephone number */ public static final String SCHEME_TEL = "tel:"; /** * URI scheme for email address */ public static final String SCHEME_MAILTO = "mailto:"; /** * URI scheme for map address */ public static final String SCHEME_GEO = "geo:0,0?q="; private int mBackgroundColor = Color.WHITE; private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second private int mAutoScrollX = 0; private int mAutoScrollY = 0; private int mMinAutoScrollX = 0; private int mMaxAutoScrollX = 0; private int mMinAutoScrollY = 0; private int mMaxAutoScrollY = 0; private Rect mScrollingLayerBounds = new Rect(); private boolean mSentAutoScrollMessage = false; // used for serializing asynchronously handled touch events. private final TouchEventQueue mTouchEventQueue = new TouchEventQueue(); // Used to track whether picture updating was paused due to a window focus change. private boolean mPictureUpdatePausedForFocusChange = false; // Used to notify listeners of a new picture. private PictureListener mPictureListener; /** * Interface to listen for new pictures as they change. * @deprecated This interface is now obsolete. */ @Deprecated public interface PictureListener { /** * Notify the listener that the picture has changed. * @param view The WebView that owns the picture. * @param picture The new picture. * @deprecated This method is now obsolete. */ @Deprecated public void onNewPicture(WebView view, Picture picture); } // FIXME: Want to make this public, but need to change the API file. public /*static*/ class HitTestResult { /** * Default HitTestResult, where the target is unknown */ public static final int UNKNOWN_TYPE = 0; /** * @deprecated This type is no longer used. */ @Deprecated public static final int ANCHOR_TYPE = 1; /** * HitTestResult for hitting a phone number */ public static final int PHONE_TYPE = 2; /** * HitTestResult for hitting a map address */ public static final int GEO_TYPE = 3; /** * HitTestResult for hitting an email address */ public static final int EMAIL_TYPE = 4; /** * HitTestResult for hitting an HTML::img tag */ public static final int IMAGE_TYPE = 5; /** * @deprecated This type is no longer used. */ @Deprecated public static final int IMAGE_ANCHOR_TYPE = 6; /** * HitTestResult for hitting a HTML::a tag with src=http */ public static final int SRC_ANCHOR_TYPE = 7; /** * HitTestResult for hitting a HTML::a tag with src=http + HTML::img */ public static final int SRC_IMAGE_ANCHOR_TYPE = 8; /** * HitTestResult for hitting an edit text area */ public static final int EDIT_TEXT_TYPE = 9; private int mType; private String mExtra; HitTestResult() { mType = UNKNOWN_TYPE; } private void setType(int type) { mType = type; } private void setExtra(String extra) { mExtra = extra; } public int getType() { return mType; } public String getExtra() { return mExtra; } } /** * Construct a new WebView with a Context object. * @param context A Context object used to access application assets. */ public WebView(Context context) { this(context, null); } /** * Construct a new WebView with layout parameters. * @param context A Context object used to access application assets. * @param attrs An AttributeSet passed to our parent. */ public WebView(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.webViewStyle); } /** * Construct a new WebView with layout parameters and a default style. * @param context A Context object used to access application assets. * @param attrs An AttributeSet passed to our parent. * @param defStyle The default style resource ID. */ public WebView(Context context, AttributeSet attrs, int defStyle) { this(context, attrs, defStyle, false); } /** * Construct a new WebView with layout parameters and a default style. * @param context A Context object used to access application assets. * @param attrs An AttributeSet passed to our parent. * @param defStyle The default style resource ID. */ public WebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) { this(context, attrs, defStyle, null, privateBrowsing); } /** * Construct a new WebView with layout parameters, a default style and a set * of custom Javscript interfaces to be added to the WebView at initialization * time. This guarantees that these interfaces will be available when the JS * context is initialized. * @param context A Context object used to access application assets. * @param attrs An AttributeSet passed to our parent. * @param defStyle The default style resource ID. * @param javaScriptInterfaces is a Map of interface names, as keys, and * object implementing those interfaces, as values. * @hide pending API council approval. */ protected WebView(Context context, AttributeSet attrs, int defStyle, Map javaScriptInterfaces, boolean privateBrowsing) { super(context, attrs, defStyle); checkThread(); if (context == null) { throw new IllegalArgumentException("Invalid context argument"); } // Used by the chrome stack to find application paths JniUtil.setContext(context); mCallbackProxy = new CallbackProxy(context, this); mViewManager = new ViewManager(this); L10nUtils.setApplicationContext(context.getApplicationContext()); mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javaScriptInterfaces); mDatabase = WebViewDatabase.getInstance(context); mScroller = new OverScroller(context, null, 0, 0, false); //TODO Use OverScroller's flywheel mZoomManager = new ZoomManager(this, mCallbackProxy); /* The init method must follow the creation of certain member variables, * such as the mZoomManager. */ init(); setupPackageListener(context); setupProxyListener(context); updateMultiTouchSupport(context); if (privateBrowsing) { startPrivateBrowsing(); } mAutoFillData = new WebViewCore.AutoFillData(); } private static class ProxyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) { handleProxyBroadcast(intent); } } } /* * Receiver for PROXY_CHANGE_ACTION, will be null when it is not added handling broadcasts. */ private static ProxyReceiver sProxyReceiver; /* * @param context This method expects this to be a valid context */ private static synchronized void setupProxyListener(Context context) { if (sProxyReceiver != null || sNotificationsEnabled == false) { return; } IntentFilter filter = new IntentFilter(); filter.addAction(Proxy.PROXY_CHANGE_ACTION); sProxyReceiver = new ProxyReceiver(); Intent currentProxy = context.getApplicationContext().registerReceiver( sProxyReceiver, filter); if (currentProxy != null) { handleProxyBroadcast(currentProxy); } } /* * @param context This method expects this to be a valid context */ private static synchronized void disableProxyListener(Context context) { if (sProxyReceiver == null) return; context.getApplicationContext().unregisterReceiver(sProxyReceiver); sProxyReceiver = null; } private static void handleProxyBroadcast(Intent intent) { ProxyProperties proxyProperties = (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO); if (proxyProperties == null || proxyProperties.getHost() == null) { WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, null); return; } WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, proxyProperties); } /* * A variable to track if there is a receiver added for ACTION_PACKAGE_ADDED * or ACTION_PACKAGE_REMOVED. */ private static boolean sPackageInstallationReceiverAdded = false; /* * A set of Google packages we monitor for the * navigator.isApplicationInstalled() API. Add additional packages as * needed. */ private static Set sGoogleApps; static { sGoogleApps = new HashSet(); sGoogleApps.add("com.google.android.youtube"); } private static class PackageListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } if (sGoogleApps.contains(packageName)) { if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { WebViewCore.sendStaticMessage(EventHub.ADD_PACKAGE_NAME, packageName); } else { WebViewCore.sendStaticMessage(EventHub.REMOVE_PACKAGE_NAME, packageName); } } PluginManager pm = PluginManager.getInstance(context); if (pm.containsPluginPermissionAndSignatures(packageName)) { pm.refreshPlugins(Intent.ACTION_PACKAGE_ADDED.equals(action)); } } } private void setupPackageListener(Context context) { /* * we must synchronize the instance check and the creation of the * receiver to ensure that only ONE receiver exists for all WebView * instances. */ synchronized (WebView.class) { // if the receiver already exists then we do not need to register it // again if (sPackageInstallationReceiverAdded) { return; } IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); BroadcastReceiver packageListener = new PackageListener(); context.getApplicationContext().registerReceiver(packageListener, filter); sPackageInstallationReceiverAdded = true; } // check if any of the monitored apps are already installed AsyncTask> task = new AsyncTask>() { @Override protected Set doInBackground(Void... unused) { Set installedPackages = new HashSet(); PackageManager pm = mContext.getPackageManager(); for (String name : sGoogleApps) { try { PackageInfo pInfo = pm.getPackageInfo(name, PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES); installedPackages.add(name); } catch (PackageManager.NameNotFoundException e) { // package not found } } return installedPackages; } // Executes on the UI thread @Override protected void onPostExecute(Set installedPackages) { if (mWebViewCore != null) { mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, installedPackages); } } }; task.execute(); } void updateMultiTouchSupport(Context context) { mZoomManager.updateMultiTouchSupport(context); } private void init() { OnTrimMemoryListener.init(getContext()); setWillNotDraw(false); setFocusable(true); setFocusableInTouchMode(true); setClickable(true); setLongClickable(true); final ViewConfiguration configuration = ViewConfiguration.get(getContext()); int slop = configuration.getScaledTouchSlop(); mTouchSlopSquare = slop * slop; slop = configuration.getScaledDoubleTapSlop(); mDoubleTapSlopSquare = slop * slop; final float density = getContext().getResources().getDisplayMetrics().density; // use one line height, 16 based on our current default font, for how // far we allow a touch be away from the edge of a link mNavSlop = (int) (16 * density); mZoomManager.init(density); mMaximumFling = configuration.getScaledMaximumFlingVelocity(); // Compute the inverse of the density squared. DRAG_LAYER_INVERSE_DENSITY_SQUARED = 1 / (density * density); mOverscrollDistance = configuration.getScaledOverscrollDistance(); mOverflingDistance = configuration.getScaledOverflingDistance(); setScrollBarStyle(super.getScrollBarStyle()); // Initially use a size of two, since the user is likely to only hold // down two keys at a time (shift + another key) mKeysPressed = new Vector(2); mHTML5VideoViewProxy = null ; } @Override public boolean shouldDelayChildPressedState() { return true; } /** * Adds accessibility APIs to JavaScript. * * Note: This method is responsible to performing the necessary * check if the accessibility APIs should be exposed. */ private void addAccessibilityApisToJavaScript() { if (AccessibilityManager.getInstance(mContext).isEnabled() && getSettings().getJavaScriptEnabled()) { // exposing the TTS for now ... mTextToSpeech = new TextToSpeech(getContext(), null); addJavascriptInterface(mTextToSpeech, ALIAS_ACCESSIBILITY_JS_INTERFACE); } } /** * Removes accessibility APIs from JavaScript. */ private void removeAccessibilityApisFromJavaScript() { // exposing the TTS for now ... if (mTextToSpeech != null) { removeJavascriptInterface(ALIAS_ACCESSIBILITY_JS_INTERFACE); mTextToSpeech.shutdown(); mTextToSpeech = null; } } @Override public void setOverScrollMode(int mode) { super.setOverScrollMode(mode); if (mode != OVER_SCROLL_NEVER) { if (mOverScrollGlow == null) { mOverScrollGlow = new OverScrollGlow(this); } } else { mOverScrollGlow = null; } } /* package */void updateDefaultZoomDensity(int zoomDensity) { final float density = mContext.getResources().getDisplayMetrics().density * 100 / zoomDensity; mNavSlop = (int) (16 * density); mZoomManager.updateDefaultZoomDensity(density); } /* package */ boolean onSavePassword(String schemePlusHost, String username, String password, final Message resumeMsg) { boolean rVal = false; if (resumeMsg == null) { // null resumeMsg implies saving password silently mDatabase.setUsernamePassword(schemePlusHost, username, password); } else { final Message remember = mPrivateHandler.obtainMessage( REMEMBER_PASSWORD); remember.getData().putString("host", schemePlusHost); remember.getData().putString("username", username); remember.getData().putString("password", password); remember.obj = resumeMsg; final Message neverRemember = mPrivateHandler.obtainMessage( NEVER_REMEMBER_PASSWORD); neverRemember.getData().putString("host", schemePlusHost); neverRemember.getData().putString("username", username); neverRemember.getData().putString("password", password); neverRemember.obj = resumeMsg; new AlertDialog.Builder(getContext()) .setTitle(com.android.internal.R.string.save_password_label) .setMessage(com.android.internal.R.string.save_password_message) .setPositiveButton(com.android.internal.R.string.save_password_notnow, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { resumeMsg.sendToTarget(); } }) .setNeutralButton(com.android.internal.R.string.save_password_remember, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { remember.sendToTarget(); } }) .setNegativeButton(com.android.internal.R.string.save_password_never, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { neverRemember.sendToTarget(); } }) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { resumeMsg.sendToTarget(); } }).show(); // Return true so that WebViewCore will pause while the dialog is // up. rVal = true; } return rVal; } @Override public void setScrollBarStyle(int style) { if (style == View.SCROLLBARS_INSIDE_INSET || style == View.SCROLLBARS_OUTSIDE_INSET) { mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false; } else { mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true; } super.setScrollBarStyle(style); } /** * Specify whether the horizontal scrollbar has overlay style. * @param overlay TRUE if horizontal scrollbar should have overlay style. */ public void setHorizontalScrollbarOverlay(boolean overlay) { checkThread(); mOverlayHorizontalScrollbar = overlay; } /** * Specify whether the vertical scrollbar has overlay style. * @param overlay TRUE if vertical scrollbar should have overlay style. */ public void setVerticalScrollbarOverlay(boolean overlay) { checkThread(); mOverlayVerticalScrollbar = overlay; } /** * Return whether horizontal scrollbar has overlay style * @return TRUE if horizontal scrollbar has overlay style. */ public boolean overlayHorizontalScrollbar() { checkThread(); return mOverlayHorizontalScrollbar; } /** * Return whether vertical scrollbar has overlay style * @return TRUE if vertical scrollbar has overlay style. */ public boolean overlayVerticalScrollbar() { checkThread(); return mOverlayVerticalScrollbar; } /* * Return the width of the view where the content of WebView should render * to. * Note: this can be called from WebCoreThread. */ /* package */ int getViewWidth() { if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { return getWidth(); } else { return Math.max(0, getWidth() - getVerticalScrollbarWidth()); } } /** * returns the height of the titlebarview (if any). Does not care about * scrolling * @hide */ protected int getTitleHeight() { return mTitleBar != null ? mTitleBar.getHeight() : 0; } /** * Return the amount of the titlebarview (if any) that is visible * * @deprecated This method is now obsolete. */ public int getVisibleTitleHeight() { checkThread(); return getVisibleTitleHeightImpl(); } private int getVisibleTitleHeightImpl() { // need to restrict mScrollY due to over scroll return Math.max(getTitleHeight() - Math.max(0, mScrollY), 0); } /* * Return the height of the view where the content of WebView should render * to. Note that this excludes mTitleBar, if there is one. * Note: this can be called from WebCoreThread. */ /* package */ int getViewHeight() { return getViewHeightWithTitle() - getVisibleTitleHeightImpl(); } int getViewHeightWithTitle() { int height = getHeight(); if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) { height -= getHorizontalScrollbarHeight(); } return height; } /** * @return The SSL certificate for the main top-level page or null if * there is no certificate (the site is not secure). */ public SslCertificate getCertificate() { checkThread(); return mCertificate; } /** * Sets the SSL certificate for the main top-level page. */ public void setCertificate(SslCertificate certificate) { checkThread(); if (DebugFlags.WEB_VIEW) { Log.v(LOGTAG, "setCertificate=" + certificate); } // here, the certificate can be null (if the site is not secure) mCertificate = certificate; } //------------------------------------------------------------------------- // Methods called by activity //------------------------------------------------------------------------- /** * Save the username and password for a particular host in the WebView's * internal database. * @param host The host that required the credentials. * @param username The username for the given host. * @param password The password for the given host. */ public void savePassword(String host, String username, String password) { checkThread(); mDatabase.setUsernamePassword(host, username, password); } /** * Set the HTTP authentication credentials for a given host and realm. * * @param host The host for the credentials. * @param realm The realm for the credentials. * @param username The username for the password. If it is null, it means * password can't be saved. * @param password The password */ public void setHttpAuthUsernamePassword(String host, String realm, String username, String password) { checkThread(); mDatabase.setHttpAuthUsernamePassword(host, realm, username, password); } /** * Retrieve the HTTP authentication username and password for a given * host & realm pair * * @param host The host for which the credentials apply. * @param realm The realm for which the credentials apply. * @return String[] if found, String[0] is username, which can be null and * String[1] is password. Return null if it can't find anything. */ public String[] getHttpAuthUsernamePassword(String host, String realm) { checkThread(); return mDatabase.getHttpAuthUsernamePassword(host, realm); } /** * Remove Find or Select ActionModes, if active. */ private void clearActionModes() { if (mSelectCallback != null) { mSelectCallback.finish(); } if (mFindCallback != null) { mFindCallback.finish(); } } /** * Called to clear state when moving from one page to another, or changing * in some other way that makes elements associated with the current page * (such as WebTextView or ActionModes) no longer relevant. */ private void clearHelpers() { clearTextEntry(); clearActionModes(); dismissFullScreenMode(); } /** * Destroy the internal state of the WebView. This method should be called * after the WebView has been removed from the view system. No other * methods may be called on a WebView after destroy. */ public void destroy() { checkThread(); destroyImpl(); } private void destroyImpl() { clearHelpers(); if (mListBoxDialog != null) { mListBoxDialog.dismiss(); mListBoxDialog = null; } if (mNativeClass != 0) nativeStopGL(); if (mWebViewCore != null) { // Set the handlers to null before destroying WebViewCore so no // more messages will be posted. mCallbackProxy.setWebViewClient(null); mCallbackProxy.setWebChromeClient(null); // Tell WebViewCore to destroy itself synchronized (this) { WebViewCore webViewCore = mWebViewCore; mWebViewCore = null; // prevent using partial webViewCore webViewCore.destroy(); } // Remove any pending messages that might not be serviced yet. mPrivateHandler.removeCallbacksAndMessages(null); mCallbackProxy.removeCallbacksAndMessages(null); // Wake up the WebCore thread just in case it is waiting for a // JavaScript dialog. synchronized (mCallbackProxy) { mCallbackProxy.notify(); } } if (mNativeClass != 0) { nativeDestroy(); mNativeClass = 0; } } /** * Enables platform notifications of data state and proxy changes. * Notifications are enabled by default. * * @deprecated This method is now obsolete. */ @Deprecated public static void enablePlatformNotifications() { checkThread(); synchronized (WebView.class) { Network.enablePlatformNotifications(); sNotificationsEnabled = true; Context context = JniUtil.getContext(); if (context != null) setupProxyListener(context); } } /** * Disables platform notifications of data state and proxy changes. * Notifications are enabled by default. * * @deprecated This method is now obsolete. */ @Deprecated public static void disablePlatformNotifications() { checkThread(); synchronized (WebView.class) { Network.disablePlatformNotifications(); sNotificationsEnabled = false; Context context = JniUtil.getContext(); if (context != null) disableProxyListener(context); } } /** * Sets JavaScript engine flags. * * @param flags JS engine flags in a String * * @hide pending API solidification */ public void setJsFlags(String flags) { checkThread(); mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags); } /** * Inform WebView of the network state. This is used to set * the JavaScript property window.navigator.isOnline and * generates the online/offline event as specified in HTML5, sec. 5.7.7 * @param networkUp boolean indicating if network is available */ public void setNetworkAvailable(boolean networkUp) { checkThread(); mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE, networkUp ? 1 : 0, 0); } /** * Inform WebView about the current network type. * {@hide} */ public void setNetworkType(String type, String subtype) { checkThread(); Map map = new HashMap(); map.put("type", type); map.put("subtype", subtype); mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map); } /** * Save the state of this WebView used in * {@link android.app.Activity#onSaveInstanceState}. Please note that this * method no longer stores the display data for this WebView. The previous * behavior could potentially leak files if {@link #restoreState} was never * called. See {@link #savePicture} and {@link #restorePicture} for saving * and restoring the display data. * @param outState The Bundle to store the WebView state. * @return The same copy of the back/forward list used to save the state. If * saveState fails, the returned list will be null. * @see #savePicture * @see #restorePicture */ public WebBackForwardList saveState(Bundle outState) { checkThread(); if (outState == null) { return null; } // We grab a copy of the back/forward list because a client of WebView // may have invalidated the history list by calling clearHistory. WebBackForwardList list = copyBackForwardList(); final int currentIndex = list.getCurrentIndex(); final int size = list.getSize(); // We should fail saving the state if the list is empty or the index is // not in a valid range. if (currentIndex < 0 || currentIndex >= size || size == 0) { return null; } outState.putInt("index", currentIndex); // FIXME: This should just be a byte[][] instead of ArrayList but // Parcel.java does not have the code to handle multi-dimensional // arrays. ArrayList history = new ArrayList(size); for (int i = 0; i < size; i++) { WebHistoryItem item = list.getItemAtIndex(i); if (null == item) { // FIXME: this shouldn't happen // need to determine how item got set to null Log.w(LOGTAG, "saveState: Unexpected null history item."); return null; } byte[] data = item.getFlattenedData(); if (data == null) { // It would be very odd to not have any data for a given history // item. And we will fail to rebuild the history list without // flattened data. return null; } history.add(data); } outState.putSerializable("history", history); if (mCertificate != null) { outState.putBundle("certificate", SslCertificate.saveState(mCertificate)); } outState.putBoolean("privateBrowsingEnabled", isPrivateBrowsingEnabled()); mZoomManager.saveZoomState(outState); return list; } /** * Save the current display data to the Bundle given. Used in conjunction * with {@link #saveState}. * @param b A Bundle to store the display data. * @param dest The file to store the serialized picture data. Will be * overwritten with this WebView's picture data. * @return True if the picture was successfully saved. * @deprecated This method is now obsolete. */ @Deprecated public boolean savePicture(Bundle b, final File dest) { checkThread(); if (dest == null || b == null) { return false; } final Picture p = capturePicture(); // Use a temporary file while writing to ensure the destination file // contains valid data. final File temp = new File(dest.getPath() + ".writing"); new Thread(new Runnable() { public void run() { FileOutputStream out = null; try { out = new FileOutputStream(temp); p.writeToStream(out); // Writing the picture succeeded, rename the temporary file // to the destination. temp.renameTo(dest); } catch (Exception e) { // too late to do anything about it. } finally { if (out != null) { try { out.close(); } catch (Exception e) { // Can't do anything about that } } temp.delete(); } } }).start(); // now update the bundle b.putInt("scrollX", mScrollX); b.putInt("scrollY", mScrollY); mZoomManager.saveZoomState(b); return true; } private void restoreHistoryPictureFields(Picture p, Bundle b) { int sx = b.getInt("scrollX", 0); int sy = b.getInt("scrollY", 0); mDrawHistory = true; mHistoryPicture = p; mScrollX = sx; mScrollY = sy; mZoomManager.restoreZoomState(b); final float scale = mZoomManager.getScale(); mHistoryWidth = Math.round(p.getWidth() * scale); mHistoryHeight = Math.round(p.getHeight() * scale); invalidate(); } /** * Restore the display data that was save in {@link #savePicture}. Used in * conjunction with {@link #restoreState}. * @param b A Bundle containing the saved display data. * @param src The file where the picture data was stored. * @return True if the picture was successfully restored. * @deprecated This method is now obsolete. */ @Deprecated public boolean restorePicture(Bundle b, File src) { checkThread(); if (src == null || b == null) { return false; } if (!src.exists()) { return false; } try { final FileInputStream in = new FileInputStream(src); final Bundle copy = new Bundle(b); new Thread(new Runnable() { public void run() { try { final Picture p = Picture.createFromStream(in); if (p != null) { // Post a runnable on the main thread to update the // history picture fields. mPrivateHandler.post(new Runnable() { public void run() { restoreHistoryPictureFields(p, copy); } }); } } finally { try { in.close(); } catch (Exception e) { // Nothing we can do now. } } } }).start(); } catch (FileNotFoundException e){ e.printStackTrace(); } return true; } /** * Saves the view data to the output stream. The output is highly * version specific, and may not be able to be loaded by newer versions * of WebView. * @param stream The {@link OutputStream} to save to * @return True if saved successfully * @hide */ public boolean saveViewState(OutputStream stream) { try { return ViewStateSerializer.serializeViewState(stream, this); } catch (IOException e) { Log.w(LOGTAG, "Failed to saveViewState", e); } return false; } /** * Loads the view data from the input stream. See * {@link #saveViewState(OutputStream)} for more information. * @param stream The {@link InputStream} to load from * @return True if loaded successfully * @hide */ public boolean loadViewState(InputStream stream) { try { mLoadedPicture = ViewStateSerializer.deserializeViewState(stream, this); mBlockWebkitViewMessages = true; setNewPicture(mLoadedPicture, true); return true; } catch (IOException e) { Log.w(LOGTAG, "Failed to loadViewState", e); } return false; } /** * Clears the view state set with {@link #loadViewState(InputStream)}. * This WebView will then switch to showing the content from webkit * @hide */ public void clearViewState() { mBlockWebkitViewMessages = false; mLoadedPicture = null; invalidate(); } /** * Restore the state of this WebView from the given map used in * {@link android.app.Activity#onRestoreInstanceState}. This method should * be called to restore the state of the WebView before using the object. If * it is called after the WebView has had a chance to build state (load * pages, create a back/forward list, etc.) there may be undesirable * side-effects. Please note that this method no longer restores the * display data for this WebView. See {@link #savePicture} and {@link * #restorePicture} for saving and restoring the display data. * @param inState The incoming Bundle of state. * @return The restored back/forward list or null if restoreState failed. * @see #savePicture * @see #restorePicture */ public WebBackForwardList restoreState(Bundle inState) { checkThread(); WebBackForwardList returnList = null; if (inState == null) { return returnList; } if (inState.containsKey("index") && inState.containsKey("history")) { mCertificate = SslCertificate.restoreState( inState.getBundle("certificate")); final WebBackForwardList list = mCallbackProxy.getBackForwardList(); final int index = inState.getInt("index"); // We can't use a clone of the list because we need to modify the // shared copy, so synchronize instead to prevent concurrent // modifications. synchronized (list) { final List history = (List) inState.getSerializable("history"); final int size = history.size(); // Check the index bounds so we don't crash in native code while // restoring the history index. if (index < 0 || index >= size) { return null; } for (int i = 0; i < size; i++) { byte[] data = history.remove(0); if (data == null) { // If we somehow have null data, we cannot reconstruct // the item and thus our history list cannot be rebuilt. return null; } WebHistoryItem item = new WebHistoryItem(data); list.addHistoryItem(item); } // Grab the most recent copy to return to the caller. returnList = copyBackForwardList(); // Update the copy to have the correct index. returnList.setCurrentIndex(index); } // Restore private browsing setting. if (inState.getBoolean("privateBrowsingEnabled")) { getSettings().setPrivateBrowsingEnabled(true); } mZoomManager.restoreZoomState(inState); // Remove all pending messages because we are restoring previous // state. mWebViewCore.removeMessages(); // Send a restore state message. mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index); } return returnList; } /** * Load the given url with the extra headers. * @param url The url of the resource to load. * @param extraHeaders The extra headers sent with this url. This should not * include the common headers like "user-agent". If it does, it * will be replaced by the intrinsic value of the WebView. */ public void loadUrl(String url, Map extraHeaders) { checkThread(); loadUrlImpl(url, extraHeaders); } private void loadUrlImpl(String url, Map extraHeaders) { switchOutDrawHistory(); WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData(); arg.mUrl = url; arg.mExtraHeaders = extraHeaders; mWebViewCore.sendMessage(EventHub.LOAD_URL, arg); clearHelpers(); } /** * Load the given url. * @param url The url of the resource to load. */ public void loadUrl(String url) { checkThread(); loadUrlImpl(url); } private void loadUrlImpl(String url) { if (url == null) { return; } loadUrlImpl(url, null); } /** * Load the url with postData using "POST" method into the WebView. If url * is not a network url, it will be loaded with {link * {@link #loadUrl(String)} instead. * * @param url The url of the resource to load. * @param postData The data will be passed to "POST" request. */ public void postUrl(String url, byte[] postData) { checkThread(); if (URLUtil.isNetworkUrl(url)) { switchOutDrawHistory(); WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData(); arg.mUrl = url; arg.mPostData = postData; mWebViewCore.sendMessage(EventHub.POST_URL, arg); clearHelpers(); } else { loadUrlImpl(url); } } /** * Load the given data into the WebView using a 'data' scheme URL. *

* Note that JavaScript's same origin policy means that script running in a * page loaded using this method will be unable to access content loaded * using any scheme other than 'data', including 'http(s)'. To avoid this * restriction, use {@link * #loadDataWithBaseURL(String,String,String,String,String) * loadDataWithBaseURL()} with an appropriate base URL. *

* If the value of the encoding parameter is 'base64', then the data must * be encoded as base64. Otherwise, the data must use ASCII encoding for * octets inside the range of safe URL characters and use the standard %xx * hex encoding of URLs for octets outside that range. * @param data A String of data in the given encoding. * @param mimeType The MIMEType of the data, e.g. 'text/html'. * @param encoding The encoding of the data. */ public void loadData(String data, String mimeType, String encoding) { checkThread(); loadDataImpl(data, mimeType, encoding); } private void loadDataImpl(String data, String mimeType, String encoding) { StringBuilder dataUrl = new StringBuilder("data:"); dataUrl.append(mimeType); if ("base64".equals(encoding)) { dataUrl.append(";base64"); } dataUrl.append(","); dataUrl.append(data); loadUrlImpl(dataUrl.toString()); } /** * Load the given data into the WebView, using baseUrl as the base URL for * the content. The base URL is used both to resolve relative URLs and when * applying JavaScript's same origin policy. The historyUrl is used for the * history entry. *

* Note that content specified in this way can access local device files * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'. *

* If the base URL uses the data scheme, this method is equivalent to * calling {@link #loadData(String,String,String) loadData()} and the * historyUrl is ignored. * @param baseUrl URL to use as the page's base URL. If null defaults to * 'about:blank' * @param data A String of data in the given encoding. * @param mimeType The MIMEType of the data, e.g. 'text/html'. If null, * defaults to 'text/html'. * @param encoding The encoding of the data. * @param historyUrl URL to use as the history entry, if null defaults to * 'about:blank'. */ public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) { checkThread(); if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) { loadDataImpl(data, mimeType, encoding); return; } switchOutDrawHistory(); WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData(); arg.mBaseUrl = baseUrl; arg.mData = data; arg.mMimeType = mimeType; arg.mEncoding = encoding; arg.mHistoryUrl = historyUrl; mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg); clearHelpers(); } /** * Saves the current view as a web archive. * * @param filename The filename where the archive should be placed. */ public void saveWebArchive(String filename) { checkThread(); saveWebArchiveImpl(filename, false, null); } /* package */ static class SaveWebArchiveMessage { SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback callback) { mBasename = basename; mAutoname = autoname; mCallback = callback; } /* package */ final String mBasename; /* package */ final boolean mAutoname; /* package */ final ValueCallback mCallback; /* package */ String mResultFile; } /** * Saves the current view as a web archive. * * @param basename The filename where the archive should be placed. * @param autoname If false, takes basename to be a file. If true, basename * is assumed to be a directory in which a filename will be * chosen according to the url of the current page. * @param callback Called after the web archive has been saved. The * parameter for onReceiveValue will either be the filename * under which the file was saved, or null if saving the * file failed. */ public void saveWebArchive(String basename, boolean autoname, ValueCallback callback) { checkThread(); saveWebArchiveImpl(basename, autoname, callback); } private void saveWebArchiveImpl(String basename, boolean autoname, ValueCallback callback) { mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE, new SaveWebArchiveMessage(basename, autoname, callback)); } /** * Stop the current load. */ public void stopLoading() { checkThread(); // TODO: should we clear all the messages in the queue before sending // STOP_LOADING? switchOutDrawHistory(); mWebViewCore.sendMessage(EventHub.STOP_LOADING); } /** * Reload the current url. */ public void reload() { checkThread(); clearHelpers(); switchOutDrawHistory(); mWebViewCore.sendMessage(EventHub.RELOAD); } /** * Return true if this WebView has a back history item. * @return True iff this WebView has a back history item. */ public boolean canGoBack() { checkThread(); WebBackForwardList l = mCallbackProxy.getBackForwardList(); synchronized (l) { if (l.getClearPending()) { return false; } else { return l.getCurrentIndex() > 0; } } } /** * Go back in the history of this WebView. */ public void goBack() { checkThread(); goBackOrForwardImpl(-1); } /** * Return true if this WebView has a forward history item. * @return True iff this Webview has a forward history item. */ public boolean canGoForward() { checkThread(); WebBackForwardList l = mCallbackProxy.getBackForwardList(); synchronized (l) { if (l.getClearPending()) { return false; } else { return l.getCurrentIndex() < l.getSize() - 1; } } } /** * Go forward in the history of this WebView. */ public void goForward() { checkThread(); goBackOrForwardImpl(1); } /** * Return true if the page can go back or forward the given * number of steps. * @param steps The negative or positive number of steps to move the * history. */ public boolean canGoBackOrForward(int steps) { checkThread(); WebBackForwardList l = mCallbackProxy.getBackForwardList(); synchronized (l) { if (l.getClearPending()) { return false; } else { int newIndex = l.getCurrentIndex() + steps; return newIndex >= 0 && newIndex < l.getSize(); } } } /** * Go to the history item that is the number of steps away from * the current item. Steps is negative if backward and positive * if forward. * @param steps The number of steps to take back or forward in the back * forward list. */ public void goBackOrForward(int steps) { checkThread(); goBackOrForwardImpl(steps); } private void goBackOrForwardImpl(int steps) { goBackOrForward(steps, false); } private void goBackOrForward(int steps, boolean ignoreSnapshot) { if (steps != 0) { clearHelpers(); mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps, ignoreSnapshot ? 1 : 0); } } /** * Returns true if private browsing is enabled in this WebView. */ public boolean isPrivateBrowsingEnabled() { checkThread(); return getSettings().isPrivateBrowsingEnabled(); } private void startPrivateBrowsing() { getSettings().setPrivateBrowsingEnabled(true); } private boolean extendScroll(int y) { int finalY = mScroller.getFinalY(); int newY = pinLocY(finalY + y); if (newY == finalY) return false; mScroller.setFinalY(newY); mScroller.extendDuration(computeDuration(0, y)); return true; } /** * Scroll the contents of the view up by half the view size * @param top true to jump to the top of the page * @return true if the page was scrolled */ public boolean pageUp(boolean top) { checkThread(); if (mNativeClass == 0) { return false; } nativeClearCursor(); // start next trackball movement from page edge if (top) { // go to the top of the document return pinScrollTo(mScrollX, 0, true, 0); } // Page up int h = getHeight(); int y; if (h > 2 * PAGE_SCROLL_OVERLAP) { y = -h + PAGE_SCROLL_OVERLAP; } else { y = -h / 2; } return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } /** * Scroll the contents of the view down by half the page size * @param bottom true to jump to bottom of page * @return true if the page was scrolled */ public boolean pageDown(boolean bottom) { checkThread(); if (mNativeClass == 0) { return false; } nativeClearCursor(); // start next trackball movement from page edge if (bottom) { return pinScrollTo(mScrollX, computeRealVerticalScrollRange(), true, 0); } // Page down. int h = getHeight(); int y; if (h > 2 * PAGE_SCROLL_OVERLAP) { y = h - PAGE_SCROLL_OVERLAP; } else { y = h / 2; } return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } /** * Clear the view so that onDraw() will draw nothing but white background, * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY */ public void clearView() { checkThread(); mContentWidth = 0; mContentHeight = 0; setBaseLayer(0, null, false, false, false); mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT); } /** * Return a new picture that captures the current display of the webview. * This is a copy of the display, and will be unaffected if the webview * later loads a different URL. * * @return a picture containing the current contents of the view. Note this * picture is of the entire document, and is not restricted to the * bounds of the view. */ public Picture capturePicture() { checkThread(); if (mNativeClass == 0) return null; Picture result = new Picture(); nativeCopyBaseContentToPicture(result); return result; } /** * Return true if the browser is displaying a TextView for text input. */ private boolean inEditingMode() { return mWebTextView != null && mWebTextView.getParent() != null; } /** * Remove the WebTextView. */ private void clearTextEntry() { if (inEditingMode()) { mWebTextView.remove(); } else { // The keyboard may be open with the WebView as the served view hideSoftKeyboard(); } } /** * Return the current scale of the WebView * @return The current scale. */ public float getScale() { checkThread(); return mZoomManager.getScale(); } /** * Return the reading level scale of the WebView * @return The reading level scale. */ /*package*/ float getReadingLevelScale() { return mZoomManager.getReadingLevelScale(); } /** * Set the initial scale for the WebView. 0 means default. If * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the * way. Otherwise it starts with 100%. If initial scale is greater than 0, * WebView starts will this value as initial scale. * * @param scaleInPercent The initial scale in percent. */ public void setInitialScale(int scaleInPercent) { checkThread(); mZoomManager.setInitialScaleInPercent(scaleInPercent); } /** * Invoke the graphical zoom picker widget for this WebView. This will * result in the zoom widget appearing on the screen to control the zoom * level of this WebView. */ public void invokeZoomPicker() { checkThread(); if (!getSettings().supportZoom()) { Log.w(LOGTAG, "This WebView doesn't support zoom."); return; } clearHelpers(); mZoomManager.invokeZoomPicker(); } /** * Return a HitTestResult based on the current cursor node. If a HTML::a tag * is found and the anchor has a non-JavaScript url, the HitTestResult type * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the * anchor does not have a url or if it is a JavaScript url, the type will * be UNKNOWN_TYPE and the url has to be retrieved through * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in * the "extra" field. A type of * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as * a child node. If a phone number is found, the HitTestResult type is set * to PHONE_TYPE and the phone number is set in the "extra" field of * HitTestResult. If a map address is found, the HitTestResult type is set * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. * If an email address is found, the HitTestResult type is set to EMAIL_TYPE * and the email is set in the "extra" field of HitTestResult. Otherwise, * HitTestResult type is set to UNKNOWN_TYPE. */ public HitTestResult getHitTestResult() { checkThread(); return hitTestResult(mInitialHitTestResult); } private HitTestResult hitTestResult(HitTestResult fallback) { if (mNativeClass == 0) { return null; } HitTestResult result = new HitTestResult(); if (nativeHasCursorNode()) { if (nativeCursorIsTextInput()) { result.setType(HitTestResult.EDIT_TEXT_TYPE); } else { String text = nativeCursorText(); if (text != null) { if (text.startsWith(SCHEME_TEL)) { result.setType(HitTestResult.PHONE_TYPE); result.setExtra(text.substring(SCHEME_TEL.length())); } else if (text.startsWith(SCHEME_MAILTO)) { result.setType(HitTestResult.EMAIL_TYPE); result.setExtra(text.substring(SCHEME_MAILTO.length())); } else if (text.startsWith(SCHEME_GEO)) { result.setType(HitTestResult.GEO_TYPE); result.setExtra(URLDecoder.decode(text .substring(SCHEME_GEO.length()))); } else if (nativeCursorIsAnchor()) { result.setType(HitTestResult.SRC_ANCHOR_TYPE); result.setExtra(text); } } } } else if (fallback != null) { /* If webkit causes a rebuild while the long press is in progress, * the cursor node may be reset, even if it is still around. This * uses the cursor node saved when the touch began. Since the * nativeImageURI below only changes the result if it is successful, * this uses the data beneath the touch if available or the original * tap data otherwise. */ Log.v(LOGTAG, "hitTestResult use fallback"); result = fallback; } int type = result.getType(); if (type == HitTestResult.UNKNOWN_TYPE || type == HitTestResult.SRC_ANCHOR_TYPE) { // Now check to see if it is an image. int contentX = viewToContentX(mLastTouchX + mScrollX); int contentY = viewToContentY(mLastTouchY + mScrollY); String text = nativeImageURI(contentX, contentY); if (text != null) { result.setType(type == HitTestResult.UNKNOWN_TYPE ? HitTestResult.IMAGE_TYPE : HitTestResult.SRC_IMAGE_ANCHOR_TYPE); result.setExtra(text); } } return result; } // Called by JNI when the DOM has changed the focus. Clear the focus so // that new keys will go to the newly focused field private void domChangedFocus() { if (inEditingMode()) { mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget(); } } /** * Request the anchor or image element URL at the last tapped point. * If hrefMsg is null, this method returns immediately and does not * dispatch hrefMsg to its target. If the tapped point hits an image, * an anchor, or an image in an anchor, the message associates * strings in named keys in its data. The value paired with the key * may be an empty string. * * @param hrefMsg This message will be dispatched with the result of the * request. The message data contains three keys: * - "url" returns the anchor's href attribute. * - "title" returns the anchor's text. * - "src" returns the image's src attribute. */ public void requestFocusNodeHref(Message hrefMsg) { checkThread(); if (hrefMsg == null) { return; } int contentX = viewToContentX(mLastTouchX + mScrollX); int contentY = viewToContentY(mLastTouchY + mScrollY); if (nativeHasCursorNode()) { Rect cursorBounds = nativeGetCursorRingBounds(); if (!cursorBounds.contains(contentX, contentY)) { int slop = viewToContentDimension(mNavSlop); cursorBounds.inset(-slop, -slop); if (cursorBounds.contains(contentX, contentY)) { contentX = (int) cursorBounds.centerX(); contentY = (int) cursorBounds.centerY(); } } } mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF, contentX, contentY, hrefMsg); } /** * Request the url of the image last touched by the user. msg will be sent * to its target with a String representing the url as its object. * * @param msg This message will be dispatched with the result of the request * as the data member with "url" as key. The result can be null. */ public void requestImageRef(Message msg) { checkThread(); if (0 == mNativeClass) return; // client isn't initialized int contentX = viewToContentX(mLastTouchX + mScrollX); int contentY = viewToContentY(mLastTouchY + mScrollY); String ref = nativeImageURI(contentX, contentY); Bundle data = msg.getData(); data.putString("url", ref); msg.setData(data); msg.sendToTarget(); } static int pinLoc(int x, int viewMax, int docMax) { // Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); if (docMax < viewMax) { // the doc has room on the sides for "blank" // pin the short document to the top/left of the screen x = 0; // Log.d(LOGTAG, "--- center " + x); } else if (x < 0) { x = 0; // Log.d(LOGTAG, "--- zero"); } else if (x + viewMax > docMax) { x = docMax - viewMax; // Log.d(LOGTAG, "--- pin " + x); } return x; } // Expects x in view coordinates int pinLocX(int x) { if (mInOverScrollMode) return x; return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange()); } // Expects y in view coordinates int pinLocY(int y) { if (mInOverScrollMode) return y; return pinLoc(y, getViewHeightWithTitle(), computeRealVerticalScrollRange() + getTitleHeight()); } /** * A title bar which is embedded in this WebView, and scrolls along with it * vertically, but not horizontally. */ private View mTitleBar; /** * the title bar rendering gravity */ private int mTitleGravity; /** * Add or remove a title bar to be embedded into the WebView, and scroll * along with it vertically, while remaining in view horizontally. Pass * null to remove the title bar from the WebView, and return to drawing * the WebView normally without translating to account for the title bar. * @hide */ public void setEmbeddedTitleBar(View v) { if (mTitleBar == v) return; if (mTitleBar != null) { removeView(mTitleBar); } if (null != v) { addView(v, new AbsoluteLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0)); } mTitleBar = v; } /** * Set where to render the embedded title bar * NO_GRAVITY at the top of the page * TOP at the top of the screen * @hide */ public void setTitleBarGravity(int gravity) { mTitleGravity = gravity; // force refresh invalidate(); } /** * Given a distance in view space, convert it to content space. Note: this * does not reflect translation, just scaling, so this should not be called * with coordinates, but should be called for dimensions like width or * height. */ private int viewToContentDimension(int d) { return Math.round(d * mZoomManager.getInvScale()); } /** * Given an x coordinate in view space, convert it to content space. Also * may be used for absolute heights (such as for the WebTextView's * textSize, which is unaffected by the height of the title bar). */ /*package*/ int viewToContentX(int x) { return viewToContentDimension(x); } /** * Given a y coordinate in view space, convert it to content space. * Takes into account the height of the title bar if there is one * embedded into the WebView. */ /*package*/ int viewToContentY(int y) { return viewToContentDimension(y - getTitleHeight()); } /** * Given a x coordinate in view space, convert it to content space. * Returns the result as a float. */ private float viewToContentXf(int x) { return x * mZoomManager.getInvScale(); } /** * Given a y coordinate in view space, convert it to content space. * Takes into account the height of the title bar if there is one * embedded into the WebView. Returns the result as a float. */ private float viewToContentYf(int y) { return (y - getTitleHeight()) * mZoomManager.getInvScale(); } /** * Given a distance in content space, convert it to view space. Note: this * does not reflect translation, just scaling, so this should not be called * with coordinates, but should be called for dimensions like width or * height. */ /*package*/ int contentToViewDimension(int d) { return Math.round(d * mZoomManager.getScale()); } /** * Given an x coordinate in content space, convert it to view * space. */ /*package*/ int contentToViewX(int x) { return contentToViewDimension(x); } /** * Given a y coordinate in content space, convert it to view * space. Takes into account the height of the title bar. */ /*package*/ int contentToViewY(int y) { return contentToViewDimension(y) + getTitleHeight(); } private Rect contentToViewRect(Rect x) { return new Rect(contentToViewX(x.left), contentToViewY(x.top), contentToViewX(x.right), contentToViewY(x.bottom)); } /* To invalidate a rectangle in content coordinates, we need to transform the rect into view coordinates, so we can then call invalidate(...). Normally, we would just call contentToView[XY](...), which eventually calls Math.round(coordinate * mActualScale). However, for invalidates, we need to account for the slop that occurs with antialiasing. To address that, we are a little more liberal in the size of the rect that we invalidate. This liberal calculation calls floor() for the top/left, and ceil() for the bottom/right coordinates. This catches the possible extra pixels of antialiasing that we might have missed with just round(). */ // Called by JNI to invalidate the View, given rectangle coordinates in // content space private void viewInvalidate(int l, int t, int r, int b) { final float scale = mZoomManager.getScale(); final int dy = getTitleHeight(); invalidate((int)Math.floor(l * scale), (int)Math.floor(t * scale) + dy, (int)Math.ceil(r * scale), (int)Math.ceil(b * scale) + dy); } // Called by JNI to invalidate the View after a delay, given rectangle // coordinates in content space private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { final float scale = mZoomManager.getScale(); final int dy = getTitleHeight(); postInvalidateDelayed(delay, (int)Math.floor(l * scale), (int)Math.floor(t * scale) + dy, (int)Math.ceil(r * scale), (int)Math.ceil(b * scale) + dy); } private void invalidateContentRect(Rect r) { viewInvalidate(r.left, r.top, r.right, r.bottom); } // stop the scroll animation, and don't let a subsequent fling add // to the existing velocity private void abortAnimation() { mScroller.abortAnimation(); mLastVelocity = 0; } /* call from webcoreview.draw(), so we're still executing in the UI thread */ private void recordNewContentSize(int w, int h, boolean updateLayout) { // premature data from webkit, ignore if ((w | h) == 0) { return; } // don't abort a scroll animation if we didn't change anything if (mContentWidth != w || mContentHeight != h) { // record new dimensions mContentWidth = w; mContentHeight = h; // If history Picture is drawn, don't update scroll. They will be // updated when we get out of that mode. if (!mDrawHistory) { // repin our scroll, taking into account the new content size updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY)); if (!mScroller.isFinished()) { // We are in the middle of a scroll. Repin the final scroll // position. mScroller.setFinalX(pinLocX(mScroller.getFinalX())); mScroller.setFinalY(pinLocY(mScroller.getFinalY())); } } } contentSizeChanged(updateLayout); } // Used to avoid sending many visible rect messages. private Rect mLastVisibleRectSent; private Rect mLastGlobalRect; Rect sendOurVisibleRect() { if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent; Rect rect = new Rect(); calcOurContentVisibleRect(rect); // Rect.equals() checks for null input. if (!rect.equals(mLastVisibleRectSent)) { if (!mBlockWebkitViewMessages) { Point pos = new Point(rect.left, rect.top); mWebViewCore.removeMessages(EventHub.SET_SCROLL_OFFSET); mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, nativeMoveGeneration(), mSendScrollEvent ? 1 : 0, pos); } mLastVisibleRectSent = rect; mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); } Rect globalRect = new Rect(); if (getGlobalVisibleRect(globalRect) && !globalRect.equals(mLastGlobalRect)) { if (DebugFlags.WEB_VIEW) { Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," + globalRect.top + ",r=" + globalRect.right + ",b=" + globalRect.bottom); } // TODO: the global offset is only used by windowRect() // in ChromeClientAndroid ; other clients such as touch // and mouse events could return view + screen relative points. if (!mBlockWebkitViewMessages) { mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); } mLastGlobalRect = globalRect; } return rect; } // Sets r to be the visible rectangle of our webview in view coordinates private void calcOurVisibleRect(Rect r) { Point p = new Point(); getGlobalVisibleRect(r, p); r.offset(-p.x, -p.y); } // Sets r to be our visible rectangle in content coordinates private void calcOurContentVisibleRect(Rect r) { calcOurVisibleRect(r); r.left = viewToContentX(r.left); // viewToContentY will remove the total height of the title bar. Add // the visible height back in to account for the fact that if the title // bar is partially visible, the part of the visible rect which is // displaying our content is displaced by that amount. r.top = viewToContentY(r.top + getVisibleTitleHeightImpl()); r.right = viewToContentX(r.right); r.bottom = viewToContentY(r.bottom); } // Sets r to be our visible rectangle in content coordinates. We use this // method on the native side to compute the position of the fixed layers. // Uses floating coordinates (necessary to correctly place elements when // the scale factor is not 1) private void calcOurContentVisibleRectF(RectF r) { Rect ri = new Rect(0,0,0,0); calcOurVisibleRect(ri); r.left = viewToContentXf(ri.left); // viewToContentY will remove the total height of the title bar. Add // the visible height back in to account for the fact that if the title // bar is partially visible, the part of the visible rect which is // displaying our content is displaced by that amount. r.top = viewToContentYf(ri.top + getVisibleTitleHeightImpl()); r.right = viewToContentXf(ri.right); r.bottom = viewToContentYf(ri.bottom); } static class ViewSizeData { int mWidth; int mHeight; float mHeightWidthRatio; int mActualViewHeight; int mTextWrapWidth; int mAnchorX; int mAnchorY; float mScale; boolean mIgnoreHeight; } /** * Compute unzoomed width and height, and if they differ from the last * values we sent, send them to webkit (to be used as new viewport) * * @param force ensures that the message is sent to webkit even if the width * or height has not changed since the last message * * @return true if new values were sent */ boolean sendViewSizeZoom(boolean force) { if (mBlockWebkitViewMessages) return false; if (mZoomManager.isPreventingWebkitUpdates()) return false; int viewWidth = getViewWidth(); int newWidth = Math.round(viewWidth * mZoomManager.getInvScale()); // This height could be fixed and be different from actual visible height. int viewHeight = getViewHeightWithTitle() - getTitleHeight(); int newHeight = Math.round(viewHeight * mZoomManager.getInvScale()); // Make the ratio more accurate than (newHeight / newWidth), since the // latter both are calculated and rounded. float heightWidthRatio = (float) viewHeight / viewWidth; /* * Because the native side may have already done a layout before the * View system was able to measure us, we have to send a height of 0 to * remove excess whitespace when we grow our width. This will trigger a * layout and a change in content size. This content size change will * mean that contentSizeChanged will either call this method directly or * indirectly from onSizeChanged. */ if (newWidth > mLastWidthSent && mWrapContent) { newHeight = 0; heightWidthRatio = 0; } // Actual visible content height. int actualViewHeight = Math.round(getViewHeight() * mZoomManager.getInvScale()); // Avoid sending another message if the dimensions have not changed. if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force || actualViewHeight != mLastActualHeightSent) { ViewSizeData data = new ViewSizeData(); data.mWidth = newWidth; data.mHeight = newHeight; data.mHeightWidthRatio = heightWidthRatio; data.mActualViewHeight = actualViewHeight; data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale()); data.mScale = mZoomManager.getScale(); data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress() && !mHeightCanMeasure; data.mAnchorX = mZoomManager.getDocumentAnchorX(); data.mAnchorY = mZoomManager.getDocumentAnchorY(); mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data); mLastWidthSent = newWidth; mLastHeightSent = newHeight; mLastActualHeightSent = actualViewHeight; mZoomManager.clearDocumentAnchor(); return true; } return false; } private int computeRealHorizontalScrollRange() { if (mDrawHistory) { return mHistoryWidth; } else { // to avoid rounding error caused unnecessary scrollbar, use floor return (int) Math.floor(mContentWidth * mZoomManager.getScale()); } } @Override protected int computeHorizontalScrollRange() { int range = computeRealHorizontalScrollRange(); // Adjust reported range if overscrolled to compress the scroll bars final int scrollX = mScrollX; final int overscrollRight = computeMaxScrollX(); if (scrollX < 0) { range -= scrollX; } else if (scrollX > overscrollRight) { range += scrollX - overscrollRight; } return range; } @Override protected int computeHorizontalScrollOffset() { return Math.max(mScrollX, 0); } private int computeRealVerticalScrollRange() { if (mDrawHistory) { return mHistoryHeight; } else { // to avoid rounding error caused unnecessary scrollbar, use floor return (int) Math.floor(mContentHeight * mZoomManager.getScale()); } } @Override protected int computeVerticalScrollRange() { int range = computeRealVerticalScrollRange(); // Adjust reported range if overscrolled to compress the scroll bars final int scrollY = mScrollY; final int overscrollBottom = computeMaxScrollY(); if (scrollY < 0) { range -= scrollY; } else if (scrollY > overscrollBottom) { range += scrollY - overscrollBottom; } return range; } @Override protected int computeVerticalScrollOffset() { return Math.max(mScrollY - getTitleHeight(), 0); } @Override protected int computeVerticalScrollExtent() { return getViewHeight(); } /** @hide */ @Override protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, int l, int t, int r, int b) { if (mScrollY < 0) { t -= mScrollY; } scrollBar.setBounds(l, t + getVisibleTitleHeightImpl(), r, b); scrollBar.draw(canvas); } @Override protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { // Special-case layer scrolling so that we do not trigger normal scroll // updating. if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { nativeScrollLayer(mScrollingLayer, scrollX, scrollY); mScrollingLayerRect.left = scrollX; mScrollingLayerRect.top = scrollY; invalidate(); return; } mInOverScrollMode = false; int maxX = computeMaxScrollX(); int maxY = computeMaxScrollY(); if (maxX == 0) { // do not over scroll x if the page just fits the screen scrollX = pinLocX(scrollX); } else if (scrollX < 0 || scrollX > maxX) { mInOverScrollMode = true; } if (scrollY < 0 || scrollY > maxY) { mInOverScrollMode = true; } int oldX = mScrollX; int oldY = mScrollY; super.scrollTo(scrollX, scrollY); if (mOverScrollGlow != null) { mOverScrollGlow.pullGlow(mScrollX, mScrollY, oldX, oldY, maxX, maxY); } } /** * Get the url for the current page. This is not always the same as the url * passed to WebViewClient.onPageStarted because although the load for * that url has begun, the current page may not have changed. * @return The url for the current page. */ public String getUrl() { checkThread(); WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getUrl() : null; } /** * Get the original url for the current page. This is not always the same * as the url passed to WebViewClient.onPageStarted because although the * load for that url has begun, the current page may not have changed. * Also, there may have been redirects resulting in a different url to that * originally requested. * @return The url that was originally requested for the current page. */ public String getOriginalUrl() { checkThread(); WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getOriginalUrl() : null; } /** * Get the title for the current page. This is the title of the current page * until WebViewClient.onReceivedTitle is called. * @return The title for the current page. */ public String getTitle() { checkThread(); WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getTitle() : null; } /** * Get the favicon for the current page. This is the favicon of the current * page until WebViewClient.onReceivedIcon is called. * @return The favicon for the current page. */ public Bitmap getFavicon() { checkThread(); WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getFavicon() : null; } /** * Get the touch icon url for the apple-touch-icon element, or * a URL on this site's server pointing to the standard location of a * touch icon. * @hide */ public String getTouchIconUrl() { WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getTouchIconUrl() : null; } /** * Get the progress for the current page. * @return The progress for the current page between 0 and 100. */ public int getProgress() { checkThread(); return mCallbackProxy.getProgress(); } /** * @return the height of the HTML content. */ public int getContentHeight() { checkThread(); return mContentHeight; } /** * @return the width of the HTML content. * @hide */ public int getContentWidth() { return mContentWidth; } /** * @hide */ public int getPageBackgroundColor() { return nativeGetBackgroundColor(); } /** * Pause all layout, parsing, and JavaScript timers for all webviews. This * is a global requests, not restricted to just this webview. This can be * useful if the application has been paused. */ public void pauseTimers() { checkThread(); mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); } /** * Resume all layout, parsing, and JavaScript timers for all webviews. * This will resume dispatching all timers. */ public void resumeTimers() { checkThread(); mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); } /** * Call this to pause any extra processing associated with this WebView and * its associated DOM, plugins, JavaScript etc. For example, if the WebView * is taken offscreen, this could be called to reduce unnecessary CPU or * network traffic. When the WebView is again "active", call onResume(). * * Note that this differs from pauseTimers(), which affects all WebViews. */ public void onPause() { checkThread(); if (!mIsPaused) { mIsPaused = true; mWebViewCore.sendMessage(EventHub.ON_PAUSE); // We want to pause the current playing video when switching out // from the current WebView/tab. if (mHTML5VideoViewProxy != null) { mHTML5VideoViewProxy.pauseAndDispatch(); } } } /** * Call this to resume a WebView after a previous call to onPause(). */ public void onResume() { checkThread(); if (mIsPaused) { mIsPaused = false; mWebViewCore.sendMessage(EventHub.ON_RESUME); } } /** * Returns true if the view is paused, meaning onPause() was called. Calling * onResume() sets the paused state back to false. * @hide */ public boolean isPaused() { return mIsPaused; } /** * Call this to inform the view that memory is low so that it can * free any available memory. */ public void freeMemory() { checkThread(); mWebViewCore.sendMessage(EventHub.FREE_MEMORY); } /** * Clear the resource cache. Note that the cache is per-application, so * this will clear the cache for all WebViews used. * * @param includeDiskFiles If false, only the RAM cache is cleared. */ public void clearCache(boolean includeDiskFiles) { checkThread(); // Note: this really needs to be a static method as it clears cache for all // WebView. But we need mWebViewCore to send message to WebCore thread, so // we can't make this static. mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, includeDiskFiles ? 1 : 0, 0); } /** * Make sure that clearing the form data removes the adapter from the * currently focused textfield if there is one. */ public void clearFormData() { checkThread(); if (inEditingMode()) { AutoCompleteAdapter adapter = null; mWebTextView.setAdapterCustom(adapter); } } /** * Tell the WebView to clear its internal back/forward list. */ public void clearHistory() { checkThread(); mCallbackProxy.getBackForwardList().setClearPending(); mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); } /** * Clear the SSL preferences table stored in response to proceeding with SSL * certificate errors. */ public void clearSslPreferences() { checkThread(); mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); } /** * Return the WebBackForwardList for this WebView. This contains the * back/forward list for use in querying each item in the history stack. * This is a copy of the private WebBackForwardList so it contains only a * snapshot of the current state. Multiple calls to this method may return * different objects. The object returned from this method will not be * updated to reflect any new state. */ public WebBackForwardList copyBackForwardList() { checkThread(); return mCallbackProxy.getBackForwardList().clone(); } /* * Highlight and scroll to the next occurance of String in findAll. * Wraps the page infinitely, and scrolls. Must be called after * calling findAll. * * @param forward Direction to search. */ public void findNext(boolean forward) { checkThread(); if (0 == mNativeClass) return; // client isn't initialized nativeFindNext(forward); } /* * Find all instances of find on the page and highlight them. * @param find String to find. * @return int The number of occurances of the String "find" * that were found. */ public int findAll(String find) { checkThread(); if (0 == mNativeClass) return 0; // client isn't initialized int result = find != null ? nativeFindAll(find.toLowerCase(), find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0; invalidate(); mLastFind = find; return result; } /** * Start an ActionMode for finding text in this WebView. Only works if this * WebView is attached to the view system. * @param text If non-null, will be the initial text to search for. * Otherwise, the last String searched for in this WebView will * be used to start. * @param showIme If true, show the IME, assuming the user will begin typing. * If false and text is non-null, perform a find all. * @return boolean True if the find dialog is shown, false otherwise. */ public boolean showFindDialog(String text, boolean showIme) { checkThread(); FindActionModeCallback callback = new FindActionModeCallback(mContext); if (getParent() == null || startActionMode(callback) == null) { // Could not start the action mode, so end Find on page return false; } mFindCallback = callback; setFindIsUp(true); mFindCallback.setWebView(this); if (showIme) { mFindCallback.showSoftInput(); } else if (text != null) { mFindCallback.setText(text); mFindCallback.findAll(); return true; } if (text == null) { text = mLastFind; } if (text != null) { mFindCallback.setText(text); } return true; } /** * Keep track of the find callback so that we can remove its titlebar if * necessary. */ private FindActionModeCallback mFindCallback; /** * Toggle whether the find dialog is showing, for both native and Java. */ private void setFindIsUp(boolean isUp) { mFindIsUp = isUp; if (0 == mNativeClass) return; // client isn't initialized nativeSetFindIsUp(isUp); } /** * Return the index of the currently highlighted match. */ int findIndex() { if (0 == mNativeClass) return -1; return nativeFindIndex(); } // Used to know whether the find dialog is open. Affects whether // or not we draw the highlights for matches. private boolean mFindIsUp; // Keep track of the last string sent, so we can search again when find is // reopened. private String mLastFind; /** * Return the first substring consisting of the address of a physical * location. Currently, only addresses in the United States are detected, * and consist of: * - a house number * - a street name * - a street type (Road, Circle, etc), either spelled out or abbreviated * - a city name * - a state or territory, either spelled out or two-letter abbr. * - an optional 5 digit or 9 digit zip code. * * All names must be correctly capitalized, and the zip code, if present, * must be valid for the state. The street type must be a standard USPS * spelling or abbreviation. The state or territory must also be spelled * or abbreviated using USPS standards. The house number may not exceed * five digits. * @param addr The string to search for addresses. * * @return the address, or if no address is found, return null. */ public static String findAddress(String addr) { checkThread(); return findAddress(addr, false); } /** * @hide * Return the first substring consisting of the address of a physical * location. Currently, only addresses in the United States are detected, * and consist of: * - a house number * - a street name * - a street type (Road, Circle, etc), either spelled out or abbreviated * - a city name * - a state or territory, either spelled out or two-letter abbr. * - an optional 5 digit or 9 digit zip code. * * Names are optionally capitalized, and the zip code, if present, * must be valid for the state. The street type must be a standard USPS * spelling or abbreviation. The state or territory must also be spelled * or abbreviated using USPS standards. The house number may not exceed * five digits. * @param addr The string to search for addresses. * @param caseInsensitive addr Set to true to make search ignore case. * * @return the address, or if no address is found, return null. */ public static String findAddress(String addr, boolean caseInsensitive) { return WebViewCore.nativeFindAddress(addr, caseInsensitive); } /* * Clear the highlighting surrounding text matches created by findAll. */ public void clearMatches() { checkThread(); if (mNativeClass == 0) return; nativeSetFindIsEmpty(); invalidate(); } /** * Called when the find ActionMode ends. */ void notifyFindDialogDismissed() { mFindCallback = null; if (mWebViewCore == null) { return; } clearMatches(); setFindIsUp(false); // Now that the dialog has been removed, ensure that we scroll to a // location that is not beyond the end of the page. pinScrollTo(mScrollX, mScrollY, false, 0); invalidate(); } /** * Query the document to see if it contains any image references. The * message object will be dispatched with arg1 being set to 1 if images * were found and 0 if the document does not reference any images. * @param response The message that will be dispatched with the result. */ public void documentHasImages(Message response) { checkThread(); if (response == null) { return; } mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); } /** * Request the scroller to abort any ongoing animation * * @hide */ public void stopScroll() { mScroller.forceFinished(true); mLastVelocity = 0; } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { int oldX = mScrollX; int oldY = mScrollY; int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); invalidate(); // So we draw again if (!mScroller.isFinished()) { int rangeX = computeMaxScrollX(); int rangeY = computeMaxScrollY(); int overflingDistance = mOverflingDistance; // Use the layer's scroll data if needed. if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { oldX = mScrollingLayerRect.left; oldY = mScrollingLayerRect.top; rangeX = mScrollingLayerRect.right; rangeY = mScrollingLayerRect.bottom; // No overscrolling for layers. overflingDistance = 0; } overScrollBy(x - oldX, y - oldY, oldX, oldY, rangeX, rangeY, overflingDistance, overflingDistance, false); if (mOverScrollGlow != null) { mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY); } } else { if (mTouchMode != TOUCH_DRAG_LAYER_MODE) { mScrollX = x; mScrollY = y; } else { // Update the layer position instead of WebView. nativeScrollLayer(mScrollingLayer, x, y); mScrollingLayerRect.left = x; mScrollingLayerRect.top = y; } abortAnimation(); mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); nativeSetIsScrolling(false); if (!mBlockWebkitViewMessages) { WebViewCore.resumePriority(); if (!mSelectingText) { WebViewCore.resumeUpdatePicture(mWebViewCore); } } if (oldX != mScrollX || oldY != mScrollY) { sendOurVisibleRect(); } } } else { super.computeScroll(); } } private static int computeDuration(int dx, int dy) { int distance = Math.max(Math.abs(dx), Math.abs(dy)); int duration = distance * 1000 / STD_SPEED; return Math.min(duration, MAX_DURATION); } // helper to pin the scrollBy parameters (already in view coordinates) // returns true if the scroll was changed private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); } // helper to pin the scrollTo parameters (already in view coordinates) // returns true if the scroll was changed private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { x = pinLocX(x); y = pinLocY(y); int dx = x - mScrollX; int dy = y - mScrollY; if ((dx | dy) == 0) { return false; } abortAnimation(); if (animate) { // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); mScroller.startScroll(mScrollX, mScrollY, dx, dy, animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); awakenScrollBars(mScroller.getDuration()); invalidate(); } else { scrollTo(x, y); } return true; } // Scale from content to view coordinates, and pin. // Also called by jni webview.cpp private boolean setContentScrollBy(int cx, int cy, boolean animate) { if (mDrawHistory) { // disallow WebView to change the scroll position as History Picture // is used in the view system. // TODO: as we switchOutDrawHistory when trackball or navigation // keys are hit, this should be safe. Right? return false; } cx = contentToViewDimension(cx); cy = contentToViewDimension(cy); if (mHeightCanMeasure) { // move our visible rect according to scroll request if (cy != 0) { Rect tempRect = new Rect(); calcOurVisibleRect(tempRect); tempRect.offset(cx, cy); requestRectangleOnScreen(tempRect); } // FIXME: We scroll horizontally no matter what because currently // ScrollView and ListView will not scroll horizontally. // FIXME: Why do we only scroll horizontally if there is no // vertical scroll? // Log.d(LOGTAG, "setContentScrollBy cy=" + cy); return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0); } else { return pinScrollBy(cx, cy, animate, 0); } } /** * Called by CallbackProxy when the page starts loading. * @param url The URL of the page which has started loading. */ /* package */ void onPageStarted(String url) { // every time we start a new page, we want to reset the // WebView certificate: if the new site is secure, we // will reload it and get a new certificate set; // if the new site is not secure, the certificate must be // null, and that will be the case setCertificate(null); // reset the flag since we set to true in if need after // loading is see onPageFinished(Url) mAccessibilityScriptInjected = false; } /** * Called by CallbackProxy when the page finishes loading. * @param url The URL of the page which has finished loading. */ /* package */ void onPageFinished(String url) { if (mPageThatNeedsToSlideTitleBarOffScreen != null) { // If the user is now on a different page, or has scrolled the page // past the point where the title bar is offscreen, ignore the // scroll request. if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url) && mScrollX == 0 && mScrollY == 0) { pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true, SLIDE_TITLE_DURATION); } mPageThatNeedsToSlideTitleBarOffScreen = null; } mZoomManager.onPageFinished(url); injectAccessibilityForUrl(url); } /** * This method injects accessibility in the loaded document if accessibility * is enabled. If JavaScript is enabled we try to inject a URL specific script. * If no URL specific script is found or JavaScript is disabled we fallback to * the default {@link AccessibilityInjector} implementation. *

* If the URL has the "axs" paramter set to 1 it has already done the * script injection so we do nothing. If the parameter is set to 0 * the URL opts out accessibility script injection so we fall back to * the default {@link AccessibilityInjector}. *

* Note: If the user has not opted-in the accessibility script injection no scripts * are injected rather the default {@link AccessibilityInjector} implementation * is used. * * @param url The URL loaded by this {@link WebView}. */ private void injectAccessibilityForUrl(String url) { if (mWebViewCore == null) { return; } AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext); if (!accessibilityManager.isEnabled()) { // it is possible that accessibility was turned off between reloads ensureAccessibilityScriptInjectorInstance(false); return; } if (!getSettings().getJavaScriptEnabled()) { // no JS so we fallback to the basic buil-in support ensureAccessibilityScriptInjectorInstance(true); return; } // check the URL "axs" parameter to choose appropriate action int axsParameterValue = getAxsUrlParameterValue(url); if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) { boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1); if (onDeviceScriptInjectionEnabled) { ensureAccessibilityScriptInjectorInstance(false); // neither script injected nor script injection opted out => we inject loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT); // TODO: Set this flag after successfull script injection. Maybe upon injection // the chooser should update the meta tag and we check it to declare success mAccessibilityScriptInjected = true; } else { // injection disabled so we fallback to the basic built-in support ensureAccessibilityScriptInjectorInstance(true); } } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) { // injection opted out so we fallback to the basic buil-in support ensureAccessibilityScriptInjectorInstance(true); } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) { ensureAccessibilityScriptInjectorInstance(false); // the URL provides accessibility but we still need to add our generic script loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT); } else { Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue); } } /** * Ensures the instance of the {@link AccessibilityInjector} to be present ot not. * * @param present True to ensure an insance, false to ensure no instance. */ private void ensureAccessibilityScriptInjectorInstance(boolean present) { if (present) { if (mAccessibilityInjector == null) { mAccessibilityInjector = new AccessibilityInjector(this); } } else { mAccessibilityInjector = null; } } /** * Gets the "axs" URL parameter value. * * @param url A url to fetch the paramter from. * @return The parameter value if such, -1 otherwise. */ private int getAxsUrlParameterValue(String url) { if (mMatchAxsUrlParameterPattern == null) { mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER); } Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url); if (matcher.find()) { String keyValuePair = url.substring(matcher.start(), matcher.end()); return Integer.parseInt(keyValuePair.split("=")[1]); } return -1; } /** * The URL of a page that sent a message to scroll the title bar off screen. * * Many mobile sites tell the page to scroll to (0,1) in order to scroll the * title bar off the screen. Sometimes, the scroll position is set before * the page finishes loading. Rather than scrolling while the page is still * loading, keep track of the URL and new scroll position so we can perform * the scroll once the page finishes loading. */ private String mPageThatNeedsToSlideTitleBarOffScreen; /** * The destination Y scroll position to be used when the page finishes * loading. See mPageThatNeedsToSlideTitleBarOffScreen. */ private int mYDistanceToSlideTitleOffScreen; // scale from content to view coordinates, and pin // return true if pin caused the final x/y different than the request cx/cy, // and a future scroll may reach the request cx/cy after our size has // changed // return false if the view scroll to the exact position as it is requested, // where negative numbers are taken to mean 0 private boolean setContentScrollTo(int cx, int cy) { if (mDrawHistory) { // disallow WebView to change the scroll position as History Picture // is used in the view system. // One known case where this is called is that WebCore tries to // restore the scroll position. As history Picture already uses the // saved scroll position, it is ok to skip this. return false; } int vx; int vy; if ((cx | cy) == 0) { // If the page is being scrolled to (0,0), do not add in the title // bar's height, and simply scroll to (0,0). (The only other work // in contentToView_ is to multiply, so this would not change 0.) vx = 0; vy = 0; } else { vx = contentToViewX(cx); vy = contentToViewY(cy); } // Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + // vx + " " + vy + "]"); // Some mobile sites attempt to scroll the title bar off the page by // scrolling to (0,1). If we are at the top left corner of the // page, assume this is an attempt to scroll off the title bar, and // animate the title bar off screen slowly enough that the user can see // it. if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0 && mTitleBar != null) { // FIXME: 100 should be defined somewhere as our max progress. if (getProgress() < 100) { // Wait to scroll the title bar off screen until the page has // finished loading. Keep track of the URL and the destination // Y position mPageThatNeedsToSlideTitleBarOffScreen = getUrl(); mYDistanceToSlideTitleOffScreen = vy; } else { pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION); } // Since we are animating, we have not yet reached the desired // scroll position. Do not return true to request another attempt return false; } pinScrollTo(vx, vy, false, 0); // If the request was to scroll to a negative coordinate, treat it as if // it was a request to scroll to 0 if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) { return true; } else { return false; } } // scale from content to view coordinates, and pin private void spawnContentScrollTo(int cx, int cy) { if (mDrawHistory) { // disallow WebView to change the scroll position as History Picture // is used in the view system. return; } int vx = contentToViewX(cx); int vy = contentToViewY(cy); pinScrollTo(vx, vy, true, 0); } /** * These are from webkit, and are in content coordinate system (unzoomed) */ private void contentSizeChanged(boolean updateLayout) { // suppress 0,0 since we usually see real dimensions soon after // this avoids drawing the prev content in a funny place. If we find a // way to consolidate these notifications, this check may become // obsolete if ((mContentWidth | mContentHeight) == 0) { return; } if (mHeightCanMeasure) { if (getMeasuredHeight() != contentToViewDimension(mContentHeight) || updateLayout) { requestLayout(); } } else if (mWidthCanMeasure) { if (getMeasuredWidth() != contentToViewDimension(mContentWidth) || updateLayout) { requestLayout(); } } else { // If we don't request a layout, try to send our view size to the // native side to ensure that WebCore has the correct dimensions. sendViewSizeZoom(false); } } /** * Set the WebViewClient that will receive various notifications and * requests. This will replace the current handler. * @param client An implementation of WebViewClient. */ public void setWebViewClient(WebViewClient client) { checkThread(); mCallbackProxy.setWebViewClient(client); } /** * Gets the WebViewClient * @return the current WebViewClient instance. * *@hide pending API council approval. */ public WebViewClient getWebViewClient() { return mCallbackProxy.getWebViewClient(); } /** * Register the interface to be used when content can not be handled by * the rendering engine, and should be downloaded instead. This will replace * the current handler. * @param listener An implementation of DownloadListener. */ public void setDownloadListener(DownloadListener listener) { checkThread(); mCallbackProxy.setDownloadListener(listener); } /** * Set the chrome handler. This is an implementation of WebChromeClient for * use in handling JavaScript dialogs, favicons, titles, and the progress. * This will replace the current handler. * @param client An implementation of WebChromeClient. */ public void setWebChromeClient(WebChromeClient client) { checkThread(); mCallbackProxy.setWebChromeClient(client); } /** * Gets the chrome handler. * @return the current WebChromeClient instance. * * @hide API council approval. */ public WebChromeClient getWebChromeClient() { return mCallbackProxy.getWebChromeClient(); } /** * Set the back/forward list client. This is an implementation of * WebBackForwardListClient for handling new items and changes in the * history index. * @param client An implementation of WebBackForwardListClient. * {@hide} */ public void setWebBackForwardListClient(WebBackForwardListClient client) { mCallbackProxy.setWebBackForwardListClient(client); } /** * Gets the WebBackForwardListClient. * {@hide} */ public WebBackForwardListClient getWebBackForwardListClient() { return mCallbackProxy.getWebBackForwardListClient(); } /** * Set the Picture listener. This is an interface used to receive * notifications of a new Picture. * @param listener An implementation of WebView.PictureListener. * @deprecated This method is now obsolete. */ @Deprecated public void setPictureListener(PictureListener listener) { checkThread(); mPictureListener = listener; } /** * {@hide} */ /* FIXME: Debug only! Remove for SDK! */ public void externalRepresentation(Message callback) { mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); } /** * {@hide} */ /* FIXME: Debug only! Remove for SDK! */ public void documentAsText(Message callback) { mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); } /** * Use this function to bind an object to JavaScript so that the * methods can be accessed from JavaScript. *

IMPORTANT: *

    *
  • Using addJavascriptInterface() allows JavaScript to control your * application. This can be a very useful feature or a dangerous security * issue. When the HTML in the WebView is untrustworthy (for example, part * or all of the HTML is provided by some person or process), then an * attacker could inject HTML that will execute your code and possibly any * code of the attacker's choosing.
    * Do not use addJavascriptInterface() unless all of the HTML in this * WebView was written by you.
  • *
  • The Java object that is bound runs in another thread and not in * the thread that it was constructed in.
  • *

* @param obj The class instance to bind to JavaScript, null instances are * ignored. * @param interfaceName The name to used to expose the instance in * JavaScript. */ public void addJavascriptInterface(Object obj, String interfaceName) { checkThread(); if (obj == null) { return; } WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); arg.mObject = obj; arg.mInterfaceName = interfaceName; mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg); } /** * Removes a previously added JavaScript interface with the given name. * @param interfaceName The name of the interface to remove. */ public void removeJavascriptInterface(String interfaceName) { checkThread(); if (mWebViewCore != null) { WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); arg.mInterfaceName = interfaceName; mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg); } } /** * Return the WebSettings object used to control the settings for this * WebView. * @return A WebSettings object that can be used to control this WebView's * settings. */ public WebSettings getSettings() { checkThread(); return (mWebViewCore != null) ? mWebViewCore.getSettings() : null; } /** * Return the list of currently loaded plugins. * @return The list of currently loaded plugins. * * @hide * @deprecated This was used for Gears, which has been deprecated. */ @Deprecated public static synchronized PluginList getPluginList() { checkThread(); return new PluginList(); } /** * @hide * @deprecated This was used for Gears, which has been deprecated. */ @Deprecated public void refreshPlugins(boolean reloadOpenPages) { checkThread(); } //------------------------------------------------------------------------- // Override View methods //------------------------------------------------------------------------- @Override protected void finalize() throws Throwable { try { if (mNativeClass != 0) { mPrivateHandler.post(new Runnable() { @Override public void run() { destroy(); } }); } } finally { super.finalize(); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (child == mTitleBar) { // When drawing the title bar, move it horizontally to always show // at the top of the WebView. mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft()); int newTop = 0; if (mTitleGravity == Gravity.NO_GRAVITY) { newTop = Math.min(0, mScrollY); } else if (mTitleGravity == Gravity.TOP) { newTop = mScrollY; } mTitleBar.setBottom(newTop + mTitleBar.getHeight()); mTitleBar.setTop(newTop); } return super.drawChild(canvas, child, drawingTime); } private void drawContent(Canvas canvas, boolean drawRings) { // Update the buttons in the picture, so when we draw the picture // to the screen, they are in the correct state. // Tell the native side if user is a) touching the screen, // b) pressing the trackball down, or c) pressing the enter key // If the cursor is on a button, we need to draw it in the pressed // state. // If mNativeClass is 0, we should not reach here, so we do not // need to check it again. boolean pressed = (mTouchMode == TOUCH_SHORTPRESS_START_MODE || mTouchMode == TOUCH_INIT_MODE || mTouchMode == TOUCH_SHORTPRESS_MODE); nativeRecordButtons(hasFocus() && hasWindowFocus(), (pressed && !USE_WEBKIT_RINGS) || mTrackballDown || mGotCenterDown, false); drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing && drawRings); } /** * Draw the background when beyond bounds * @param canvas Canvas to draw into */ private void drawOverScrollBackground(Canvas canvas) { if (mOverScrollBackground == null) { mOverScrollBackground = new Paint(); Bitmap bm = BitmapFactory.decodeResource( mContext.getResources(), com.android.internal.R.drawable.status_bar_background); mOverScrollBackground.setShader(new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)); mOverScrollBorder = new Paint(); mOverScrollBorder.setStyle(Paint.Style.STROKE); mOverScrollBorder.setStrokeWidth(0); mOverScrollBorder.setColor(0xffbbbbbb); } int top = 0; int right = computeRealHorizontalScrollRange(); int bottom = top + computeRealVerticalScrollRange(); // first draw the background and anchor to the top of the view canvas.save(); canvas.translate(mScrollX, mScrollY); canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom - mScrollY, Region.Op.DIFFERENCE); canvas.drawPaint(mOverScrollBackground); canvas.restore(); // then draw the border canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder); // next clip the region for the content canvas.clipRect(0, top, right, bottom); } @Override protected void onDraw(Canvas canvas) { // if mNativeClass is 0, the WebView is either destroyed or not // initialized. In either case, just draw the background color and return if (mNativeClass == 0) { canvas.drawColor(mBackgroundColor); return; } // if both mContentWidth and mContentHeight are 0, it means there is no // valid Picture passed to WebView yet. This can happen when WebView // just starts. Draw the background and return. if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) { canvas.drawColor(mBackgroundColor); return; } if (canvas.isHardwareAccelerated()) { mZoomManager.setHardwareAccelerated(); } int saveCount = canvas.save(); if (mInOverScrollMode && !getSettings() .getUseWebViewBackgroundForOverscrollBackground()) { drawOverScrollBackground(canvas); } if (mTitleBar != null) { canvas.translate(0, getTitleHeight()); } boolean drawJavaRings = !mTouchHighlightRegion.isEmpty() && (mTouchMode == TOUCH_INIT_MODE || mTouchMode == TOUCH_SHORTPRESS_START_MODE || mTouchMode == TOUCH_SHORTPRESS_MODE || mTouchMode == TOUCH_DONE_MODE); boolean drawNativeRings = !drawJavaRings; if (USE_WEBKIT_RINGS) { drawNativeRings = !drawJavaRings && !isInTouchMode(); } drawContent(canvas, drawNativeRings); canvas.restoreToCount(saveCount); if (AUTO_REDRAW_HACK && mAutoRedraw) { invalidate(); } mWebViewCore.signalRepaintDone(); if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) { invalidate(); } // paint the highlight in the end if (drawJavaRings) { long delay = System.currentTimeMillis() - mTouchHighlightRequested; if (delay < ViewConfiguration.getTapTimeout()) { Rect r = mTouchHighlightRegion.getBounds(); postInvalidateDelayed(delay, r.left, r.top, r.right, r.bottom); } else { if (mTouchHightlightPaint == null) { mTouchHightlightPaint = new Paint(); mTouchHightlightPaint.setColor(HIGHLIGHT_COLOR); } RegionIterator iter = new RegionIterator(mTouchHighlightRegion); Rect r = new Rect(); while (iter.next(r)) { canvas.drawRect(r, mTouchHightlightPaint); } } } if (DEBUG_TOUCH_HIGHLIGHT) { if (getSettings().getNavDump()) { if ((mTouchHighlightX | mTouchHighlightY) != 0) { if (mTouchCrossHairColor == null) { mTouchCrossHairColor = new Paint(); mTouchCrossHairColor.setColor(Color.RED); } canvas.drawLine(mTouchHighlightX - mNavSlop, mTouchHighlightY - mNavSlop, mTouchHighlightX + mNavSlop + 1, mTouchHighlightY + mNavSlop + 1, mTouchCrossHairColor); canvas.drawLine(mTouchHighlightX + mNavSlop + 1, mTouchHighlightY - mNavSlop, mTouchHighlightX - mNavSlop, mTouchHighlightY + mNavSlop + 1, mTouchCrossHairColor); } } } } private void removeTouchHighlight() { mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS); mPrivateHandler.removeMessages(SET_TOUCH_HIGHLIGHT_RECTS); setTouchHighlightRects(null); } @Override public void setLayoutParams(ViewGroup.LayoutParams params) { if (params.height == LayoutParams.WRAP_CONTENT) { mWrapContent = true; } super.setLayoutParams(params); } @Override public boolean performLongClick() { // performLongClick() is the result of a delayed message. If we switch // to windows overview, the WebView will be temporarily removed from the // view system. In that case, do nothing. if (getParent() == null) return false; // A multi-finger gesture can look like a long press; make sure we don't take // long press actions if we're scaling. final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector(); if (detector != null && detector.isInProgress()) { return false; } if (mNativeClass != 0 && nativeCursorIsTextInput()) { // Send the click so that the textfield is in focus centerKeyPressOnTextField(); rebuildWebTextView(); } else { clearTextEntry(); } if (inEditingMode()) { // Since we just called rebuildWebTextView, the layout is not set // properly. Update it so it can correctly find the word to select. mWebTextView.ensureLayout(); // Provide a touch down event to WebTextView, which will allow it // to store the location to use in performLongClick. AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams(); MotionEvent fake = MotionEvent.obtain(mLastTouchTime, mLastTouchTime, MotionEvent.ACTION_DOWN, mLastTouchX - params.x + mScrollX, mLastTouchY - params.y + mScrollY, 0); mWebTextView.dispatchTouchEvent(fake); return mWebTextView.performLongClick(); } if (mSelectingText) return false; // long click does nothing on selection /* if long click brings up a context menu, the super function * returns true and we're done. Otherwise, nothing happened when * the user clicked. */ if (super.performLongClick()) { return true; } /* In the case where the application hasn't already handled the long * click action, look for a word under the click. If one is found, * animate the text selection into view. * FIXME: no animation code yet */ final boolean isSelecting = selectText(); if (isSelecting) { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } return isSelecting; } /** * Select the word at the last click point. * * @hide pending API council approval */ public boolean selectText() { int x = viewToContentX(mLastTouchX + mScrollX); int y = viewToContentY(mLastTouchY + mScrollY); return selectText(x, y); } /** * Select the word at the indicated content coordinates. */ boolean selectText(int x, int y) { if (!setUpSelect(true, x, y)) { return false; } nativeSetExtendSelection(); mDrawSelectionPointer = false; mTouchMode = TOUCH_DRAG_MODE; return true; } private int mOrientation = Configuration.ORIENTATION_UNDEFINED; @Override protected void onConfigurationChanged(Configuration newConfig) { if (mSelectingText && mOrientation != newConfig.orientation) { selectionDone(); } mOrientation = newConfig.orientation; } /** * Keep track of the Callback so we can end its ActionMode or remove its * titlebar. */ private SelectActionModeCallback mSelectCallback; // These values are possible options for didUpdateWebTextViewDimensions. private static final int FULLY_ON_SCREEN = 0; private static final int INTERSECTS_SCREEN = 1; private static final int ANYWHERE = 2; /** * Check to see if the focused textfield/textarea is still on screen. If it * is, update the the dimensions and location of WebTextView. Otherwise, * remove the WebTextView. Should be called when the zoom level changes. * @param intersection How to determine whether the textfield/textarea is * still on screen. * @return boolean True if the textfield/textarea is still on screen and the * dimensions/location of WebTextView have been updated. */ private boolean didUpdateWebTextViewDimensions(int intersection) { Rect contentBounds = nativeFocusCandidateNodeBounds(); Rect vBox = contentToViewRect(contentBounds); Rect visibleRect = new Rect(); calcOurVisibleRect(visibleRect); // If the textfield is on screen, place the WebTextView in // its new place, accounting for our new scroll/zoom values, // and adjust its textsize. boolean onScreen; switch (intersection) { case FULLY_ON_SCREEN: onScreen = visibleRect.contains(vBox); break; case INTERSECTS_SCREEN: onScreen = Rect.intersects(visibleRect, vBox); break; case ANYWHERE: onScreen = true; break; default: throw new AssertionError( "invalid parameter passed to didUpdateWebTextViewDimensions"); } if (onScreen) { mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); mWebTextView.updateTextSize(); updateWebTextViewPadding(); return true; } else { // The textfield is now off screen. The user probably // was not zooming to see the textfield better. Remove // the WebTextView. If the user types a key, and the // textfield is still in focus, we will reconstruct // the WebTextView and scroll it back on screen. mWebTextView.remove(); return false; } } void setBaseLayer(int layer, Region invalRegion, boolean showVisualIndicator, boolean isPictureAfterFirstLayout, boolean registerPageSwapCallback) { if (mNativeClass == 0) return; nativeSetBaseLayer(layer, invalRegion, showVisualIndicator, isPictureAfterFirstLayout, registerPageSwapCallback); if (mHTML5VideoViewProxy != null) { mHTML5VideoViewProxy.setBaseLayer(layer); } } int getBaseLayer() { if (mNativeClass == 0) { return 0; } return nativeGetBaseLayer(); } private void onZoomAnimationStart() { // If it is in password mode, turn it off so it does not draw misplaced. if (inEditingMode()) { mWebTextView.setVisibility(INVISIBLE); } } private void onZoomAnimationEnd() { // adjust the edit text view if needed if (inEditingMode() && didUpdateWebTextViewDimensions(FULLY_ON_SCREEN)) { // If it is a password field, start drawing the WebTextView once // again. mWebTextView.setVisibility(VISIBLE); } } void onFixedLengthZoomAnimationStart() { WebViewCore.pauseUpdatePicture(getWebViewCore()); onZoomAnimationStart(); } void onFixedLengthZoomAnimationEnd() { if (!mBlockWebkitViewMessages && !mSelectingText) { WebViewCore.resumeUpdatePicture(mWebViewCore); } onZoomAnimationEnd(); } private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG; private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG; private final DrawFilter mZoomFilter = new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG); // If we need to trade better quality for speed, set mScrollFilter to null private final DrawFilter mScrollFilter = new PaintFlagsDrawFilter(SCROLL_BITS, 0); private void drawCoreAndCursorRing(Canvas canvas, int color, boolean drawCursorRing) { if (mDrawHistory) { canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); canvas.drawPicture(mHistoryPicture); return; } if (mNativeClass == 0) return; boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress(); boolean animateScroll = ((!mScroller.isFinished() || mVelocityTracker != null) && (mTouchMode != TOUCH_DRAG_MODE || mHeldMotionless != MOTIONLESS_TRUE)) || mDeferTouchMode == TOUCH_DRAG_MODE; if (mTouchMode == TOUCH_DRAG_MODE) { if (mHeldMotionless == MOTIONLESS_PENDING) { mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); mHeldMotionless = MOTIONLESS_FALSE; } if (mHeldMotionless == MOTIONLESS_FALSE) { mPrivateHandler.sendMessageDelayed(mPrivateHandler .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME); mHeldMotionless = MOTIONLESS_PENDING; } } int saveCount = canvas.save(); if (animateZoom) { mZoomManager.animateZoom(canvas); } else if (!canvas.isHardwareAccelerated()) { canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); } boolean UIAnimationsRunning = false; // Currently for each draw we compute the animation values; // We may in the future decide to do that independently. if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) { UIAnimationsRunning = true; // If we have unfinished (or unstarted) animations, // we ask for a repaint. We only need to do this in software // rendering (with hardware rendering we already have a different // method of requesting a repaint) if (!canvas.isHardwareAccelerated()) invalidate(); } // decide which adornments to draw int extras = DRAW_EXTRAS_NONE; if (mFindIsUp) { extras = DRAW_EXTRAS_FIND; } else if (mSelectingText && !USE_JAVA_TEXT_SELECTION) { extras = DRAW_EXTRAS_SELECTION; nativeSetSelectionPointer(mDrawSelectionPointer, mZoomManager.getInvScale(), mSelectX, mSelectY - getTitleHeight()); } else if (drawCursorRing) { extras = DRAW_EXTRAS_CURSOR_RING; } if (DebugFlags.WEB_VIEW) { Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp + " mSelectingText=" + mSelectingText + " nativePageShouldHandleShiftAndArrows()=" + nativePageShouldHandleShiftAndArrows() + " animateZoom=" + animateZoom + " extras=" + extras); } if (canvas.isHardwareAccelerated()) { int functor = nativeGetDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport, mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras); ((HardwareCanvas) canvas).callDrawGLFunction(functor); if (mHardwareAccelSkia != getSettings().getHardwareAccelSkiaEnabled()) { mHardwareAccelSkia = getSettings().getHardwareAccelSkiaEnabled(); nativeUseHardwareAccelSkia(mHardwareAccelSkia); } } else { DrawFilter df = null; if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) { df = mZoomFilter; } else if (animateScroll) { df = mScrollFilter; } canvas.setDrawFilter(df); // XXX: Revisit splitting content. Right now it causes a // synchronization problem with layers. int content = nativeDraw(canvas, color, extras, false); canvas.setDrawFilter(null); if (!mBlockWebkitViewMessages && content != 0) { mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0); } } canvas.restoreToCount(saveCount); if (mSelectingText && USE_JAVA_TEXT_SELECTION) { drawTextSelectionHandles(canvas); } if (extras == DRAW_EXTRAS_CURSOR_RING) { if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { mTouchMode = TOUCH_SHORTPRESS_MODE; } } if (mFocusSizeChanged) { mFocusSizeChanged = false; // If we are zooming, this will get handled above, when the zoom // finishes. We also do not need to do this unless the WebTextView // is showing. With hardware acceleration, the pageSwapCallback() // updates the WebTextView position in sync with page swapping if (!canvas.isHardwareAccelerated() && !animateZoom && inEditingMode()) { didUpdateWebTextViewDimensions(ANYWHERE); } } } private void drawTextSelectionHandles(Canvas canvas) { if (mTextSelectionPaint == null) { mTextSelectionPaint = new Paint(); mTextSelectionPaint.setColor(HIGHLIGHT_COLOR); } mTextSelectionRegion.setEmpty(); nativeGetTextSelectionRegion(mTextSelectionRegion); Rect r = new Rect(); RegionIterator iter = new RegionIterator(mTextSelectionRegion); int start_x = -1; int start_y = -1; int end_x = -1; int end_y = -1; while (iter.next(r)) { r = new Rect( contentToViewDimension(r.left), contentToViewDimension(r.top), contentToViewDimension(r.right), contentToViewDimension(r.bottom)); // Regions are in order. First one is where selection starts, // last one is where it ends if (start_x < 0 || start_y < 0) { start_x = r.left; start_y = r.bottom; } end_x = r.right; end_y = r.bottom; canvas.drawRect(r, mTextSelectionPaint); } if (mSelectHandleLeft == null) { mSelectHandleLeft = mContext.getResources().getDrawable( com.android.internal.R.drawable.text_select_handle_left); } // Magic formula copied from TextView start_x -= (mSelectHandleLeft.getIntrinsicWidth() * 3) / 4; mSelectHandleLeft.setBounds(start_x, start_y, start_x + mSelectHandleLeft.getIntrinsicWidth(), start_y + mSelectHandleLeft.getIntrinsicHeight()); if (mSelectHandleRight == null) { mSelectHandleRight = mContext.getResources().getDrawable( com.android.internal.R.drawable.text_select_handle_right); } end_x -= mSelectHandleRight.getIntrinsicWidth() / 4; mSelectHandleRight.setBounds(end_x, end_y, end_x + mSelectHandleRight.getIntrinsicWidth(), end_y + mSelectHandleRight.getIntrinsicHeight()); mSelectHandleLeft.draw(canvas); mSelectHandleRight.draw(canvas); } // draw history private boolean mDrawHistory = false; private Picture mHistoryPicture = null; private int mHistoryWidth = 0; private int mHistoryHeight = 0; // Only check the flag, can be called from WebCore thread boolean drawHistory() { return mDrawHistory; } int getHistoryPictureWidth() { return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0; } // Should only be called in UI thread void switchOutDrawHistory() { if (null == mWebViewCore) return; // CallbackProxy may trigger this if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) { mDrawHistory = false; mHistoryPicture = null; invalidate(); int oldScrollX = mScrollX; int oldScrollY = mScrollY; mScrollX = pinLocX(mScrollX); mScrollY = pinLocY(mScrollY); if (oldScrollX != mScrollX || oldScrollY != mScrollY) { onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY); } else { sendOurVisibleRect(); } } } WebViewCore.CursorData cursorData() { WebViewCore.CursorData result = cursorDataNoPosition(); Point position = nativeCursorPosition(); result.mX = position.x; result.mY = position.y; return result; } WebViewCore.CursorData cursorDataNoPosition() { WebViewCore.CursorData result = new WebViewCore.CursorData(); result.mMoveGeneration = nativeMoveGeneration(); result.mFrame = nativeCursorFramePointer(); return result; } /** * Delete text from start to end in the focused textfield. If there is no * focus, or if start == end, silently fail. If start and end are out of * order, swap them. * @param start Beginning of selection to delete. * @param end End of selection to delete. */ /* package */ void deleteSelection(int start, int end) { mTextGeneration++; WebViewCore.TextSelectionData data = new WebViewCore.TextSelectionData(start, end); mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, data); } /** * Set the selection to (start, end) in the focused textfield. If start and * end are out of order, swap them. * @param start Beginning of selection. * @param end End of selection. */ /* package */ void setSelection(int start, int end) { if (mWebViewCore != null) { mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); } } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { InputConnection connection = super.onCreateInputConnection(outAttrs); outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN; return connection; } /** * Called in response to a message from webkit telling us that the soft * keyboard should be launched. */ private void displaySoftKeyboard(boolean isTextView) { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); // bring it back to the default level scale so that user can enter text boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale(); if (zoom) { mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY); mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false); } if (isTextView) { rebuildWebTextView(); if (inEditingMode()) { imm.showSoftInput(mWebTextView, 0, mWebTextView.getResultReceiver()); if (zoom) { didUpdateWebTextViewDimensions(INTERSECTS_SCREEN); } return; } } // Used by plugins and contentEditable. // Also used if the navigation cache is out of date, and // does not recognize that a textfield is in focus. In that // case, use WebView as the targeted view. // see http://b/issue?id=2457459 imm.showSoftInput(this, 0); } // Called by WebKit to instruct the UI to hide the keyboard private void hideSoftKeyboard() { InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null && (imm.isActive(this) || (inEditingMode() && imm.isActive(mWebTextView)))) { imm.hideSoftInputFromWindow(this.getWindowToken(), 0); } } /* * This method checks the current focus and cursor and potentially rebuilds * mWebTextView to have the appropriate properties, such as password, * multiline, and what text it contains. It also removes it if necessary. */ /* package */ void rebuildWebTextView() { // If the WebView does not have focus, do nothing until it gains focus. if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { return; } boolean alreadyThere = inEditingMode(); // inEditingMode can only return true if mWebTextView is non-null, // so we can safely call remove() if (alreadyThere) if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { if (alreadyThere) { mWebTextView.remove(); } return; } // At this point, we know we have found an input field, so go ahead // and create the WebTextView if necessary. if (mWebTextView == null) { mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId()); // Initialize our generation number. mTextGeneration = 0; } mWebTextView.updateTextSize(); Rect visibleRect = new Rect(); calcOurContentVisibleRect(visibleRect); // Note that sendOurVisibleRect calls viewToContent, so the coordinates // should be in content coordinates. Rect bounds = nativeFocusCandidateNodeBounds(); Rect vBox = contentToViewRect(bounds); mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); if (!Rect.intersects(bounds, visibleRect)) { revealSelection(); } String text = nativeFocusCandidateText(); int nodePointer = nativeFocusCandidatePointer(); mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? Gravity.RIGHT : Gravity.NO_GRAVITY); // This needs to be called before setType, which may call // requestFormData, and it needs to have the correct nodePointer. mWebTextView.setNodePointer(nodePointer); mWebTextView.setType(nativeFocusCandidateType()); updateWebTextViewPadding(); if (null == text) { if (DebugFlags.WEB_VIEW) { Log.v(LOGTAG, "rebuildWebTextView null == text"); } text = ""; } mWebTextView.setTextAndKeepSelection(text); InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null && imm.isActive(mWebTextView)) { imm.restartInput(mWebTextView); } if (isFocused()) { mWebTextView.requestFocus(); } } /** * Update the padding of mWebTextView based on the native textfield/textarea */ void updateWebTextViewPadding() { Rect paddingRect = nativeFocusCandidatePaddingRect(); if (paddingRect != null) { // Use contentToViewDimension since these are the dimensions of // the padding. mWebTextView.setPadding( contentToViewDimension(paddingRect.left), contentToViewDimension(paddingRect.top), contentToViewDimension(paddingRect.right), contentToViewDimension(paddingRect.bottom)); } } /** * Tell webkit to put the cursor on screen. */ /* package */ void revealSelection() { if (mWebViewCore != null) { mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION); } } /** * Called by WebTextView to find saved form data associated with the * textfield * @param name Name of the textfield. * @param nodePointer Pointer to the node of the textfield, so it can be * compared to the currently focused textfield when the data is * retrieved. * @param autoFillable true if WebKit has determined this field is part of * a form that can be auto filled. * @param autoComplete true if the attribute "autocomplete" is set to true * on the textfield. */ /* package */ void requestFormData(String name, int nodePointer, boolean autoFillable, boolean autoComplete) { if (mWebViewCore.getSettings().getSaveFormData()) { Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); update.arg1 = nodePointer; RequestFormData updater = new RequestFormData(name, getUrl(), update, autoFillable, autoComplete); Thread t = new Thread(updater); t.start(); } } /** * Pass a message to find out the