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