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