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