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