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