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