WebView.java revision 90b48b2cde42d7acab99bb065fe6ce4468a0ef2f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import android.annotation.Widget;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.graphics.Bitmap;
23import android.graphics.Canvas;
24import android.graphics.Paint;
25import android.graphics.Picture;
26import android.graphics.Rect;
27import android.graphics.drawable.Drawable;
28import android.net.http.SslCertificate;
29import android.os.Build;
30import android.os.Bundle;
31import android.os.Looper;
32import android.os.Message;
33import android.os.StrictMode;
34import android.print.PrintDocumentAdapter;
35import android.util.AttributeSet;
36import android.util.Log;
37import android.view.KeyEvent;
38import android.view.MotionEvent;
39import android.view.View;
40import android.view.ViewDebug;
41import android.view.ViewGroup;
42import android.view.ViewTreeObserver;
43import android.view.accessibility.AccessibilityEvent;
44import android.view.accessibility.AccessibilityNodeInfo;
45import android.view.accessibility.AccessibilityNodeProvider;
46import android.view.inputmethod.EditorInfo;
47import android.view.inputmethod.InputConnection;
48import android.widget.AbsoluteLayout;
49
50import java.io.BufferedWriter;
51import java.io.File;
52import java.io.OutputStream;
53import java.util.Map;
54
55/**
56 * <p>A View that displays web pages. This class is the basis upon which you
57 * can roll your own web browser or simply display some online content within your Activity.
58 * It uses the WebKit rendering engine to display
59 * web pages and includes methods to navigate forward and backward
60 * through a history, zoom in and out, perform text searches and more.</p>
61 * <p>To enable the built-in zoom, set
62 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
63 * (introduced in API level {@link android.os.Build.VERSION_CODES#CUPCAKE}).
64 * <p>Note that, in order for your Activity to access the Internet and load web pages
65 * in a WebView, you must add the {@code INTERNET} permissions to your
66 * Android Manifest file:</p>
67 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
68 *
69 * <p>This must be a child of the <a
70 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a>
71 * element.</p>
72 *
73 * <p>For more information, read
74 * <a href="{@docRoot}guide/webapps/webview.html">Building Web Apps in WebView</a>.</p>
75 *
76 * <h3>Basic usage</h3>
77 *
78 * <p>By default, a WebView provides no browser-like widgets, does not
79 * enable JavaScript and web page errors are ignored. If your goal is only
80 * to display some HTML as a part of your UI, this is probably fine;
81 * the user won't need to interact with the web page beyond reading
82 * it, and the web page won't need to interact with the user. If you
83 * actually want a full-blown web browser, then you probably want to
84 * invoke the Browser application with a URL Intent rather than show it
85 * with a WebView. For example:
86 * <pre>
87 * Uri uri = Uri.parse("http://www.example.com");
88 * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
89 * startActivity(intent);
90 * </pre>
91 * <p>See {@link android.content.Intent} for more information.</p>
92 *
93 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout,
94 * or set the entire Activity window as a WebView during {@link
95 * android.app.Activity#onCreate(Bundle) onCreate()}:</p>
96 * <pre class="prettyprint">
97 * WebView webview = new WebView(this);
98 * setContentView(webview);
99 * </pre>
100 *
101 * <p>Then load the desired web page:</p>
102 * <pre>
103 * // Simplest usage: note that an exception will NOT be thrown
104 * // if there is an error loading this page (see below).
105 * webview.loadUrl("http://slashdot.org/");
106 *
107 * // OR, you can also load from an HTML string:
108 * String summary = "&lt;html>&lt;body>You scored &lt;b>192&lt;/b> points.&lt;/body>&lt;/html>";
109 * webview.loadData(summary, "text/html", null);
110 * // ... although note that there are restrictions on what this HTML can do.
111 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
112 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
113 * </pre>
114 *
115 * <p>A WebView has several customization points where you can add your
116 * own behavior. These are:</p>
117 *
118 * <ul>
119 *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
120 *       This class is called when something that might impact a
121 *       browser UI happens, for instance, progress updates and
122 *       JavaScript alerts are sent here (see <a
123 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>).
124 *   </li>
125 *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
126 *       It will be called when things happen that impact the
127 *       rendering of the content, eg, errors or form submissions. You
128 *       can also intercept URL loading here (via {@link
129 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String)
130 * shouldOverrideUrlLoading()}).</li>
131 *   <li>Modifying the {@link android.webkit.WebSettings}, such as
132 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean)
133 * setJavaScriptEnabled()}. </li>
134 *   <li>Injecting Java objects into the WebView using the
135 *       {@link android.webkit.WebView#addJavascriptInterface} method. This
136 *       method allows you to inject Java objects into a page's JavaScript
137 *       context, so that they can be accessed by JavaScript in the page.</li>
138 * </ul>
139 *
140 * <p>Here's a more complicated example, showing error handling,
141 *    settings, and progress notification:</p>
142 *
143 * <pre class="prettyprint">
144 * // Let's display the progress in the activity title bar, like the
145 * // browser app does.
146 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
147 *
148 * webview.getSettings().setJavaScriptEnabled(true);
149 *
150 * final Activity activity = this;
151 * webview.setWebChromeClient(new WebChromeClient() {
152 *   public void onProgressChanged(WebView view, int progress) {
153 *     // Activities and WebViews measure progress with different scales.
154 *     // The progress meter will automatically disappear when we reach 100%
155 *     activity.setProgress(progress * 1000);
156 *   }
157 * });
158 * webview.setWebViewClient(new WebViewClient() {
159 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
160 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
161 *   }
162 * });
163 *
164 * webview.loadUrl("http://slashdot.org/");
165 * </pre>
166 *
167 * <h3>Cookie and window management</h3>
168 *
169 * <p>For obvious security reasons, your application has its own
170 * cache, cookie store etc.&mdash;it does not share the Browser
171 * application's data.
172 * </p>
173 *
174 * <p>By default, requests by the HTML to open new windows are
175 * ignored. This is true whether they be opened by JavaScript or by
176 * the target attribute on a link. You can customize your
177 * {@link WebChromeClient} to provide your own behaviour for opening multiple windows,
178 * and render them in whatever manner you want.</p>
179 *
180 * <p>The standard behavior for an Activity is to be destroyed and
181 * recreated when the device orientation or any other configuration changes. This will cause
182 * the WebView to reload the current page. If you don't want that, you
183 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden}
184 * changes, and then just leave the WebView alone. It'll automatically
185 * re-orient itself as appropriate. Read <a
186 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for
187 * more information about how to handle configuration changes during runtime.</p>
188 *
189 *
190 * <h3>Building web pages to support different screen densities</h3>
191 *
192 * <p>The screen density of a device is based on the screen resolution. A screen with low density
193 * has fewer available pixels per inch, where a screen with high density
194 * has more &mdash; sometimes significantly more &mdash; pixels per inch. The density of a
195 * screen is important because, other things being equal, a UI element (such as a button) whose
196 * height and width are defined in terms of screen pixels will appear larger on the lower density
197 * screen and smaller on the higher density screen.
198 * For simplicity, Android collapses all actual screen densities into three generalized densities:
199 * high, medium, and low.</p>
200 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default
201 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen
202 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels
203 * are bigger).
204 * Starting with API level {@link android.os.Build.VERSION_CODES#ECLAIR}, WebView supports DOM, CSS,
205 * and meta tag features to help you (as a web developer) target screens with different screen
206 * densities.</p>
207 * <p>Here's a summary of the features you can use to handle different screen densities:</p>
208 * <ul>
209 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the
210 * default scaling factor used for the current device. For example, if the value of {@code
211 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device
212 * and default scaling is not applied to the web page; if the value is "1.5", then the device is
213 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the
214 * value is "0.75", then the device is considered a low density device (ldpi) and the content is
215 * scaled 0.75x.</li>
216 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen
217 * densities for which this style sheet is to be used. The corresponding value should be either
218 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium
219 * density, or high density screens, respectively. For example:
220 * <pre>
221 * &lt;link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /&gt;</pre>
222 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5,
223 * which is the high density pixel ratio.</p>
224 * </li>
225 *
226 * <h3>HTML5 Video support</h3>
227 *
228 * <p>In order to support inline HTML5 video in your application, you need to have hardware
229 * acceleration turned on, and set a {@link android.webkit.WebChromeClient}. For full screen support,
230 * implementations of {@link WebChromeClient#onShowCustomView(View, WebChromeClient.CustomViewCallback)}
231 * and {@link WebChromeClient#onHideCustomView()} are required,
232 * {@link WebChromeClient#getVideoLoadingProgressView()} is optional.
233 * </p>
234 */
235// Implementation notes.
236// The WebView is a thin API class that delegates its public API to a backend WebViewProvider
237// class instance. WebView extends {@link AbsoluteLayout} for backward compatibility reasons.
238// Methods are delegated to the provider implementation: all public API methods introduced in this
239// file are fully delegated, whereas public and protected methods from the View base classes are
240// only delegated where a specific need exists for them to do so.
241@Widget
242public class WebView extends AbsoluteLayout
243        implements ViewTreeObserver.OnGlobalFocusChangeListener,
244        ViewGroup.OnHierarchyChangeListener, ViewDebug.HierarchyHandler {
245
246    private static final String LOGTAG = "WebView";
247
248    // Throwing an exception for incorrect thread usage if the
249    // build target is JB MR2 or newer. Defaults to false, and is
250    // set in the WebView constructor.
251    private static volatile boolean sEnforceThreadChecking = false;
252
253    /**
254     *  Transportation object for returning WebView across thread boundaries.
255     */
256    public class WebViewTransport {
257        private WebView mWebview;
258
259        /**
260         * Sets the WebView to the transportation object.
261         *
262         * @param webview the WebView to transport
263         */
264        public synchronized void setWebView(WebView webview) {
265            mWebview = webview;
266        }
267
268        /**
269         * Gets the WebView object.
270         *
271         * @return the transported WebView object
272         */
273        public synchronized WebView getWebView() {
274            return mWebview;
275        }
276    }
277
278    /**
279     * URI scheme for telephone number.
280     */
281    public static final String SCHEME_TEL = "tel:";
282    /**
283     * URI scheme for email address.
284     */
285    public static final String SCHEME_MAILTO = "mailto:";
286    /**
287     * URI scheme for map address.
288     */
289    public static final String SCHEME_GEO = "geo:0,0?q=";
290
291    /**
292     * Interface to listen for find results.
293     */
294    public interface FindListener {
295        /**
296         * Notifies the listener about progress made by a find operation.
297         *
298         * @param activeMatchOrdinal the zero-based ordinal of the currently selected match
299         * @param numberOfMatches how many matches have been found
300         * @param isDoneCounting whether the find operation has actually completed. The listener
301         *                       may be notified multiple times while the
302         *                       operation is underway, and the numberOfMatches
303         *                       value should not be considered final unless
304         *                       isDoneCounting is true.
305         */
306        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
307            boolean isDoneCounting);
308    }
309
310    /**
311     * Interface to listen for new pictures as they change.
312     *
313     * @deprecated This interface is now obsolete.
314     */
315    @Deprecated
316    public interface PictureListener {
317        /**
318         * Used to provide notification that the WebView's picture has changed.
319         * See {@link WebView#capturePicture} for details of the picture.
320         *
321         * @param view the WebView that owns the picture
322         * @param picture the new picture. Applications targeting
323         *     {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} or above
324         *     will always receive a null Picture.
325         * @deprecated Deprecated due to internal changes.
326         */
327        @Deprecated
328        public void onNewPicture(WebView view, Picture picture);
329    }
330
331    public static class HitTestResult {
332        /**
333         * Default HitTestResult, where the target is unknown.
334         */
335        public static final int UNKNOWN_TYPE = 0;
336        /**
337         * @deprecated This type is no longer used.
338         */
339        @Deprecated
340        public static final int ANCHOR_TYPE = 1;
341        /**
342         * HitTestResult for hitting a phone number.
343         */
344        public static final int PHONE_TYPE = 2;
345        /**
346         * HitTestResult for hitting a map address.
347         */
348        public static final int GEO_TYPE = 3;
349        /**
350         * HitTestResult for hitting an email address.
351         */
352        public static final int EMAIL_TYPE = 4;
353        /**
354         * HitTestResult for hitting an HTML::img tag.
355         */
356        public static final int IMAGE_TYPE = 5;
357        /**
358         * @deprecated This type is no longer used.
359         */
360        @Deprecated
361        public static final int IMAGE_ANCHOR_TYPE = 6;
362        /**
363         * HitTestResult for hitting a HTML::a tag with src=http.
364         */
365        public static final int SRC_ANCHOR_TYPE = 7;
366        /**
367         * HitTestResult for hitting a HTML::a tag with src=http + HTML::img.
368         */
369        public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
370        /**
371         * HitTestResult for hitting an edit text area.
372         */
373        public static final int EDIT_TEXT_TYPE = 9;
374
375        private int mType;
376        private String mExtra;
377
378        /**
379         * @hide Only for use by WebViewProvider implementations
380         */
381        public HitTestResult() {
382            mType = UNKNOWN_TYPE;
383        }
384
385        /**
386         * @hide Only for use by WebViewProvider implementations
387         */
388        public void setType(int type) {
389            mType = type;
390        }
391
392        /**
393         * @hide Only for use by WebViewProvider implementations
394         */
395        public void setExtra(String extra) {
396            mExtra = extra;
397        }
398
399        /**
400         * Gets the type of the hit test result. See the XXX_TYPE constants
401         * defined in this class.
402         *
403         * @return the type of the hit test result
404         */
405        public int getType() {
406            return mType;
407        }
408
409        /**
410         * Gets additional type-dependant information about the result. See
411         * {@link WebView#getHitTestResult()} for details. May either be null
412         * or contain extra information about this result.
413         *
414         * @return additional type-dependant information about the result
415         */
416        public String getExtra() {
417            return mExtra;
418        }
419    }
420
421    /**
422     * Constructs a new WebView with a Context object.
423     *
424     * @param context a Context object used to access application assets
425     */
426    public WebView(Context context) {
427        this(context, null);
428    }
429
430    /**
431     * Constructs a new WebView with layout parameters.
432     *
433     * @param context a Context object used to access application assets
434     * @param attrs an AttributeSet passed to our parent
435     */
436    public WebView(Context context, AttributeSet attrs) {
437        this(context, attrs, com.android.internal.R.attr.webViewStyle);
438    }
439
440    /**
441     * Constructs a new WebView with layout parameters and a default style.
442     *
443     * @param context a Context object used to access application assets
444     * @param attrs an AttributeSet passed to our parent
445     * @param defStyleAttr an attribute in the current theme that contains a
446     *        reference to a style resource that supplies default values for
447     *        the view. Can be 0 to not look for defaults.
448     */
449    public WebView(Context context, AttributeSet attrs, int defStyleAttr) {
450        this(context, attrs, defStyleAttr, 0);
451    }
452
453    /**
454     * Constructs a new WebView with layout parameters and a default style.
455     *
456     * @param context a Context object used to access application assets
457     * @param attrs an AttributeSet passed to our parent
458     * @param defStyleAttr an attribute in the current theme that contains a
459     *        reference to a style resource that supplies default values for
460     *        the view. Can be 0 to not look for defaults.
461     * @param defStyleRes a resource identifier of a style resource that
462     *        supplies default values for the view, used only if
463     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
464     *        to not look for defaults.
465     */
466    public WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
467        this(context, attrs, defStyleAttr, defStyleRes, null, false);
468    }
469
470    /**
471     * Constructs a new WebView with layout parameters and a default style.
472     *
473     * @param context a Context object used to access application assets
474     * @param attrs an AttributeSet passed to our parent
475     * @param defStyleAttr an attribute in the current theme that contains a
476     *        reference to a style resource that supplies default values for
477     *        the view. Can be 0 to not look for defaults.
478     * @param privateBrowsing whether this WebView will be initialized in
479     *                        private mode
480     *
481     * @deprecated Private browsing is no longer supported directly via
482     * WebView and will be removed in a future release. Prefer using
483     * {@link WebSettings}, {@link WebViewDatabase}, {@link CookieManager}
484     * and {@link WebStorage} for fine-grained control of privacy data.
485     */
486    @Deprecated
487    public WebView(Context context, AttributeSet attrs, int defStyleAttr,
488            boolean privateBrowsing) {
489        this(context, attrs, defStyleAttr, 0, null, privateBrowsing);
490    }
491
492    /**
493     * Constructs a new WebView with layout parameters, a default style and a set
494     * of custom Javscript interfaces to be added to this WebView at initialization
495     * time. This guarantees that these interfaces will be available when the JS
496     * context is initialized.
497     *
498     * @param context a Context object used to access application assets
499     * @param attrs an AttributeSet passed to our parent
500     * @param defStyleAttr an attribute in the current theme that contains a
501     *        reference to a style resource that supplies default values for
502     *        the view. Can be 0 to not look for defaults.
503     * @param javaScriptInterfaces a Map of interface names, as keys, and
504     *                             object implementing those interfaces, as
505     *                             values
506     * @param privateBrowsing whether this WebView will be initialized in
507     *                        private mode
508     * @hide This is used internally by dumprendertree, as it requires the javaScript interfaces to
509     *       be added synchronously, before a subsequent loadUrl call takes effect.
510     */
511    protected WebView(Context context, AttributeSet attrs, int defStyleAttr,
512            Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
513        this(context, attrs, defStyleAttr, 0, javaScriptInterfaces, privateBrowsing);
514    }
515
516    /**
517     * @hide
518     */
519    @SuppressWarnings("deprecation")  // for super() call into deprecated base class constructor.
520    protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes,
521            Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
522        super(context, attrs, defStyleAttr, defStyleRes);
523        if (context == null) {
524            throw new IllegalArgumentException("Invalid context argument");
525        }
526        sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
527                Build.VERSION_CODES.JELLY_BEAN_MR2;
528        checkThread();
529        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "WebView<init>");
530
531        ensureProviderCreated();
532        mProvider.init(javaScriptInterfaces, privateBrowsing);
533        // Post condition of creating a webview is the CookieSyncManager instance exists.
534        CookieSyncManager.createInstance(getContext());
535    }
536
537    /**
538     * Specifies whether the horizontal scrollbar has overlay style.
539     *
540     * @param overlay true if horizontal scrollbar should have overlay style
541     */
542    public void setHorizontalScrollbarOverlay(boolean overlay) {
543        checkThread();
544        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setHorizontalScrollbarOverlay=" + overlay);
545        mProvider.setHorizontalScrollbarOverlay(overlay);
546    }
547
548    /**
549     * Specifies whether the vertical scrollbar has overlay style.
550     *
551     * @param overlay true if vertical scrollbar should have overlay style
552     */
553    public void setVerticalScrollbarOverlay(boolean overlay) {
554        checkThread();
555        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setVerticalScrollbarOverlay=" + overlay);
556        mProvider.setVerticalScrollbarOverlay(overlay);
557    }
558
559    /**
560     * Gets whether horizontal scrollbar has overlay style.
561     *
562     * @return true if horizontal scrollbar has overlay style
563     */
564    public boolean overlayHorizontalScrollbar() {
565        checkThread();
566        return mProvider.overlayHorizontalScrollbar();
567    }
568
569    /**
570     * Gets whether vertical scrollbar has overlay style.
571     *
572     * @return true if vertical scrollbar has overlay style
573     */
574    public boolean overlayVerticalScrollbar() {
575        checkThread();
576        return mProvider.overlayVerticalScrollbar();
577    }
578
579    /**
580     * Gets the visible height (in pixels) of the embedded title bar (if any).
581     *
582     * @deprecated This method is now obsolete.
583     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
584     */
585    public int getVisibleTitleHeight() {
586        checkThread();
587        return mProvider.getVisibleTitleHeight();
588    }
589
590    /**
591     * Gets the SSL certificate for the main top-level page or null if there is
592     * no certificate (the site is not secure).
593     *
594     * @return the SSL certificate for the main top-level page
595     */
596    public SslCertificate getCertificate() {
597        checkThread();
598        return mProvider.getCertificate();
599    }
600
601    /**
602     * Sets the SSL certificate for the main top-level page.
603     *
604     * @deprecated Calling this function has no useful effect, and will be
605     * ignored in future releases.
606     */
607    @Deprecated
608    public void setCertificate(SslCertificate certificate) {
609        checkThread();
610        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setCertificate=" + certificate);
611        mProvider.setCertificate(certificate);
612    }
613
614    //-------------------------------------------------------------------------
615    // Methods called by activity
616    //-------------------------------------------------------------------------
617
618    /**
619     * Sets a username and password pair for the specified host. This data is
620     * used by the Webview to autocomplete username and password fields in web
621     * forms. Note that this is unrelated to the credentials used for HTTP
622     * authentication.
623     *
624     * @param host the host that required the credentials
625     * @param username the username for the given host
626     * @param password the password for the given host
627     * @see WebViewDatabase#clearUsernamePassword
628     * @see WebViewDatabase#hasUsernamePassword
629     * @deprecated Saving passwords in WebView will not be supported in future versions.
630     */
631    @Deprecated
632    public void savePassword(String host, String username, String password) {
633        checkThread();
634        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "savePassword=" + host);
635        mProvider.savePassword(host, username, password);
636    }
637
638    /**
639     * Stores HTTP authentication credentials for a given host and realm. This
640     * method is intended to be used with
641     * {@link WebViewClient#onReceivedHttpAuthRequest}.
642     *
643     * @param host the host to which the credentials apply
644     * @param realm the realm to which the credentials apply
645     * @param username the username
646     * @param password the password
647     * @see #getHttpAuthUsernamePassword
648     * @see WebViewDatabase#hasHttpAuthUsernamePassword
649     * @see WebViewDatabase#clearHttpAuthUsernamePassword
650     */
651    public void setHttpAuthUsernamePassword(String host, String realm,
652            String username, String password) {
653        checkThread();
654        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setHttpAuthUsernamePassword=" + host);
655        mProvider.setHttpAuthUsernamePassword(host, realm, username, password);
656    }
657
658    /**
659     * Retrieves HTTP authentication credentials for a given host and realm.
660     * This method is intended to be used with
661     * {@link WebViewClient#onReceivedHttpAuthRequest}.
662     *
663     * @param host the host to which the credentials apply
664     * @param realm the realm to which the credentials apply
665     * @return the credentials as a String array, if found. The first element
666     *         is the username and the second element is the password. Null if
667     *         no credentials are found.
668     * @see #setHttpAuthUsernamePassword
669     * @see WebViewDatabase#hasHttpAuthUsernamePassword
670     * @see WebViewDatabase#clearHttpAuthUsernamePassword
671     */
672    public String[] getHttpAuthUsernamePassword(String host, String realm) {
673        checkThread();
674        return mProvider.getHttpAuthUsernamePassword(host, realm);
675    }
676
677    /**
678     * Destroys the internal state of this WebView. This method should be called
679     * after this WebView has been removed from the view system. No other
680     * methods may be called on this WebView after destroy.
681     */
682    public void destroy() {
683        checkThread();
684        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "destroy");
685        mProvider.destroy();
686    }
687
688    /**
689     * Enables platform notifications of data state and proxy changes.
690     * Notifications are enabled by default.
691     *
692     * @deprecated This method is now obsolete.
693     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
694     */
695    @Deprecated
696    public static void enablePlatformNotifications() {
697        checkThread();
698        getFactory().getStatics().setPlatformNotificationsEnabled(true);
699    }
700
701    /**
702     * Disables platform notifications of data state and proxy changes.
703     * Notifications are enabled by default.
704     *
705     * @deprecated This method is now obsolete.
706     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
707     */
708    @Deprecated
709    public static void disablePlatformNotifications() {
710        checkThread();
711        getFactory().getStatics().setPlatformNotificationsEnabled(false);
712    }
713
714    /**
715     * Used only by internal tests to free up memory.
716     *
717     * @hide
718     */
719    public static void freeMemoryForTests() {
720        checkThread();
721        getFactory().getStatics().freeMemoryForTests();
722    }
723
724    /**
725     * Informs WebView of the network state. This is used to set
726     * the JavaScript property window.navigator.isOnline and
727     * generates the online/offline event as specified in HTML5, sec. 5.7.7
728     *
729     * @param networkUp a boolean indicating if network is available
730     */
731    public void setNetworkAvailable(boolean networkUp) {
732        checkThread();
733        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setNetworkAvailable=" + networkUp);
734        mProvider.setNetworkAvailable(networkUp);
735    }
736
737    /**
738     * Saves the state of this WebView used in
739     * {@link android.app.Activity#onSaveInstanceState}. Please note that this
740     * method no longer stores the display data for this WebView. The previous
741     * behavior could potentially leak files if {@link #restoreState} was never
742     * called.
743     *
744     * @param outState the Bundle to store this WebView's state
745     * @return the same copy of the back/forward list used to save the state. If
746     *         saveState fails, the returned list will be null.
747     */
748    public WebBackForwardList saveState(Bundle outState) {
749        checkThread();
750        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveState");
751        return mProvider.saveState(outState);
752    }
753
754    /**
755     * Saves the current display data to the Bundle given. Used in conjunction
756     * with {@link #saveState}.
757     * @param b a Bundle to store the display data
758     * @param dest the file to store the serialized picture data. Will be
759     *             overwritten with this WebView's picture data.
760     * @return true if the picture was successfully saved
761     * @deprecated This method is now obsolete.
762     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
763     */
764    @Deprecated
765    public boolean savePicture(Bundle b, final File dest) {
766        checkThread();
767        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "savePicture=" + dest.getName());
768        return mProvider.savePicture(b, dest);
769    }
770
771    /**
772     * Restores the display data that was saved in {@link #savePicture}. Used in
773     * conjunction with {@link #restoreState}. Note that this will not work if
774     * this WebView is hardware accelerated.
775     *
776     * @param b a Bundle containing the saved display data
777     * @param src the file where the picture data was stored
778     * @return true if the picture was successfully restored
779     * @deprecated This method is now obsolete.
780     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
781     */
782    @Deprecated
783    public boolean restorePicture(Bundle b, File src) {
784        checkThread();
785        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "restorePicture=" + src.getName());
786        return mProvider.restorePicture(b, src);
787    }
788
789    /**
790     * Restores the state of this WebView from the given Bundle. This method is
791     * intended for use in {@link android.app.Activity#onRestoreInstanceState}
792     * and should be called to restore the state of this WebView. If
793     * it is called after this WebView has had a chance to build state (load
794     * pages, create a back/forward list, etc.) there may be undesirable
795     * side-effects. Please note that this method no longer restores the
796     * display data for this WebView.
797     *
798     * @param inState the incoming Bundle of state
799     * @return the restored back/forward list or null if restoreState failed
800     */
801    public WebBackForwardList restoreState(Bundle inState) {
802        checkThread();
803        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "restoreState");
804        return mProvider.restoreState(inState);
805    }
806
807    /**
808     * Loads the given URL with the specified additional HTTP headers.
809     *
810     * @param url the URL of the resource to load
811     * @param additionalHttpHeaders the additional headers to be used in the
812     *            HTTP request for this URL, specified as a map from name to
813     *            value. Note that if this map contains any of the headers
814     *            that are set by default by this WebView, such as those
815     *            controlling caching, accept types or the User-Agent, their
816     *            values may be overriden by this WebView's defaults.
817     */
818    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
819        checkThread();
820        if (DebugFlags.TRACE_API) {
821            StringBuilder headers = new StringBuilder();
822            if (additionalHttpHeaders != null) {
823                for (Map.Entry<String, String> entry : additionalHttpHeaders.entrySet()) {
824                    headers.append(entry.getKey() + ":" + entry.getValue() + "\n");
825                }
826            }
827            Log.d(LOGTAG, "loadUrl(extra headers)=" + url + "\n" + headers);
828        }
829        mProvider.loadUrl(url, additionalHttpHeaders);
830    }
831
832    /**
833     * Loads the given URL.
834     *
835     * @param url the URL of the resource to load
836     */
837    public void loadUrl(String url) {
838        checkThread();
839        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadUrl=" + url);
840        mProvider.loadUrl(url);
841    }
842
843    /**
844     * Loads the URL with postData using "POST" method into this WebView. If url
845     * is not a network URL, it will be loaded with {link
846     * {@link #loadUrl(String)} instead.
847     *
848     * @param url the URL of the resource to load
849     * @param postData the data will be passed to "POST" request, which must be
850     *     be "application/x-www-form-urlencoded" encoded.
851     */
852    public void postUrl(String url, byte[] postData) {
853        checkThread();
854        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "postUrl=" + url);
855        mProvider.postUrl(url, postData);
856    }
857
858    /**
859     * Loads the given data into this WebView using a 'data' scheme URL.
860     * <p>
861     * Note that JavaScript's same origin policy means that script running in a
862     * page loaded using this method will be unable to access content loaded
863     * using any scheme other than 'data', including 'http(s)'. To avoid this
864     * restriction, use {@link
865     * #loadDataWithBaseURL(String,String,String,String,String)
866     * loadDataWithBaseURL()} with an appropriate base URL.
867     * <p>
868     * The encoding parameter specifies whether the data is base64 or URL
869     * encoded. If the data is base64 encoded, the value of the encoding
870     * parameter must be 'base64'. For all other values of the parameter,
871     * including null, it is assumed that the data uses ASCII encoding for
872     * octets inside the range of safe URL characters and use the standard %xx
873     * hex encoding of URLs for octets outside that range. For example, '#',
874     * '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
875     * <p>
876     * The 'data' scheme URL formed by this method uses the default US-ASCII
877     * charset. If you need need to set a different charset, you should form a
878     * 'data' scheme URL which explicitly specifies a charset parameter in the
879     * mediatype portion of the URL and call {@link #loadUrl(String)} instead.
880     * Note that the charset obtained from the mediatype portion of a data URL
881     * always overrides that specified in the HTML or XML document itself.
882     *
883     * @param data a String of data in the given encoding
884     * @param mimeType the MIME type of the data, e.g. 'text/html'
885     * @param encoding the encoding of the data
886     */
887    public void loadData(String data, String mimeType, String encoding) {
888        checkThread();
889        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadData");
890        mProvider.loadData(data, mimeType, encoding);
891    }
892
893    /**
894     * Loads the given data into this WebView, using baseUrl as the base URL for
895     * the content. The base URL is used both to resolve relative URLs and when
896     * applying JavaScript's same origin policy. The historyUrl is used for the
897     * history entry.
898     * <p>
899     * Note that content specified in this way can access local device files
900     * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
901     * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
902     * <p>
903     * If the base URL uses the data scheme, this method is equivalent to
904     * calling {@link #loadData(String,String,String) loadData()} and the
905     * historyUrl is ignored, and the data will be treated as part of a data: URL.
906     * If the base URL uses any other scheme, then the data will be loaded into
907     * the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded
908     * entities in the string will not be decoded.
909     *
910     * @param baseUrl the URL to use as the page's base URL. If null defaults to
911     *                'about:blank'.
912     * @param data a String of data in the given encoding
913     * @param mimeType the MIMEType of the data, e.g. 'text/html'. If null,
914     *                 defaults to 'text/html'.
915     * @param encoding the encoding of the data
916     * @param historyUrl the URL to use as the history entry. If null defaults
917     *                   to 'about:blank'. If non-null, this must be a valid URL.
918     */
919    public void loadDataWithBaseURL(String baseUrl, String data,
920            String mimeType, String encoding, String historyUrl) {
921        checkThread();
922        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "loadDataWithBaseURL=" + baseUrl);
923        mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
924    }
925
926    /**
927     * Asynchronously evaluates JavaScript in the context of the currently displayed page.
928     * If non-null, |resultCallback| will be invoked with any result returned from that
929     * execution. This method must be called on the UI thread and the callback will
930     * be made on the UI thread.
931     *
932     * @param script the JavaScript to execute.
933     * @param resultCallback A callback to be invoked when the script execution
934     *                       completes with the result of the execution (if any).
935     *                       May be null if no notificaion of the result is required.
936     */
937    public void evaluateJavascript(String script, ValueCallback<String> resultCallback) {
938        checkThread();
939        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "evaluateJavascript=" + script);
940        mProvider.evaluateJavaScript(script, resultCallback);
941    }
942
943    /**
944     * Saves the current view as a web archive.
945     *
946     * @param filename the filename where the archive should be placed
947     */
948    public void saveWebArchive(String filename) {
949        checkThread();
950        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveWebArchive=" + filename);
951        mProvider.saveWebArchive(filename);
952    }
953
954    /**
955     * Saves the current view as a web archive.
956     *
957     * @param basename the filename where the archive should be placed
958     * @param autoname if false, takes basename to be a file. If true, basename
959     *                 is assumed to be a directory in which a filename will be
960     *                 chosen according to the URL of the current page.
961     * @param callback called after the web archive has been saved. The
962     *                 parameter for onReceiveValue will either be the filename
963     *                 under which the file was saved, or null if saving the
964     *                 file failed.
965     */
966    public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
967        checkThread();
968        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "saveWebArchive(auto)=" + basename);
969        mProvider.saveWebArchive(basename, autoname, callback);
970    }
971
972    /**
973     * Stops the current load.
974     */
975    public void stopLoading() {
976        checkThread();
977        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "stopLoading");
978        mProvider.stopLoading();
979    }
980
981    /**
982     * Reloads the current URL.
983     */
984    public void reload() {
985        checkThread();
986        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "reload");
987        mProvider.reload();
988    }
989
990    /**
991     * Gets whether this WebView has a back history item.
992     *
993     * @return true iff this WebView has a back history item
994     */
995    public boolean canGoBack() {
996        checkThread();
997        return mProvider.canGoBack();
998    }
999
1000    /**
1001     * Goes back in the history of this WebView.
1002     */
1003    public void goBack() {
1004        checkThread();
1005        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goBack");
1006        mProvider.goBack();
1007    }
1008
1009    /**
1010     * Gets whether this WebView has a forward history item.
1011     *
1012     * @return true iff this Webview has a forward history item
1013     */
1014    public boolean canGoForward() {
1015        checkThread();
1016        return mProvider.canGoForward();
1017    }
1018
1019    /**
1020     * Goes forward in the history of this WebView.
1021     */
1022    public void goForward() {
1023        checkThread();
1024        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goForward");
1025        mProvider.goForward();
1026    }
1027
1028    /**
1029     * Gets whether the page can go back or forward the given
1030     * number of steps.
1031     *
1032     * @param steps the negative or positive number of steps to move the
1033     *              history
1034     */
1035    public boolean canGoBackOrForward(int steps) {
1036        checkThread();
1037        return mProvider.canGoBackOrForward(steps);
1038    }
1039
1040    /**
1041     * Goes to the history item that is the number of steps away from
1042     * the current item. Steps is negative if backward and positive
1043     * if forward.
1044     *
1045     * @param steps the number of steps to take back or forward in the back
1046     *              forward list
1047     */
1048    public void goBackOrForward(int steps) {
1049        checkThread();
1050        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "goBackOrForwad=" + steps);
1051        mProvider.goBackOrForward(steps);
1052    }
1053
1054    /**
1055     * Gets whether private browsing is enabled in this WebView.
1056     */
1057    public boolean isPrivateBrowsingEnabled() {
1058        checkThread();
1059        return mProvider.isPrivateBrowsingEnabled();
1060    }
1061
1062    /**
1063     * Scrolls the contents of this WebView up by half the view size.
1064     *
1065     * @param top true to jump to the top of the page
1066     * @return true if the page was scrolled
1067     */
1068    public boolean pageUp(boolean top) {
1069        checkThread();
1070        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pageUp");
1071        return mProvider.pageUp(top);
1072    }
1073
1074    /**
1075     * Scrolls the contents of this WebView down by half the page size.
1076     *
1077     * @param bottom true to jump to bottom of page
1078     * @return true if the page was scrolled
1079     */
1080    public boolean pageDown(boolean bottom) {
1081        checkThread();
1082        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pageDown");
1083        return mProvider.pageDown(bottom);
1084    }
1085
1086    /**
1087     * Clears this WebView so that onDraw() will draw nothing but white background,
1088     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY.
1089     * @deprecated Use WebView.loadUrl("about:blank") to reliably reset the view state
1090     *             and release page resources (including any running JavaScript).
1091     */
1092    @Deprecated
1093    public void clearView() {
1094        checkThread();
1095        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearView");
1096        mProvider.clearView();
1097    }
1098
1099    /**
1100     * Gets a new picture that captures the current contents of this WebView.
1101     * The picture is of the entire document being displayed, and is not
1102     * limited to the area currently displayed by this WebView. Also, the
1103     * picture is a static copy and is unaffected by later changes to the
1104     * content being displayed.
1105     * <p>
1106     * Note that due to internal changes, for API levels between
1107     * {@link android.os.Build.VERSION_CODES#HONEYCOMB} and
1108     * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} inclusive, the
1109     * picture does not include fixed position elements or scrollable divs.
1110     *
1111     * @return a picture that captures the current contents of this WebView
1112     */
1113    public Picture capturePicture() {
1114        checkThread();
1115        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "capturePicture");
1116        return mProvider.capturePicture();
1117    }
1118
1119    /**
1120     * Creates a PrintDocumentAdapter that provides the content of this Webview for printing.
1121     * Only supported for API levels
1122     * {@link android.os.Build.VERSION_CODES#KITKAT} and above.
1123     *
1124     * The adapter works by converting the Webview contents to a PDF stream. The Webview cannot
1125     * be drawn during the conversion process - any such draws are undefined. It is recommended
1126     * to use a dedicated off screen Webview for the printing. If necessary, an application may
1127     * temporarily hide a visible WebView by using a custom PrintDocumentAdapter instance
1128     * wrapped around the object returned and observing the onStart and onFinish methods. See
1129     * {@link android.print.PrintDocumentAdapter} for more information.
1130     */
1131    public PrintDocumentAdapter createPrintDocumentAdapter() {
1132        checkThread();
1133        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "createPrintDocumentAdapter");
1134        return mProvider.createPrintDocumentAdapter();
1135    }
1136
1137    /**
1138     * Gets the current scale of this WebView.
1139     *
1140     * @return the current scale
1141     *
1142     * @deprecated This method is prone to inaccuracy due to race conditions
1143     * between the web rendering and UI threads; prefer
1144     * {@link WebViewClient#onScaleChanged}.
1145     */
1146    @Deprecated
1147    @ViewDebug.ExportedProperty(category = "webview")
1148    public float getScale() {
1149        checkThread();
1150        return mProvider.getScale();
1151    }
1152
1153    /**
1154     * Sets the initial scale for this WebView. 0 means default.
1155     * The behavior for the default scale depends on the state of
1156     * {@link WebSettings#getUseWideViewPort()} and
1157     * {@link WebSettings#getLoadWithOverviewMode()}.
1158     * If the content fits into the WebView control by width, then
1159     * the zoom is set to 100%. For wide content, the behavor
1160     * depends on the state of {@link WebSettings#getLoadWithOverviewMode()}.
1161     * If its value is true, the content will be zoomed out to be fit
1162     * by width into the WebView control, otherwise not.
1163     *
1164     * If initial scale is greater than 0, WebView starts with this value
1165     * as initial scale.
1166     * Please note that unlike the scale properties in the viewport meta tag,
1167     * this method doesn't take the screen density into account.
1168     *
1169     * @param scaleInPercent the initial scale in percent
1170     */
1171    public void setInitialScale(int scaleInPercent) {
1172        checkThread();
1173        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setInitialScale=" + scaleInPercent);
1174        mProvider.setInitialScale(scaleInPercent);
1175    }
1176
1177    /**
1178     * Invokes the graphical zoom picker widget for this WebView. This will
1179     * result in the zoom widget appearing on the screen to control the zoom
1180     * level of this WebView.
1181     */
1182    public void invokeZoomPicker() {
1183        checkThread();
1184        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "invokeZoomPicker");
1185        mProvider.invokeZoomPicker();
1186    }
1187
1188    /**
1189     * Gets a HitTestResult based on the current cursor node. If a HTML::a
1190     * tag is found and the anchor has a non-JavaScript URL, the HitTestResult
1191     * type is set to SRC_ANCHOR_TYPE and the URL is set in the "extra" field.
1192     * If the anchor does not have a URL or if it is a JavaScript URL, the type
1193     * will be UNKNOWN_TYPE and the URL has to be retrieved through
1194     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1195     * found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in
1196     * the "extra" field. A type of
1197     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as
1198     * a child node. If a phone number is found, the HitTestResult type is set
1199     * to PHONE_TYPE and the phone number is set in the "extra" field of
1200     * HitTestResult. If a map address is found, the HitTestResult type is set
1201     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1202     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1203     * and the email is set in the "extra" field of HitTestResult. Otherwise,
1204     * HitTestResult type is set to UNKNOWN_TYPE.
1205     */
1206    public HitTestResult getHitTestResult() {
1207        checkThread();
1208        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "getHitTestResult");
1209        return mProvider.getHitTestResult();
1210    }
1211
1212    /**
1213     * Requests the anchor or image element URL at the last tapped point.
1214     * If hrefMsg is null, this method returns immediately and does not
1215     * dispatch hrefMsg to its target. If the tapped point hits an image,
1216     * an anchor, or an image in an anchor, the message associates
1217     * strings in named keys in its data. The value paired with the key
1218     * may be an empty string.
1219     *
1220     * @param hrefMsg the message to be dispatched with the result of the
1221     *                request. The message data contains three keys. "url"
1222     *                returns the anchor's href attribute. "title" returns the
1223     *                anchor's text. "src" returns the image's src attribute.
1224     */
1225    public void requestFocusNodeHref(Message hrefMsg) {
1226        checkThread();
1227        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "requestFocusNodeHref");
1228        mProvider.requestFocusNodeHref(hrefMsg);
1229    }
1230
1231    /**
1232     * Requests the URL of the image last touched by the user. msg will be sent
1233     * to its target with a String representing the URL as its object.
1234     *
1235     * @param msg the message to be dispatched with the result of the request
1236     *            as the data member with "url" as key. The result can be null.
1237     */
1238    public void requestImageRef(Message msg) {
1239        checkThread();
1240        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "requestImageRef");
1241        mProvider.requestImageRef(msg);
1242    }
1243
1244    /**
1245     * Gets the URL for the current page. This is not always the same as the URL
1246     * passed to WebViewClient.onPageStarted because although the load for
1247     * that URL has begun, the current page may not have changed.
1248     *
1249     * @return the URL for the current page
1250     */
1251    @ViewDebug.ExportedProperty(category = "webview")
1252    public String getUrl() {
1253        checkThread();
1254        return mProvider.getUrl();
1255    }
1256
1257    /**
1258     * Gets the original URL for the current page. This is not always the same
1259     * as the URL passed to WebViewClient.onPageStarted because although the
1260     * load for that URL has begun, the current page may not have changed.
1261     * Also, there may have been redirects resulting in a different URL to that
1262     * originally requested.
1263     *
1264     * @return the URL that was originally requested for the current page
1265     */
1266    @ViewDebug.ExportedProperty(category = "webview")
1267    public String getOriginalUrl() {
1268        checkThread();
1269        return mProvider.getOriginalUrl();
1270    }
1271
1272    /**
1273     * Gets the title for the current page. This is the title of the current page
1274     * until WebViewClient.onReceivedTitle is called.
1275     *
1276     * @return the title for the current page
1277     */
1278    @ViewDebug.ExportedProperty(category = "webview")
1279    public String getTitle() {
1280        checkThread();
1281        return mProvider.getTitle();
1282    }
1283
1284    /**
1285     * Gets the favicon for the current page. This is the favicon of the current
1286     * page until WebViewClient.onReceivedIcon is called.
1287     *
1288     * @return the favicon for the current page
1289     */
1290    public Bitmap getFavicon() {
1291        checkThread();
1292        return mProvider.getFavicon();
1293    }
1294
1295    /**
1296     * Gets the touch icon URL for the apple-touch-icon <link> element, or
1297     * a URL on this site's server pointing to the standard location of a
1298     * touch icon.
1299     *
1300     * @hide
1301     */
1302    public String getTouchIconUrl() {
1303        return mProvider.getTouchIconUrl();
1304    }
1305
1306    /**
1307     * Gets the progress for the current page.
1308     *
1309     * @return the progress for the current page between 0 and 100
1310     */
1311    public int getProgress() {
1312        checkThread();
1313        return mProvider.getProgress();
1314    }
1315
1316    /**
1317     * Gets the height of the HTML content.
1318     *
1319     * @return the height of the HTML content
1320     */
1321    @ViewDebug.ExportedProperty(category = "webview")
1322    public int getContentHeight() {
1323        checkThread();
1324        return mProvider.getContentHeight();
1325    }
1326
1327    /**
1328     * Gets the width of the HTML content.
1329     *
1330     * @return the width of the HTML content
1331     * @hide
1332     */
1333    @ViewDebug.ExportedProperty(category = "webview")
1334    public int getContentWidth() {
1335        return mProvider.getContentWidth();
1336    }
1337
1338    /**
1339     * Pauses all layout, parsing, and JavaScript timers for all WebViews. This
1340     * is a global requests, not restricted to just this WebView. This can be
1341     * useful if the application has been paused.
1342     */
1343    public void pauseTimers() {
1344        checkThread();
1345        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "pauseTimers");
1346        mProvider.pauseTimers();
1347    }
1348
1349    /**
1350     * Resumes all layout, parsing, and JavaScript timers for all WebViews.
1351     * This will resume dispatching all timers.
1352     */
1353    public void resumeTimers() {
1354        checkThread();
1355        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "resumeTimers");
1356        mProvider.resumeTimers();
1357    }
1358
1359    /**
1360     * Pauses any extra processing associated with this WebView and its
1361     * associated DOM, plugins, JavaScript etc. For example, if this WebView is
1362     * taken offscreen, this could be called to reduce unnecessary CPU or
1363     * network traffic. When this WebView is again "active", call onResume().
1364     * Note that this differs from pauseTimers(), which affects all WebViews.
1365     */
1366    public void onPause() {
1367        checkThread();
1368        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "onPause");
1369        mProvider.onPause();
1370    }
1371
1372    /**
1373     * Resumes a WebView after a previous call to onPause().
1374     */
1375    public void onResume() {
1376        checkThread();
1377        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "onResume");
1378        mProvider.onResume();
1379    }
1380
1381    /**
1382     * Gets whether this WebView is paused, meaning onPause() was called.
1383     * Calling onResume() sets the paused state back to false.
1384     *
1385     * @hide
1386     */
1387    public boolean isPaused() {
1388        return mProvider.isPaused();
1389    }
1390
1391    /**
1392     * Informs this WebView that memory is low so that it can free any available
1393     * memory.
1394     */
1395    public void freeMemory() {
1396        checkThread();
1397        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "freeMemory");
1398        mProvider.freeMemory();
1399    }
1400
1401    /**
1402     * Clears the resource cache. Note that the cache is per-application, so
1403     * this will clear the cache for all WebViews used.
1404     *
1405     * @param includeDiskFiles if false, only the RAM cache is cleared
1406     */
1407    public void clearCache(boolean includeDiskFiles) {
1408        checkThread();
1409        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearCache");
1410        mProvider.clearCache(includeDiskFiles);
1411    }
1412
1413    /**
1414     * Removes the autocomplete popup from the currently focused form field, if
1415     * present. Note this only affects the display of the autocomplete popup,
1416     * it does not remove any saved form data from this WebView's store. To do
1417     * that, use {@link WebViewDatabase#clearFormData}.
1418     */
1419    public void clearFormData() {
1420        checkThread();
1421        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearFormData");
1422        mProvider.clearFormData();
1423    }
1424
1425    /**
1426     * Tells this WebView to clear its internal back/forward list.
1427     */
1428    public void clearHistory() {
1429        checkThread();
1430        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearHistory");
1431        mProvider.clearHistory();
1432    }
1433
1434    /**
1435     * Clears the SSL preferences table stored in response to proceeding with
1436     * SSL certificate errors.
1437     */
1438    public void clearSslPreferences() {
1439        checkThread();
1440        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearSslPreferences");
1441        mProvider.clearSslPreferences();
1442    }
1443
1444    /**
1445     * Gets the WebBackForwardList for this WebView. This contains the
1446     * back/forward list for use in querying each item in the history stack.
1447     * This is a copy of the private WebBackForwardList so it contains only a
1448     * snapshot of the current state. Multiple calls to this method may return
1449     * different objects. The object returned from this method will not be
1450     * updated to reflect any new state.
1451     */
1452    public WebBackForwardList copyBackForwardList() {
1453        checkThread();
1454        return mProvider.copyBackForwardList();
1455
1456    }
1457
1458    /**
1459     * Registers the listener to be notified as find-on-page operations
1460     * progress. This will replace the current listener.
1461     *
1462     * @param listener an implementation of {@link FindListener}
1463     */
1464    public void setFindListener(FindListener listener) {
1465        checkThread();
1466        setupFindListenerIfNeeded();
1467        mFindListener.mUserFindListener = listener;
1468    }
1469
1470    /**
1471     * Highlights and scrolls to the next match found by
1472     * {@link #findAllAsync}, wrapping around page boundaries as necessary.
1473     * Notifies any registered {@link FindListener}. If {@link #findAllAsync(String)}
1474     * has not been called yet, or if {@link #clearMatches} has been called since the
1475     * last find operation, this function does nothing.
1476     *
1477     * @param forward the direction to search
1478     * @see #setFindListener
1479     */
1480    public void findNext(boolean forward) {
1481        checkThread();
1482        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findNext");
1483        mProvider.findNext(forward);
1484    }
1485
1486    /**
1487     * Finds all instances of find on the page and highlights them.
1488     * Notifies any registered {@link FindListener}.
1489     *
1490     * @param find the string to find
1491     * @return the number of occurances of the String "find" that were found
1492     * @deprecated {@link #findAllAsync} is preferred.
1493     * @see #setFindListener
1494     */
1495    @Deprecated
1496    public int findAll(String find) {
1497        checkThread();
1498        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findAll");
1499        StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync");
1500        return mProvider.findAll(find);
1501    }
1502
1503    /**
1504     * Finds all instances of find on the page and highlights them,
1505     * asynchronously. Notifies any registered {@link FindListener}.
1506     * Successive calls to this will cancel any pending searches.
1507     *
1508     * @param find the string to find.
1509     * @see #setFindListener
1510     */
1511    public void findAllAsync(String find) {
1512        checkThread();
1513        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "findAllAsync");
1514        mProvider.findAllAsync(find);
1515    }
1516
1517    /**
1518     * Starts an ActionMode for finding text in this WebView.  Only works if this
1519     * WebView is attached to the view system.
1520     *
1521     * @param text if non-null, will be the initial text to search for.
1522     *             Otherwise, the last String searched for in this WebView will
1523     *             be used to start.
1524     * @param showIme if true, show the IME, assuming the user will begin typing.
1525     *                If false and text is non-null, perform a find all.
1526     * @return true if the find dialog is shown, false otherwise
1527     * @deprecated This method does not work reliably on all Android versions;
1528     *             implementing a custom find dialog using WebView.findAllAsync()
1529     *             provides a more robust solution.
1530     */
1531    @Deprecated
1532    public boolean showFindDialog(String text, boolean showIme) {
1533        checkThread();
1534        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "showFindDialog");
1535        return mProvider.showFindDialog(text, showIme);
1536    }
1537
1538    /**
1539     * Gets the first substring consisting of the address of a physical
1540     * location. Currently, only addresses in the United States are detected,
1541     * and consist of:
1542     * <ul>
1543     *   <li>a house number</li>
1544     *   <li>a street name</li>
1545     *   <li>a street type (Road, Circle, etc), either spelled out or
1546     *       abbreviated</li>
1547     *   <li>a city name</li>
1548     *   <li>a state or territory, either spelled out or two-letter abbr</li>
1549     *   <li>an optional 5 digit or 9 digit zip code</li>
1550     * </ul>
1551     * All names must be correctly capitalized, and the zip code, if present,
1552     * must be valid for the state. The street type must be a standard USPS
1553     * spelling or abbreviation. The state or territory must also be spelled
1554     * or abbreviated using USPS standards. The house number may not exceed
1555     * five digits.
1556     *
1557     * @param addr the string to search for addresses
1558     * @return the address, or if no address is found, null
1559     */
1560    public static String findAddress(String addr) {
1561        return getFactory().getStatics().findAddress(addr);
1562    }
1563
1564    /**
1565     * Clears the highlighting surrounding text matches created by
1566     * {@link #findAllAsync}.
1567     */
1568    public void clearMatches() {
1569        checkThread();
1570        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "clearMatches");
1571        mProvider.clearMatches();
1572    }
1573
1574    /**
1575     * Queries the document to see if it contains any image references. The
1576     * message object will be dispatched with arg1 being set to 1 if images
1577     * were found and 0 if the document does not reference any images.
1578     *
1579     * @param response the message that will be dispatched with the result
1580     */
1581    public void documentHasImages(Message response) {
1582        checkThread();
1583        mProvider.documentHasImages(response);
1584    }
1585
1586    /**
1587     * Sets the WebViewClient that will receive various notifications and
1588     * requests. This will replace the current handler.
1589     *
1590     * @param client an implementation of WebViewClient
1591     */
1592    public void setWebViewClient(WebViewClient client) {
1593        checkThread();
1594        mProvider.setWebViewClient(client);
1595    }
1596
1597    /**
1598     * Registers the interface to be used when content can not be handled by
1599     * the rendering engine, and should be downloaded instead. This will replace
1600     * the current handler.
1601     *
1602     * @param listener an implementation of DownloadListener
1603     */
1604    public void setDownloadListener(DownloadListener listener) {
1605        checkThread();
1606        mProvider.setDownloadListener(listener);
1607    }
1608
1609    /**
1610     * Sets the chrome handler. This is an implementation of WebChromeClient for
1611     * use in handling JavaScript dialogs, favicons, titles, and the progress.
1612     * This will replace the current handler.
1613     *
1614     * @param client an implementation of WebChromeClient
1615     */
1616    public void setWebChromeClient(WebChromeClient client) {
1617        checkThread();
1618        mProvider.setWebChromeClient(client);
1619    }
1620
1621    /**
1622     * Sets the Picture listener. This is an interface used to receive
1623     * notifications of a new Picture.
1624     *
1625     * @param listener an implementation of WebView.PictureListener
1626     * @deprecated This method is now obsolete.
1627     */
1628    @Deprecated
1629    public void setPictureListener(PictureListener listener) {
1630        checkThread();
1631        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "setPictureListener=" + listener);
1632        mProvider.setPictureListener(listener);
1633    }
1634
1635    /**
1636     * Injects the supplied Java object into this WebView. The object is
1637     * injected into the JavaScript context of the main frame, using the
1638     * supplied name. This allows the Java object's methods to be
1639     * accessed from JavaScript. For applications targeted to API
1640     * level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1641     * and above, only public methods that are annotated with
1642     * {@link android.webkit.JavascriptInterface} can be accessed from JavaScript.
1643     * For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below,
1644     * all public methods (including the inherited ones) can be accessed, see the
1645     * important security note below for implications.
1646     * <p> Note that injected objects will not
1647     * appear in JavaScript until the page is next (re)loaded. For example:
1648     * <pre>
1649     * class JsObject {
1650     *    {@literal @}JavascriptInterface
1651     *    public String toString() { return "injectedObject"; }
1652     * }
1653     * webView.addJavascriptInterface(new JsObject(), "injectedObject");
1654     * webView.loadData("<!DOCTYPE html><title></title>", "text/html", null);
1655     * webView.loadUrl("javascript:alert(injectedObject.toString())");</pre>
1656     * <p>
1657     * <strong>IMPORTANT:</strong>
1658     * <ul>
1659     * <li> This method can be used to allow JavaScript to control the host
1660     * application. This is a powerful feature, but also presents a security
1661     * risk for applications targeted to API level
1662     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, because
1663     * JavaScript could use reflection to access an
1664     * injected object's public fields. Use of this method in a WebView
1665     * containing untrusted content could allow an attacker to manipulate the
1666     * host application in unintended ways, executing Java code with the
1667     * permissions of the host application. Use extreme care when using this
1668     * method in a WebView which could contain untrusted content.</li>
1669     * <li> JavaScript interacts with Java object on a private, background
1670     * thread of this WebView. Care is therefore required to maintain thread
1671     * safety.</li>
1672     * <li> The Java object's fields are not accessible.</li>
1673     * </ul>
1674     *
1675     * @param object the Java object to inject into this WebView's JavaScript
1676     *               context. Null values are ignored.
1677     * @param name the name used to expose the object in JavaScript
1678     */
1679    public void addJavascriptInterface(Object object, String name) {
1680        checkThread();
1681        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "addJavascriptInterface=" + name);
1682        mProvider.addJavascriptInterface(object, name);
1683    }
1684
1685    /**
1686     * Removes a previously injected Java object from this WebView. Note that
1687     * the removal will not be reflected in JavaScript until the page is next
1688     * (re)loaded. See {@link #addJavascriptInterface}.
1689     *
1690     * @param name the name used to expose the object in JavaScript
1691     */
1692    public void removeJavascriptInterface(String name) {
1693        checkThread();
1694        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "removeJavascriptInterface=" + name);
1695        mProvider.removeJavascriptInterface(name);
1696    }
1697
1698    /**
1699     * Gets the WebSettings object used to control the settings for this
1700     * WebView.
1701     *
1702     * @return a WebSettings object that can be used to control this WebView's
1703     *         settings
1704     */
1705    public WebSettings getSettings() {
1706        checkThread();
1707        return mProvider.getSettings();
1708    }
1709
1710    /**
1711     * Gets the list of currently loaded plugins.
1712     *
1713     * @return the list of currently loaded plugins
1714     * @deprecated This was used for Gears, which has been deprecated.
1715     * @hide
1716     */
1717    @Deprecated
1718    public static synchronized PluginList getPluginList() {
1719        checkThread();
1720        return new PluginList();
1721    }
1722
1723    /**
1724     * @deprecated This was used for Gears, which has been deprecated.
1725     * @hide
1726     */
1727    @Deprecated
1728    public void refreshPlugins(boolean reloadOpenPages) {
1729        checkThread();
1730    }
1731
1732    /**
1733     * Puts this WebView into text selection mode. Do not rely on this
1734     * functionality; it will be deprecated in the future.
1735     *
1736     * @deprecated This method is now obsolete.
1737     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1738     */
1739    @Deprecated
1740    public void emulateShiftHeld() {
1741        checkThread();
1742    }
1743
1744    /**
1745     * @deprecated WebView no longer needs to implement
1746     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
1747     */
1748    @Override
1749    // Cannot add @hide as this can always be accessed via the interface.
1750    @Deprecated
1751    public void onChildViewAdded(View parent, View child) {}
1752
1753    /**
1754     * @deprecated WebView no longer needs to implement
1755     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
1756     */
1757    @Override
1758    // Cannot add @hide as this can always be accessed via the interface.
1759    @Deprecated
1760    public void onChildViewRemoved(View p, View child) {}
1761
1762    /**
1763     * @deprecated WebView should not have implemented
1764     * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
1765     */
1766    @Override
1767    // Cannot add @hide as this can always be accessed via the interface.
1768    @Deprecated
1769    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
1770    }
1771
1772    /**
1773     * @deprecated Only the default case, true, will be supported in a future version.
1774     */
1775    @Deprecated
1776    public void setMapTrackballToArrowKeys(boolean setMap) {
1777        checkThread();
1778        mProvider.setMapTrackballToArrowKeys(setMap);
1779    }
1780
1781
1782    public void flingScroll(int vx, int vy) {
1783        checkThread();
1784        if (DebugFlags.TRACE_API) Log.d(LOGTAG, "flingScroll");
1785        mProvider.flingScroll(vx, vy);
1786    }
1787
1788    /**
1789     * Gets the zoom controls for this WebView, as a separate View. The caller
1790     * is responsible for inserting this View into the layout hierarchy.
1791     * <p/>
1792     * API level {@link android.os.Build.VERSION_CODES#CUPCAKE} introduced
1793     * built-in zoom mechanisms for the WebView, as opposed to these separate
1794     * zoom controls. The built-in mechanisms are preferred and can be enabled
1795     * using {@link WebSettings#setBuiltInZoomControls}.
1796     *
1797     * @deprecated the built-in zoom mechanisms are preferred
1798     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN}
1799     */
1800    @Deprecated
1801    public View getZoomControls() {
1802        checkThread();
1803        return mProvider.getZoomControls();
1804    }
1805
1806    /**
1807     * Gets whether this WebView can be zoomed in.
1808     *
1809     * @return true if this WebView can be zoomed in
1810     *
1811     * @deprecated This method is prone to inaccuracy due to race conditions
1812     * between the web rendering and UI threads; prefer
1813     * {@link WebViewClient#onScaleChanged}.
1814     */
1815    @Deprecated
1816    public boolean canZoomIn() {
1817        checkThread();
1818        return mProvider.canZoomIn();
1819    }
1820
1821    /**
1822     * Gets whether this WebView can be zoomed out.
1823     *
1824     * @return true if this WebView can be zoomed out
1825     *
1826     * @deprecated This method is prone to inaccuracy due to race conditions
1827     * between the web rendering and UI threads; prefer
1828     * {@link WebViewClient#onScaleChanged}.
1829     */
1830    @Deprecated
1831    public boolean canZoomOut() {
1832        checkThread();
1833        return mProvider.canZoomOut();
1834    }
1835
1836    /**
1837     * Performs zoom in in this WebView.
1838     *
1839     * @return true if zoom in succeeds, false if no zoom changes
1840     */
1841    public boolean zoomIn() {
1842        checkThread();
1843        return mProvider.zoomIn();
1844    }
1845
1846    /**
1847     * Performs zoom out in this WebView.
1848     *
1849     * @return true if zoom out succeeds, false if no zoom changes
1850     */
1851    public boolean zoomOut() {
1852        checkThread();
1853        return mProvider.zoomOut();
1854    }
1855
1856    /**
1857     * @deprecated This method is now obsolete.
1858     * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
1859     */
1860    @Deprecated
1861    public void debugDump() {
1862        checkThread();
1863    }
1864
1865    /**
1866     * See {@link ViewDebug.HierarchyHandler#dumpViewHierarchyWithProperties(BufferedWriter, int)}
1867     * @hide
1868     */
1869    @Override
1870    public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) {
1871        mProvider.dumpViewHierarchyWithProperties(out, level);
1872    }
1873
1874    /**
1875     * See {@link ViewDebug.HierarchyHandler#findHierarchyView(String, int)}
1876     * @hide
1877     */
1878    @Override
1879    public View findHierarchyView(String className, int hashCode) {
1880        return mProvider.findHierarchyView(className, hashCode);
1881    }
1882
1883    //-------------------------------------------------------------------------
1884    // Interface for WebView providers
1885    //-------------------------------------------------------------------------
1886
1887    /**
1888     * Gets the WebViewProvider. Used by providers to obtain the underlying
1889     * implementation, e.g. when the appliction responds to
1890     * WebViewClient.onCreateWindow() request.
1891     *
1892     * @hide WebViewProvider is not public API.
1893     */
1894    public WebViewProvider getWebViewProvider() {
1895        return mProvider;
1896    }
1897
1898    /**
1899     * Callback interface, allows the provider implementation to access non-public methods
1900     * and fields, and make super-class calls in this WebView instance.
1901     * @hide Only for use by WebViewProvider implementations
1902     */
1903    public class PrivateAccess {
1904        // ---- Access to super-class methods ----
1905        public int super_getScrollBarStyle() {
1906            return WebView.super.getScrollBarStyle();
1907        }
1908
1909        public void super_scrollTo(int scrollX, int scrollY) {
1910            WebView.super.scrollTo(scrollX, scrollY);
1911        }
1912
1913        public void super_computeScroll() {
1914            WebView.super.computeScroll();
1915        }
1916
1917        public boolean super_onHoverEvent(MotionEvent event) {
1918            return WebView.super.onHoverEvent(event);
1919        }
1920
1921        public boolean super_performAccessibilityAction(int action, Bundle arguments) {
1922            return WebView.super.performAccessibilityAction(action, arguments);
1923        }
1924
1925        public boolean super_performLongClick() {
1926            return WebView.super.performLongClick();
1927        }
1928
1929        public boolean super_setFrame(int left, int top, int right, int bottom) {
1930            return WebView.super.setFrame(left, top, right, bottom);
1931        }
1932
1933        public boolean super_dispatchKeyEvent(KeyEvent event) {
1934            return WebView.super.dispatchKeyEvent(event);
1935        }
1936
1937        public boolean super_onGenericMotionEvent(MotionEvent event) {
1938            return WebView.super.onGenericMotionEvent(event);
1939        }
1940
1941        public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) {
1942            return WebView.super.requestFocus(direction, previouslyFocusedRect);
1943        }
1944
1945        public void super_setLayoutParams(ViewGroup.LayoutParams params) {
1946            WebView.super.setLayoutParams(params);
1947        }
1948
1949        // ---- Access to non-public methods ----
1950        public void overScrollBy(int deltaX, int deltaY,
1951                int scrollX, int scrollY,
1952                int scrollRangeX, int scrollRangeY,
1953                int maxOverScrollX, int maxOverScrollY,
1954                boolean isTouchEvent) {
1955            WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY,
1956                    maxOverScrollX, maxOverScrollY, isTouchEvent);
1957        }
1958
1959        public void awakenScrollBars(int duration) {
1960            WebView.this.awakenScrollBars(duration);
1961        }
1962
1963        public void awakenScrollBars(int duration, boolean invalidate) {
1964            WebView.this.awakenScrollBars(duration, invalidate);
1965        }
1966
1967        public float getVerticalScrollFactor() {
1968            return WebView.this.getVerticalScrollFactor();
1969        }
1970
1971        public float getHorizontalScrollFactor() {
1972            return WebView.this.getHorizontalScrollFactor();
1973        }
1974
1975        public void setMeasuredDimension(int measuredWidth, int measuredHeight) {
1976            WebView.this.setMeasuredDimension(measuredWidth, measuredHeight);
1977        }
1978
1979        public void onScrollChanged(int l, int t, int oldl, int oldt) {
1980            WebView.this.onScrollChanged(l, t, oldl, oldt);
1981        }
1982
1983        public int getHorizontalScrollbarHeight() {
1984            return WebView.this.getHorizontalScrollbarHeight();
1985        }
1986
1987        public void super_onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
1988                int l, int t, int r, int b) {
1989            WebView.super.onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b);
1990        }
1991
1992        // ---- Access to (non-public) fields ----
1993        /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */
1994        public void setScrollXRaw(int scrollX) {
1995            WebView.this.mScrollX = scrollX;
1996        }
1997
1998        /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */
1999        public void setScrollYRaw(int scrollY) {
2000            WebView.this.mScrollY = scrollY;
2001        }
2002
2003    }
2004
2005    //-------------------------------------------------------------------------
2006    // Package-private internal stuff
2007    //-------------------------------------------------------------------------
2008
2009    // Only used by android.webkit.FindActionModeCallback.
2010    void setFindDialogFindListener(FindListener listener) {
2011        checkThread();
2012        setupFindListenerIfNeeded();
2013        mFindListener.mFindDialogFindListener = listener;
2014    }
2015
2016    // Only used by android.webkit.FindActionModeCallback.
2017    void notifyFindDialogDismissed() {
2018        checkThread();
2019        mProvider.notifyFindDialogDismissed();
2020    }
2021
2022    //-------------------------------------------------------------------------
2023    // Private internal stuff
2024    //-------------------------------------------------------------------------
2025
2026    private WebViewProvider mProvider;
2027
2028    /**
2029     * In addition to the FindListener that the user may set via the WebView.setFindListener
2030     * API, FindActionModeCallback will register it's own FindListener. We keep them separate
2031     * via this class so that that the two FindListeners can potentially exist at once.
2032     */
2033    private class FindListenerDistributor implements FindListener {
2034        private FindListener mFindDialogFindListener;
2035        private FindListener mUserFindListener;
2036
2037        @Override
2038        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
2039                boolean isDoneCounting) {
2040            if (mFindDialogFindListener != null) {
2041                mFindDialogFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches,
2042                        isDoneCounting);
2043            }
2044
2045            if (mUserFindListener != null) {
2046                mUserFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches,
2047                        isDoneCounting);
2048            }
2049        }
2050    }
2051    private FindListenerDistributor mFindListener;
2052
2053    private void setupFindListenerIfNeeded() {
2054        if (mFindListener == null) {
2055            mFindListener = new FindListenerDistributor();
2056            mProvider.setFindListener(mFindListener);
2057        }
2058    }
2059
2060    private void ensureProviderCreated() {
2061        checkThread();
2062        if (mProvider == null) {
2063            // As this can get called during the base class constructor chain, pass the minimum
2064            // number of dependencies here; the rest are deferred to init().
2065            mProvider = getFactory().createWebView(this, new PrivateAccess());
2066        }
2067    }
2068
2069    private static synchronized WebViewFactoryProvider getFactory() {
2070        return WebViewFactory.getProvider();
2071    }
2072
2073    private static void checkThread() {
2074        if (Looper.myLooper() != Looper.getMainLooper()) {
2075            Throwable throwable = new Throwable(
2076                    "Warning: A WebView method was called on thread '" +
2077                    Thread.currentThread().getName() + "'. " +
2078                    "All WebView methods must be called on the UI thread. " +
2079                    "Future versions of WebView may not support use on other threads.");
2080            Log.w(LOGTAG, Log.getStackTraceString(throwable));
2081            StrictMode.onWebViewMethodCalledOnWrongThread(throwable);
2082
2083            if (sEnforceThreadChecking) {
2084                throw new RuntimeException(throwable);
2085            }
2086        }
2087    }
2088
2089    //-------------------------------------------------------------------------
2090    // Override View methods
2091    //-------------------------------------------------------------------------
2092
2093    // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures
2094    // there's a corresponding override (or better, caller) for each of them in here.
2095
2096    @Override
2097    protected void onAttachedToWindow() {
2098        super.onAttachedToWindow();
2099        mProvider.getViewDelegate().onAttachedToWindow();
2100    }
2101
2102    @Override
2103    protected void onDetachedFromWindow() {
2104        mProvider.getViewDelegate().onDetachedFromWindow();
2105        super.onDetachedFromWindow();
2106    }
2107
2108    @Override
2109    public void setLayoutParams(ViewGroup.LayoutParams params) {
2110        mProvider.getViewDelegate().setLayoutParams(params);
2111    }
2112
2113    @Override
2114    public void setOverScrollMode(int mode) {
2115        super.setOverScrollMode(mode);
2116        // This method may be called in the constructor chain, before the WebView provider is
2117        // created.
2118        ensureProviderCreated();
2119        mProvider.getViewDelegate().setOverScrollMode(mode);
2120    }
2121
2122    @Override
2123    public void setScrollBarStyle(int style) {
2124        mProvider.getViewDelegate().setScrollBarStyle(style);
2125        super.setScrollBarStyle(style);
2126    }
2127
2128    @Override
2129    protected int computeHorizontalScrollRange() {
2130        return mProvider.getScrollDelegate().computeHorizontalScrollRange();
2131    }
2132
2133    @Override
2134    protected int computeHorizontalScrollOffset() {
2135        return mProvider.getScrollDelegate().computeHorizontalScrollOffset();
2136    }
2137
2138    @Override
2139    protected int computeVerticalScrollRange() {
2140        return mProvider.getScrollDelegate().computeVerticalScrollRange();
2141    }
2142
2143    @Override
2144    protected int computeVerticalScrollOffset() {
2145        return mProvider.getScrollDelegate().computeVerticalScrollOffset();
2146    }
2147
2148    @Override
2149    protected int computeVerticalScrollExtent() {
2150        return mProvider.getScrollDelegate().computeVerticalScrollExtent();
2151    }
2152
2153    @Override
2154    public void computeScroll() {
2155        mProvider.getScrollDelegate().computeScroll();
2156    }
2157
2158    @Override
2159    public boolean onHoverEvent(MotionEvent event) {
2160        return mProvider.getViewDelegate().onHoverEvent(event);
2161    }
2162
2163    @Override
2164    public boolean onTouchEvent(MotionEvent event) {
2165        return mProvider.getViewDelegate().onTouchEvent(event);
2166    }
2167
2168    @Override
2169    public boolean onGenericMotionEvent(MotionEvent event) {
2170        return mProvider.getViewDelegate().onGenericMotionEvent(event);
2171    }
2172
2173    @Override
2174    public boolean onTrackballEvent(MotionEvent event) {
2175        return mProvider.getViewDelegate().onTrackballEvent(event);
2176    }
2177
2178    @Override
2179    public boolean onKeyDown(int keyCode, KeyEvent event) {
2180        return mProvider.getViewDelegate().onKeyDown(keyCode, event);
2181    }
2182
2183    @Override
2184    public boolean onKeyUp(int keyCode, KeyEvent event) {
2185        return mProvider.getViewDelegate().onKeyUp(keyCode, event);
2186    }
2187
2188    @Override
2189    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2190        return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event);
2191    }
2192
2193    /*
2194    TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not
2195    to be delegating them too.
2196
2197    @Override
2198    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
2199        return mProvider.getViewDelegate().onKeyPreIme(keyCode, event);
2200    }
2201    @Override
2202    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2203        return mProvider.getViewDelegate().onKeyLongPress(keyCode, event);
2204    }
2205    @Override
2206    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2207        return mProvider.getViewDelegate().onKeyShortcut(keyCode, event);
2208    }
2209    */
2210
2211    @Override
2212    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
2213        AccessibilityNodeProvider provider =
2214                mProvider.getViewDelegate().getAccessibilityNodeProvider();
2215        return provider == null ? super.getAccessibilityNodeProvider() : provider;
2216    }
2217
2218    @Deprecated
2219    @Override
2220    public boolean shouldDelayChildPressedState() {
2221        return mProvider.getViewDelegate().shouldDelayChildPressedState();
2222    }
2223
2224    @Override
2225    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2226        super.onInitializeAccessibilityNodeInfo(info);
2227        info.setClassName(WebView.class.getName());
2228        mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info);
2229    }
2230
2231    @Override
2232    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2233        super.onInitializeAccessibilityEvent(event);
2234        event.setClassName(WebView.class.getName());
2235        mProvider.getViewDelegate().onInitializeAccessibilityEvent(event);
2236    }
2237
2238    @Override
2239    public boolean performAccessibilityAction(int action, Bundle arguments) {
2240        return mProvider.getViewDelegate().performAccessibilityAction(action, arguments);
2241    }
2242
2243    /** @hide */
2244    @Override
2245    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
2246            int l, int t, int r, int b) {
2247        mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b);
2248    }
2249
2250    @Override
2251    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
2252        mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY);
2253    }
2254
2255    @Override
2256    protected void onWindowVisibilityChanged(int visibility) {
2257        super.onWindowVisibilityChanged(visibility);
2258        mProvider.getViewDelegate().onWindowVisibilityChanged(visibility);
2259    }
2260
2261    @Override
2262    protected void onDraw(Canvas canvas) {
2263        mProvider.getViewDelegate().onDraw(canvas);
2264    }
2265
2266    @Override
2267    public boolean performLongClick() {
2268        return mProvider.getViewDelegate().performLongClick();
2269    }
2270
2271    @Override
2272    protected void onConfigurationChanged(Configuration newConfig) {
2273        mProvider.getViewDelegate().onConfigurationChanged(newConfig);
2274    }
2275
2276    @Override
2277    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
2278        return mProvider.getViewDelegate().onCreateInputConnection(outAttrs);
2279    }
2280
2281    @Override
2282    protected void onVisibilityChanged(View changedView, int visibility) {
2283        super.onVisibilityChanged(changedView, visibility);
2284        // This method may be called in the constructor chain, before the WebView provider is
2285        // created.
2286        ensureProviderCreated();
2287        mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility);
2288    }
2289
2290    @Override
2291    public void onWindowFocusChanged(boolean hasWindowFocus) {
2292        mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus);
2293        super.onWindowFocusChanged(hasWindowFocus);
2294    }
2295
2296    @Override
2297    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
2298        mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect);
2299        super.onFocusChanged(focused, direction, previouslyFocusedRect);
2300    }
2301
2302    /** @hide */
2303    @Override
2304    protected boolean setFrame(int left, int top, int right, int bottom) {
2305        return mProvider.getViewDelegate().setFrame(left, top, right, bottom);
2306    }
2307
2308    @Override
2309    protected void onSizeChanged(int w, int h, int ow, int oh) {
2310        super.onSizeChanged(w, h, ow, oh);
2311        mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh);
2312    }
2313
2314    @Override
2315    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
2316        super.onScrollChanged(l, t, oldl, oldt);
2317        mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt);
2318    }
2319
2320    @Override
2321    public boolean dispatchKeyEvent(KeyEvent event) {
2322        return mProvider.getViewDelegate().dispatchKeyEvent(event);
2323    }
2324
2325    @Override
2326    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
2327        return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect);
2328    }
2329
2330    @Override
2331    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2332        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
2333        mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec);
2334    }
2335
2336    @Override
2337    public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
2338        return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate);
2339    }
2340
2341    @Override
2342    public void setBackgroundColor(int color) {
2343        mProvider.getViewDelegate().setBackgroundColor(color);
2344    }
2345
2346    @Override
2347    public void setLayerType(int layerType, Paint paint) {
2348        super.setLayerType(layerType, paint);
2349        mProvider.getViewDelegate().setLayerType(layerType, paint);
2350    }
2351
2352    @Override
2353    protected void dispatchDraw(Canvas canvas) {
2354        mProvider.getViewDelegate().preDispatchDraw(canvas);
2355        super.dispatchDraw(canvas);
2356    }
2357}
2358