WebView.java revision 430ad4733472592a7bb3ff3f88db7385a7728edb
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.app.AlertDialog;
21import android.content.BroadcastReceiver;
22import android.content.ClipboardManager;
23import android.content.Context;
24import android.content.DialogInterface;
25import android.content.DialogInterface.OnCancelListener;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.PackageInfo;
29import android.content.pm.PackageManager;
30import android.content.res.AssetManager;
31import android.content.res.Configuration;
32import android.database.DataSetObserver;
33import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
35import android.graphics.BitmapShader;
36import android.graphics.Canvas;
37import android.graphics.Color;
38import android.graphics.CornerPathEffect;
39import android.graphics.DrawFilter;
40import android.graphics.Paint;
41import android.graphics.PaintFlagsDrawFilter;
42import android.graphics.Picture;
43import android.graphics.Point;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region;
47import android.graphics.Shader;
48import android.graphics.drawable.Drawable;
49import android.net.Proxy;
50import android.net.ProxyProperties;
51import android.net.Uri;
52import android.net.http.SslCertificate;
53import android.os.AsyncTask;
54import android.os.Bundle;
55import android.os.Handler;
56import android.os.Looper;
57import android.os.Message;
58import android.os.StrictMode;
59import android.provider.Settings;
60import android.speech.tts.TextToSpeech;
61import android.text.Selection;
62import android.text.Spannable;
63import android.util.AttributeSet;
64import android.util.EventLog;
65import android.util.Log;
66import android.view.Gravity;
67import android.view.HardwareCanvas;
68import android.view.InputDevice;
69import android.view.KeyCharacterMap;
70import android.view.KeyEvent;
71import android.view.LayoutInflater;
72import android.view.MotionEvent;
73import android.view.ScaleGestureDetector;
74import android.view.SoundEffectConstants;
75import android.view.VelocityTracker;
76import android.view.View;
77import android.view.ViewConfiguration;
78import android.view.ViewGroup;
79import android.view.ViewParent;
80import android.view.ViewTreeObserver;
81import android.view.accessibility.AccessibilityManager;
82import android.view.inputmethod.EditorInfo;
83import android.view.inputmethod.InputConnection;
84import android.view.inputmethod.InputMethodManager;
85import android.webkit.WebTextView.AutoCompleteAdapter;
86import android.webkit.WebViewCore.DrawData;
87import android.webkit.WebViewCore.EventHub;
88import android.webkit.WebViewCore.TouchEventData;
89import android.webkit.WebViewCore.TouchHighlightData;
90import android.widget.AbsoluteLayout;
91import android.widget.Adapter;
92import android.widget.AdapterView;
93import android.widget.AdapterView.OnItemClickListener;
94import android.widget.ArrayAdapter;
95import android.widget.CheckedTextView;
96import android.widget.LinearLayout;
97import android.widget.ListView;
98import android.widget.OverScroller;
99import android.widget.Toast;
100
101import junit.framework.Assert;
102
103import java.io.File;
104import java.io.FileInputStream;
105import java.io.FileNotFoundException;
106import java.io.FileOutputStream;
107import java.io.IOException;
108import java.io.InputStream;
109import java.io.OutputStream;
110import java.net.URLDecoder;
111import java.util.ArrayList;
112import java.util.HashMap;
113import java.util.HashSet;
114import java.util.List;
115import java.util.Map;
116import java.util.Set;
117import java.util.Vector;
118import java.util.regex.Matcher;
119import java.util.regex.Pattern;
120
121/**
122 * <p>A View that displays web pages. This class is the basis upon which you
123 * can roll your own web browser or simply display some online content within your Activity.
124 * It uses the WebKit rendering engine to display
125 * web pages and includes methods to navigate forward and backward
126 * through a history, zoom in and out, perform text searches and more.</p>
127 * <p>To enable the built-in zoom, set
128 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
129 * (introduced in API version 3).
130 * <p>Note that, in order for your Activity to access the Internet and load web pages
131 * in a WebView, you must add the {@code INTERNET} permissions to your
132 * Android Manifest file:</p>
133 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
134 *
135 * <p>This must be a child of the <a
136 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a>
137 * element.</p>
138 *
139 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-webview.html">Web View
140 * tutorial</a>.</p>
141 *
142 * <h3>Basic usage</h3>
143 *
144 * <p>By default, a WebView provides no browser-like widgets, does not
145 * enable JavaScript and web page errors are ignored. If your goal is only
146 * to display some HTML as a part of your UI, this is probably fine;
147 * the user won't need to interact with the web page beyond reading
148 * it, and the web page won't need to interact with the user. If you
149 * actually want a full-blown web browser, then you probably want to
150 * invoke the Browser application with a URL Intent rather than show it
151 * with a WebView. For example:
152 * <pre>
153 * Uri uri = Uri.parse("http://www.example.com");
154 * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
155 * startActivity(intent);
156 * </pre>
157 * <p>See {@link android.content.Intent} for more information.</p>
158 *
159 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout,
160 * or set the entire Activity window as a WebView during {@link
161 * android.app.Activity#onCreate(Bundle) onCreate()}:</p>
162 * <pre class="prettyprint">
163 * WebView webview = new WebView(this);
164 * setContentView(webview);
165 * </pre>
166 *
167 * <p>Then load the desired web page:</p>
168 * <pre>
169 * // Simplest usage: note that an exception will NOT be thrown
170 * // if there is an error loading this page (see below).
171 * webview.loadUrl("http://slashdot.org/");
172 *
173 * // OR, you can also load from an HTML string:
174 * String summary = "&lt;html>&lt;body>You scored &lt;b>192&lt;/b> points.&lt;/body>&lt;/html>";
175 * webview.loadData(summary, "text/html", null);
176 * // ... although note that there are restrictions on what this HTML can do.
177 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
178 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
179 * </pre>
180 *
181 * <p>A WebView has several customization points where you can add your
182 * own behavior. These are:</p>
183 *
184 * <ul>
185 *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
186 *       This class is called when something that might impact a
187 *       browser UI happens, for instance, progress updates and
188 *       JavaScript alerts are sent here (see <a
189 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>).
190 *   </li>
191 *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
192 *       It will be called when things happen that impact the
193 *       rendering of the content, eg, errors or form submissions. You
194 *       can also intercept URL loading here (via {@link
195 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String)
196 * shouldOverrideUrlLoading()}).</li>
197 *   <li>Modifying the {@link android.webkit.WebSettings}, such as
198 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean)
199 * setJavaScriptEnabled()}. </li>
200 *   <li>Adding JavaScript-to-Java interfaces with the {@link
201 * android.webkit.WebView#addJavascriptInterface} method.
202 *       This lets you bind Java objects into the WebView so they can be
203 *       controlled from the web pages JavaScript.</li>
204 * </ul>
205 *
206 * <p>Here's a more complicated example, showing error handling,
207 *    settings, and progress notification:</p>
208 *
209 * <pre class="prettyprint">
210 * // Let's display the progress in the activity title bar, like the
211 * // browser app does.
212 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
213 *
214 * webview.getSettings().setJavaScriptEnabled(true);
215 *
216 * final Activity activity = this;
217 * webview.setWebChromeClient(new WebChromeClient() {
218 *   public void onProgressChanged(WebView view, int progress) {
219 *     // Activities and WebViews measure progress with different scales.
220 *     // The progress meter will automatically disappear when we reach 100%
221 *     activity.setProgress(progress * 1000);
222 *   }
223 * });
224 * webview.setWebViewClient(new WebViewClient() {
225 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
226 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
227 *   }
228 * });
229 *
230 * webview.loadUrl("http://slashdot.org/");
231 * </pre>
232 *
233 * <h3>Cookie and window management</h3>
234 *
235 * <p>For obvious security reasons, your application has its own
236 * cache, cookie store etc.&mdash;it does not share the Browser
237 * application's data. Cookies are managed on a separate thread, so
238 * operations like index building don't block the UI
239 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
240 * if you want to use cookies in your application.
241 * </p>
242 *
243 * <p>By default, requests by the HTML to open new windows are
244 * ignored. This is true whether they be opened by JavaScript or by
245 * the target attribute on a link. You can customize your
246 * {@link WebChromeClient} to provide your own behaviour for opening multiple windows,
247 * and render them in whatever manner you want.</p>
248 *
249 * <p>The standard behavior for an Activity is to be destroyed and
250 * recreated when the device orientation or any other configuration changes. This will cause
251 * the WebView to reload the current page. If you don't want that, you
252 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden}
253 * changes, and then just leave the WebView alone. It'll automatically
254 * re-orient itself as appropriate. Read <a
255 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for
256 * more information about how to handle configuration changes during runtime.</p>
257 *
258 *
259 * <h3>Building web pages to support different screen densities</h3>
260 *
261 * <p>The screen density of a device is based on the screen resolution. A screen with low density
262 * has fewer available pixels per inch, where a screen with high density
263 * has more &mdash; sometimes significantly more &mdash; pixels per inch. The density of a
264 * screen is important because, other things being equal, a UI element (such as a button) whose
265 * height and width are defined in terms of screen pixels will appear larger on the lower density
266 * screen and smaller on the higher density screen.
267 * For simplicity, Android collapses all actual screen densities into three generalized densities:
268 * high, medium, and low.</p>
269 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default
270 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen
271 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels
272 * are bigger).
273 * Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help
274 * you (as a web developer) target screens with different screen densities.</p>
275 * <p>Here's a summary of the features you can use to handle different screen densities:</p>
276 * <ul>
277 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the
278 * default scaling factor used for the current device. For example, if the value of {@code
279 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device
280 * and default scaling is not applied to the web page; if the value is "1.5", then the device is
281 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the
282 * value is "0.75", then the device is considered a low density device (ldpi) and the content is
283 * scaled 0.75x. However, if you specify the {@code "target-densitydpi"} meta property
284 * (discussed below), then you can stop this default scaling behavior.</li>
285 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen
286 * densities for which this style sheet is to be used. The corresponding value should be either
287 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium
288 * density, or high density screens, respectively. For example:
289 * <pre>
290 * &lt;link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /&gt;</pre>
291 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5,
292 * which is the high density pixel ratio.</p>
293 * </li>
294 * <li>The {@code target-densitydpi} property for the {@code viewport} meta tag. You can use
295 * this to specify the target density for which the web page is designed, using the following
296 * values:
297 * <ul>
298 * <li>{@code device-dpi} - Use the device's native dpi as the target dpi. Default scaling never
299 * occurs.</li>
300 * <li>{@code high-dpi} - Use hdpi as the target dpi. Medium and low density screens scale down
301 * as appropriate.</li>
302 * <li>{@code medium-dpi} - Use mdpi as the target dpi. High density screens scale up and
303 * low density screens scale down. This is also the default behavior.</li>
304 * <li>{@code low-dpi} - Use ldpi as the target dpi. Medium and high density screens scale up
305 * as appropriate.</li>
306 * <li><em>{@code <value>}</em> - Specify a dpi value to use as the target dpi (accepted
307 * values are 70-400).</li>
308 * </ul>
309 * <p>Here's an example meta tag to specify the target density:</p>
310 * <pre>&lt;meta name="viewport" content="target-densitydpi=device-dpi" /&gt;</pre></li>
311 * </ul>
312 * <p>If you want to modify your web page for different densities, by using the {@code
313 * -webkit-device-pixel-ratio} CSS media query and/or the {@code
314 * window.devicePixelRatio} DOM property, then you should set the {@code target-densitydpi} meta
315 * property to {@code device-dpi}. This stops Android from performing scaling in your web page and
316 * allows you to make the necessary adjustments for each density via CSS and JavaScript.</p>
317 *
318 *
319 */
320@Widget
321public class WebView extends AbsoluteLayout
322        implements ViewTreeObserver.OnGlobalFocusChangeListener,
323        ViewGroup.OnHierarchyChangeListener {
324
325    private class InnerGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
326        public void onGlobalLayout() {
327            if (isShown()) {
328                setGLRectViewport();
329            }
330        }
331    }
332
333    private class InnerScrollChangedListener implements ViewTreeObserver.OnScrollChangedListener {
334        public void onScrollChanged() {
335            if (isShown()) {
336                setGLRectViewport();
337            }
338        }
339    }
340
341    // The listener to capture global layout change event.
342    private InnerGlobalLayoutListener mGlobalLayoutListener = null;
343
344    // The listener to capture scroll event.
345    private InnerScrollChangedListener mScrollChangedListener = null;
346
347    // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
348    // the screen all-the-time. Good for profiling our drawing code
349    static private final boolean AUTO_REDRAW_HACK = false;
350    // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
351    private boolean mAutoRedraw;
352
353    // Reference to the AlertDialog displayed by InvokeListBox.
354    // It's used to dismiss the dialog in destroy if not done before.
355    private AlertDialog mListBoxDialog = null;
356
357    static final String LOGTAG = "webview";
358
359    private ZoomManager mZoomManager;
360
361    private final Rect mGLRectViewport = new Rect();
362    private final Rect mViewRectViewport = new Rect();
363    private boolean mGLViewportEmpty = false;
364
365    /**
366     *  Transportation object for returning WebView across thread boundaries.
367     */
368    public class WebViewTransport {
369        private WebView mWebview;
370
371        /**
372         * Set the WebView to the transportation object.
373         * @param webview The WebView to transport.
374         */
375        public synchronized void setWebView(WebView webview) {
376            mWebview = webview;
377        }
378
379        /**
380         * Return the WebView object.
381         * @return WebView The transported WebView object.
382         */
383        public synchronized WebView getWebView() {
384            return mWebview;
385        }
386    }
387
388    // A final CallbackProxy shared by WebViewCore and BrowserFrame.
389    private final CallbackProxy mCallbackProxy;
390
391    private final WebViewDatabase mDatabase;
392
393    // SSL certificate for the main top-level page (if secure)
394    private SslCertificate mCertificate;
395
396    // Native WebView pointer that is 0 until the native object has been
397    // created.
398    private int mNativeClass;
399    // This would be final but it needs to be set to null when the WebView is
400    // destroyed.
401    private WebViewCore mWebViewCore;
402    // Handler for dispatching UI messages.
403    /* package */ final Handler mPrivateHandler = new PrivateHandler();
404    private WebTextView mWebTextView;
405    // Used to ignore changes to webkit text that arrives to the UI side after
406    // more key events.
407    private int mTextGeneration;
408
409    /* package */ void incrementTextGeneration() { mTextGeneration++; }
410
411    // Used by WebViewCore to create child views.
412    /* package */ final ViewManager mViewManager;
413
414    // Used to display in full screen mode
415    PluginFullScreenHolder mFullScreenHolder;
416
417    /**
418     * Position of the last touch event in pixels.
419     * Use integer to prevent loss of dragging delta calculation accuracy;
420     * which was done in float and converted to integer, and resulted in gradual
421     * and compounding touch position and view dragging mismatch.
422     */
423    private int mLastTouchX;
424    private int mLastTouchY;
425
426    /**
427     * Time of the last touch event.
428     */
429    private long mLastTouchTime;
430
431    /**
432     * Time of the last time sending touch event to WebViewCore
433     */
434    private long mLastSentTouchTime;
435
436    /**
437     * The minimum elapsed time before sending another ACTION_MOVE event to
438     * WebViewCore. This really should be tuned for each type of the devices.
439     * For example in Google Map api test case, it takes Dream device at least
440     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
441     * triggering the layout and drawing the picture. While the same process
442     * takes 60+ms on the current high speed device. If we make
443     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
444     * to WebViewCore queue and the real layout and draw events will be pushed
445     * to further, which slows down the refresh rate. Choose 50 to favor the
446     * current high speed devices. For Dream like devices, 100 is a better
447     * choice. Maybe make this in the buildspec later.
448     * (Update 12/14/2010: changed to 0 since current device should be able to
449     * handle the raw events and Map team voted to have the raw events too.
450     */
451    private static final int TOUCH_SENT_INTERVAL = 0;
452    private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL;
453
454    /**
455     * Helper class to get velocity for fling
456     */
457    VelocityTracker mVelocityTracker;
458    private int mMaximumFling;
459    private float mLastVelocity;
460    private float mLastVelX;
461    private float mLastVelY;
462
463    // The id of the native layer being scrolled.
464    private int mScrollingLayer;
465    private Rect mScrollingLayerRect = new Rect();
466
467    // only trigger accelerated fling if the new velocity is at least
468    // MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION times of the previous velocity
469    private static final float MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION = 0.2f;
470
471    /**
472     * Touch mode
473     */
474    private int mTouchMode = TOUCH_DONE_MODE;
475    private static final int TOUCH_INIT_MODE = 1;
476    private static final int TOUCH_DRAG_START_MODE = 2;
477    private static final int TOUCH_DRAG_MODE = 3;
478    private static final int TOUCH_SHORTPRESS_START_MODE = 4;
479    private static final int TOUCH_SHORTPRESS_MODE = 5;
480    private static final int TOUCH_DOUBLE_TAP_MODE = 6;
481    private static final int TOUCH_DONE_MODE = 7;
482    private static final int TOUCH_PINCH_DRAG = 8;
483    private static final int TOUCH_DRAG_LAYER_MODE = 9;
484
485    // Whether to forward the touch events to WebCore
486    // Can only be set by WebKit via JNI.
487    private boolean mForwardTouchEvents = false;
488
489    // Whether to prevent default during touch. The initial value depends on
490    // mForwardTouchEvents. If WebCore wants all the touch events, it says yes
491    // for touch down. Otherwise UI will wait for the answer of the first
492    // confirmed move before taking over the control.
493    private static final int PREVENT_DEFAULT_NO = 0;
494    private static final int PREVENT_DEFAULT_MAYBE_YES = 1;
495    private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2;
496    private static final int PREVENT_DEFAULT_YES = 3;
497    private static final int PREVENT_DEFAULT_IGNORE = 4;
498    private int mPreventDefault = PREVENT_DEFAULT_IGNORE;
499
500    // true when the touch movement exceeds the slop
501    private boolean mConfirmMove;
502
503    // if true, touch events will be first processed by WebCore, if prevent
504    // default is not set, the UI will continue handle them.
505    private boolean mDeferTouchProcess;
506
507    // to avoid interfering with the current touch events, track them
508    // separately. Currently no snapping or fling in the deferred process mode
509    private int mDeferTouchMode = TOUCH_DONE_MODE;
510    private float mLastDeferTouchX;
511    private float mLastDeferTouchY;
512
513    // To keep track of whether the current drag was initiated by a WebTextView,
514    // so that we know not to hide the cursor
515    boolean mDragFromTextInput;
516
517    // Whether or not to draw the cursor ring.
518    private boolean mDrawCursorRing = true;
519
520    // true if onPause has been called (and not onResume)
521    private boolean mIsPaused;
522
523    private HitTestResult mInitialHitTestResult;
524
525    /**
526     * Customizable constant
527     */
528    // pre-computed square of ViewConfiguration.getScaledTouchSlop()
529    private int mTouchSlopSquare;
530    // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
531    private int mDoubleTapSlopSquare;
532    // pre-computed density adjusted navigation slop
533    private int mNavSlop;
534    // This should be ViewConfiguration.getTapTimeout()
535    // But system time out is 100ms, which is too short for the browser.
536    // In the browser, if it switches out of tap too soon, jump tap won't work.
537    private static final int TAP_TIMEOUT = 200;
538    // This should be ViewConfiguration.getLongPressTimeout()
539    // But system time out is 500ms, which is too short for the browser.
540    // With a short timeout, it's difficult to treat trigger a short press.
541    private static final int LONG_PRESS_TIMEOUT = 1000;
542    // needed to avoid flinging after a pause of no movement
543    private static final int MIN_FLING_TIME = 250;
544    // draw unfiltered after drag is held without movement
545    private static final int MOTIONLESS_TIME = 100;
546    // The amount of content to overlap between two screens when going through
547    // pages with the space bar, in pixels.
548    private static final int PAGE_SCROLL_OVERLAP = 24;
549
550    /**
551     * These prevent calling requestLayout if either dimension is fixed. This
552     * depends on the layout parameters and the measure specs.
553     */
554    boolean mWidthCanMeasure;
555    boolean mHeightCanMeasure;
556
557    // Remember the last dimensions we sent to the native side so we can avoid
558    // sending the same dimensions more than once.
559    int mLastWidthSent;
560    int mLastHeightSent;
561    // Since view height sent to webkit could be fixed to avoid relayout, this
562    // value records the last sent actual view height.
563    int mLastActualHeightSent;
564
565    private int mContentWidth;   // cache of value from WebViewCore
566    private int mContentHeight;  // cache of value from WebViewCore
567
568    // Need to have the separate control for horizontal and vertical scrollbar
569    // style than the View's single scrollbar style
570    private boolean mOverlayHorizontalScrollbar = true;
571    private boolean mOverlayVerticalScrollbar = false;
572
573    // our standard speed. this way small distances will be traversed in less
574    // time than large distances, but we cap the duration, so that very large
575    // distances won't take too long to get there.
576    private static final int STD_SPEED = 480;  // pixels per second
577    // time for the longest scroll animation
578    private static final int MAX_DURATION = 750;   // milliseconds
579    private static final int SLIDE_TITLE_DURATION = 500;   // milliseconds
580
581    // Used by OverScrollGlow
582    OverScroller mScroller;
583
584    private boolean mInOverScrollMode = false;
585    private static Paint mOverScrollBackground;
586    private static Paint mOverScrollBorder;
587
588    private boolean mWrapContent;
589    private static final int MOTIONLESS_FALSE           = 0;
590    private static final int MOTIONLESS_PENDING         = 1;
591    private static final int MOTIONLESS_TRUE            = 2;
592    private static final int MOTIONLESS_IGNORE          = 3;
593    private int mHeldMotionless;
594
595    // An instance for injecting accessibility in WebViews with disabled
596    // JavaScript or ones for which no accessibility script exists
597    private AccessibilityInjector mAccessibilityInjector;
598
599    // flag indicating if accessibility script is injected so we
600    // know to handle Shift and arrows natively first
601    private boolean mAccessibilityScriptInjected;
602
603    // the color used to highlight the touch rectangles
604    private static final int mHightlightColor = 0x33000000;
605    // the round corner for the highlight path
606    private static final float TOUCH_HIGHLIGHT_ARC = 5.0f;
607    // the region indicating where the user touched on the screen
608    private Region mTouchHighlightRegion = new Region();
609    // the paint for the touch highlight
610    private Paint mTouchHightlightPaint;
611    // debug only
612    private static final boolean DEBUG_TOUCH_HIGHLIGHT = true;
613    private static final int TOUCH_HIGHLIGHT_ELAPSE_TIME = 2000;
614    private Paint mTouchCrossHairColor;
615    private int mTouchHighlightX;
616    private int mTouchHighlightY;
617
618    // Basically this proxy is used to tell the Video to update layer tree at
619    // SetBaseLayer time and to pause when WebView paused.
620    private HTML5VideoViewProxy mHTML5VideoViewProxy;
621
622    // If we are using a set picture, don't send view updates to webkit
623    private boolean mBlockWebkitViewMessages = false;
624
625    /*
626     * Private message ids
627     */
628    private static final int REMEMBER_PASSWORD          = 1;
629    private static final int NEVER_REMEMBER_PASSWORD    = 2;
630    private static final int SWITCH_TO_SHORTPRESS       = 3;
631    private static final int SWITCH_TO_LONGPRESS        = 4;
632    private static final int RELEASE_SINGLE_TAP         = 5;
633    private static final int REQUEST_FORM_DATA          = 6;
634    private static final int RESUME_WEBCORE_PRIORITY    = 7;
635    private static final int DRAG_HELD_MOTIONLESS       = 8;
636    private static final int AWAKEN_SCROLL_BARS         = 9;
637    private static final int PREVENT_DEFAULT_TIMEOUT    = 10;
638    private static final int SCROLL_SELECT_TEXT         = 11;
639
640
641    private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
642    private static final int LAST_PRIVATE_MSG_ID = SCROLL_SELECT_TEXT;
643
644    /*
645     * Package message ids
646     */
647    static final int SCROLL_TO_MSG_ID                   = 101;
648    static final int NEW_PICTURE_MSG_ID                 = 105;
649    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 106;
650    static final int WEBCORE_INITIALIZED_MSG_ID         = 107;
651    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 108;
652    static final int UPDATE_ZOOM_RANGE                  = 109;
653    static final int UNHANDLED_NAV_KEY                  = 110;
654    static final int CLEAR_TEXT_ENTRY                   = 111;
655    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 112;
656    static final int SHOW_RECT_MSG_ID                   = 113;
657    static final int LONG_PRESS_CENTER                  = 114;
658    static final int PREVENT_TOUCH_ID                   = 115;
659    static final int WEBCORE_NEED_TOUCH_EVENTS          = 116;
660    // obj=Rect in doc coordinates
661    static final int INVAL_RECT_MSG_ID                  = 117;
662    static final int REQUEST_KEYBOARD                   = 118;
663    static final int DO_MOTION_UP                       = 119;
664    static final int SHOW_FULLSCREEN                    = 120;
665    static final int HIDE_FULLSCREEN                    = 121;
666    static final int DOM_FOCUS_CHANGED                  = 122;
667    static final int REPLACE_BASE_CONTENT               = 123;
668    static final int FORM_DID_BLUR                      = 124;
669    static final int RETURN_LABEL                       = 125;
670    static final int FIND_AGAIN                         = 126;
671    static final int CENTER_FIT_RECT                    = 127;
672    static final int REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID = 128;
673    static final int SET_SCROLLBAR_MODES                = 129;
674    static final int SELECTION_STRING_CHANGED           = 130;
675    static final int SET_TOUCH_HIGHLIGHT_RECTS          = 131;
676    static final int SAVE_WEBARCHIVE_FINISHED           = 132;
677
678    static final int SET_AUTOFILLABLE                   = 133;
679    static final int AUTOFILL_COMPLETE                  = 134;
680
681    static final int SELECT_AT                          = 135;
682    static final int SCREEN_ON                          = 136;
683    static final int ENTER_FULLSCREEN_VIDEO             = 137;
684
685    private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
686    private static final int LAST_PACKAGE_MSG_ID = SET_TOUCH_HIGHLIGHT_RECTS;
687
688    static final String[] HandlerPrivateDebugString = {
689        "REMEMBER_PASSWORD", //              = 1;
690        "NEVER_REMEMBER_PASSWORD", //        = 2;
691        "SWITCH_TO_SHORTPRESS", //           = 3;
692        "SWITCH_TO_LONGPRESS", //            = 4;
693        "RELEASE_SINGLE_TAP", //             = 5;
694        "REQUEST_FORM_DATA", //              = 6;
695        "RESUME_WEBCORE_PRIORITY", //        = 7;
696        "DRAG_HELD_MOTIONLESS", //           = 8;
697        "AWAKEN_SCROLL_BARS", //             = 9;
698        "PREVENT_DEFAULT_TIMEOUT", //        = 10;
699        "SCROLL_SELECT_TEXT" //              = 11;
700    };
701
702    static final String[] HandlerPackageDebugString = {
703        "SCROLL_TO_MSG_ID", //               = 101;
704        "102", //                            = 102;
705        "103", //                            = 103;
706        "104", //                            = 104;
707        "NEW_PICTURE_MSG_ID", //             = 105;
708        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 106;
709        "WEBCORE_INITIALIZED_MSG_ID", //     = 107;
710        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 108;
711        "UPDATE_ZOOM_RANGE", //              = 109;
712        "UNHANDLED_NAV_KEY", //              = 110;
713        "CLEAR_TEXT_ENTRY", //               = 111;
714        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 112;
715        "SHOW_RECT_MSG_ID", //               = 113;
716        "LONG_PRESS_CENTER", //              = 114;
717        "PREVENT_TOUCH_ID", //               = 115;
718        "WEBCORE_NEED_TOUCH_EVENTS", //      = 116;
719        "INVAL_RECT_MSG_ID", //              = 117;
720        "REQUEST_KEYBOARD", //               = 118;
721        "DO_MOTION_UP", //                   = 119;
722        "SHOW_FULLSCREEN", //                = 120;
723        "HIDE_FULLSCREEN", //                = 121;
724        "DOM_FOCUS_CHANGED", //              = 122;
725        "REPLACE_BASE_CONTENT", //           = 123;
726        "FORM_DID_BLUR", //                  = 124;
727        "RETURN_LABEL", //                   = 125;
728        "FIND_AGAIN", //                     = 126;
729        "CENTER_FIT_RECT", //                = 127;
730        "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128;
731        "SET_SCROLLBAR_MODES", //            = 129;
732        "SELECTION_STRING_CHANGED", //       = 130;
733        "SET_TOUCH_HIGHLIGHT_RECTS", //      = 131;
734        "SAVE_WEBARCHIVE_FINISHED", //       = 132;
735        "SET_AUTOFILLABLE", //               = 133;
736        "AUTOFILL_COMPLETE", //              = 134;
737        "SELECT_AT", //                      = 135;
738        "SCREEN_ON", //                      = 136;
739        "ENTER_FULLSCREEN_VIDEO" //          = 137;
740    };
741
742    // If the site doesn't use the viewport meta tag to specify the viewport,
743    // use DEFAULT_VIEWPORT_WIDTH as the default viewport width
744    static final int DEFAULT_VIEWPORT_WIDTH = 980;
745
746    // normally we try to fit the content to the minimum preferred width
747    // calculated by the Webkit. To avoid the bad behavior when some site's
748    // minimum preferred width keeps growing when changing the viewport width or
749    // the minimum preferred width is huge, an upper limit is needed.
750    static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH;
751
752    // initial scale in percent. 0 means using default.
753    private int mInitialScaleInPercent = 0;
754
755    // Whether or not a scroll event should be sent to webkit.  This is only set
756    // to false when restoring the scroll position.
757    private boolean mSendScrollEvent = true;
758
759    private int mSnapScrollMode = SNAP_NONE;
760    private static final int SNAP_NONE = 0;
761    private static final int SNAP_LOCK = 1; // not a separate state
762    private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
763    private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
764    private boolean mSnapPositive;
765
766    // keep these in sync with their counterparts in WebView.cpp
767    private static final int DRAW_EXTRAS_NONE = 0;
768    private static final int DRAW_EXTRAS_FIND = 1;
769    private static final int DRAW_EXTRAS_SELECTION = 2;
770    private static final int DRAW_EXTRAS_CURSOR_RING = 3;
771
772    // keep this in sync with WebCore:ScrollbarMode in WebKit
773    private static final int SCROLLBAR_AUTO = 0;
774    private static final int SCROLLBAR_ALWAYSOFF = 1;
775    // as we auto fade scrollbar, this is ignored.
776    private static final int SCROLLBAR_ALWAYSON = 2;
777    private int mHorizontalScrollBarMode = SCROLLBAR_AUTO;
778    private int mVerticalScrollBarMode = SCROLLBAR_AUTO;
779
780    // constants for determining script injection strategy
781    private static final int ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED = -1;
782    private static final int ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT = 0;
783    private static final int ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED = 1;
784
785    // the alias via which accessibility JavaScript interface is exposed
786    private static final String ALIAS_ACCESSIBILITY_JS_INTERFACE = "accessibility";
787
788    // JavaScript to inject the script chooser which will
789    // pick the right script for the current URL
790    private static final String ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT =
791        "javascript:(function() {" +
792        "    var chooser = document.createElement('script');" +
793        "    chooser.type = 'text/javascript';" +
794        "    chooser.src = 'https://ssl.gstatic.com/accessibility/javascript/android/AndroidScriptChooser.user.js';" +
795        "    document.getElementsByTagName('head')[0].appendChild(chooser);" +
796        "  })();";
797
798    // Regular expression that matches the "axs" URL parameter.
799    // The value of 0 means the accessibility script is opted out
800    // The value of 1 means the accessibility script is already injected
801    private static final String PATTERN_MATCH_AXS_URL_PARAMETER = "(\\?axs=(0|1))|(&axs=(0|1))";
802
803    // TextToSpeech instance exposed to JavaScript to the injected screenreader.
804    private TextToSpeech mTextToSpeech;
805
806    // variable to cache the above pattern in case accessibility is enabled.
807    private Pattern mMatchAxsUrlParameterPattern;
808
809    /**
810     * Max distance to overscroll by in pixels.
811     * This how far content can be pulled beyond its normal bounds by the user.
812     */
813    private int mOverscrollDistance;
814
815    /**
816     * Max distance to overfling by in pixels.
817     * This is how far flinged content can move beyond the end of its normal bounds.
818     */
819    private int mOverflingDistance;
820
821    private OverScrollGlow mOverScrollGlow;
822
823    // Used to match key downs and key ups
824    private Vector<Integer> mKeysPressed;
825
826    /* package */ static boolean mLogEvent = true;
827
828    // for event log
829    private long mLastTouchUpTime = 0;
830
831    private WebViewCore.AutoFillData mAutoFillData;
832
833    private static boolean sNotificationsEnabled = true;
834
835    /**
836     * URI scheme for telephone number
837     */
838    public static final String SCHEME_TEL = "tel:";
839    /**
840     * URI scheme for email address
841     */
842    public static final String SCHEME_MAILTO = "mailto:";
843    /**
844     * URI scheme for map address
845     */
846    public static final String SCHEME_GEO = "geo:0,0?q=";
847
848    private int mBackgroundColor = Color.WHITE;
849
850    private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second
851    private int mAutoScrollX = 0;
852    private int mAutoScrollY = 0;
853    private int mMinAutoScrollX = 0;
854    private int mMaxAutoScrollX = 0;
855    private int mMinAutoScrollY = 0;
856    private int mMaxAutoScrollY = 0;
857    private Rect mScrollingLayerBounds = new Rect();
858    private boolean mSentAutoScrollMessage = false;
859
860    // used for serializing asynchronously handled touch events.
861    private final TouchEventQueue mTouchEventQueue = new TouchEventQueue();
862
863    // Used to notify listeners of a new picture.
864    private PictureListener mPictureListener;
865    /**
866     * Interface to listen for new pictures as they change.
867     * @deprecated This interface is now obsolete.
868     */
869    @Deprecated
870    public interface PictureListener {
871        /**
872         * Notify the listener that the picture has changed.
873         * @param view The WebView that owns the picture.
874         * @param picture The new picture.
875         * @deprecated This method is now obsolete.
876         */
877        @Deprecated
878        public void onNewPicture(WebView view, Picture picture);
879    }
880
881    // FIXME: Want to make this public, but need to change the API file.
882    public /*static*/ class HitTestResult {
883        /**
884         * Default HitTestResult, where the target is unknown
885         */
886        public static final int UNKNOWN_TYPE = 0;
887        /**
888         * @deprecated This type is no longer used.
889         */
890        @Deprecated
891        public static final int ANCHOR_TYPE = 1;
892        /**
893         * HitTestResult for hitting a phone number
894         */
895        public static final int PHONE_TYPE = 2;
896        /**
897         * HitTestResult for hitting a map address
898         */
899        public static final int GEO_TYPE = 3;
900        /**
901         * HitTestResult for hitting an email address
902         */
903        public static final int EMAIL_TYPE = 4;
904        /**
905         * HitTestResult for hitting an HTML::img tag
906         */
907        public static final int IMAGE_TYPE = 5;
908        /**
909         * @deprecated This type is no longer used.
910         */
911        @Deprecated
912        public static final int IMAGE_ANCHOR_TYPE = 6;
913        /**
914         * HitTestResult for hitting a HTML::a tag with src=http
915         */
916        public static final int SRC_ANCHOR_TYPE = 7;
917        /**
918         * HitTestResult for hitting a HTML::a tag with src=http + HTML::img
919         */
920        public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
921        /**
922         * HitTestResult for hitting an edit text area
923         */
924        public static final int EDIT_TEXT_TYPE = 9;
925
926        private int mType;
927        private String mExtra;
928
929        HitTestResult() {
930            mType = UNKNOWN_TYPE;
931        }
932
933        private void setType(int type) {
934            mType = type;
935        }
936
937        private void setExtra(String extra) {
938            mExtra = extra;
939        }
940
941        public int getType() {
942            return mType;
943        }
944
945        public String getExtra() {
946            return mExtra;
947        }
948    }
949
950    /**
951     * Construct a new WebView with a Context object.
952     * @param context A Context object used to access application assets.
953     */
954    public WebView(Context context) {
955        this(context, null);
956    }
957
958    /**
959     * Construct a new WebView with layout parameters.
960     * @param context A Context object used to access application assets.
961     * @param attrs An AttributeSet passed to our parent.
962     */
963    public WebView(Context context, AttributeSet attrs) {
964        this(context, attrs, com.android.internal.R.attr.webViewStyle);
965    }
966
967    /**
968     * Construct a new WebView with layout parameters and a default style.
969     * @param context A Context object used to access application assets.
970     * @param attrs An AttributeSet passed to our parent.
971     * @param defStyle The default style resource ID.
972     */
973    public WebView(Context context, AttributeSet attrs, int defStyle) {
974        this(context, attrs, defStyle, false);
975    }
976
977    /**
978     * Construct a new WebView with layout parameters and a default style.
979     * @param context A Context object used to access application assets.
980     * @param attrs An AttributeSet passed to our parent.
981     * @param defStyle The default style resource ID.
982     */
983    public WebView(Context context, AttributeSet attrs, int defStyle,
984            boolean privateBrowsing) {
985        this(context, attrs, defStyle, null, privateBrowsing);
986    }
987
988    /**
989     * Construct a new WebView with layout parameters, a default style and a set
990     * of custom Javscript interfaces to be added to the WebView at initialization
991     * time. This guarantees that these interfaces will be available when the JS
992     * context is initialized.
993     * @param context A Context object used to access application assets.
994     * @param attrs An AttributeSet passed to our parent.
995     * @param defStyle The default style resource ID.
996     * @param javaScriptInterfaces is a Map of interface names, as keys, and
997     * object implementing those interfaces, as values.
998     * @hide pending API council approval.
999     */
1000    protected WebView(Context context, AttributeSet attrs, int defStyle,
1001            Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
1002        super(context, attrs, defStyle);
1003        checkThread();
1004
1005        // Used by the chrome stack to find application paths
1006        JniUtil.setContext(context);
1007
1008        mCallbackProxy = new CallbackProxy(context, this);
1009        mViewManager = new ViewManager(this);
1010        L10nUtils.setApplicationContext(context.getApplicationContext());
1011        mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javaScriptInterfaces);
1012        mDatabase = WebViewDatabase.getInstance(context);
1013        mScroller = new OverScroller(context, null, 0, 0, false); //TODO Use OverScroller's flywheel
1014        mZoomManager = new ZoomManager(this, mCallbackProxy);
1015
1016        /* The init method must follow the creation of certain member variables,
1017         * such as the mZoomManager.
1018         */
1019        init();
1020        setupPackageListener(context);
1021        setupProxyListener(context);
1022        updateMultiTouchSupport(context);
1023
1024        if (privateBrowsing) {
1025            startPrivateBrowsing();
1026        }
1027
1028        mAutoFillData = new WebViewCore.AutoFillData();
1029    }
1030
1031    private static class ProxyReceiver extends BroadcastReceiver {
1032        @Override
1033        public void onReceive(Context context, Intent intent) {
1034            if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
1035                handleProxyBroadcast(intent);
1036            }
1037        }
1038    }
1039
1040    /*
1041     * Receiver for PROXY_CHANGE_ACTION, will be null when it is not added handling broadcasts.
1042     */
1043    private static ProxyReceiver sProxyReceiver;
1044
1045    /*
1046     * @param context This method expects this to be a valid context
1047     */
1048    private static synchronized void setupProxyListener(Context context) {
1049        if (sProxyReceiver != null || sNotificationsEnabled == false) {
1050            return;
1051        }
1052        IntentFilter filter = new IntentFilter();
1053        filter.addAction(Proxy.PROXY_CHANGE_ACTION);
1054        sProxyReceiver = new ProxyReceiver();
1055        Intent currentProxy = context.getApplicationContext().registerReceiver(
1056                sProxyReceiver, filter);
1057        if (currentProxy != null) {
1058            handleProxyBroadcast(currentProxy);
1059        }
1060    }
1061
1062    /*
1063     * @param context This method expects this to be a valid context
1064     */
1065    private static synchronized void disableProxyListener(Context context) {
1066        if (sProxyReceiver == null)
1067            return;
1068
1069        context.getApplicationContext().unregisterReceiver(sProxyReceiver);
1070        sProxyReceiver = null;
1071    }
1072
1073    private static void handleProxyBroadcast(Intent intent) {
1074        ProxyProperties proxyProperties = (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
1075        if (proxyProperties == null || proxyProperties.getHost() == null) {
1076            WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, null);
1077            return;
1078        }
1079        WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, proxyProperties);
1080    }
1081
1082    /*
1083     * A variable to track if there is a receiver added for ACTION_PACKAGE_ADDED
1084     * or ACTION_PACKAGE_REMOVED.
1085     */
1086    private static boolean sPackageInstallationReceiverAdded = false;
1087
1088    /*
1089     * A set of Google packages we monitor for the
1090     * navigator.isApplicationInstalled() API. Add additional packages as
1091     * needed.
1092     */
1093    private static Set<String> sGoogleApps;
1094    static {
1095        sGoogleApps = new HashSet<String>();
1096        sGoogleApps.add("com.google.android.youtube");
1097    }
1098
1099    private static class PackageListener extends BroadcastReceiver {
1100        @Override
1101        public void onReceive(Context context, Intent intent) {
1102            final String action = intent.getAction();
1103            final String packageName = intent.getData().getSchemeSpecificPart();
1104            final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1105            if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
1106                // if it is replacing, refreshPlugins() when adding
1107                return;
1108            }
1109
1110            if (sGoogleApps.contains(packageName)) {
1111                if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1112                    WebViewCore.sendStaticMessage(EventHub.ADD_PACKAGE_NAME, packageName);
1113                } else {
1114                    WebViewCore.sendStaticMessage(EventHub.REMOVE_PACKAGE_NAME, packageName);
1115                }
1116            }
1117
1118            PluginManager pm = PluginManager.getInstance(context);
1119            if (pm.containsPluginPermissionAndSignatures(packageName)) {
1120                pm.refreshPlugins(Intent.ACTION_PACKAGE_ADDED.equals(action));
1121            }
1122        }
1123    }
1124
1125    private void setupPackageListener(Context context) {
1126
1127        /*
1128         * we must synchronize the instance check and the creation of the
1129         * receiver to ensure that only ONE receiver exists for all WebView
1130         * instances.
1131         */
1132        synchronized (WebView.class) {
1133
1134            // if the receiver already exists then we do not need to register it
1135            // again
1136            if (sPackageInstallationReceiverAdded) {
1137                return;
1138            }
1139
1140            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1141            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1142            filter.addDataScheme("package");
1143            BroadcastReceiver packageListener = new PackageListener();
1144            context.getApplicationContext().registerReceiver(packageListener, filter);
1145            sPackageInstallationReceiverAdded = true;
1146        }
1147
1148        // check if any of the monitored apps are already installed
1149        AsyncTask<Void, Void, Set<String>> task = new AsyncTask<Void, Void, Set<String>>() {
1150
1151            @Override
1152            protected Set<String> doInBackground(Void... unused) {
1153                Set<String> installedPackages = new HashSet<String>();
1154                PackageManager pm = mContext.getPackageManager();
1155                for (String name : sGoogleApps) {
1156                    try {
1157                        PackageInfo pInfo = pm.getPackageInfo(name,
1158                                PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
1159                        installedPackages.add(name);
1160                    } catch (PackageManager.NameNotFoundException e) {
1161                        // package not found
1162                    }
1163                }
1164                return installedPackages;
1165            }
1166
1167            // Executes on the UI thread
1168            @Override
1169            protected void onPostExecute(Set<String> installedPackages) {
1170                if (mWebViewCore != null) {
1171                    mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, installedPackages);
1172                }
1173            }
1174        };
1175        task.execute();
1176    }
1177
1178    void updateMultiTouchSupport(Context context) {
1179        mZoomManager.updateMultiTouchSupport(context);
1180    }
1181
1182    private void init() {
1183        setWillNotDraw(false);
1184        setFocusable(true);
1185        setFocusableInTouchMode(true);
1186        setClickable(true);
1187        setLongClickable(true);
1188
1189        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
1190        int slop = configuration.getScaledTouchSlop();
1191        mTouchSlopSquare = slop * slop;
1192        mMinLockSnapReverseDistance = slop;
1193        slop = configuration.getScaledDoubleTapSlop();
1194        mDoubleTapSlopSquare = slop * slop;
1195        final float density = getContext().getResources().getDisplayMetrics().density;
1196        // use one line height, 16 based on our current default font, for how
1197        // far we allow a touch be away from the edge of a link
1198        mNavSlop = (int) (16 * density);
1199        mZoomManager.init(density);
1200        mMaximumFling = configuration.getScaledMaximumFlingVelocity();
1201
1202        // Compute the inverse of the density squared.
1203        DRAG_LAYER_INVERSE_DENSITY_SQUARED = 1 / (density * density);
1204
1205        mOverscrollDistance = configuration.getScaledOverscrollDistance();
1206        mOverflingDistance = configuration.getScaledOverflingDistance();
1207
1208        setScrollBarStyle(super.getScrollBarStyle());
1209        // Initially use a size of two, since the user is likely to only hold
1210        // down two keys at a time (shift + another key)
1211        mKeysPressed = new Vector<Integer>(2);
1212        mHTML5VideoViewProxy = null ;
1213    }
1214
1215    @Override
1216    public boolean shouldDelayChildPressedState() {
1217        return true;
1218    }
1219
1220    /**
1221     * Adds accessibility APIs to JavaScript.
1222     *
1223     * Note: This method is responsible to performing the necessary
1224     *       check if the accessibility APIs should be exposed.
1225     */
1226    private void addAccessibilityApisToJavaScript() {
1227        if (AccessibilityManager.getInstance(mContext).isEnabled()
1228                && getSettings().getJavaScriptEnabled()) {
1229            // exposing the TTS for now ...
1230            mTextToSpeech = new TextToSpeech(getContext(), null);
1231            addJavascriptInterface(mTextToSpeech, ALIAS_ACCESSIBILITY_JS_INTERFACE);
1232        }
1233    }
1234
1235    /**
1236     * Removes accessibility APIs from JavaScript.
1237     */
1238    private void removeAccessibilityApisFromJavaScript() {
1239        // exposing the TTS for now ...
1240        if (mTextToSpeech != null) {
1241            removeJavascriptInterface(ALIAS_ACCESSIBILITY_JS_INTERFACE);
1242            mTextToSpeech.shutdown();
1243            mTextToSpeech = null;
1244        }
1245    }
1246
1247    @Override
1248    public void setOverScrollMode(int mode) {
1249        super.setOverScrollMode(mode);
1250        if (mode != OVER_SCROLL_NEVER) {
1251            if (mOverScrollGlow == null) {
1252                mOverScrollGlow = new OverScrollGlow(this);
1253            }
1254        } else {
1255            mOverScrollGlow = null;
1256        }
1257    }
1258
1259    /* package */void updateDefaultZoomDensity(int zoomDensity) {
1260        final float density = mContext.getResources().getDisplayMetrics().density
1261                * 100 / zoomDensity;
1262        mNavSlop = (int) (16 * density);
1263        mZoomManager.updateDefaultZoomDensity(density);
1264    }
1265
1266    /* package */ boolean onSavePassword(String schemePlusHost, String username,
1267            String password, final Message resumeMsg) {
1268       boolean rVal = false;
1269       if (resumeMsg == null) {
1270           // null resumeMsg implies saving password silently
1271           mDatabase.setUsernamePassword(schemePlusHost, username, password);
1272       } else {
1273            final Message remember = mPrivateHandler.obtainMessage(
1274                    REMEMBER_PASSWORD);
1275            remember.getData().putString("host", schemePlusHost);
1276            remember.getData().putString("username", username);
1277            remember.getData().putString("password", password);
1278            remember.obj = resumeMsg;
1279
1280            final Message neverRemember = mPrivateHandler.obtainMessage(
1281                    NEVER_REMEMBER_PASSWORD);
1282            neverRemember.getData().putString("host", schemePlusHost);
1283            neverRemember.getData().putString("username", username);
1284            neverRemember.getData().putString("password", password);
1285            neverRemember.obj = resumeMsg;
1286
1287            new AlertDialog.Builder(getContext())
1288                    .setTitle(com.android.internal.R.string.save_password_label)
1289                    .setMessage(com.android.internal.R.string.save_password_message)
1290                    .setPositiveButton(com.android.internal.R.string.save_password_notnow,
1291                    new DialogInterface.OnClickListener() {
1292                        public void onClick(DialogInterface dialog, int which) {
1293                            resumeMsg.sendToTarget();
1294                        }
1295                    })
1296                    .setNeutralButton(com.android.internal.R.string.save_password_remember,
1297                    new DialogInterface.OnClickListener() {
1298                        public void onClick(DialogInterface dialog, int which) {
1299                            remember.sendToTarget();
1300                        }
1301                    })
1302                    .setNegativeButton(com.android.internal.R.string.save_password_never,
1303                    new DialogInterface.OnClickListener() {
1304                        public void onClick(DialogInterface dialog, int which) {
1305                            neverRemember.sendToTarget();
1306                        }
1307                    })
1308                    .setOnCancelListener(new OnCancelListener() {
1309                        public void onCancel(DialogInterface dialog) {
1310                            resumeMsg.sendToTarget();
1311                        }
1312                    }).show();
1313            // Return true so that WebViewCore will pause while the dialog is
1314            // up.
1315            rVal = true;
1316        }
1317       return rVal;
1318    }
1319
1320    @Override
1321    public void setScrollBarStyle(int style) {
1322        if (style == View.SCROLLBARS_INSIDE_INSET
1323                || style == View.SCROLLBARS_OUTSIDE_INSET) {
1324            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
1325        } else {
1326            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
1327        }
1328        super.setScrollBarStyle(style);
1329    }
1330
1331    /**
1332     * Specify whether the horizontal scrollbar has overlay style.
1333     * @param overlay TRUE if horizontal scrollbar should have overlay style.
1334     */
1335    public void setHorizontalScrollbarOverlay(boolean overlay) {
1336        checkThread();
1337        mOverlayHorizontalScrollbar = overlay;
1338    }
1339
1340    /**
1341     * Specify whether the vertical scrollbar has overlay style.
1342     * @param overlay TRUE if vertical scrollbar should have overlay style.
1343     */
1344    public void setVerticalScrollbarOverlay(boolean overlay) {
1345        checkThread();
1346        mOverlayVerticalScrollbar = overlay;
1347    }
1348
1349    /**
1350     * Return whether horizontal scrollbar has overlay style
1351     * @return TRUE if horizontal scrollbar has overlay style.
1352     */
1353    public boolean overlayHorizontalScrollbar() {
1354        checkThread();
1355        return mOverlayHorizontalScrollbar;
1356    }
1357
1358    /**
1359     * Return whether vertical scrollbar has overlay style
1360     * @return TRUE if vertical scrollbar has overlay style.
1361     */
1362    public boolean overlayVerticalScrollbar() {
1363        checkThread();
1364        return mOverlayVerticalScrollbar;
1365    }
1366
1367    /*
1368     * Return the width of the view where the content of WebView should render
1369     * to.
1370     * Note: this can be called from WebCoreThread.
1371     */
1372    /* package */ int getViewWidth() {
1373        if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
1374            return getWidth();
1375        } else {
1376            return Math.max(0, getWidth() - getVerticalScrollbarWidth());
1377        }
1378    }
1379
1380    /**
1381     * returns the height of the titlebarview (if any). Does not care about
1382     * scrolling
1383     * @hide
1384     */
1385    protected int getTitleHeight() {
1386        return mTitleBar != null ? mTitleBar.getHeight() : 0;
1387    }
1388
1389    /**
1390     * Return the amount of the titlebarview (if any) that is visible
1391     *
1392     * @deprecated This method is now obsolete.
1393     */
1394    public int getVisibleTitleHeight() {
1395        checkThread();
1396        // need to restrict mScrollY due to over scroll
1397        return Math.max(getTitleHeight() - Math.max(0, mScrollY), 0);
1398    }
1399
1400    /*
1401     * Return the height of the view where the content of WebView should render
1402     * to.  Note that this excludes mTitleBar, if there is one.
1403     * Note: this can be called from WebCoreThread.
1404     */
1405    /* package */ int getViewHeight() {
1406        return getViewHeightWithTitle() - getVisibleTitleHeight();
1407    }
1408
1409    int getViewHeightWithTitle() {
1410        int height = getHeight();
1411        if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
1412            height -= getHorizontalScrollbarHeight();
1413        }
1414        return height;
1415    }
1416
1417    /**
1418     * @return The SSL certificate for the main top-level page or null if
1419     * there is no certificate (the site is not secure).
1420     */
1421    public SslCertificate getCertificate() {
1422        checkThread();
1423        return mCertificate;
1424    }
1425
1426    /**
1427     * Sets the SSL certificate for the main top-level page.
1428     */
1429    public void setCertificate(SslCertificate certificate) {
1430        checkThread();
1431        if (DebugFlags.WEB_VIEW) {
1432            Log.v(LOGTAG, "setCertificate=" + certificate);
1433        }
1434        // here, the certificate can be null (if the site is not secure)
1435        mCertificate = certificate;
1436    }
1437
1438    //-------------------------------------------------------------------------
1439    // Methods called by activity
1440    //-------------------------------------------------------------------------
1441
1442    /**
1443     * Save the username and password for a particular host in the WebView's
1444     * internal database.
1445     * @param host The host that required the credentials.
1446     * @param username The username for the given host.
1447     * @param password The password for the given host.
1448     */
1449    public void savePassword(String host, String username, String password) {
1450        checkThread();
1451        mDatabase.setUsernamePassword(host, username, password);
1452    }
1453
1454    /**
1455     * Set the HTTP authentication credentials for a given host and realm.
1456     *
1457     * @param host The host for the credentials.
1458     * @param realm The realm for the credentials.
1459     * @param username The username for the password. If it is null, it means
1460     *                 password can't be saved.
1461     * @param password The password
1462     */
1463    public void setHttpAuthUsernamePassword(String host, String realm,
1464            String username, String password) {
1465        checkThread();
1466        mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
1467    }
1468
1469    /**
1470     * Retrieve the HTTP authentication username and password for a given
1471     * host & realm pair
1472     *
1473     * @param host The host for which the credentials apply.
1474     * @param realm The realm for which the credentials apply.
1475     * @return String[] if found, String[0] is username, which can be null and
1476     *         String[1] is password. Return null if it can't find anything.
1477     */
1478    public String[] getHttpAuthUsernamePassword(String host, String realm) {
1479        checkThread();
1480        return mDatabase.getHttpAuthUsernamePassword(host, realm);
1481    }
1482
1483    /**
1484     * Remove Find or Select ActionModes, if active.
1485     */
1486    private void clearActionModes() {
1487        if (mSelectCallback != null) {
1488            mSelectCallback.finish();
1489        }
1490        if (mFindCallback != null) {
1491            mFindCallback.finish();
1492        }
1493    }
1494
1495    /**
1496     * Called to clear state when moving from one page to another, or changing
1497     * in some other way that makes elements associated with the current page
1498     * (such as WebTextView or ActionModes) no longer relevant.
1499     */
1500    private void clearHelpers() {
1501        clearTextEntry();
1502        clearActionModes();
1503        dismissFullScreenMode();
1504    }
1505
1506    /**
1507     * Destroy the internal state of the WebView. This method should be called
1508     * after the WebView has been removed from the view system. No other
1509     * methods may be called on a WebView after destroy.
1510     */
1511    public void destroy() {
1512        checkThread();
1513        destroyImpl();
1514    }
1515
1516    private void destroyImpl() {
1517        clearHelpers();
1518        if (mListBoxDialog != null) {
1519            mListBoxDialog.dismiss();
1520            mListBoxDialog = null;
1521        }
1522        if (mNativeClass != 0) nativeStopGL();
1523        if (mWebViewCore != null) {
1524            // Set the handlers to null before destroying WebViewCore so no
1525            // more messages will be posted.
1526            mCallbackProxy.setWebViewClient(null);
1527            mCallbackProxy.setWebChromeClient(null);
1528            // Tell WebViewCore to destroy itself
1529            synchronized (this) {
1530                WebViewCore webViewCore = mWebViewCore;
1531                mWebViewCore = null; // prevent using partial webViewCore
1532                webViewCore.destroy();
1533            }
1534            // Remove any pending messages that might not be serviced yet.
1535            mPrivateHandler.removeCallbacksAndMessages(null);
1536            mCallbackProxy.removeCallbacksAndMessages(null);
1537            // Wake up the WebCore thread just in case it is waiting for a
1538            // JavaScript dialog.
1539            synchronized (mCallbackProxy) {
1540                mCallbackProxy.notify();
1541            }
1542        }
1543        if (mNativeClass != 0) {
1544            nativeDestroy();
1545            mNativeClass = 0;
1546        }
1547    }
1548
1549    /**
1550     * Enables platform notifications of data state and proxy changes.
1551     * Notifications are enabled by default.
1552     *
1553     * @deprecated This method is now obsolete.
1554     */
1555    @Deprecated
1556    public static void enablePlatformNotifications() {
1557        checkThread();
1558        synchronized (WebView.class) {
1559            Network.enablePlatformNotifications();
1560            sNotificationsEnabled = true;
1561            Context context = JniUtil.getContext();
1562            if (context != null)
1563                setupProxyListener(context);
1564        }
1565    }
1566
1567    /**
1568     * Disables platform notifications of data state and proxy changes.
1569     * Notifications are enabled by default.
1570     *
1571     * @deprecated This method is now obsolete.
1572     */
1573    @Deprecated
1574    public static void disablePlatformNotifications() {
1575        checkThread();
1576        synchronized (WebView.class) {
1577            Network.disablePlatformNotifications();
1578            sNotificationsEnabled = false;
1579            Context context = JniUtil.getContext();
1580            if (context != null)
1581                disableProxyListener(context);
1582        }
1583    }
1584
1585    /**
1586     * Sets JavaScript engine flags.
1587     *
1588     * @param flags JS engine flags in a String
1589     *
1590     * @hide pending API solidification
1591     */
1592    public void setJsFlags(String flags) {
1593        checkThread();
1594        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
1595    }
1596
1597    /**
1598     * Inform WebView of the network state. This is used to set
1599     * the JavaScript property window.navigator.isOnline and
1600     * generates the online/offline event as specified in HTML5, sec. 5.7.7
1601     * @param networkUp boolean indicating if network is available
1602     */
1603    public void setNetworkAvailable(boolean networkUp) {
1604        checkThread();
1605        mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
1606                networkUp ? 1 : 0, 0);
1607    }
1608
1609    /**
1610     * Inform WebView about the current network type.
1611     * {@hide}
1612     */
1613    public void setNetworkType(String type, String subtype) {
1614        checkThread();
1615        Map<String, String> map = new HashMap<String, String>();
1616        map.put("type", type);
1617        map.put("subtype", subtype);
1618        mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map);
1619    }
1620    /**
1621     * Save the state of this WebView used in
1622     * {@link android.app.Activity#onSaveInstanceState}. Please note that this
1623     * method no longer stores the display data for this WebView. The previous
1624     * behavior could potentially leak files if {@link #restoreState} was never
1625     * called. See {@link #savePicture} and {@link #restorePicture} for saving
1626     * and restoring the display data.
1627     * @param outState The Bundle to store the WebView state.
1628     * @return The same copy of the back/forward list used to save the state. If
1629     *         saveState fails, the returned list will be null.
1630     * @see #savePicture
1631     * @see #restorePicture
1632     */
1633    public WebBackForwardList saveState(Bundle outState) {
1634        checkThread();
1635        if (outState == null) {
1636            return null;
1637        }
1638        // We grab a copy of the back/forward list because a client of WebView
1639        // may have invalidated the history list by calling clearHistory.
1640        WebBackForwardList list = copyBackForwardList();
1641        final int currentIndex = list.getCurrentIndex();
1642        final int size = list.getSize();
1643        // We should fail saving the state if the list is empty or the index is
1644        // not in a valid range.
1645        if (currentIndex < 0 || currentIndex >= size || size == 0) {
1646            return null;
1647        }
1648        outState.putInt("index", currentIndex);
1649        // FIXME: This should just be a byte[][] instead of ArrayList but
1650        // Parcel.java does not have the code to handle multi-dimensional
1651        // arrays.
1652        ArrayList<byte[]> history = new ArrayList<byte[]>(size);
1653        for (int i = 0; i < size; i++) {
1654            WebHistoryItem item = list.getItemAtIndex(i);
1655            if (null == item) {
1656                // FIXME: this shouldn't happen
1657                // need to determine how item got set to null
1658                Log.w(LOGTAG, "saveState: Unexpected null history item.");
1659                return null;
1660            }
1661            byte[] data = item.getFlattenedData();
1662            if (data == null) {
1663                // It would be very odd to not have any data for a given history
1664                // item. And we will fail to rebuild the history list without
1665                // flattened data.
1666                return null;
1667            }
1668            history.add(data);
1669        }
1670        outState.putSerializable("history", history);
1671        if (mCertificate != null) {
1672            outState.putBundle("certificate",
1673                               SslCertificate.saveState(mCertificate));
1674        }
1675        outState.putBoolean("privateBrowsingEnabled", isPrivateBrowsingEnabled());
1676        mZoomManager.saveZoomState(outState);
1677        return list;
1678    }
1679
1680    /**
1681     * Save the current display data to the Bundle given. Used in conjunction
1682     * with {@link #saveState}.
1683     * @param b A Bundle to store the display data.
1684     * @param dest The file to store the serialized picture data. Will be
1685     *             overwritten with this WebView's picture data.
1686     * @return True if the picture was successfully saved.
1687     * @deprecated This method is now obsolete.
1688     */
1689    @Deprecated
1690    public boolean savePicture(Bundle b, final File dest) {
1691        checkThread();
1692        if (dest == null || b == null) {
1693            return false;
1694        }
1695        final Picture p = capturePicture();
1696        // Use a temporary file while writing to ensure the destination file
1697        // contains valid data.
1698        final File temp = new File(dest.getPath() + ".writing");
1699        new Thread(new Runnable() {
1700            public void run() {
1701                FileOutputStream out = null;
1702                try {
1703                    out = new FileOutputStream(temp);
1704                    p.writeToStream(out);
1705                    // Writing the picture succeeded, rename the temporary file
1706                    // to the destination.
1707                    temp.renameTo(dest);
1708                } catch (Exception e) {
1709                    // too late to do anything about it.
1710                } finally {
1711                    if (out != null) {
1712                        try {
1713                            out.close();
1714                        } catch (Exception e) {
1715                            // Can't do anything about that
1716                        }
1717                    }
1718                    temp.delete();
1719                }
1720            }
1721        }).start();
1722        // now update the bundle
1723        b.putInt("scrollX", mScrollX);
1724        b.putInt("scrollY", mScrollY);
1725        mZoomManager.saveZoomState(b);
1726        return true;
1727    }
1728
1729    private void restoreHistoryPictureFields(Picture p, Bundle b) {
1730        int sx = b.getInt("scrollX", 0);
1731        int sy = b.getInt("scrollY", 0);
1732
1733        mDrawHistory = true;
1734        mHistoryPicture = p;
1735
1736        mScrollX = sx;
1737        mScrollY = sy;
1738        mZoomManager.restoreZoomState(b);
1739        final float scale = mZoomManager.getScale();
1740        mHistoryWidth = Math.round(p.getWidth() * scale);
1741        mHistoryHeight = Math.round(p.getHeight() * scale);
1742
1743        invalidate();
1744    }
1745
1746    /**
1747     * Restore the display data that was save in {@link #savePicture}. Used in
1748     * conjunction with {@link #restoreState}.
1749     * @param b A Bundle containing the saved display data.
1750     * @param src The file where the picture data was stored.
1751     * @return True if the picture was successfully restored.
1752     * @deprecated This method is now obsolete.
1753     */
1754    @Deprecated
1755    public boolean restorePicture(Bundle b, File src) {
1756        checkThread();
1757        if (src == null || b == null) {
1758            return false;
1759        }
1760        if (!src.exists()) {
1761            return false;
1762        }
1763        try {
1764            final FileInputStream in = new FileInputStream(src);
1765            final Bundle copy = new Bundle(b);
1766            new Thread(new Runnable() {
1767                public void run() {
1768                    try {
1769                        final Picture p = Picture.createFromStream(in);
1770                        if (p != null) {
1771                            // Post a runnable on the main thread to update the
1772                            // history picture fields.
1773                            mPrivateHandler.post(new Runnable() {
1774                                public void run() {
1775                                    restoreHistoryPictureFields(p, copy);
1776                                }
1777                            });
1778                        }
1779                    } finally {
1780                        try {
1781                            in.close();
1782                        } catch (Exception e) {
1783                            // Nothing we can do now.
1784                        }
1785                    }
1786                }
1787            }).start();
1788        } catch (FileNotFoundException e){
1789            e.printStackTrace();
1790        }
1791        return true;
1792    }
1793
1794    /**
1795     * Saves the view data to the output stream. The output is highly
1796     * version specific, and may not be able to be loaded by newer versions
1797     * of WebView.
1798     * @param stream The {@link OutputStream} to save to
1799     * @return True if saved successfully
1800     * @hide
1801     */
1802    public boolean saveViewState(OutputStream stream) {
1803        try {
1804            return ViewStateSerializer.serializeViewState(stream, this);
1805        } catch (IOException e) {
1806            Log.w(LOGTAG, "Failed to saveViewState", e);
1807        }
1808        return false;
1809    }
1810
1811    /**
1812     * Loads the view data from the input stream. See
1813     * {@link #saveViewState(OutputStream)} for more information.
1814     * @param stream The {@link InputStream} to load from
1815     * @return True if loaded successfully
1816     * @hide
1817     */
1818    public boolean loadViewState(InputStream stream) {
1819        try {
1820            mLoadedPicture = ViewStateSerializer.deserializeViewState(stream, this);
1821            mBlockWebkitViewMessages = true;
1822            setNewPicture(mLoadedPicture, true);
1823            return true;
1824        } catch (IOException e) {
1825            Log.w(LOGTAG, "Failed to loadViewState", e);
1826        }
1827        return false;
1828    }
1829
1830    /**
1831     * Clears the view state set with {@link #loadViewState(InputStream)}.
1832     * This WebView will then switch to showing the content from webkit
1833     * @hide
1834     */
1835    public void clearViewState() {
1836        mBlockWebkitViewMessages = false;
1837        mLoadedPicture = null;
1838        invalidate();
1839    }
1840
1841    /**
1842     * Restore the state of this WebView from the given map used in
1843     * {@link android.app.Activity#onRestoreInstanceState}. This method should
1844     * be called to restore the state of the WebView before using the object. If
1845     * it is called after the WebView has had a chance to build state (load
1846     * pages, create a back/forward list, etc.) there may be undesirable
1847     * side-effects. Please note that this method no longer restores the
1848     * display data for this WebView. See {@link #savePicture} and {@link
1849     * #restorePicture} for saving and restoring the display data.
1850     * @param inState The incoming Bundle of state.
1851     * @return The restored back/forward list or null if restoreState failed.
1852     * @see #savePicture
1853     * @see #restorePicture
1854     */
1855    public WebBackForwardList restoreState(Bundle inState) {
1856        checkThread();
1857        WebBackForwardList returnList = null;
1858        if (inState == null) {
1859            return returnList;
1860        }
1861        if (inState.containsKey("index") && inState.containsKey("history")) {
1862            mCertificate = SslCertificate.restoreState(
1863                inState.getBundle("certificate"));
1864
1865            final WebBackForwardList list = mCallbackProxy.getBackForwardList();
1866            final int index = inState.getInt("index");
1867            // We can't use a clone of the list because we need to modify the
1868            // shared copy, so synchronize instead to prevent concurrent
1869            // modifications.
1870            synchronized (list) {
1871                final List<byte[]> history =
1872                        (List<byte[]>) inState.getSerializable("history");
1873                final int size = history.size();
1874                // Check the index bounds so we don't crash in native code while
1875                // restoring the history index.
1876                if (index < 0 || index >= size) {
1877                    return null;
1878                }
1879                for (int i = 0; i < size; i++) {
1880                    byte[] data = history.remove(0);
1881                    if (data == null) {
1882                        // If we somehow have null data, we cannot reconstruct
1883                        // the item and thus our history list cannot be rebuilt.
1884                        return null;
1885                    }
1886                    WebHistoryItem item = new WebHistoryItem(data);
1887                    list.addHistoryItem(item);
1888                }
1889                // Grab the most recent copy to return to the caller.
1890                returnList = copyBackForwardList();
1891                // Update the copy to have the correct index.
1892                returnList.setCurrentIndex(index);
1893            }
1894            // Restore private browsing setting.
1895            if (inState.getBoolean("privateBrowsingEnabled")) {
1896                getSettings().setPrivateBrowsingEnabled(true);
1897            }
1898            mZoomManager.restoreZoomState(inState);
1899            // Remove all pending messages because we are restoring previous
1900            // state.
1901            mWebViewCore.removeMessages();
1902            // Send a restore state message.
1903            mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
1904        }
1905        return returnList;
1906    }
1907
1908    /**
1909     * Load the given url with the extra headers.
1910     * @param url The url of the resource to load.
1911     * @param extraHeaders The extra headers sent with this url. This should not
1912     *            include the common headers like "user-agent". If it does, it
1913     *            will be replaced by the intrinsic value of the WebView.
1914     */
1915    public void loadUrl(String url, Map<String, String> extraHeaders) {
1916        checkThread();
1917        loadUrlImpl(url, extraHeaders);
1918    }
1919
1920    private void loadUrlImpl(String url, Map<String, String> extraHeaders) {
1921        switchOutDrawHistory();
1922        WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData();
1923        arg.mUrl = url;
1924        arg.mExtraHeaders = extraHeaders;
1925        mWebViewCore.sendMessage(EventHub.LOAD_URL, arg);
1926        clearHelpers();
1927    }
1928
1929    /**
1930     * Load the given url.
1931     * @param url The url of the resource to load.
1932     */
1933    public void loadUrl(String url) {
1934        checkThread();
1935        loadUrlImpl(url);
1936    }
1937
1938    private void loadUrlImpl(String url) {
1939        if (url == null) {
1940            return;
1941        }
1942        loadUrlImpl(url, null);
1943    }
1944
1945    /**
1946     * Load the url with postData using "POST" method into the WebView. If url
1947     * is not a network url, it will be loaded with {link
1948     * {@link #loadUrl(String)} instead.
1949     *
1950     * @param url The url of the resource to load.
1951     * @param postData The data will be passed to "POST" request.
1952     */
1953    public void postUrl(String url, byte[] postData) {
1954        checkThread();
1955        if (URLUtil.isNetworkUrl(url)) {
1956            switchOutDrawHistory();
1957            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
1958            arg.mUrl = url;
1959            arg.mPostData = postData;
1960            mWebViewCore.sendMessage(EventHub.POST_URL, arg);
1961            clearHelpers();
1962        } else {
1963            loadUrlImpl(url);
1964        }
1965    }
1966
1967    /**
1968     * Load the given data into the WebView using a 'data' scheme URL. Content
1969     * loaded in this way does not have the ability to load content from the
1970     * network.
1971     * <p>
1972     * If the value of the encoding parameter is 'base64', then the data must
1973     * be encoded as base64. Otherwise, the data must use ASCII encoding for
1974     * octets inside the range of safe URL characters and use the standard %xx
1975     * hex encoding of URLs for octets outside that range.
1976     * @param data A String of data in the given encoding.
1977     * @param mimeType The MIMEType of the data, e.g. 'text/html'.
1978     * @param encoding The encoding of the data.
1979     */
1980    public void loadData(String data, String mimeType, String encoding) {
1981        checkThread();
1982        loadDataImpl(data, mimeType, encoding);
1983    }
1984
1985    private void loadDataImpl(String data, String mimeType, String encoding) {
1986        StringBuilder dataUrl = new StringBuilder("data:");
1987        dataUrl.append(mimeType);
1988        if ("base64".equals(encoding)) {
1989            dataUrl.append(";base64");
1990        }
1991        dataUrl.append(",");
1992        dataUrl.append(data);
1993        loadUrlImpl(dataUrl.toString());
1994    }
1995
1996    /**
1997     * Load the given data into the WebView, use the provided URL as the base
1998     * URL for the content. The base URL is the URL that represents the page
1999     * that is loaded through this interface. As such, it is used to resolve any
2000     * relative URLs. The historyUrl is used for the history entry.
2001     * <p>
2002     * Note that content specified in this way can access local device files
2003     * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
2004     * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
2005     * @param baseUrl Url to resolve relative paths with, if null defaults to
2006     *            "about:blank"
2007     * @param data A String of data in the given encoding.
2008     * @param mimeType The MIMEType of the data. i.e. text/html. If null,
2009     *            defaults to "text/html"
2010     * @param encoding The encoding of the data. i.e. utf-8, us-ascii
2011     * @param historyUrl URL to use as the history entry.  Can be null.
2012     */
2013    public void loadDataWithBaseURL(String baseUrl, String data,
2014            String mimeType, String encoding, String historyUrl) {
2015        checkThread();
2016
2017        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
2018            loadDataImpl(data, mimeType, encoding);
2019            return;
2020        }
2021        switchOutDrawHistory();
2022        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
2023        arg.mBaseUrl = baseUrl;
2024        arg.mData = data;
2025        arg.mMimeType = mimeType;
2026        arg.mEncoding = encoding;
2027        arg.mHistoryUrl = historyUrl;
2028        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
2029        clearHelpers();
2030    }
2031
2032    /**
2033     * Saves the current view as a web archive.
2034     *
2035     * @param filename The filename where the archive should be placed.
2036     */
2037    public void saveWebArchive(String filename) {
2038        checkThread();
2039        saveWebArchiveImpl(filename, false, null);
2040    }
2041
2042    /* package */ static class SaveWebArchiveMessage {
2043        SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback<String> callback) {
2044            mBasename = basename;
2045            mAutoname = autoname;
2046            mCallback = callback;
2047        }
2048
2049        /* package */ final String mBasename;
2050        /* package */ final boolean mAutoname;
2051        /* package */ final ValueCallback<String> mCallback;
2052        /* package */ String mResultFile;
2053    }
2054
2055    /**
2056     * Saves the current view as a web archive.
2057     *
2058     * @param basename The filename where the archive should be placed.
2059     * @param autoname If false, takes basename to be a file. If true, basename
2060     *                 is assumed to be a directory in which a filename will be
2061     *                 chosen according to the url of the current page.
2062     * @param callback Called after the web archive has been saved. The
2063     *                 parameter for onReceiveValue will either be the filename
2064     *                 under which the file was saved, or null if saving the
2065     *                 file failed.
2066     */
2067    public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
2068        checkThread();
2069        saveWebArchiveImpl(basename, autoname, callback);
2070    }
2071
2072    private void saveWebArchiveImpl(String basename, boolean autoname,
2073            ValueCallback<String> callback) {
2074        mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE,
2075            new SaveWebArchiveMessage(basename, autoname, callback));
2076    }
2077
2078    /**
2079     * Stop the current load.
2080     */
2081    public void stopLoading() {
2082        checkThread();
2083        // TODO: should we clear all the messages in the queue before sending
2084        // STOP_LOADING?
2085        switchOutDrawHistory();
2086        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
2087    }
2088
2089    /**
2090     * Reload the current url.
2091     */
2092    public void reload() {
2093        checkThread();
2094        clearHelpers();
2095        switchOutDrawHistory();
2096        mWebViewCore.sendMessage(EventHub.RELOAD);
2097    }
2098
2099    /**
2100     * Return true if this WebView has a back history item.
2101     * @return True iff this WebView has a back history item.
2102     */
2103    public boolean canGoBack() {
2104        checkThread();
2105        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2106        synchronized (l) {
2107            if (l.getClearPending()) {
2108                return false;
2109            } else {
2110                return l.getCurrentIndex() > 0;
2111            }
2112        }
2113    }
2114
2115    /**
2116     * Go back in the history of this WebView.
2117     */
2118    public void goBack() {
2119        checkThread();
2120        goBackOrForwardImpl(-1);
2121    }
2122
2123    /**
2124     * Return true if this WebView has a forward history item.
2125     * @return True iff this Webview has a forward history item.
2126     */
2127    public boolean canGoForward() {
2128        checkThread();
2129        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2130        synchronized (l) {
2131            if (l.getClearPending()) {
2132                return false;
2133            } else {
2134                return l.getCurrentIndex() < l.getSize() - 1;
2135            }
2136        }
2137    }
2138
2139    /**
2140     * Go forward in the history of this WebView.
2141     */
2142    public void goForward() {
2143        checkThread();
2144        goBackOrForwardImpl(1);
2145    }
2146
2147    /**
2148     * Return true if the page can go back or forward the given
2149     * number of steps.
2150     * @param steps The negative or positive number of steps to move the
2151     *              history.
2152     */
2153    public boolean canGoBackOrForward(int steps) {
2154        checkThread();
2155        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2156        synchronized (l) {
2157            if (l.getClearPending()) {
2158                return false;
2159            } else {
2160                int newIndex = l.getCurrentIndex() + steps;
2161                return newIndex >= 0 && newIndex < l.getSize();
2162            }
2163        }
2164    }
2165
2166    /**
2167     * Go to the history item that is the number of steps away from
2168     * the current item. Steps is negative if backward and positive
2169     * if forward.
2170     * @param steps The number of steps to take back or forward in the back
2171     *              forward list.
2172     */
2173    public void goBackOrForward(int steps) {
2174        checkThread();
2175        goBackOrForwardImpl(steps);
2176    }
2177
2178    private void goBackOrForwardImpl(int steps) {
2179        goBackOrForward(steps, false);
2180    }
2181
2182    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
2183        if (steps != 0) {
2184            clearHelpers();
2185            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
2186                    ignoreSnapshot ? 1 : 0);
2187        }
2188    }
2189
2190    /**
2191     * Returns true if private browsing is enabled in this WebView.
2192     */
2193    public boolean isPrivateBrowsingEnabled() {
2194        checkThread();
2195        return getSettings().isPrivateBrowsingEnabled();
2196    }
2197
2198    private void startPrivateBrowsing() {
2199        getSettings().setPrivateBrowsingEnabled(true);
2200    }
2201
2202    private boolean extendScroll(int y) {
2203        int finalY = mScroller.getFinalY();
2204        int newY = pinLocY(finalY + y);
2205        if (newY == finalY) return false;
2206        mScroller.setFinalY(newY);
2207        mScroller.extendDuration(computeDuration(0, y));
2208        return true;
2209    }
2210
2211    /**
2212     * Scroll the contents of the view up by half the view size
2213     * @param top true to jump to the top of the page
2214     * @return true if the page was scrolled
2215     */
2216    public boolean pageUp(boolean top) {
2217        checkThread();
2218        if (mNativeClass == 0) {
2219            return false;
2220        }
2221        nativeClearCursor(); // start next trackball movement from page edge
2222        if (top) {
2223            // go to the top of the document
2224            return pinScrollTo(mScrollX, 0, true, 0);
2225        }
2226        // Page up
2227        int h = getHeight();
2228        int y;
2229        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2230            y = -h + PAGE_SCROLL_OVERLAP;
2231        } else {
2232            y = -h / 2;
2233        }
2234        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2235                : extendScroll(y);
2236    }
2237
2238    /**
2239     * Scroll the contents of the view down by half the page size
2240     * @param bottom true to jump to bottom of page
2241     * @return true if the page was scrolled
2242     */
2243    public boolean pageDown(boolean bottom) {
2244        checkThread();
2245        if (mNativeClass == 0) {
2246            return false;
2247        }
2248        nativeClearCursor(); // start next trackball movement from page edge
2249        if (bottom) {
2250            return pinScrollTo(mScrollX, computeRealVerticalScrollRange(), true, 0);
2251        }
2252        // Page down.
2253        int h = getHeight();
2254        int y;
2255        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2256            y = h - PAGE_SCROLL_OVERLAP;
2257        } else {
2258            y = h / 2;
2259        }
2260        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2261                : extendScroll(y);
2262    }
2263
2264    /**
2265     * Clear the view so that onDraw() will draw nothing but white background,
2266     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
2267     */
2268    public void clearView() {
2269        checkThread();
2270        mContentWidth = 0;
2271        mContentHeight = 0;
2272        setBaseLayer(0, null, false, false);
2273        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
2274    }
2275
2276    /**
2277     * Return a new picture that captures the current display of the webview.
2278     * This is a copy of the display, and will be unaffected if the webview
2279     * later loads a different URL.
2280     *
2281     * @return a picture containing the current contents of the view. Note this
2282     *         picture is of the entire document, and is not restricted to the
2283     *         bounds of the view.
2284     */
2285    public Picture capturePicture() {
2286        checkThread();
2287        if (mNativeClass == 0) return null;
2288        Picture result = new Picture();
2289        nativeCopyBaseContentToPicture(result);
2290        return result;
2291    }
2292
2293    /**
2294     *  Return true if the browser is displaying a TextView for text input.
2295     */
2296    private boolean inEditingMode() {
2297        return mWebTextView != null && mWebTextView.getParent() != null;
2298    }
2299
2300    /**
2301     * Remove the WebTextView.
2302     */
2303    private void clearTextEntry() {
2304        if (inEditingMode()) {
2305            mWebTextView.remove();
2306        } else {
2307            // The keyboard may be open with the WebView as the served view
2308            hideSoftKeyboard();
2309        }
2310    }
2311
2312    /**
2313     * Return the current scale of the WebView
2314     * @return The current scale.
2315     */
2316    public float getScale() {
2317        checkThread();
2318        return mZoomManager.getScale();
2319    }
2320
2321    /**
2322     * Set the initial scale for the WebView. 0 means default. If
2323     * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
2324     * way. Otherwise it starts with 100%. If initial scale is greater than 0,
2325     * WebView starts will this value as initial scale.
2326     *
2327     * @param scaleInPercent The initial scale in percent.
2328     */
2329    public void setInitialScale(int scaleInPercent) {
2330        checkThread();
2331        mZoomManager.setInitialScaleInPercent(scaleInPercent);
2332    }
2333
2334    /**
2335     * Invoke the graphical zoom picker widget for this WebView. This will
2336     * result in the zoom widget appearing on the screen to control the zoom
2337     * level of this WebView.
2338     */
2339    public void invokeZoomPicker() {
2340        checkThread();
2341        if (!getSettings().supportZoom()) {
2342            Log.w(LOGTAG, "This WebView doesn't support zoom.");
2343            return;
2344        }
2345        clearHelpers();
2346        mZoomManager.invokeZoomPicker();
2347    }
2348
2349    /**
2350     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
2351     * is found and the anchor has a non-JavaScript url, the HitTestResult type
2352     * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
2353     * anchor does not have a url or if it is a JavaScript url, the type will
2354     * be UNKNOWN_TYPE and the url has to be retrieved through
2355     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
2356     * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
2357     * the "extra" field. A type of
2358     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
2359     * a child node. If a phone number is found, the HitTestResult type is set
2360     * to PHONE_TYPE and the phone number is set in the "extra" field of
2361     * HitTestResult. If a map address is found, the HitTestResult type is set
2362     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
2363     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
2364     * and the email is set in the "extra" field of HitTestResult. Otherwise,
2365     * HitTestResult type is set to UNKNOWN_TYPE.
2366     */
2367    public HitTestResult getHitTestResult() {
2368        checkThread();
2369        return hitTestResult(mInitialHitTestResult);
2370    }
2371
2372    private HitTestResult hitTestResult(HitTestResult fallback) {
2373        if (mNativeClass == 0) {
2374            return null;
2375        }
2376
2377        HitTestResult result = new HitTestResult();
2378        if (nativeHasCursorNode()) {
2379            if (nativeCursorIsTextInput()) {
2380                result.setType(HitTestResult.EDIT_TEXT_TYPE);
2381            } else {
2382                String text = nativeCursorText();
2383                if (text != null) {
2384                    if (text.startsWith(SCHEME_TEL)) {
2385                        result.setType(HitTestResult.PHONE_TYPE);
2386                        result.setExtra(text.substring(SCHEME_TEL.length()));
2387                    } else if (text.startsWith(SCHEME_MAILTO)) {
2388                        result.setType(HitTestResult.EMAIL_TYPE);
2389                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
2390                    } else if (text.startsWith(SCHEME_GEO)) {
2391                        result.setType(HitTestResult.GEO_TYPE);
2392                        result.setExtra(URLDecoder.decode(text
2393                                .substring(SCHEME_GEO.length())));
2394                    } else if (nativeCursorIsAnchor()) {
2395                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
2396                        result.setExtra(text);
2397                    }
2398                }
2399            }
2400        } else if (fallback != null) {
2401            /* If webkit causes a rebuild while the long press is in progress,
2402             * the cursor node may be reset, even if it is still around. This
2403             * uses the cursor node saved when the touch began. Since the
2404             * nativeImageURI below only changes the result if it is successful,
2405             * this uses the data beneath the touch if available or the original
2406             * tap data otherwise.
2407             */
2408            Log.v(LOGTAG, "hitTestResult use fallback");
2409            result = fallback;
2410        }
2411        int type = result.getType();
2412        if (type == HitTestResult.UNKNOWN_TYPE
2413                || type == HitTestResult.SRC_ANCHOR_TYPE) {
2414            // Now check to see if it is an image.
2415            int contentX = viewToContentX(mLastTouchX + mScrollX);
2416            int contentY = viewToContentY(mLastTouchY + mScrollY);
2417            String text = nativeImageURI(contentX, contentY);
2418            if (text != null) {
2419                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
2420                        HitTestResult.IMAGE_TYPE :
2421                        HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
2422                result.setExtra(text);
2423            }
2424        }
2425        return result;
2426    }
2427
2428    // Called by JNI when the DOM has changed the focus.  Clear the focus so
2429    // that new keys will go to the newly focused field
2430    private void domChangedFocus() {
2431        if (inEditingMode()) {
2432            mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget();
2433        }
2434    }
2435    /**
2436     * Request the anchor or image element URL at the last tapped point.
2437     * If hrefMsg is null, this method returns immediately and does not
2438     * dispatch hrefMsg to its target. If the tapped point hits an image,
2439     * an anchor, or an image in an anchor, the message associates
2440     * strings in named keys in its data. The value paired with the key
2441     * may be an empty string.
2442     *
2443     * @param hrefMsg This message will be dispatched with the result of the
2444     *                request. The message data contains three keys:
2445     *                - "url" returns the anchor's href attribute.
2446     *                - "title" returns the anchor's text.
2447     *                - "src" returns the image's src attribute.
2448     */
2449    public void requestFocusNodeHref(Message hrefMsg) {
2450        checkThread();
2451        if (hrefMsg == null) {
2452            return;
2453        }
2454        int contentX = viewToContentX(mLastTouchX + mScrollX);
2455        int contentY = viewToContentY(mLastTouchY + mScrollY);
2456        if (nativeHasCursorNode()) {
2457            Rect cursorBounds = nativeGetCursorRingBounds();
2458            if (!cursorBounds.contains(contentX, contentY)) {
2459                int slop = viewToContentDimension(mNavSlop);
2460                cursorBounds.inset(-slop, -slop);
2461                if (cursorBounds.contains(contentX, contentY)) {
2462                    contentX = (int) cursorBounds.centerX();
2463                    contentY = (int) cursorBounds.centerY();
2464                }
2465            }
2466        }
2467        mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
2468                contentX, contentY, hrefMsg);
2469    }
2470
2471    /**
2472     * Request the url of the image last touched by the user. msg will be sent
2473     * to its target with a String representing the url as its object.
2474     *
2475     * @param msg This message will be dispatched with the result of the request
2476     *            as the data member with "url" as key. The result can be null.
2477     */
2478    public void requestImageRef(Message msg) {
2479        checkThread();
2480        if (0 == mNativeClass) return; // client isn't initialized
2481        int contentX = viewToContentX(mLastTouchX + mScrollX);
2482        int contentY = viewToContentY(mLastTouchY + mScrollY);
2483        String ref = nativeImageURI(contentX, contentY);
2484        Bundle data = msg.getData();
2485        data.putString("url", ref);
2486        msg.setData(data);
2487        msg.sendToTarget();
2488    }
2489
2490    static int pinLoc(int x, int viewMax, int docMax) {
2491//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
2492        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
2493            // pin the short document to the top/left of the screen
2494            x = 0;
2495//            Log.d(LOGTAG, "--- center " + x);
2496        } else if (x < 0) {
2497            x = 0;
2498//            Log.d(LOGTAG, "--- zero");
2499        } else if (x + viewMax > docMax) {
2500            x = docMax - viewMax;
2501//            Log.d(LOGTAG, "--- pin " + x);
2502        }
2503        return x;
2504    }
2505
2506    // Expects x in view coordinates
2507    int pinLocX(int x) {
2508        if (mInOverScrollMode) return x;
2509        return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange());
2510    }
2511
2512    // Expects y in view coordinates
2513    int pinLocY(int y) {
2514        if (mInOverScrollMode) return y;
2515        return pinLoc(y, getViewHeightWithTitle(),
2516                      computeRealVerticalScrollRange() + getTitleHeight());
2517    }
2518
2519    /**
2520     * A title bar which is embedded in this WebView, and scrolls along with it
2521     * vertically, but not horizontally.
2522     */
2523    private View mTitleBar;
2524
2525    /**
2526     * the title bar rendering gravity
2527     */
2528    private int mTitleGravity;
2529
2530    /**
2531     * Add or remove a title bar to be embedded into the WebView, and scroll
2532     * along with it vertically, while remaining in view horizontally. Pass
2533     * null to remove the title bar from the WebView, and return to drawing
2534     * the WebView normally without translating to account for the title bar.
2535     * @hide
2536     */
2537    public void setEmbeddedTitleBar(View v) {
2538        if (mTitleBar == v) return;
2539        if (mTitleBar != null) {
2540            removeView(mTitleBar);
2541        }
2542        if (null != v) {
2543            addView(v, new AbsoluteLayout.LayoutParams(
2544                    ViewGroup.LayoutParams.MATCH_PARENT,
2545                    ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
2546        }
2547        mTitleBar = v;
2548    }
2549
2550    /**
2551     * Set where to render the embedded title bar
2552     * NO_GRAVITY at the top of the page
2553     * TOP        at the top of the screen
2554     * @hide
2555     */
2556    public void setTitleBarGravity(int gravity) {
2557        mTitleGravity = gravity;
2558        // force refresh
2559        invalidate();
2560    }
2561
2562    /**
2563     * Given a distance in view space, convert it to content space. Note: this
2564     * does not reflect translation, just scaling, so this should not be called
2565     * with coordinates, but should be called for dimensions like width or
2566     * height.
2567     */
2568    private int viewToContentDimension(int d) {
2569        return Math.round(d * mZoomManager.getInvScale());
2570    }
2571
2572    /**
2573     * Given an x coordinate in view space, convert it to content space.  Also
2574     * may be used for absolute heights (such as for the WebTextView's
2575     * textSize, which is unaffected by the height of the title bar).
2576     */
2577    /*package*/ int viewToContentX(int x) {
2578        return viewToContentDimension(x);
2579    }
2580
2581    /**
2582     * Given a y coordinate in view space, convert it to content space.
2583     * Takes into account the height of the title bar if there is one
2584     * embedded into the WebView.
2585     */
2586    /*package*/ int viewToContentY(int y) {
2587        return viewToContentDimension(y - getTitleHeight());
2588    }
2589
2590    /**
2591     * Given a x coordinate in view space, convert it to content space.
2592     * Returns the result as a float.
2593     */
2594    private float viewToContentXf(int x) {
2595        return x * mZoomManager.getInvScale();
2596    }
2597
2598    /**
2599     * Given a y coordinate in view space, convert it to content space.
2600     * Takes into account the height of the title bar if there is one
2601     * embedded into the WebView. Returns the result as a float.
2602     */
2603    private float viewToContentYf(int y) {
2604        return (y - getTitleHeight()) * mZoomManager.getInvScale();
2605    }
2606
2607    /**
2608     * Given a distance in content space, convert it to view space. Note: this
2609     * does not reflect translation, just scaling, so this should not be called
2610     * with coordinates, but should be called for dimensions like width or
2611     * height.
2612     */
2613    /*package*/ int contentToViewDimension(int d) {
2614        return Math.round(d * mZoomManager.getScale());
2615    }
2616
2617    /**
2618     * Given an x coordinate in content space, convert it to view
2619     * space.
2620     */
2621    /*package*/ int contentToViewX(int x) {
2622        return contentToViewDimension(x);
2623    }
2624
2625    /**
2626     * Given a y coordinate in content space, convert it to view
2627     * space.  Takes into account the height of the title bar.
2628     */
2629    /*package*/ int contentToViewY(int y) {
2630        return contentToViewDimension(y) + getTitleHeight();
2631    }
2632
2633    private Rect contentToViewRect(Rect x) {
2634        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
2635                        contentToViewX(x.right), contentToViewY(x.bottom));
2636    }
2637
2638    /*  To invalidate a rectangle in content coordinates, we need to transform
2639        the rect into view coordinates, so we can then call invalidate(...).
2640
2641        Normally, we would just call contentToView[XY](...), which eventually
2642        calls Math.round(coordinate * mActualScale). However, for invalidates,
2643        we need to account for the slop that occurs with antialiasing. To
2644        address that, we are a little more liberal in the size of the rect that
2645        we invalidate.
2646
2647        This liberal calculation calls floor() for the top/left, and ceil() for
2648        the bottom/right coordinates. This catches the possible extra pixels of
2649        antialiasing that we might have missed with just round().
2650     */
2651
2652    // Called by JNI to invalidate the View, given rectangle coordinates in
2653    // content space
2654    private void viewInvalidate(int l, int t, int r, int b) {
2655        final float scale = mZoomManager.getScale();
2656        final int dy = getTitleHeight();
2657        invalidate((int)Math.floor(l * scale),
2658                   (int)Math.floor(t * scale) + dy,
2659                   (int)Math.ceil(r * scale),
2660                   (int)Math.ceil(b * scale) + dy);
2661    }
2662
2663    // Called by JNI to invalidate the View after a delay, given rectangle
2664    // coordinates in content space
2665    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
2666        final float scale = mZoomManager.getScale();
2667        final int dy = getTitleHeight();
2668        postInvalidateDelayed(delay,
2669                              (int)Math.floor(l * scale),
2670                              (int)Math.floor(t * scale) + dy,
2671                              (int)Math.ceil(r * scale),
2672                              (int)Math.ceil(b * scale) + dy);
2673    }
2674
2675    private void invalidateContentRect(Rect r) {
2676        viewInvalidate(r.left, r.top, r.right, r.bottom);
2677    }
2678
2679    // stop the scroll animation, and don't let a subsequent fling add
2680    // to the existing velocity
2681    private void abortAnimation() {
2682        mScroller.abortAnimation();
2683        mLastVelocity = 0;
2684    }
2685
2686    /* call from webcoreview.draw(), so we're still executing in the UI thread
2687    */
2688    private void recordNewContentSize(int w, int h, boolean updateLayout) {
2689
2690        // premature data from webkit, ignore
2691        if ((w | h) == 0) {
2692            return;
2693        }
2694
2695        // don't abort a scroll animation if we didn't change anything
2696        if (mContentWidth != w || mContentHeight != h) {
2697            // record new dimensions
2698            mContentWidth = w;
2699            mContentHeight = h;
2700            // If history Picture is drawn, don't update scroll. They will be
2701            // updated when we get out of that mode.
2702            if (!mDrawHistory) {
2703                // repin our scroll, taking into account the new content size
2704                updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY));
2705                if (!mScroller.isFinished()) {
2706                    // We are in the middle of a scroll.  Repin the final scroll
2707                    // position.
2708                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
2709                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
2710                }
2711            }
2712        }
2713        contentSizeChanged(updateLayout);
2714    }
2715
2716    // Used to avoid sending many visible rect messages.
2717    private Rect mLastVisibleRectSent;
2718    private Rect mLastGlobalRect;
2719
2720    Rect sendOurVisibleRect() {
2721        if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
2722        Rect rect = new Rect();
2723        calcOurContentVisibleRect(rect);
2724        // Rect.equals() checks for null input.
2725        if (!rect.equals(mLastVisibleRectSent)) {
2726            if (!mBlockWebkitViewMessages) {
2727                Point pos = new Point(rect.left, rect.top);
2728                mWebViewCore.removeMessages(EventHub.SET_SCROLL_OFFSET);
2729                mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
2730                        nativeMoveGeneration(), mSendScrollEvent ? 1 : 0, pos);
2731            }
2732            mLastVisibleRectSent = rect;
2733            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
2734        }
2735        Rect globalRect = new Rect();
2736        if (getGlobalVisibleRect(globalRect)
2737                && !globalRect.equals(mLastGlobalRect)) {
2738            if (DebugFlags.WEB_VIEW) {
2739                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2740                        + globalRect.top + ",r=" + globalRect.right + ",b="
2741                        + globalRect.bottom);
2742            }
2743            // TODO: the global offset is only used by windowRect()
2744            // in ChromeClientAndroid ; other clients such as touch
2745            // and mouse events could return view + screen relative points.
2746            if (!mBlockWebkitViewMessages) {
2747                mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2748            }
2749            mLastGlobalRect = globalRect;
2750        }
2751        return rect;
2752    }
2753
2754    // Sets r to be the visible rectangle of our webview in view coordinates
2755    private void calcOurVisibleRect(Rect r) {
2756        Point p = new Point();
2757        getGlobalVisibleRect(r, p);
2758        r.offset(-p.x, -p.y);
2759    }
2760
2761    // Sets r to be our visible rectangle in content coordinates
2762    private void calcOurContentVisibleRect(Rect r) {
2763        calcOurVisibleRect(r);
2764        r.left = viewToContentX(r.left);
2765        // viewToContentY will remove the total height of the title bar.  Add
2766        // the visible height back in to account for the fact that if the title
2767        // bar is partially visible, the part of the visible rect which is
2768        // displaying our content is displaced by that amount.
2769        r.top = viewToContentY(r.top + getVisibleTitleHeight());
2770        r.right = viewToContentX(r.right);
2771        r.bottom = viewToContentY(r.bottom);
2772    }
2773
2774    // Sets r to be our visible rectangle in content coordinates. We use this
2775    // method on the native side to compute the position of the fixed layers.
2776    // Uses floating coordinates (necessary to correctly place elements when
2777    // the scale factor is not 1)
2778    private void calcOurContentVisibleRectF(RectF r) {
2779        Rect ri = new Rect(0,0,0,0);
2780        calcOurVisibleRect(ri);
2781        r.left = viewToContentXf(ri.left);
2782        // viewToContentY will remove the total height of the title bar.  Add
2783        // the visible height back in to account for the fact that if the title
2784        // bar is partially visible, the part of the visible rect which is
2785        // displaying our content is displaced by that amount.
2786        r.top = viewToContentYf(ri.top + getVisibleTitleHeight());
2787        r.right = viewToContentXf(ri.right);
2788        r.bottom = viewToContentYf(ri.bottom);
2789    }
2790
2791    static class ViewSizeData {
2792        int mWidth;
2793        int mHeight;
2794        float mHeightWidthRatio;
2795        int mActualViewHeight;
2796        int mTextWrapWidth;
2797        int mAnchorX;
2798        int mAnchorY;
2799        float mScale;
2800        boolean mIgnoreHeight;
2801    }
2802
2803    /**
2804     * Compute unzoomed width and height, and if they differ from the last
2805     * values we sent, send them to webkit (to be used as new viewport)
2806     *
2807     * @param force ensures that the message is sent to webkit even if the width
2808     * or height has not changed since the last message
2809     *
2810     * @return true if new values were sent
2811     */
2812    boolean sendViewSizeZoom(boolean force) {
2813        if (mBlockWebkitViewMessages) return false;
2814        if (mZoomManager.isPreventingWebkitUpdates()) return false;
2815
2816        int viewWidth = getViewWidth();
2817        int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
2818        // This height could be fixed and be different from actual visible height.
2819        int viewHeight = getViewHeightWithTitle() - getTitleHeight();
2820        int newHeight = Math.round(viewHeight * mZoomManager.getInvScale());
2821        // Make the ratio more accurate than (newHeight / newWidth), since the
2822        // latter both are calculated and rounded.
2823        float heightWidthRatio = (float) viewHeight / viewWidth;
2824        /*
2825         * Because the native side may have already done a layout before the
2826         * View system was able to measure us, we have to send a height of 0 to
2827         * remove excess whitespace when we grow our width. This will trigger a
2828         * layout and a change in content size. This content size change will
2829         * mean that contentSizeChanged will either call this method directly or
2830         * indirectly from onSizeChanged.
2831         */
2832        if (newWidth > mLastWidthSent && mWrapContent) {
2833            newHeight = 0;
2834            heightWidthRatio = 0;
2835        }
2836        // Actual visible content height.
2837        int actualViewHeight = Math.round(getViewHeight() * mZoomManager.getInvScale());
2838        // Avoid sending another message if the dimensions have not changed.
2839        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force ||
2840                actualViewHeight != mLastActualHeightSent) {
2841            ViewSizeData data = new ViewSizeData();
2842            data.mWidth = newWidth;
2843            data.mHeight = newHeight;
2844            data.mHeightWidthRatio = heightWidthRatio;
2845            data.mActualViewHeight = actualViewHeight;
2846            data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
2847            data.mScale = mZoomManager.getScale();
2848            data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
2849                    && !mHeightCanMeasure;
2850            data.mAnchorX = mZoomManager.getDocumentAnchorX();
2851            data.mAnchorY = mZoomManager.getDocumentAnchorY();
2852            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
2853            mLastWidthSent = newWidth;
2854            mLastHeightSent = newHeight;
2855            mLastActualHeightSent = actualViewHeight;
2856            mZoomManager.clearDocumentAnchor();
2857            return true;
2858        }
2859        return false;
2860    }
2861
2862    private int computeRealHorizontalScrollRange() {
2863        if (mDrawHistory) {
2864            return mHistoryWidth;
2865        } else {
2866            // to avoid rounding error caused unnecessary scrollbar, use floor
2867            return (int) Math.floor(mContentWidth * mZoomManager.getScale());
2868        }
2869    }
2870
2871    @Override
2872    protected int computeHorizontalScrollRange() {
2873        int range = computeRealHorizontalScrollRange();
2874
2875        // Adjust reported range if overscrolled to compress the scroll bars
2876        final int scrollX = mScrollX;
2877        final int overscrollRight = computeMaxScrollX();
2878        if (scrollX < 0) {
2879            range -= scrollX;
2880        } else if (scrollX > overscrollRight) {
2881            range += scrollX - overscrollRight;
2882        }
2883
2884        return range;
2885    }
2886
2887    @Override
2888    protected int computeHorizontalScrollOffset() {
2889        return Math.max(mScrollX, 0);
2890    }
2891
2892    private int computeRealVerticalScrollRange() {
2893        if (mDrawHistory) {
2894            return mHistoryHeight;
2895        } else {
2896            // to avoid rounding error caused unnecessary scrollbar, use floor
2897            return (int) Math.floor(mContentHeight * mZoomManager.getScale());
2898        }
2899    }
2900
2901    @Override
2902    protected int computeVerticalScrollRange() {
2903        int range = computeRealVerticalScrollRange();
2904
2905        // Adjust reported range if overscrolled to compress the scroll bars
2906        final int scrollY = mScrollY;
2907        final int overscrollBottom = computeMaxScrollY();
2908        if (scrollY < 0) {
2909            range -= scrollY;
2910        } else if (scrollY > overscrollBottom) {
2911            range += scrollY - overscrollBottom;
2912        }
2913
2914        return range;
2915    }
2916
2917    @Override
2918    protected int computeVerticalScrollOffset() {
2919        return Math.max(mScrollY - getTitleHeight(), 0);
2920    }
2921
2922    @Override
2923    protected int computeVerticalScrollExtent() {
2924        return getViewHeight();
2925    }
2926
2927    /** @hide */
2928    @Override
2929    protected void onDrawVerticalScrollBar(Canvas canvas,
2930                                           Drawable scrollBar,
2931                                           int l, int t, int r, int b) {
2932        if (mScrollY < 0) {
2933            t -= mScrollY;
2934        }
2935        scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b);
2936        scrollBar.draw(canvas);
2937    }
2938
2939    @Override
2940    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX,
2941            boolean clampedY) {
2942        // Special-case layer scrolling so that we do not trigger normal scroll
2943        // updating.
2944        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
2945            nativeScrollLayer(mScrollingLayer, scrollX, scrollY);
2946            mScrollingLayerRect.left = scrollX;
2947            mScrollingLayerRect.top = scrollY;
2948            invalidate();
2949            return;
2950        }
2951        mInOverScrollMode = false;
2952        int maxX = computeMaxScrollX();
2953        int maxY = computeMaxScrollY();
2954        if (maxX == 0) {
2955            // do not over scroll x if the page just fits the screen
2956            scrollX = pinLocX(scrollX);
2957        } else if (scrollX < 0 || scrollX > maxX) {
2958            mInOverScrollMode = true;
2959        }
2960        if (scrollY < 0 || scrollY > maxY) {
2961            mInOverScrollMode = true;
2962        }
2963
2964        int oldX = mScrollX;
2965        int oldY = mScrollY;
2966
2967        super.scrollTo(scrollX, scrollY);
2968
2969        if (mOverScrollGlow != null) {
2970            mOverScrollGlow.pullGlow(mScrollX, mScrollY, oldX, oldY, maxX, maxY);
2971        }
2972    }
2973
2974    /**
2975     * Get the url for the current page. This is not always the same as the url
2976     * passed to WebViewClient.onPageStarted because although the load for
2977     * that url has begun, the current page may not have changed.
2978     * @return The url for the current page.
2979     */
2980    public String getUrl() {
2981        checkThread();
2982        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2983        return h != null ? h.getUrl() : null;
2984    }
2985
2986    /**
2987     * Get the original url for the current page. This is not always the same
2988     * as the url passed to WebViewClient.onPageStarted because although the
2989     * load for that url has begun, the current page may not have changed.
2990     * Also, there may have been redirects resulting in a different url to that
2991     * originally requested.
2992     * @return The url that was originally requested for the current page.
2993     */
2994    public String getOriginalUrl() {
2995        checkThread();
2996        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2997        return h != null ? h.getOriginalUrl() : null;
2998    }
2999
3000    /**
3001     * Get the title for the current page. This is the title of the current page
3002     * until WebViewClient.onReceivedTitle is called.
3003     * @return The title for the current page.
3004     */
3005    public String getTitle() {
3006        checkThread();
3007        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3008        return h != null ? h.getTitle() : null;
3009    }
3010
3011    /**
3012     * Get the favicon for the current page. This is the favicon of the current
3013     * page until WebViewClient.onReceivedIcon is called.
3014     * @return The favicon for the current page.
3015     */
3016    public Bitmap getFavicon() {
3017        checkThread();
3018        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3019        return h != null ? h.getFavicon() : null;
3020    }
3021
3022    /**
3023     * Get the touch icon url for the apple-touch-icon <link> element, or
3024     * a URL on this site's server pointing to the standard location of a
3025     * touch icon.
3026     * @hide
3027     */
3028    public String getTouchIconUrl() {
3029        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3030        return h != null ? h.getTouchIconUrl() : null;
3031    }
3032
3033    /**
3034     * Get the progress for the current page.
3035     * @return The progress for the current page between 0 and 100.
3036     */
3037    public int getProgress() {
3038        checkThread();
3039        return mCallbackProxy.getProgress();
3040    }
3041
3042    /**
3043     * @return the height of the HTML content.
3044     */
3045    public int getContentHeight() {
3046        checkThread();
3047        return mContentHeight;
3048    }
3049
3050    /**
3051     * @return the width of the HTML content.
3052     * @hide
3053     */
3054    public int getContentWidth() {
3055        return mContentWidth;
3056    }
3057
3058    /**
3059     * Pause all layout, parsing, and JavaScript timers for all webviews. This
3060     * is a global requests, not restricted to just this webview. This can be
3061     * useful if the application has been paused.
3062     */
3063    public void pauseTimers() {
3064        checkThread();
3065        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
3066    }
3067
3068    /**
3069     * Resume all layout, parsing, and JavaScript timers for all webviews.
3070     * This will resume dispatching all timers.
3071     */
3072    public void resumeTimers() {
3073        checkThread();
3074        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
3075    }
3076
3077    /**
3078     * Call this to pause any extra processing associated with this WebView and
3079     * its associated DOM, plugins, JavaScript etc. For example, if the WebView
3080     * is taken offscreen, this could be called to reduce unnecessary CPU or
3081     * network traffic. When the WebView is again "active", call onResume().
3082     *
3083     * Note that this differs from pauseTimers(), which affects all WebViews.
3084     */
3085    public void onPause() {
3086        checkThread();
3087        if (!mIsPaused) {
3088            mIsPaused = true;
3089            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
3090            // We want to pause the current playing video when switching out
3091            // from the current WebView/tab.
3092            if (mHTML5VideoViewProxy != null) {
3093                mHTML5VideoViewProxy.pauseAndDispatch();
3094            }
3095        }
3096    }
3097
3098    /**
3099     * Call this to resume a WebView after a previous call to onPause().
3100     */
3101    public void onResume() {
3102        checkThread();
3103        if (mIsPaused) {
3104            mIsPaused = false;
3105            mWebViewCore.sendMessage(EventHub.ON_RESUME);
3106        }
3107    }
3108
3109    /**
3110     * Returns true if the view is paused, meaning onPause() was called. Calling
3111     * onResume() sets the paused state back to false.
3112     * @hide
3113     */
3114    public boolean isPaused() {
3115        return mIsPaused;
3116    }
3117
3118    /**
3119     * Call this to inform the view that memory is low so that it can
3120     * free any available memory.
3121     */
3122    public void freeMemory() {
3123        checkThread();
3124        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
3125    }
3126
3127    /**
3128     * Clear the resource cache. Note that the cache is per-application, so
3129     * this will clear the cache for all WebViews used.
3130     *
3131     * @param includeDiskFiles If false, only the RAM cache is cleared.
3132     */
3133    public void clearCache(boolean includeDiskFiles) {
3134        checkThread();
3135        // Note: this really needs to be a static method as it clears cache for all
3136        // WebView. But we need mWebViewCore to send message to WebCore thread, so
3137        // we can't make this static.
3138        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
3139                includeDiskFiles ? 1 : 0, 0);
3140    }
3141
3142    /**
3143     * Make sure that clearing the form data removes the adapter from the
3144     * currently focused textfield if there is one.
3145     */
3146    public void clearFormData() {
3147        checkThread();
3148        if (inEditingMode()) {
3149            AutoCompleteAdapter adapter = null;
3150            mWebTextView.setAdapterCustom(adapter);
3151        }
3152    }
3153
3154    /**
3155     * Tell the WebView to clear its internal back/forward list.
3156     */
3157    public void clearHistory() {
3158        checkThread();
3159        mCallbackProxy.getBackForwardList().setClearPending();
3160        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
3161    }
3162
3163    /**
3164     * Clear the SSL preferences table stored in response to proceeding with SSL
3165     * certificate errors.
3166     */
3167    public void clearSslPreferences() {
3168        checkThread();
3169        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
3170    }
3171
3172    /**
3173     * Return the WebBackForwardList for this WebView. This contains the
3174     * back/forward list for use in querying each item in the history stack.
3175     * This is a copy of the private WebBackForwardList so it contains only a
3176     * snapshot of the current state. Multiple calls to this method may return
3177     * different objects. The object returned from this method will not be
3178     * updated to reflect any new state.
3179     */
3180    public WebBackForwardList copyBackForwardList() {
3181        checkThread();
3182        return mCallbackProxy.getBackForwardList().clone();
3183    }
3184
3185    /*
3186     * Highlight and scroll to the next occurance of String in findAll.
3187     * Wraps the page infinitely, and scrolls.  Must be called after
3188     * calling findAll.
3189     *
3190     * @param forward Direction to search.
3191     */
3192    public void findNext(boolean forward) {
3193        checkThread();
3194        if (0 == mNativeClass) return; // client isn't initialized
3195        nativeFindNext(forward);
3196    }
3197
3198    /*
3199     * Find all instances of find on the page and highlight them.
3200     * @param find  String to find.
3201     * @return int  The number of occurances of the String "find"
3202     *              that were found.
3203     */
3204    public int findAll(String find) {
3205        checkThread();
3206        if (0 == mNativeClass) return 0; // client isn't initialized
3207        int result = find != null ? nativeFindAll(find.toLowerCase(),
3208                find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0;
3209        invalidate();
3210        mLastFind = find;
3211        return result;
3212    }
3213
3214    /**
3215     * Start an ActionMode for finding text in this WebView.  Only works if this
3216     *              WebView is attached to the view system.
3217     * @param text If non-null, will be the initial text to search for.
3218     *             Otherwise, the last String searched for in this WebView will
3219     *             be used to start.
3220     * @param showIme If true, show the IME, assuming the user will begin typing.
3221     *             If false and text is non-null, perform a find all.
3222     * @return boolean True if the find dialog is shown, false otherwise.
3223     */
3224    public boolean showFindDialog(String text, boolean showIme) {
3225        checkThread();
3226        FindActionModeCallback callback = new FindActionModeCallback(mContext);
3227        if (getParent() == null || startActionMode(callback) == null) {
3228            // Could not start the action mode, so end Find on page
3229            return false;
3230        }
3231        mFindCallback = callback;
3232        setFindIsUp(true);
3233        mFindCallback.setWebView(this);
3234        if (showIme) {
3235            mFindCallback.showSoftInput();
3236        } else if (text != null) {
3237            mFindCallback.setText(text);
3238            mFindCallback.findAll();
3239            return true;
3240        }
3241        if (text == null) {
3242            text = mLastFind;
3243        }
3244        if (text != null) {
3245            mFindCallback.setText(text);
3246        }
3247        return true;
3248    }
3249
3250    /**
3251     * Keep track of the find callback so that we can remove its titlebar if
3252     * necessary.
3253     */
3254    private FindActionModeCallback mFindCallback;
3255
3256    /**
3257     * Toggle whether the find dialog is showing, for both native and Java.
3258     */
3259    private void setFindIsUp(boolean isUp) {
3260        mFindIsUp = isUp;
3261        if (0 == mNativeClass) return; // client isn't initialized
3262        nativeSetFindIsUp(isUp);
3263    }
3264
3265    /**
3266     * Return the index of the currently highlighted match.
3267     */
3268    int findIndex() {
3269        if (0 == mNativeClass) return -1;
3270        return nativeFindIndex();
3271    }
3272
3273    // Used to know whether the find dialog is open.  Affects whether
3274    // or not we draw the highlights for matches.
3275    private boolean mFindIsUp;
3276
3277    // Keep track of the last string sent, so we can search again when find is
3278    // reopened.
3279    private String mLastFind;
3280
3281    /**
3282     * Return the first substring consisting of the address of a physical
3283     * location. Currently, only addresses in the United States are detected,
3284     * and consist of:
3285     * - a house number
3286     * - a street name
3287     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3288     * - a city name
3289     * - a state or territory, either spelled out or two-letter abbr.
3290     * - an optional 5 digit or 9 digit zip code.
3291     *
3292     * All names must be correctly capitalized, and the zip code, if present,
3293     * must be valid for the state. The street type must be a standard USPS
3294     * spelling or abbreviation. The state or territory must also be spelled
3295     * or abbreviated using USPS standards. The house number may not exceed
3296     * five digits.
3297     * @param addr The string to search for addresses.
3298     *
3299     * @return the address, or if no address is found, return null.
3300     */
3301    public static String findAddress(String addr) {
3302        checkThread();
3303        return findAddress(addr, false);
3304    }
3305
3306    /**
3307     * @hide
3308     * Return the first substring consisting of the address of a physical
3309     * location. Currently, only addresses in the United States are detected,
3310     * and consist of:
3311     * - a house number
3312     * - a street name
3313     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3314     * - a city name
3315     * - a state or territory, either spelled out or two-letter abbr.
3316     * - an optional 5 digit or 9 digit zip code.
3317     *
3318     * Names are optionally capitalized, and the zip code, if present,
3319     * must be valid for the state. The street type must be a standard USPS
3320     * spelling or abbreviation. The state or territory must also be spelled
3321     * or abbreviated using USPS standards. The house number may not exceed
3322     * five digits.
3323     * @param addr The string to search for addresses.
3324     * @param caseInsensitive addr Set to true to make search ignore case.
3325     *
3326     * @return the address, or if no address is found, return null.
3327     */
3328    public static String findAddress(String addr, boolean caseInsensitive) {
3329        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
3330    }
3331
3332    /*
3333     * Clear the highlighting surrounding text matches created by findAll.
3334     */
3335    public void clearMatches() {
3336        checkThread();
3337        if (mNativeClass == 0)
3338            return;
3339        nativeSetFindIsEmpty();
3340        invalidate();
3341    }
3342
3343    /**
3344     * Called when the find ActionMode ends.
3345     */
3346    void notifyFindDialogDismissed() {
3347        mFindCallback = null;
3348        if (mWebViewCore == null) {
3349            return;
3350        }
3351        clearMatches();
3352        setFindIsUp(false);
3353        // Now that the dialog has been removed, ensure that we scroll to a
3354        // location that is not beyond the end of the page.
3355        pinScrollTo(mScrollX, mScrollY, false, 0);
3356        invalidate();
3357    }
3358
3359    /**
3360     * Query the document to see if it contains any image references. The
3361     * message object will be dispatched with arg1 being set to 1 if images
3362     * were found and 0 if the document does not reference any images.
3363     * @param response The message that will be dispatched with the result.
3364     */
3365    public void documentHasImages(Message response) {
3366        checkThread();
3367        if (response == null) {
3368            return;
3369        }
3370        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
3371    }
3372
3373    /**
3374     * Request the scroller to abort any ongoing animation
3375     *
3376     * @hide
3377     */
3378    public void stopScroll() {
3379        mScroller.forceFinished(true);
3380        mLastVelocity = 0;
3381    }
3382
3383    @Override
3384    public void computeScroll() {
3385        if (mScroller.computeScrollOffset()) {
3386            int oldX = mScrollX;
3387            int oldY = mScrollY;
3388            int x = mScroller.getCurrX();
3389            int y = mScroller.getCurrY();
3390            invalidate();  // So we draw again
3391
3392            if (!mScroller.isFinished()) {
3393                int rangeX = computeMaxScrollX();
3394                int rangeY = computeMaxScrollY();
3395                int overflingDistance = mOverflingDistance;
3396
3397                // Use the layer's scroll data if needed.
3398                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3399                    oldX = mScrollingLayerRect.left;
3400                    oldY = mScrollingLayerRect.top;
3401                    rangeX = mScrollingLayerRect.right;
3402                    rangeY = mScrollingLayerRect.bottom;
3403                    // No overscrolling for layers.
3404                    overflingDistance = 0;
3405                }
3406
3407                overScrollBy(x - oldX, y - oldY, oldX, oldY,
3408                        rangeX, rangeY,
3409                        overflingDistance, overflingDistance, false);
3410
3411                if (mOverScrollGlow != null) {
3412                    mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY);
3413                }
3414            } else {
3415                if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
3416                    mScrollX = x;
3417                    mScrollY = y;
3418                } else {
3419                    // Update the layer position instead of WebView.
3420                    nativeScrollLayer(mScrollingLayer, x, y);
3421                    mScrollingLayerRect.left = x;
3422                    mScrollingLayerRect.top = y;
3423                }
3424                abortAnimation();
3425                mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
3426                if (!mBlockWebkitViewMessages) {
3427                    WebViewCore.resumePriority();
3428                    if (!mSelectingText) {
3429                        WebViewCore.resumeUpdatePicture(mWebViewCore);
3430                    }
3431                }
3432                if (oldX != mScrollX || oldY != mScrollY) {
3433                    sendOurVisibleRect();
3434                }
3435            }
3436        } else {
3437            super.computeScroll();
3438        }
3439    }
3440
3441    private static int computeDuration(int dx, int dy) {
3442        int distance = Math.max(Math.abs(dx), Math.abs(dy));
3443        int duration = distance * 1000 / STD_SPEED;
3444        return Math.min(duration, MAX_DURATION);
3445    }
3446
3447    // helper to pin the scrollBy parameters (already in view coordinates)
3448    // returns true if the scroll was changed
3449    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
3450        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
3451    }
3452    // helper to pin the scrollTo parameters (already in view coordinates)
3453    // returns true if the scroll was changed
3454    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
3455        x = pinLocX(x);
3456        y = pinLocY(y);
3457        int dx = x - mScrollX;
3458        int dy = y - mScrollY;
3459
3460        if ((dx | dy) == 0) {
3461            return false;
3462        }
3463        abortAnimation();
3464        if (animate) {
3465            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
3466            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
3467                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
3468            awakenScrollBars(mScroller.getDuration());
3469            invalidate();
3470        } else {
3471            scrollTo(x, y);
3472        }
3473        return true;
3474    }
3475
3476    // Scale from content to view coordinates, and pin.
3477    // Also called by jni webview.cpp
3478    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
3479        if (mDrawHistory) {
3480            // disallow WebView to change the scroll position as History Picture
3481            // is used in the view system.
3482            // TODO: as we switchOutDrawHistory when trackball or navigation
3483            // keys are hit, this should be safe. Right?
3484            return false;
3485        }
3486        cx = contentToViewDimension(cx);
3487        cy = contentToViewDimension(cy);
3488        if (mHeightCanMeasure) {
3489            // move our visible rect according to scroll request
3490            if (cy != 0) {
3491                Rect tempRect = new Rect();
3492                calcOurVisibleRect(tempRect);
3493                tempRect.offset(cx, cy);
3494                requestRectangleOnScreen(tempRect);
3495            }
3496            // FIXME: We scroll horizontally no matter what because currently
3497            // ScrollView and ListView will not scroll horizontally.
3498            // FIXME: Why do we only scroll horizontally if there is no
3499            // vertical scroll?
3500//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
3501            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
3502        } else {
3503            return pinScrollBy(cx, cy, animate, 0);
3504        }
3505    }
3506
3507    /**
3508     * Called by CallbackProxy when the page starts loading.
3509     * @param url The URL of the page which has started loading.
3510     */
3511    /* package */ void onPageStarted(String url) {
3512        // every time we start a new page, we want to reset the
3513        // WebView certificate:  if the new site is secure, we
3514        // will reload it and get a new certificate set;
3515        // if the new site is not secure, the certificate must be
3516        // null, and that will be the case
3517        setCertificate(null);
3518
3519        // reset the flag since we set to true in if need after
3520        // loading is see onPageFinished(Url)
3521        mAccessibilityScriptInjected = false;
3522    }
3523
3524    /**
3525     * Called by CallbackProxy when the page finishes loading.
3526     * @param url The URL of the page which has finished loading.
3527     */
3528    /* package */ void onPageFinished(String url) {
3529        if (mPageThatNeedsToSlideTitleBarOffScreen != null) {
3530            // If the user is now on a different page, or has scrolled the page
3531            // past the point where the title bar is offscreen, ignore the
3532            // scroll request.
3533            if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url)
3534                    && mScrollX == 0 && mScrollY == 0) {
3535                pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true,
3536                        SLIDE_TITLE_DURATION);
3537            }
3538            mPageThatNeedsToSlideTitleBarOffScreen = null;
3539        }
3540        mZoomManager.onPageFinished(url);
3541        injectAccessibilityForUrl(url);
3542    }
3543
3544    /**
3545     * This method injects accessibility in the loaded document if accessibility
3546     * is enabled. If JavaScript is enabled we try to inject a URL specific script.
3547     * If no URL specific script is found or JavaScript is disabled we fallback to
3548     * the default {@link AccessibilityInjector} implementation.
3549     * </p>
3550     * If the URL has the "axs" paramter set to 1 it has already done the
3551     * script injection so we do nothing. If the parameter is set to 0
3552     * the URL opts out accessibility script injection so we fall back to
3553     * the default {@link AccessibilityInjector}.
3554     * </p>
3555     * Note: If the user has not opted-in the accessibility script injection no scripts
3556     * are injected rather the default {@link AccessibilityInjector} implementation
3557     * is used.
3558     *
3559     * @param url The URL loaded by this {@link WebView}.
3560     */
3561    private void injectAccessibilityForUrl(String url) {
3562        if (mWebViewCore == null) {
3563            return;
3564        }
3565        AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
3566
3567        if (!accessibilityManager.isEnabled()) {
3568            // it is possible that accessibility was turned off between reloads
3569            ensureAccessibilityScriptInjectorInstance(false);
3570            return;
3571        }
3572
3573        if (!getSettings().getJavaScriptEnabled()) {
3574            // no JS so we fallback to the basic buil-in support
3575            ensureAccessibilityScriptInjectorInstance(true);
3576            return;
3577        }
3578
3579        // check the URL "axs" parameter to choose appropriate action
3580        int axsParameterValue = getAxsUrlParameterValue(url);
3581        if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) {
3582            boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext
3583                    .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1);
3584            if (onDeviceScriptInjectionEnabled) {
3585                ensureAccessibilityScriptInjectorInstance(false);
3586                // neither script injected nor script injection opted out => we inject
3587                loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3588                // TODO: Set this flag after successfull script injection. Maybe upon injection
3589                // the chooser should update the meta tag and we check it to declare success
3590                mAccessibilityScriptInjected = true;
3591            } else {
3592                // injection disabled so we fallback to the basic built-in support
3593                ensureAccessibilityScriptInjectorInstance(true);
3594            }
3595        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) {
3596            // injection opted out so we fallback to the basic buil-in support
3597            ensureAccessibilityScriptInjectorInstance(true);
3598        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) {
3599            ensureAccessibilityScriptInjectorInstance(false);
3600            // the URL provides accessibility but we still need to add our generic script
3601            loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3602        } else {
3603            Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue);
3604        }
3605    }
3606
3607    /**
3608     * Ensures the instance of the {@link AccessibilityInjector} to be present ot not.
3609     *
3610     * @param present True to ensure an insance, false to ensure no instance.
3611     */
3612    private void ensureAccessibilityScriptInjectorInstance(boolean present) {
3613        if (present) {
3614            if (mAccessibilityInjector == null) {
3615                mAccessibilityInjector = new AccessibilityInjector(this);
3616            }
3617        } else {
3618            mAccessibilityInjector = null;
3619        }
3620    }
3621
3622    /**
3623     * Gets the "axs" URL parameter value.
3624     *
3625     * @param url A url to fetch the paramter from.
3626     * @return The parameter value if such, -1 otherwise.
3627     */
3628    private int getAxsUrlParameterValue(String url) {
3629        if (mMatchAxsUrlParameterPattern == null) {
3630            mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER);
3631        }
3632        Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url);
3633        if (matcher.find()) {
3634            String keyValuePair = url.substring(matcher.start(), matcher.end());
3635            return Integer.parseInt(keyValuePair.split("=")[1]);
3636        }
3637        return -1;
3638    }
3639
3640    /**
3641     * The URL of a page that sent a message to scroll the title bar off screen.
3642     *
3643     * Many mobile sites tell the page to scroll to (0,1) in order to scroll the
3644     * title bar off the screen.  Sometimes, the scroll position is set before
3645     * the page finishes loading.  Rather than scrolling while the page is still
3646     * loading, keep track of the URL and new scroll position so we can perform
3647     * the scroll once the page finishes loading.
3648     */
3649    private String mPageThatNeedsToSlideTitleBarOffScreen;
3650
3651    /**
3652     * The destination Y scroll position to be used when the page finishes
3653     * loading.  See mPageThatNeedsToSlideTitleBarOffScreen.
3654     */
3655    private int mYDistanceToSlideTitleOffScreen;
3656
3657    // scale from content to view coordinates, and pin
3658    // return true if pin caused the final x/y different than the request cx/cy,
3659    // and a future scroll may reach the request cx/cy after our size has
3660    // changed
3661    // return false if the view scroll to the exact position as it is requested,
3662    // where negative numbers are taken to mean 0
3663    private boolean setContentScrollTo(int cx, int cy) {
3664        if (mDrawHistory) {
3665            // disallow WebView to change the scroll position as History Picture
3666            // is used in the view system.
3667            // One known case where this is called is that WebCore tries to
3668            // restore the scroll position. As history Picture already uses the
3669            // saved scroll position, it is ok to skip this.
3670            return false;
3671        }
3672        int vx;
3673        int vy;
3674        if ((cx | cy) == 0) {
3675            // If the page is being scrolled to (0,0), do not add in the title
3676            // bar's height, and simply scroll to (0,0). (The only other work
3677            // in contentToView_ is to multiply, so this would not change 0.)
3678            vx = 0;
3679            vy = 0;
3680        } else {
3681            vx = contentToViewX(cx);
3682            vy = contentToViewY(cy);
3683        }
3684//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
3685//                      vx + " " + vy + "]");
3686        // Some mobile sites attempt to scroll the title bar off the page by
3687        // scrolling to (0,1).  If we are at the top left corner of the
3688        // page, assume this is an attempt to scroll off the title bar, and
3689        // animate the title bar off screen slowly enough that the user can see
3690        // it.
3691        if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0
3692                && mTitleBar != null) {
3693            // FIXME: 100 should be defined somewhere as our max progress.
3694            if (getProgress() < 100) {
3695                // Wait to scroll the title bar off screen until the page has
3696                // finished loading.  Keep track of the URL and the destination
3697                // Y position
3698                mPageThatNeedsToSlideTitleBarOffScreen = getUrl();
3699                mYDistanceToSlideTitleOffScreen = vy;
3700            } else {
3701                pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
3702            }
3703            // Since we are animating, we have not yet reached the desired
3704            // scroll position.  Do not return true to request another attempt
3705            return false;
3706        }
3707        pinScrollTo(vx, vy, false, 0);
3708        // If the request was to scroll to a negative coordinate, treat it as if
3709        // it was a request to scroll to 0
3710        if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
3711            return true;
3712        } else {
3713            return false;
3714        }
3715    }
3716
3717    // scale from content to view coordinates, and pin
3718    private void spawnContentScrollTo(int cx, int cy) {
3719        if (mDrawHistory) {
3720            // disallow WebView to change the scroll position as History Picture
3721            // is used in the view system.
3722            return;
3723        }
3724        int vx = contentToViewX(cx);
3725        int vy = contentToViewY(cy);
3726        pinScrollTo(vx, vy, true, 0);
3727    }
3728
3729    /**
3730     * These are from webkit, and are in content coordinate system (unzoomed)
3731     */
3732    private void contentSizeChanged(boolean updateLayout) {
3733        // suppress 0,0 since we usually see real dimensions soon after
3734        // this avoids drawing the prev content in a funny place. If we find a
3735        // way to consolidate these notifications, this check may become
3736        // obsolete
3737        if ((mContentWidth | mContentHeight) == 0) {
3738            return;
3739        }
3740
3741        if (mHeightCanMeasure) {
3742            if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
3743                    || updateLayout) {
3744                requestLayout();
3745            }
3746        } else if (mWidthCanMeasure) {
3747            if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
3748                    || updateLayout) {
3749                requestLayout();
3750            }
3751        } else {
3752            // If we don't request a layout, try to send our view size to the
3753            // native side to ensure that WebCore has the correct dimensions.
3754            sendViewSizeZoom(false);
3755        }
3756    }
3757
3758    /**
3759     * Set the WebViewClient that will receive various notifications and
3760     * requests. This will replace the current handler.
3761     * @param client An implementation of WebViewClient.
3762     */
3763    public void setWebViewClient(WebViewClient client) {
3764        checkThread();
3765        mCallbackProxy.setWebViewClient(client);
3766    }
3767
3768    /**
3769     * Gets the WebViewClient
3770     * @return the current WebViewClient instance.
3771     *
3772     *@hide pending API council approval.
3773     */
3774    public WebViewClient getWebViewClient() {
3775        return mCallbackProxy.getWebViewClient();
3776    }
3777
3778    /**
3779     * Register the interface to be used when content can not be handled by
3780     * the rendering engine, and should be downloaded instead. This will replace
3781     * the current handler.
3782     * @param listener An implementation of DownloadListener.
3783     */
3784    public void setDownloadListener(DownloadListener listener) {
3785        checkThread();
3786        mCallbackProxy.setDownloadListener(listener);
3787    }
3788
3789    /**
3790     * Set the chrome handler. This is an implementation of WebChromeClient for
3791     * use in handling JavaScript dialogs, favicons, titles, and the progress.
3792     * This will replace the current handler.
3793     * @param client An implementation of WebChromeClient.
3794     */
3795    public void setWebChromeClient(WebChromeClient client) {
3796        checkThread();
3797        mCallbackProxy.setWebChromeClient(client);
3798    }
3799
3800    /**
3801     * Gets the chrome handler.
3802     * @return the current WebChromeClient instance.
3803     *
3804     * @hide API council approval.
3805     */
3806    public WebChromeClient getWebChromeClient() {
3807        return mCallbackProxy.getWebChromeClient();
3808    }
3809
3810    /**
3811     * Set the back/forward list client. This is an implementation of
3812     * WebBackForwardListClient for handling new items and changes in the
3813     * history index.
3814     * @param client An implementation of WebBackForwardListClient.
3815     * {@hide}
3816     */
3817    public void setWebBackForwardListClient(WebBackForwardListClient client) {
3818        mCallbackProxy.setWebBackForwardListClient(client);
3819    }
3820
3821    /**
3822     * Gets the WebBackForwardListClient.
3823     * {@hide}
3824     */
3825    public WebBackForwardListClient getWebBackForwardListClient() {
3826        return mCallbackProxy.getWebBackForwardListClient();
3827    }
3828
3829    /**
3830     * Set the Picture listener. This is an interface used to receive
3831     * notifications of a new Picture.
3832     * @param listener An implementation of WebView.PictureListener.
3833     * @deprecated This method is now obsolete.
3834     */
3835    @Deprecated
3836    public void setPictureListener(PictureListener listener) {
3837        checkThread();
3838        mPictureListener = listener;
3839    }
3840
3841    /**
3842     * {@hide}
3843     */
3844    /* FIXME: Debug only! Remove for SDK! */
3845    public void externalRepresentation(Message callback) {
3846        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
3847    }
3848
3849    /**
3850     * {@hide}
3851     */
3852    /* FIXME: Debug only! Remove for SDK! */
3853    public void documentAsText(Message callback) {
3854        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
3855    }
3856
3857    /**
3858     * Use this function to bind an object to JavaScript so that the
3859     * methods can be accessed from JavaScript.
3860     * <p><strong>IMPORTANT:</strong>
3861     * <ul>
3862     * <li> Using addJavascriptInterface() allows JavaScript to control your
3863     * application. This can be a very useful feature or a dangerous security
3864     * issue. When the HTML in the WebView is untrustworthy (for example, part
3865     * or all of the HTML is provided by some person or process), then an
3866     * attacker could inject HTML that will execute your code and possibly any
3867     * code of the attacker's choosing.<br>
3868     * Do not use addJavascriptInterface() unless all of the HTML in this
3869     * WebView was written by you.</li>
3870     * <li> The Java object that is bound runs in another thread and not in
3871     * the thread that it was constructed in.</li>
3872     * </ul></p>
3873     * @param obj The class instance to bind to JavaScript, null instances are
3874     *            ignored.
3875     * @param interfaceName The name to used to expose the instance in
3876     *                      JavaScript.
3877     */
3878    public void addJavascriptInterface(Object obj, String interfaceName) {
3879        checkThread();
3880        if (obj == null) {
3881            return;
3882        }
3883        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3884        arg.mObject = obj;
3885        arg.mInterfaceName = interfaceName;
3886        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
3887    }
3888
3889    /**
3890     * Removes a previously added JavaScript interface with the given name.
3891     * @param interfaceName The name of the interface to remove.
3892     */
3893    public void removeJavascriptInterface(String interfaceName) {
3894        checkThread();
3895        if (mWebViewCore != null) {
3896            WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3897            arg.mInterfaceName = interfaceName;
3898            mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg);
3899        }
3900    }
3901
3902    /**
3903     * Return the WebSettings object used to control the settings for this
3904     * WebView.
3905     * @return A WebSettings object that can be used to control this WebView's
3906     *         settings.
3907     */
3908    public WebSettings getSettings() {
3909        checkThread();
3910        return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
3911    }
3912
3913   /**
3914    * Return the list of currently loaded plugins.
3915    * @return The list of currently loaded plugins.
3916    *
3917    * @hide
3918    * @deprecated This was used for Gears, which has been deprecated.
3919    */
3920    @Deprecated
3921    public static synchronized PluginList getPluginList() {
3922        checkThread();
3923        return new PluginList();
3924    }
3925
3926   /**
3927    * @hide
3928    * @deprecated This was used for Gears, which has been deprecated.
3929    */
3930    @Deprecated
3931    public void refreshPlugins(boolean reloadOpenPages) {
3932        checkThread();
3933    }
3934
3935    //-------------------------------------------------------------------------
3936    // Override View methods
3937    //-------------------------------------------------------------------------
3938
3939    @Override
3940    protected void finalize() throws Throwable {
3941        try {
3942            destroyImpl();
3943        } finally {
3944            super.finalize();
3945        }
3946    }
3947
3948    @Override
3949    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3950        if (child == mTitleBar) {
3951            // When drawing the title bar, move it horizontally to always show
3952            // at the top of the WebView.
3953            mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
3954            int newTop = 0;
3955            if (mTitleGravity == Gravity.NO_GRAVITY) {
3956                newTop = Math.min(0, mScrollY);
3957            } else if (mTitleGravity == Gravity.TOP) {
3958                newTop = mScrollY;
3959            }
3960            mTitleBar.setBottom(newTop + mTitleBar.getHeight());
3961            mTitleBar.setTop(newTop);
3962        }
3963        return super.drawChild(canvas, child, drawingTime);
3964    }
3965
3966    private void drawContent(Canvas canvas) {
3967        // Update the buttons in the picture, so when we draw the picture
3968        // to the screen, they are in the correct state.
3969        // Tell the native side if user is a) touching the screen,
3970        // b) pressing the trackball down, or c) pressing the enter key
3971        // If the cursor is on a button, we need to draw it in the pressed
3972        // state.
3973        // If mNativeClass is 0, we should not reach here, so we do not
3974        // need to check it again.
3975        nativeRecordButtons(hasFocus() && hasWindowFocus(),
3976                            mTouchMode == TOUCH_SHORTPRESS_START_MODE
3977                            || mTrackballDown || mGotCenterDown, false);
3978        drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
3979    }
3980
3981    /**
3982     * Draw the background when beyond bounds
3983     * @param canvas Canvas to draw into
3984     */
3985    private void drawOverScrollBackground(Canvas canvas) {
3986        if (mOverScrollBackground == null) {
3987            mOverScrollBackground = new Paint();
3988            Bitmap bm = BitmapFactory.decodeResource(
3989                    mContext.getResources(),
3990                    com.android.internal.R.drawable.status_bar_background);
3991            mOverScrollBackground.setShader(new BitmapShader(bm,
3992                    Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
3993            mOverScrollBorder = new Paint();
3994            mOverScrollBorder.setStyle(Paint.Style.STROKE);
3995            mOverScrollBorder.setStrokeWidth(0);
3996            mOverScrollBorder.setColor(0xffbbbbbb);
3997        }
3998
3999        int top = 0;
4000        int right = computeRealHorizontalScrollRange();
4001        int bottom = top + computeRealVerticalScrollRange();
4002        // first draw the background and anchor to the top of the view
4003        canvas.save();
4004        canvas.translate(mScrollX, mScrollY);
4005        canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom
4006                - mScrollY, Region.Op.DIFFERENCE);
4007        canvas.drawPaint(mOverScrollBackground);
4008        canvas.restore();
4009        // then draw the border
4010        canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder);
4011        // next clip the region for the content
4012        canvas.clipRect(0, top, right, bottom);
4013    }
4014
4015    @Override
4016    protected void onDraw(Canvas canvas) {
4017        // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
4018        if (mNativeClass == 0) {
4019            return;
4020        }
4021
4022        // if both mContentWidth and mContentHeight are 0, it means there is no
4023        // valid Picture passed to WebView yet. This can happen when WebView
4024        // just starts. Draw the background and return.
4025        if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
4026            canvas.drawColor(mBackgroundColor);
4027            return;
4028        }
4029
4030        if (canvas.isHardwareAccelerated()) {
4031            mZoomManager.setHardwareAccelerated();
4032        }
4033
4034        int saveCount = canvas.save();
4035        if (mInOverScrollMode && !getSettings()
4036                .getUseWebViewBackgroundForOverscrollBackground()) {
4037            drawOverScrollBackground(canvas);
4038        }
4039        if (mTitleBar != null) {
4040            canvas.translate(0, getTitleHeight());
4041        }
4042        drawContent(canvas);
4043        canvas.restoreToCount(saveCount);
4044
4045        if (AUTO_REDRAW_HACK && mAutoRedraw) {
4046            invalidate();
4047        }
4048        if (inEditingMode()) {
4049            mWebTextView.onDrawSubstitute();
4050        }
4051        mWebViewCore.signalRepaintDone();
4052
4053        if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
4054            invalidate();
4055        }
4056
4057        // paint the highlight in the end
4058        if (!mTouchHighlightRegion.isEmpty()) {
4059            if (mTouchHightlightPaint == null) {
4060                mTouchHightlightPaint = new Paint();
4061                mTouchHightlightPaint.setColor(mHightlightColor);
4062                mTouchHightlightPaint.setAntiAlias(true);
4063                mTouchHightlightPaint.setPathEffect(new CornerPathEffect(
4064                        TOUCH_HIGHLIGHT_ARC));
4065            }
4066            canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(),
4067                    mTouchHightlightPaint);
4068        }
4069        if (DEBUG_TOUCH_HIGHLIGHT) {
4070            if (getSettings().getNavDump()) {
4071                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
4072                    if (mTouchCrossHairColor == null) {
4073                        mTouchCrossHairColor = new Paint();
4074                        mTouchCrossHairColor.setColor(Color.RED);
4075                    }
4076                    canvas.drawLine(mTouchHighlightX - mNavSlop,
4077                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4078                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
4079                                    + 1, mTouchCrossHairColor);
4080                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
4081                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4082                                    - mNavSlop,
4083                            mTouchHighlightY + mNavSlop + 1,
4084                            mTouchCrossHairColor);
4085                }
4086            }
4087        }
4088    }
4089
4090    private void removeTouchHighlight(boolean removePendingMessage) {
4091        if (removePendingMessage) {
4092            mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS);
4093        }
4094        mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS);
4095    }
4096
4097    @Override
4098    public void setLayoutParams(ViewGroup.LayoutParams params) {
4099        if (params.height == LayoutParams.WRAP_CONTENT) {
4100            mWrapContent = true;
4101        }
4102        super.setLayoutParams(params);
4103    }
4104
4105    @Override
4106    public boolean performLongClick() {
4107        // performLongClick() is the result of a delayed message. If we switch
4108        // to windows overview, the WebView will be temporarily removed from the
4109        // view system. In that case, do nothing.
4110        if (getParent() == null) return false;
4111
4112        // A multi-finger gesture can look like a long press; make sure we don't take
4113        // long press actions if we're scaling.
4114        final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
4115        if (detector != null && detector.isInProgress()) {
4116            return false;
4117        }
4118
4119        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
4120            // Send the click so that the textfield is in focus
4121            centerKeyPressOnTextField();
4122            rebuildWebTextView();
4123        } else {
4124            clearTextEntry();
4125        }
4126        if (inEditingMode()) {
4127            // Since we just called rebuildWebTextView, the layout is not set
4128            // properly.  Update it so it can correctly find the word to select.
4129            mWebTextView.ensureLayout();
4130            // Provide a touch down event to WebTextView, which will allow it
4131            // to store the location to use in performLongClick.
4132            AbsoluteLayout.LayoutParams params
4133                    = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams();
4134            MotionEvent fake = MotionEvent.obtain(mLastTouchTime,
4135                    mLastTouchTime, MotionEvent.ACTION_DOWN,
4136                    mLastTouchX - params.x + mScrollX,
4137                    mLastTouchY - params.y + mScrollY, 0);
4138            mWebTextView.dispatchTouchEvent(fake);
4139            return mWebTextView.performLongClick();
4140        }
4141        if (mSelectingText) return false; // long click does nothing on selection
4142        /* if long click brings up a context menu, the super function
4143         * returns true and we're done. Otherwise, nothing happened when
4144         * the user clicked. */
4145        if (super.performLongClick()) {
4146            return true;
4147        }
4148        /* In the case where the application hasn't already handled the long
4149         * click action, look for a word under the  click. If one is found,
4150         * animate the text selection into view.
4151         * FIXME: no animation code yet */
4152        return selectText();
4153    }
4154
4155    /**
4156     * Select the word at the last click point.
4157     *
4158     * @hide pending API council approval
4159     */
4160    public boolean selectText() {
4161        int x = viewToContentX(mLastTouchX + mScrollX);
4162        int y = viewToContentY(mLastTouchY + mScrollY);
4163        return selectText(x, y);
4164    }
4165
4166    /**
4167     * Select the word at the indicated content coordinates.
4168     */
4169    boolean selectText(int x, int y) {
4170        if (!setUpSelect(true, x, y)) {
4171            return false;
4172        }
4173        nativeSetExtendSelection();
4174        mDrawSelectionPointer = false;
4175        mSelectionStarted = true;
4176        mTouchMode = TOUCH_DRAG_MODE;
4177        return true;
4178    }
4179
4180    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
4181
4182    @Override
4183    protected void onConfigurationChanged(Configuration newConfig) {
4184        if (mSelectingText && mOrientation != newConfig.orientation) {
4185            selectionDone();
4186        }
4187        mOrientation = newConfig.orientation;
4188    }
4189
4190    /**
4191     * Keep track of the Callback so we can end its ActionMode or remove its
4192     * titlebar.
4193     */
4194    private SelectActionModeCallback mSelectCallback;
4195
4196    // These values are possible options for didUpdateWebTextViewDimensions.
4197    private static final int FULLY_ON_SCREEN = 0;
4198    private static final int INTERSECTS_SCREEN = 1;
4199    private static final int ANYWHERE = 2;
4200
4201    /**
4202     * Check to see if the focused textfield/textarea is still on screen.  If it
4203     * is, update the the dimensions and location of WebTextView.  Otherwise,
4204     * remove the WebTextView.  Should be called when the zoom level changes.
4205     * @param intersection How to determine whether the textfield/textarea is
4206     *        still on screen.
4207     * @return boolean True if the textfield/textarea is still on screen and the
4208     *         dimensions/location of WebTextView have been updated.
4209     */
4210    private boolean didUpdateWebTextViewDimensions(int intersection) {
4211        Rect contentBounds = nativeFocusCandidateNodeBounds();
4212        Rect vBox = contentToViewRect(contentBounds);
4213        Rect visibleRect = new Rect();
4214        calcOurVisibleRect(visibleRect);
4215        // If the textfield is on screen, place the WebTextView in
4216        // its new place, accounting for our new scroll/zoom values,
4217        // and adjust its textsize.
4218        boolean onScreen;
4219        switch (intersection) {
4220            case FULLY_ON_SCREEN:
4221                onScreen = visibleRect.contains(vBox);
4222                break;
4223            case INTERSECTS_SCREEN:
4224                onScreen = Rect.intersects(visibleRect, vBox);
4225                break;
4226            case ANYWHERE:
4227                onScreen = true;
4228                break;
4229            default:
4230                throw new AssertionError(
4231                        "invalid parameter passed to didUpdateWebTextViewDimensions");
4232        }
4233        if (onScreen) {
4234            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
4235                    vBox.height());
4236            mWebTextView.updateTextSize();
4237            updateWebTextViewPadding();
4238            return true;
4239        } else {
4240            // The textfield is now off screen.  The user probably
4241            // was not zooming to see the textfield better.  Remove
4242            // the WebTextView.  If the user types a key, and the
4243            // textfield is still in focus, we will reconstruct
4244            // the WebTextView and scroll it back on screen.
4245            mWebTextView.remove();
4246            return false;
4247        }
4248    }
4249
4250    void setBaseLayer(int layer, Region invalRegion, boolean showVisualIndicator,
4251            boolean isPictureAfterFirstLayout) {
4252        if (mNativeClass == 0)
4253            return;
4254        nativeSetBaseLayer(layer, invalRegion, showVisualIndicator,
4255                isPictureAfterFirstLayout);
4256        if (mHTML5VideoViewProxy != null) {
4257            mHTML5VideoViewProxy.setBaseLayer(layer);
4258        }
4259    }
4260
4261    int getBaseLayer() {
4262        return nativeGetBaseLayer();
4263    }
4264
4265    private void onZoomAnimationStart() {
4266        // If it is in password mode, turn it off so it does not draw misplaced.
4267        if (inEditingMode() && nativeFocusCandidateIsPassword()) {
4268            mWebTextView.setInPassword(false);
4269        }
4270    }
4271
4272    private void onZoomAnimationEnd() {
4273        // adjust the edit text view if needed
4274        if (inEditingMode() && didUpdateWebTextViewDimensions(FULLY_ON_SCREEN)
4275                && nativeFocusCandidateIsPassword()) {
4276            // If it is a password field, start drawing the WebTextView once
4277            // again.
4278            mWebTextView.setInPassword(true);
4279        }
4280    }
4281
4282    void onFixedLengthZoomAnimationStart() {
4283        WebViewCore.pauseUpdatePicture(getWebViewCore());
4284        onZoomAnimationStart();
4285    }
4286
4287    void onFixedLengthZoomAnimationEnd() {
4288        if (!mBlockWebkitViewMessages && !mSelectingText) {
4289            WebViewCore.resumeUpdatePicture(mWebViewCore);
4290        }
4291        onZoomAnimationEnd();
4292    }
4293
4294    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4295                                         Paint.DITHER_FLAG |
4296                                         Paint.SUBPIXEL_TEXT_FLAG;
4297    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
4298                                           Paint.DITHER_FLAG;
4299
4300    private final DrawFilter mZoomFilter =
4301            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4302    // If we need to trade better quality for speed, set mScrollFilter to null
4303    private final DrawFilter mScrollFilter =
4304            new PaintFlagsDrawFilter(SCROLL_BITS, 0);
4305
4306    private void drawCoreAndCursorRing(Canvas canvas, int color,
4307        boolean drawCursorRing) {
4308        if (mDrawHistory) {
4309            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4310            canvas.drawPicture(mHistoryPicture);
4311            return;
4312        }
4313        if (mNativeClass == 0) return;
4314
4315        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
4316        boolean animateScroll = ((!mScroller.isFinished()
4317                || mVelocityTracker != null)
4318                && (mTouchMode != TOUCH_DRAG_MODE ||
4319                mHeldMotionless != MOTIONLESS_TRUE))
4320                || mDeferTouchMode == TOUCH_DRAG_MODE;
4321        if (mTouchMode == TOUCH_DRAG_MODE) {
4322            if (mHeldMotionless == MOTIONLESS_PENDING) {
4323                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4324                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4325                mHeldMotionless = MOTIONLESS_FALSE;
4326            }
4327            if (mHeldMotionless == MOTIONLESS_FALSE) {
4328                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4329                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
4330                mHeldMotionless = MOTIONLESS_PENDING;
4331            }
4332        }
4333        if (animateZoom) {
4334            mZoomManager.animateZoom(canvas);
4335        } else if (!canvas.isHardwareAccelerated()) {
4336            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4337        }
4338
4339        boolean UIAnimationsRunning = false;
4340        // Currently for each draw we compute the animation values;
4341        // We may in the future decide to do that independently.
4342        if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) {
4343            UIAnimationsRunning = true;
4344            // If we have unfinished (or unstarted) animations,
4345            // we ask for a repaint. We only need to do this in software
4346            // rendering (with hardware rendering we already have a different
4347            // method of requesting a repaint)
4348            if (!canvas.isHardwareAccelerated())
4349                invalidate();
4350        }
4351
4352        // decide which adornments to draw
4353        int extras = DRAW_EXTRAS_NONE;
4354        if (mFindIsUp) {
4355            extras = DRAW_EXTRAS_FIND;
4356        } else if (mSelectingText) {
4357            extras = DRAW_EXTRAS_SELECTION;
4358            nativeSetSelectionPointer(mDrawSelectionPointer,
4359                    mZoomManager.getInvScale(),
4360                    mSelectX, mSelectY - getTitleHeight());
4361        } else if (drawCursorRing) {
4362            extras = DRAW_EXTRAS_CURSOR_RING;
4363        }
4364        if (DebugFlags.WEB_VIEW) {
4365            Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp
4366                    + " mSelectingText=" + mSelectingText
4367                    + " nativePageShouldHandleShiftAndArrows()="
4368                    + nativePageShouldHandleShiftAndArrows()
4369                    + " animateZoom=" + animateZoom
4370                    + " extras=" + extras);
4371        }
4372
4373        if (canvas.isHardwareAccelerated()) {
4374            int functor = nativeGetDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport,
4375                    mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras);
4376            ((HardwareCanvas) canvas).callDrawGLFunction(functor);
4377        } else {
4378            DrawFilter df = null;
4379            if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
4380                df = mZoomFilter;
4381            } else if (animateScroll) {
4382                df = mScrollFilter;
4383            }
4384            canvas.setDrawFilter(df);
4385            // XXX: Revisit splitting content.  Right now it causes a
4386            // synchronization problem with layers.
4387            int content = nativeDraw(canvas, color, extras, false);
4388            canvas.setDrawFilter(null);
4389            if (!mBlockWebkitViewMessages && content != 0) {
4390                mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
4391            }
4392        }
4393
4394        if (extras == DRAW_EXTRAS_CURSOR_RING) {
4395            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
4396                mTouchMode = TOUCH_SHORTPRESS_MODE;
4397            }
4398        }
4399        if (mFocusSizeChanged) {
4400            mFocusSizeChanged = false;
4401            // If we are zooming, this will get handled above, when the zoom
4402            // finishes.  We also do not need to do this unless the WebTextView
4403            // is showing.
4404            if (!animateZoom && inEditingMode()) {
4405                didUpdateWebTextViewDimensions(ANYWHERE);
4406            }
4407        }
4408    }
4409
4410    // draw history
4411    private boolean mDrawHistory = false;
4412    private Picture mHistoryPicture = null;
4413    private int mHistoryWidth = 0;
4414    private int mHistoryHeight = 0;
4415
4416    // Only check the flag, can be called from WebCore thread
4417    boolean drawHistory() {
4418        return mDrawHistory;
4419    }
4420
4421    int getHistoryPictureWidth() {
4422        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
4423    }
4424
4425    // Should only be called in UI thread
4426    void switchOutDrawHistory() {
4427        if (null == mWebViewCore) return; // CallbackProxy may trigger this
4428        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
4429            mDrawHistory = false;
4430            mHistoryPicture = null;
4431            invalidate();
4432            int oldScrollX = mScrollX;
4433            int oldScrollY = mScrollY;
4434            mScrollX = pinLocX(mScrollX);
4435            mScrollY = pinLocY(mScrollY);
4436            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
4437                onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY);
4438            } else {
4439                sendOurVisibleRect();
4440            }
4441        }
4442    }
4443
4444    WebViewCore.CursorData cursorData() {
4445        WebViewCore.CursorData result = cursorDataNoPosition();
4446        Point position = nativeCursorPosition();
4447        result.mX = position.x;
4448        result.mY = position.y;
4449        return result;
4450    }
4451
4452    WebViewCore.CursorData cursorDataNoPosition() {
4453        WebViewCore.CursorData result = new WebViewCore.CursorData();
4454        result.mMoveGeneration = nativeMoveGeneration();
4455        result.mFrame = nativeCursorFramePointer();
4456        return result;
4457    }
4458
4459    /**
4460     *  Delete text from start to end in the focused textfield. If there is no
4461     *  focus, or if start == end, silently fail.  If start and end are out of
4462     *  order, swap them.
4463     *  @param  start   Beginning of selection to delete.
4464     *  @param  end     End of selection to delete.
4465     */
4466    /* package */ void deleteSelection(int start, int end) {
4467        mTextGeneration++;
4468        WebViewCore.TextSelectionData data
4469                = new WebViewCore.TextSelectionData(start, end);
4470        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
4471                data);
4472    }
4473
4474    /**
4475     *  Set the selection to (start, end) in the focused textfield. If start and
4476     *  end are out of order, swap them.
4477     *  @param  start   Beginning of selection.
4478     *  @param  end     End of selection.
4479     */
4480    /* package */ void setSelection(int start, int end) {
4481        if (mWebViewCore != null) {
4482            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
4483        }
4484    }
4485
4486    @Override
4487    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4488      InputConnection connection = super.onCreateInputConnection(outAttrs);
4489      outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN;
4490      return connection;
4491    }
4492
4493    /**
4494     * Called in response to a message from webkit telling us that the soft
4495     * keyboard should be launched.
4496     */
4497    private void displaySoftKeyboard(boolean isTextView) {
4498        InputMethodManager imm = (InputMethodManager)
4499                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
4500
4501        // bring it back to the default level scale so that user can enter text
4502        boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
4503        if (zoom) {
4504            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
4505            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
4506        }
4507        if (isTextView) {
4508            rebuildWebTextView();
4509            if (inEditingMode()) {
4510                imm.showSoftInput(mWebTextView, 0, mWebTextView.getResultReceiver());
4511                if (zoom) {
4512                    didUpdateWebTextViewDimensions(INTERSECTS_SCREEN);
4513                }
4514                return;
4515            }
4516        }
4517        // Used by plugins and contentEditable.
4518        // Also used if the navigation cache is out of date, and
4519        // does not recognize that a textfield is in focus.  In that
4520        // case, use WebView as the targeted view.
4521        // see http://b/issue?id=2457459
4522        imm.showSoftInput(this, 0);
4523    }
4524
4525    // Called by WebKit to instruct the UI to hide the keyboard
4526    private void hideSoftKeyboard() {
4527        InputMethodManager imm = InputMethodManager.peekInstance();
4528        if (imm != null && (imm.isActive(this)
4529                || (inEditingMode() && imm.isActive(mWebTextView)))) {
4530            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
4531        }
4532    }
4533
4534    /*
4535     * This method checks the current focus and cursor and potentially rebuilds
4536     * mWebTextView to have the appropriate properties, such as password,
4537     * multiline, and what text it contains.  It also removes it if necessary.
4538     */
4539    /* package */ void rebuildWebTextView() {
4540        // If the WebView does not have focus, do nothing until it gains focus.
4541        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
4542            return;
4543        }
4544        boolean alreadyThere = inEditingMode();
4545        // inEditingMode can only return true if mWebTextView is non-null,
4546        // so we can safely call remove() if (alreadyThere)
4547        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
4548            if (alreadyThere) {
4549                mWebTextView.remove();
4550            }
4551            return;
4552        }
4553        // At this point, we know we have found an input field, so go ahead
4554        // and create the WebTextView if necessary.
4555        if (mWebTextView == null) {
4556            mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId());
4557            // Initialize our generation number.
4558            mTextGeneration = 0;
4559        }
4560        mWebTextView.updateTextSize();
4561        Rect visibleRect = new Rect();
4562        calcOurContentVisibleRect(visibleRect);
4563        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
4564        // should be in content coordinates.
4565        Rect bounds = nativeFocusCandidateNodeBounds();
4566        Rect vBox = contentToViewRect(bounds);
4567        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
4568        if (!Rect.intersects(bounds, visibleRect)) {
4569            revealSelection();
4570        }
4571        String text = nativeFocusCandidateText();
4572        int nodePointer = nativeFocusCandidatePointer();
4573        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
4574            // It is possible that we have the same textfield, but it has moved,
4575            // i.e. In the case of opening/closing the screen.
4576            // In that case, we need to set the dimensions, but not the other
4577            // aspects.
4578            // If the text has been changed by webkit, update it.  However, if
4579            // there has been more UI text input, ignore it.  We will receive
4580            // another update when that text is recognized.
4581            if (text != null && !text.equals(mWebTextView.getText().toString())
4582                    && nativeTextGeneration() == mTextGeneration) {
4583                mWebTextView.setTextAndKeepSelection(text);
4584            }
4585        } else {
4586            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
4587                    Gravity.RIGHT : Gravity.NO_GRAVITY);
4588            // This needs to be called before setType, which may call
4589            // requestFormData, and it needs to have the correct nodePointer.
4590            mWebTextView.setNodePointer(nodePointer);
4591            mWebTextView.setType(nativeFocusCandidateType());
4592            updateWebTextViewPadding();
4593            if (null == text) {
4594                if (DebugFlags.WEB_VIEW) {
4595                    Log.v(LOGTAG, "rebuildWebTextView null == text");
4596                }
4597                text = "";
4598            }
4599            mWebTextView.setTextAndKeepSelection(text);
4600            InputMethodManager imm = InputMethodManager.peekInstance();
4601            if (imm != null && imm.isActive(mWebTextView)) {
4602                imm.restartInput(mWebTextView);
4603            }
4604        }
4605        if (isFocused()) {
4606            mWebTextView.requestFocus();
4607        }
4608    }
4609
4610    /**
4611     * Update the padding of mWebTextView based on the native textfield/textarea
4612     */
4613    void updateWebTextViewPadding() {
4614        Rect paddingRect = nativeFocusCandidatePaddingRect();
4615        if (paddingRect != null) {
4616            // Use contentToViewDimension since these are the dimensions of
4617            // the padding.
4618            mWebTextView.setPadding(
4619                    contentToViewDimension(paddingRect.left),
4620                    contentToViewDimension(paddingRect.top),
4621                    contentToViewDimension(paddingRect.right),
4622                    contentToViewDimension(paddingRect.bottom));
4623        }
4624    }
4625
4626    /**
4627     * Tell webkit to put the cursor on screen.
4628     */
4629    /* package */ void revealSelection() {
4630        if (mWebViewCore != null) {
4631            mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION);
4632        }
4633    }
4634
4635    /**
4636     * Called by WebTextView to find saved form data associated with the
4637     * textfield
4638     * @param name Name of the textfield.
4639     * @param nodePointer Pointer to the node of the textfield, so it can be
4640     *          compared to the currently focused textfield when the data is
4641     *          retrieved.
4642     * @param autoFillable true if WebKit has determined this field is part of
4643     *          a form that can be auto filled.
4644     * @param autoComplete true if the attribute "autocomplete" is set to true
4645     *          on the textfield.
4646     */
4647    /* package */ void requestFormData(String name, int nodePointer,
4648            boolean autoFillable, boolean autoComplete) {
4649        if (mWebViewCore.getSettings().getSaveFormData()) {
4650            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
4651            update.arg1 = nodePointer;
4652            RequestFormData updater = new RequestFormData(name, getUrl(),
4653                    update, autoFillable, autoComplete);
4654            Thread t = new Thread(updater);
4655            t.start();
4656        }
4657    }
4658
4659    /**
4660     * Pass a message to find out the <label> associated with the <input>
4661     * identified by nodePointer
4662     * @param framePointer Pointer to the frame containing the <input> node
4663     * @param nodePointer Pointer to the node for which a <label> is desired.
4664     */
4665    /* package */ void requestLabel(int framePointer, int nodePointer) {
4666        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
4667                nodePointer);
4668    }
4669
4670    /*
4671     * This class requests an Adapter for the WebTextView which shows past
4672     * entries stored in the database.  It is a Runnable so that it can be done
4673     * in its own thread, without slowing down the UI.
4674     */
4675    private class RequestFormData implements Runnable {
4676        private String mName;
4677        private String mUrl;
4678        private Message mUpdateMessage;
4679        private boolean mAutoFillable;
4680        private boolean mAutoComplete;
4681
4682        public RequestFormData(String name, String url, Message msg,
4683                boolean autoFillable, boolean autoComplete) {
4684            mName = name;
4685            mUrl = url;
4686            mUpdateMessage = msg;
4687            mAutoFillable = autoFillable;
4688            mAutoComplete = autoComplete;
4689        }
4690
4691        public void run() {
4692            ArrayList<String> pastEntries = new ArrayList<String>();
4693
4694            if (mAutoFillable) {
4695                // Note that code inside the adapter click handler in WebTextView depends
4696                // on the AutoFill item being at the top of the drop down list. If you change
4697                // the order, make sure to do it there too!
4698                WebSettings settings = getSettings();
4699                if (settings != null && settings.getAutoFillProfile() != null) {
4700                    pastEntries.add(getResources().getText(
4701                            com.android.internal.R.string.autofill_this_form).toString() +
4702                            " " +
4703                            mAutoFillData.getPreviewString());
4704                    mWebTextView.setAutoFillProfileIsSet(true);
4705                } else {
4706                    // There is no autofill profile set up yet, so add an option that
4707                    // will invite the user to set their profile up.
4708                    pastEntries.add(getResources().getText(
4709                            com.android.internal.R.string.setup_autofill).toString());
4710                    mWebTextView.setAutoFillProfileIsSet(false);
4711                }
4712            }
4713
4714            if (mAutoComplete) {
4715                pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
4716            }
4717
4718            if (pastEntries.size() > 0) {
4719                AutoCompleteAdapter adapter = new
4720                        AutoCompleteAdapter(mContext, pastEntries);
4721                mUpdateMessage.obj = adapter;
4722                mUpdateMessage.sendToTarget();
4723            }
4724        }
4725    }
4726
4727    /**
4728     * Dump the display tree to "/sdcard/displayTree.txt"
4729     *
4730     * @hide debug only
4731     */
4732    public void dumpDisplayTree() {
4733        nativeDumpDisplayTree(getUrl());
4734    }
4735
4736    /**
4737     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
4738     * "/sdcard/domTree.txt"
4739     *
4740     * @hide debug only
4741     */
4742    public void dumpDomTree(boolean toFile) {
4743        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
4744    }
4745
4746    /**
4747     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
4748     * to "/sdcard/renderTree.txt"
4749     *
4750     * @hide debug only
4751     */
4752    public void dumpRenderTree(boolean toFile) {
4753        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
4754    }
4755
4756    /**
4757     * Called by DRT on UI thread, need to proxy to WebCore thread.
4758     *
4759     * @hide debug only
4760     */
4761    public void useMockDeviceOrientation() {
4762        mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
4763    }
4764
4765    /**
4766     * Called by DRT on WebCore thread.
4767     *
4768     * @hide debug only
4769     */
4770    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
4771            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
4772        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
4773                canProvideGamma, gamma);
4774    }
4775
4776    /**
4777     * Dump the V8 counters to standard output.
4778     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
4779     * true. Otherwise, this will do nothing.
4780     *
4781     * @hide debug only
4782     */
4783    public void dumpV8Counters() {
4784        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
4785    }
4786
4787    // This is used to determine long press with the center key.  Does not
4788    // affect long press with the trackball/touch.
4789    private boolean mGotCenterDown = false;
4790
4791    @Override
4792    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4793        if (mBlockWebkitViewMessages) {
4794            return false;
4795        }
4796        // send complex characters to webkit for use by JS and plugins
4797        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
4798            // pass the key to DOM
4799            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4800            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4801            // return true as DOM handles the key
4802            return true;
4803        }
4804        return false;
4805    }
4806
4807    private boolean isEnterActionKey(int keyCode) {
4808        return keyCode == KeyEvent.KEYCODE_DPAD_CENTER
4809                || keyCode == KeyEvent.KEYCODE_ENTER
4810                || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER;
4811    }
4812
4813    @Override
4814    public boolean onKeyDown(int keyCode, KeyEvent event) {
4815        if (DebugFlags.WEB_VIEW) {
4816            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
4817                    + "keyCode=" + keyCode
4818                    + ", " + event + ", unicode=" + event.getUnicodeChar());
4819        }
4820        if (mBlockWebkitViewMessages) {
4821            return false;
4822        }
4823
4824        // don't implement accelerator keys here; defer to host application
4825        if (event.isCtrlPressed()) {
4826            return false;
4827        }
4828
4829        if (mNativeClass == 0) {
4830            return false;
4831        }
4832
4833        // do this hack up front, so it always works, regardless of touch-mode
4834        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
4835            mAutoRedraw = !mAutoRedraw;
4836            if (mAutoRedraw) {
4837                invalidate();
4838            }
4839            return true;
4840        }
4841
4842        // Bubble up the key event if
4843        // 1. it is a system key; or
4844        // 2. the host application wants to handle it;
4845        if (event.isSystem()
4846                || mCallbackProxy.uiOverrideKeyEvent(event)) {
4847            return false;
4848        }
4849
4850        // accessibility support
4851        if (accessibilityScriptInjected()) {
4852            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4853                // if an accessibility script is injected we delegate to it the key handling.
4854                // this script is a screen reader which is a fully fledged solution for blind
4855                // users to navigate in and interact with web pages.
4856                mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4857                return true;
4858            } else {
4859                // Clean up if accessibility was disabled after loading the current URL.
4860                mAccessibilityScriptInjected = false;
4861            }
4862        } else if (mAccessibilityInjector != null) {
4863            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4864                if (mAccessibilityInjector.onKeyEvent(event)) {
4865                    // if an accessibility injector is present (no JavaScript enabled or the site
4866                    // opts out injecting our JavaScript screen reader) we let it decide whether
4867                    // to act on and consume the event.
4868                    return true;
4869                }
4870            } else {
4871                // Clean up if accessibility was disabled after loading the current URL.
4872                mAccessibilityInjector = null;
4873            }
4874        }
4875
4876        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
4877            if (event.hasNoModifiers()) {
4878                pageUp(false);
4879                return true;
4880            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4881                pageUp(true);
4882                return true;
4883            }
4884        }
4885
4886        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
4887            if (event.hasNoModifiers()) {
4888                pageDown(false);
4889                return true;
4890            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4891                pageDown(true);
4892                return true;
4893            }
4894        }
4895
4896        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) {
4897            pageUp(true);
4898            return true;
4899        }
4900
4901        if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) {
4902            pageDown(true);
4903            return true;
4904        }
4905
4906        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4907                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
4908            switchOutDrawHistory();
4909            if (nativePageShouldHandleShiftAndArrows()) {
4910                letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState());
4911                return true;
4912            }
4913            if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4914                switch (keyCode) {
4915                    case KeyEvent.KEYCODE_DPAD_UP:
4916                        pageUp(true);
4917                        return true;
4918                    case KeyEvent.KEYCODE_DPAD_DOWN:
4919                        pageDown(true);
4920                        return true;
4921                    case KeyEvent.KEYCODE_DPAD_LEFT:
4922                        nativeClearCursor(); // start next trackball movement from page edge
4923                        return pinScrollTo(0, mScrollY, true, 0);
4924                    case KeyEvent.KEYCODE_DPAD_RIGHT:
4925                        nativeClearCursor(); // start next trackball movement from page edge
4926                        return pinScrollTo(mContentWidth, mScrollY, true, 0);
4927                }
4928            }
4929            if (mSelectingText) {
4930                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
4931                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
4932                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
4933                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
4934                int multiplier = event.getRepeatCount() + 1;
4935                moveSelection(xRate * multiplier, yRate * multiplier);
4936                return true;
4937            }
4938            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
4939                playSoundEffect(keyCodeToSoundsEffect(keyCode));
4940                return true;
4941            }
4942            // Bubble up the key event as WebView doesn't handle it
4943            return false;
4944        }
4945
4946        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
4947            switchOutDrawHistory();
4948            boolean wantsKeyEvents = nativeCursorNodePointer() == 0
4949                || nativeCursorWantsKeyEvents();
4950            if (event.getRepeatCount() == 0) {
4951                if (mSelectingText) {
4952                    return true; // discard press if copy in progress
4953                }
4954                mGotCenterDown = true;
4955                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4956                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
4957                // Already checked mNativeClass, so we do not need to check it
4958                // again.
4959                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4960                if (!wantsKeyEvents) return true;
4961            }
4962            // Bubble up the key event as WebView doesn't handle it
4963            if (!wantsKeyEvents) return false;
4964        }
4965
4966        if (getSettings().getNavDump()) {
4967            switch (keyCode) {
4968                case KeyEvent.KEYCODE_4:
4969                    dumpDisplayTree();
4970                    break;
4971                case KeyEvent.KEYCODE_5:
4972                case KeyEvent.KEYCODE_6:
4973                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
4974                    break;
4975                case KeyEvent.KEYCODE_7:
4976                case KeyEvent.KEYCODE_8:
4977                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
4978                    break;
4979                case KeyEvent.KEYCODE_9:
4980                    nativeInstrumentReport();
4981                    return true;
4982            }
4983        }
4984
4985        if (nativeCursorIsTextInput()) {
4986            // This message will put the node in focus, for the DOM's notion
4987            // of focus.
4988            mWebViewCore.sendMessage(EventHub.FAKE_CLICK, nativeCursorFramePointer(),
4989                    nativeCursorNodePointer());
4990            // This will bring up the WebTextView and put it in focus, for
4991            // our view system's notion of focus
4992            rebuildWebTextView();
4993            // Now we need to pass the event to it
4994            if (inEditingMode()) {
4995                mWebTextView.setDefaultSelection();
4996                return mWebTextView.dispatchKeyEvent(event);
4997            }
4998        } else if (nativeHasFocusNode()) {
4999            // In this case, the cursor is not on a text input, but the focus
5000            // might be.  Check it, and if so, hand over to the WebTextView.
5001            rebuildWebTextView();
5002            if (inEditingMode()) {
5003                mWebTextView.setDefaultSelection();
5004                return mWebTextView.dispatchKeyEvent(event);
5005            }
5006        }
5007
5008        // TODO: should we pass all the keys to DOM or check the meta tag
5009        if (nativeCursorWantsKeyEvents() || true) {
5010            // pass the key to DOM
5011            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5012            // return true as DOM handles the key
5013            return true;
5014        }
5015
5016        // Bubble up the key event as WebView doesn't handle it
5017        return false;
5018    }
5019
5020    @Override
5021    public boolean onKeyUp(int keyCode, KeyEvent event) {
5022        if (DebugFlags.WEB_VIEW) {
5023            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
5024                    + ", " + event + ", unicode=" + event.getUnicodeChar());
5025        }
5026        if (mBlockWebkitViewMessages) {
5027            return false;
5028        }
5029
5030        if (mNativeClass == 0) {
5031            return false;
5032        }
5033
5034        // special CALL handling when cursor node's href is "tel:XXX"
5035        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
5036            String text = nativeCursorText();
5037            if (!nativeCursorIsTextInput() && text != null
5038                    && text.startsWith(SCHEME_TEL)) {
5039                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
5040                getContext().startActivity(intent);
5041                return true;
5042            }
5043        }
5044
5045        // Bubble up the key event if
5046        // 1. it is a system key; or
5047        // 2. the host application wants to handle it;
5048        if (event.isSystem()
5049                || mCallbackProxy.uiOverrideKeyEvent(event)) {
5050            return false;
5051        }
5052
5053        // accessibility support
5054        if (accessibilityScriptInjected()) {
5055            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5056                // if an accessibility script is injected we delegate to it the key handling.
5057                // this script is a screen reader which is a fully fledged solution for blind
5058                // users to navigate in and interact with web pages.
5059                mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5060                return true;
5061            } else {
5062                // Clean up if accessibility was disabled after loading the current URL.
5063                mAccessibilityScriptInjected = false;
5064            }
5065        } else if (mAccessibilityInjector != null) {
5066            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5067                if (mAccessibilityInjector.onKeyEvent(event)) {
5068                    // if an accessibility injector is present (no JavaScript enabled or the site
5069                    // opts out injecting our JavaScript screen reader) we let it decide whether to
5070                    // act on and consume the event.
5071                    return true;
5072                }
5073            } else {
5074                // Clean up if accessibility was disabled after loading the current URL.
5075                mAccessibilityInjector = null;
5076            }
5077        }
5078
5079        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
5080                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
5081            if (nativePageShouldHandleShiftAndArrows()) {
5082                letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState());
5083                return true;
5084            }
5085            // always handle the navigation keys in the UI thread
5086            // Bubble up the key event as WebView doesn't handle it
5087            return false;
5088        }
5089
5090        if (isEnterActionKey(keyCode)) {
5091            // remove the long press message first
5092            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5093            mGotCenterDown = false;
5094
5095            if (mSelectingText) {
5096                if (mExtendSelection) {
5097                    copySelection();
5098                    selectionDone();
5099                } else {
5100                    mExtendSelection = true;
5101                    nativeSetExtendSelection();
5102                    invalidate(); // draw the i-beam instead of the arrow
5103                }
5104                return true; // discard press if copy in progress
5105            }
5106
5107            // perform the single click
5108            Rect visibleRect = sendOurVisibleRect();
5109            // Note that sendOurVisibleRect calls viewToContent, so the
5110            // coordinates should be in content coordinates.
5111            if (!nativeCursorIntersects(visibleRect)) {
5112                return false;
5113            }
5114            WebViewCore.CursorData data = cursorData();
5115            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
5116            playSoundEffect(SoundEffectConstants.CLICK);
5117            if (nativeCursorIsTextInput()) {
5118                rebuildWebTextView();
5119                centerKeyPressOnTextField();
5120                if (inEditingMode()) {
5121                    mWebTextView.setDefaultSelection();
5122                }
5123                return true;
5124            }
5125            clearTextEntry();
5126            nativeShowCursorTimed();
5127            if (mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
5128                return true;
5129            }
5130            if (nativeCursorNodePointer() != 0 && !nativeCursorWantsKeyEvents()) {
5131                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
5132                        nativeCursorNodePointer());
5133                return true;
5134            }
5135        }
5136
5137        // TODO: should we pass all the keys to DOM or check the meta tag
5138        if (nativeCursorWantsKeyEvents() || true) {
5139            // pass the key to DOM
5140            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5141            // return true as DOM handles the key
5142            return true;
5143        }
5144
5145        // Bubble up the key event as WebView doesn't handle it
5146        return false;
5147    }
5148
5149    /*
5150     * Enter selecting text mode, and see if CAB should be shown.
5151     * Returns true if the WebView is now in
5152     * selecting text mode (including if it was already in that mode, and this
5153     * method did nothing).
5154     */
5155    private boolean setUpSelect(boolean selectWord, int x, int y) {
5156        if (0 == mNativeClass) return false; // client isn't initialized
5157        if (inFullScreenMode()) return false;
5158        if (mSelectingText) return true;
5159        nativeResetSelection();
5160        if (selectWord && !nativeWordSelection(x, y)) {
5161            selectionDone();
5162            return false;
5163        }
5164        mSelectCallback = new SelectActionModeCallback();
5165        mSelectCallback.setWebView(this);
5166        if (startActionMode(mSelectCallback) == null) {
5167            // There is no ActionMode, so do not allow the user to modify a
5168            // selection.
5169            selectionDone();
5170            return false;
5171        }
5172        mExtendSelection = false;
5173        mSelectingText = mDrawSelectionPointer = true;
5174        // don't let the picture change during text selection
5175        WebViewCore.pauseUpdatePicture(mWebViewCore);
5176        if (nativeHasCursorNode()) {
5177            Rect rect = nativeCursorNodeBounds();
5178            mSelectX = contentToViewX(rect.left);
5179            mSelectY = contentToViewY(rect.top);
5180        } else if (mLastTouchY > getVisibleTitleHeight()) {
5181            mSelectX = mScrollX + mLastTouchX;
5182            mSelectY = mScrollY + mLastTouchY;
5183        } else {
5184            mSelectX = mScrollX + getViewWidth() / 2;
5185            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
5186        }
5187        nativeHideCursor();
5188        mMinAutoScrollX = 0;
5189        mMaxAutoScrollX = getViewWidth();
5190        mMinAutoScrollY = 0;
5191        mMaxAutoScrollY = getViewHeightWithTitle();
5192        mScrollingLayer = nativeScrollableLayer(viewToContentX(mSelectX),
5193                viewToContentY(mSelectY), mScrollingLayerRect,
5194                mScrollingLayerBounds);
5195        if (mScrollingLayer != 0) {
5196            if (mScrollingLayerRect.left != mScrollingLayerRect.right) {
5197                mMinAutoScrollX = Math.max(mMinAutoScrollX,
5198                        contentToViewX(mScrollingLayerBounds.left));
5199                mMaxAutoScrollX = Math.min(mMaxAutoScrollX,
5200                        contentToViewX(mScrollingLayerBounds.right));
5201            }
5202            if (mScrollingLayerRect.top != mScrollingLayerRect.bottom) {
5203                mMinAutoScrollY = Math.max(mMinAutoScrollY,
5204                        contentToViewY(mScrollingLayerBounds.top));
5205                mMaxAutoScrollY = Math.min(mMaxAutoScrollY,
5206                        contentToViewY(mScrollingLayerBounds.bottom));
5207            }
5208        }
5209        mMinAutoScrollX += SELECT_SCROLL;
5210        mMaxAutoScrollX -= SELECT_SCROLL;
5211        mMinAutoScrollY += SELECT_SCROLL;
5212        mMaxAutoScrollY -= SELECT_SCROLL;
5213        return true;
5214    }
5215
5216    /**
5217     * Use this method to put the WebView into text selection mode.
5218     * Do not rely on this functionality; it will be deprecated in the future.
5219     * @deprecated This method is now obsolete.
5220     */
5221    @Deprecated
5222    public void emulateShiftHeld() {
5223        checkThread();
5224        setUpSelect(false, 0, 0);
5225    }
5226
5227    /**
5228     * Select all of the text in this WebView.
5229     *
5230     * @hide pending API council approval.
5231     */
5232    public void selectAll() {
5233        if (0 == mNativeClass) return; // client isn't initialized
5234        if (inFullScreenMode()) return;
5235        if (!mSelectingText) {
5236            // retrieve a point somewhere within the text
5237            Point select = nativeSelectableText();
5238            if (!selectText(select.x, select.y)) return;
5239        }
5240        nativeSelectAll();
5241        mDrawSelectionPointer = false;
5242        mExtendSelection = true;
5243        invalidate();
5244    }
5245
5246    /**
5247     * Called when the selection has been removed.
5248     */
5249    void selectionDone() {
5250        if (mSelectingText) {
5251            mSelectingText = false;
5252            // finish is idempotent, so this is fine even if selectionDone was
5253            // called by mSelectCallback.onDestroyActionMode
5254            mSelectCallback.finish();
5255            mSelectCallback = null;
5256            WebViewCore.resumePriority();
5257            WebViewCore.resumeUpdatePicture(mWebViewCore);
5258            invalidate(); // redraw without selection
5259            mAutoScrollX = 0;
5260            mAutoScrollY = 0;
5261            mSentAutoScrollMessage = false;
5262        }
5263    }
5264
5265    /**
5266     * Copy the selection to the clipboard
5267     *
5268     * @hide pending API council approval.
5269     */
5270    public boolean copySelection() {
5271        boolean copiedSomething = false;
5272        String selection = getSelection();
5273        if (selection != null && selection != "") {
5274            if (DebugFlags.WEB_VIEW) {
5275                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
5276            }
5277            Toast.makeText(mContext
5278                    , com.android.internal.R.string.text_copied
5279                    , Toast.LENGTH_SHORT).show();
5280            copiedSomething = true;
5281            ClipboardManager cm = (ClipboardManager)getContext()
5282                    .getSystemService(Context.CLIPBOARD_SERVICE);
5283            cm.setText(selection);
5284        }
5285        invalidate(); // remove selection region and pointer
5286        return copiedSomething;
5287    }
5288
5289    /**
5290     * @hide pending API Council approval.
5291     */
5292    public SearchBox getSearchBox() {
5293        if ((mWebViewCore == null) || (mWebViewCore.getBrowserFrame() == null)) {
5294            return null;
5295        }
5296        return mWebViewCore.getBrowserFrame().getSearchBox();
5297    }
5298
5299    /**
5300     * Returns the currently highlighted text as a string.
5301     */
5302    String getSelection() {
5303        if (mNativeClass == 0) return "";
5304        return nativeGetSelection();
5305    }
5306
5307    @Override
5308    protected void onAttachedToWindow() {
5309        super.onAttachedToWindow();
5310        if (hasWindowFocus()) setActive(true);
5311        final ViewTreeObserver treeObserver = getViewTreeObserver();
5312        if (mGlobalLayoutListener == null) {
5313            mGlobalLayoutListener = new InnerGlobalLayoutListener();
5314            treeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);
5315        }
5316        if (mScrollChangedListener == null) {
5317            mScrollChangedListener = new InnerScrollChangedListener();
5318            treeObserver.addOnScrollChangedListener(mScrollChangedListener);
5319        }
5320
5321        addAccessibilityApisToJavaScript();
5322
5323        mTouchEventQueue.reset();
5324    }
5325
5326    @Override
5327    protected void onDetachedFromWindow() {
5328        clearHelpers();
5329        mZoomManager.dismissZoomPicker();
5330        if (hasWindowFocus()) setActive(false);
5331
5332        final ViewTreeObserver treeObserver = getViewTreeObserver();
5333        if (mGlobalLayoutListener != null) {
5334            treeObserver.removeGlobalOnLayoutListener(mGlobalLayoutListener);
5335            mGlobalLayoutListener = null;
5336        }
5337        if (mScrollChangedListener != null) {
5338            treeObserver.removeOnScrollChangedListener(mScrollChangedListener);
5339            mScrollChangedListener = null;
5340        }
5341
5342        removeAccessibilityApisFromJavaScript();
5343
5344        super.onDetachedFromWindow();
5345    }
5346
5347    @Override
5348    protected void onVisibilityChanged(View changedView, int visibility) {
5349        super.onVisibilityChanged(changedView, visibility);
5350        // The zoomManager may be null if the webview is created from XML that
5351        // specifies the view's visibility param as not visible (see http://b/2794841)
5352        if (visibility != View.VISIBLE && mZoomManager != null) {
5353            mZoomManager.dismissZoomPicker();
5354        }
5355    }
5356
5357    /**
5358     * @deprecated WebView no longer needs to implement
5359     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5360     */
5361    @Deprecated
5362    public void onChildViewAdded(View parent, View child) {}
5363
5364    /**
5365     * @deprecated WebView no longer needs to implement
5366     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5367     */
5368    @Deprecated
5369    public void onChildViewRemoved(View p, View child) {}
5370
5371    /**
5372     * @deprecated WebView should not have implemented
5373     * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
5374     */
5375    @Deprecated
5376    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
5377    }
5378
5379    void setActive(boolean active) {
5380        if (active) {
5381            if (hasFocus()) {
5382                // If our window regained focus, and we have focus, then begin
5383                // drawing the cursor ring
5384                mDrawCursorRing = true;
5385                setFocusControllerActive(true);
5386                if (mNativeClass != 0) {
5387                    nativeRecordButtons(true, false, true);
5388                }
5389            } else {
5390                if (!inEditingMode()) {
5391                    // If our window gained focus, but we do not have it, do not
5392                    // draw the cursor ring.
5393                    mDrawCursorRing = false;
5394                    setFocusControllerActive(false);
5395                }
5396                // We do not call nativeRecordButtons here because we assume
5397                // that when we lost focus, or window focus, it got called with
5398                // false for the first parameter
5399            }
5400        } else {
5401            if (!mZoomManager.isZoomPickerVisible()) {
5402                /*
5403                 * The external zoom controls come in their own window, so our
5404                 * window loses focus. Our policy is to not draw the cursor ring
5405                 * if our window is not focused, but this is an exception since
5406                 * the user can still navigate the web page with the zoom
5407                 * controls showing.
5408                 */
5409                mDrawCursorRing = false;
5410            }
5411            mKeysPressed.clear();
5412            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5413            mTouchMode = TOUCH_DONE_MODE;
5414            if (mNativeClass != 0) {
5415                nativeRecordButtons(false, false, true);
5416            }
5417            setFocusControllerActive(false);
5418        }
5419        invalidate();
5420    }
5421
5422    // To avoid drawing the cursor ring, and remove the TextView when our window
5423    // loses focus.
5424    @Override
5425    public void onWindowFocusChanged(boolean hasWindowFocus) {
5426        setActive(hasWindowFocus);
5427        if (hasWindowFocus) {
5428            JWebCoreJavaBridge.setActiveWebView(this);
5429        } else {
5430            JWebCoreJavaBridge.removeActiveWebView(this);
5431        }
5432        super.onWindowFocusChanged(hasWindowFocus);
5433    }
5434
5435    /*
5436     * Pass a message to WebCore Thread, telling the WebCore::Page's
5437     * FocusController to be  "inactive" so that it will
5438     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
5439     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
5440     */
5441    /* package */ void setFocusControllerActive(boolean active) {
5442        if (mWebViewCore == null) return;
5443        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
5444        // Need to send this message after the document regains focus.
5445        if (active && mListBoxMessage != null) {
5446            mWebViewCore.sendMessage(mListBoxMessage);
5447            mListBoxMessage = null;
5448        }
5449    }
5450
5451    @Override
5452    protected void onFocusChanged(boolean focused, int direction,
5453            Rect previouslyFocusedRect) {
5454        if (DebugFlags.WEB_VIEW) {
5455            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
5456        }
5457        if (focused) {
5458            // When we regain focus, if we have window focus, resume drawing
5459            // the cursor ring
5460            if (hasWindowFocus()) {
5461                mDrawCursorRing = true;
5462                if (mNativeClass != 0) {
5463                    nativeRecordButtons(true, false, true);
5464                }
5465                setFocusControllerActive(true);
5466            //} else {
5467                // The WebView has gained focus while we do not have
5468                // windowfocus.  When our window lost focus, we should have
5469                // called nativeRecordButtons(false...)
5470            }
5471        } else {
5472            // When we lost focus, unless focus went to the TextView (which is
5473            // true if we are in editing mode), stop drawing the cursor ring.
5474            if (!inEditingMode()) {
5475                mDrawCursorRing = false;
5476                if (mNativeClass != 0) {
5477                    nativeRecordButtons(false, false, true);
5478                }
5479                setFocusControllerActive(false);
5480            }
5481            mKeysPressed.clear();
5482        }
5483
5484        super.onFocusChanged(focused, direction, previouslyFocusedRect);
5485    }
5486
5487    void setGLRectViewport() {
5488        // Use the getGlobalVisibleRect() to get the intersection among the parents
5489        // visible == false means we're clipped - send a null rect down to indicate that
5490        // we should not draw
5491        boolean visible = getGlobalVisibleRect(mGLRectViewport);
5492        if (visible) {
5493            // Then need to invert the Y axis, just for GL
5494            View rootView = getRootView();
5495            int rootViewHeight = rootView.getHeight();
5496            mViewRectViewport.set(mGLRectViewport);
5497            int savedWebViewBottom = mGLRectViewport.bottom;
5498            mGLRectViewport.bottom = rootViewHeight - mGLRectViewport.top - getVisibleTitleHeight();
5499            mGLRectViewport.top = rootViewHeight - savedWebViewBottom;
5500            mGLViewportEmpty = false;
5501        } else {
5502            mGLViewportEmpty = true;
5503        }
5504        nativeUpdateDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport,
5505                mGLViewportEmpty ? null : mViewRectViewport);
5506    }
5507
5508    /**
5509     * @hide
5510     */
5511    @Override
5512    protected boolean setFrame(int left, int top, int right, int bottom) {
5513        boolean changed = super.setFrame(left, top, right, bottom);
5514        if (!changed && mHeightCanMeasure) {
5515            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
5516            // in WebViewCore after we get the first layout. We do call
5517            // requestLayout() when we get contentSizeChanged(). But the View
5518            // system won't call onSizeChanged if the dimension is not changed.
5519            // In this case, we need to call sendViewSizeZoom() explicitly to
5520            // notify the WebKit about the new dimensions.
5521            sendViewSizeZoom(false);
5522        }
5523        setGLRectViewport();
5524        return changed;
5525    }
5526
5527    @Override
5528    protected void onSizeChanged(int w, int h, int ow, int oh) {
5529        super.onSizeChanged(w, h, ow, oh);
5530
5531        // adjust the max viewport width depending on the view dimensions. This
5532        // is to ensure the scaling is not going insane. So do not shrink it if
5533        // the view size is temporarily smaller, e.g. when soft keyboard is up.
5534        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
5535        if (newMaxViewportWidth > sMaxViewportWidth) {
5536            sMaxViewportWidth = newMaxViewportWidth;
5537        }
5538
5539        mZoomManager.onSizeChanged(w, h, ow, oh);
5540
5541        if (mLoadedPicture != null && mDelaySetPicture == null) {
5542            // Size changes normally result in a new picture
5543            // Re-set the loaded picture to simulate that
5544            // However, do not update the base layer as that hasn't changed
5545            setNewPicture(mLoadedPicture, false);
5546        }
5547    }
5548
5549    @Override
5550    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5551        super.onScrollChanged(l, t, oldl, oldt);
5552        if (!mInOverScrollMode) {
5553            sendOurVisibleRect();
5554            // update WebKit if visible title bar height changed. The logic is same
5555            // as getVisibleTitleHeight.
5556            int titleHeight = getTitleHeight();
5557            if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
5558                sendViewSizeZoom(false);
5559            }
5560        }
5561    }
5562
5563    @Override
5564    public boolean dispatchKeyEvent(KeyEvent event) {
5565        switch (event.getAction()) {
5566            case KeyEvent.ACTION_DOWN:
5567                mKeysPressed.add(Integer.valueOf(event.getKeyCode()));
5568                break;
5569            case KeyEvent.ACTION_MULTIPLE:
5570                // Always accept the action.
5571                break;
5572            case KeyEvent.ACTION_UP:
5573                int location = mKeysPressed.indexOf(Integer.valueOf(event.getKeyCode()));
5574                if (location == -1) {
5575                    // We did not receive the key down for this key, so do not
5576                    // handle the key up.
5577                    return false;
5578                } else {
5579                    // We did receive the key down.  Handle the key up, and
5580                    // remove it from our pressed keys.
5581                    mKeysPressed.remove(location);
5582                }
5583                break;
5584            default:
5585                // Accept the action.  This should not happen, unless a new
5586                // action is added to KeyEvent.
5587                break;
5588        }
5589        if (inEditingMode() && mWebTextView.isFocused()) {
5590            // Ensure that the WebTextView gets the event, even if it does
5591            // not currently have a bounds.
5592            return mWebTextView.dispatchKeyEvent(event);
5593        } else {
5594            return super.dispatchKeyEvent(event);
5595        }
5596    }
5597
5598    // Here are the snap align logic:
5599    // 1. If it starts nearly horizontally or vertically, snap align;
5600    // 2. If there is a dramitic direction change, let it go;
5601    // 3. If there is a same direction back and forth, lock it.
5602
5603    // adjustable parameters
5604    private int mMinLockSnapReverseDistance;
5605    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
5606    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
5607
5608    private boolean hitFocusedPlugin(int contentX, int contentY) {
5609        if (DebugFlags.WEB_VIEW) {
5610            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
5611            Rect r = nativeFocusNodeBounds();
5612            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
5613                    + ", " + r.right + ", " + r.bottom + ")");
5614        }
5615        return nativeFocusIsPlugin()
5616                && nativeFocusNodeBounds().contains(contentX, contentY);
5617    }
5618
5619    private boolean shouldForwardTouchEvent() {
5620        if (mFullScreenHolder != null) return true;
5621        if (mBlockWebkitViewMessages) return false;
5622        return mForwardTouchEvents
5623                && !mSelectingText
5624                && mPreventDefault != PREVENT_DEFAULT_IGNORE
5625                && mPreventDefault != PREVENT_DEFAULT_NO;
5626    }
5627
5628    private boolean inFullScreenMode() {
5629        return mFullScreenHolder != null;
5630    }
5631
5632    private void dismissFullScreenMode() {
5633        if (inFullScreenMode()) {
5634            mFullScreenHolder.hide();
5635            mFullScreenHolder = null;
5636        }
5637    }
5638
5639    void onPinchToZoomAnimationStart() {
5640        // cancel the single touch handling
5641        cancelTouch();
5642        onZoomAnimationStart();
5643    }
5644
5645    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
5646        onZoomAnimationEnd();
5647        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
5648        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
5649        // as it may trigger the unwanted fling.
5650        mTouchMode = TOUCH_PINCH_DRAG;
5651        mConfirmMove = true;
5652        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
5653    }
5654
5655    // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a
5656    // layer is found.
5657    private void startScrollingLayer(float x, float y) {
5658        int contentX = viewToContentX((int) x + mScrollX);
5659        int contentY = viewToContentY((int) y + mScrollY);
5660        mScrollingLayer = nativeScrollableLayer(contentX, contentY,
5661                mScrollingLayerRect, mScrollingLayerBounds);
5662        if (mScrollingLayer != 0) {
5663            mTouchMode = TOUCH_DRAG_LAYER_MODE;
5664        }
5665    }
5666
5667    // 1/(density * density) used to compute the distance between points.
5668    // Computed in init().
5669    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
5670
5671    // The distance between two points reported in onTouchEvent scaled by the
5672    // density of the screen.
5673    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
5674
5675    @Override
5676    public boolean onHoverEvent(MotionEvent event) {
5677        if (mNativeClass == 0) {
5678            return false;
5679        }
5680        WebViewCore.CursorData data = cursorDataNoPosition();
5681        data.mX = viewToContentX((int) event.getX());
5682        data.mY = viewToContentY((int) event.getY());
5683        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
5684        return true;
5685    }
5686
5687    @Override
5688    public boolean onTouchEvent(MotionEvent ev) {
5689        if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) {
5690            return false;
5691        }
5692
5693        if (DebugFlags.WEB_VIEW) {
5694            Log.v(LOGTAG, ev + " at " + ev.getEventTime()
5695                + " mTouchMode=" + mTouchMode
5696                + " numPointers=" + ev.getPointerCount());
5697        }
5698
5699        // If WebKit wasn't interested in this multitouch gesture, enqueue
5700        // the event for handling directly rather than making the round trip
5701        // to WebKit and back.
5702        if (ev.getPointerCount() > 1 && mPreventDefault != PREVENT_DEFAULT_NO) {
5703            passMultiTouchToWebKit(ev, mTouchEventQueue.nextTouchSequence());
5704        } else {
5705            mTouchEventQueue.enqueueTouchEvent(ev);
5706        }
5707
5708        // Since all events are handled asynchronously, we always want the gesture stream.
5709        return true;
5710    }
5711
5712    /*
5713     * Common code for single touch and multi-touch.
5714     * (x, y) denotes current focus point, which is the touch point for single touch
5715     * and the middle point for multi-touch.
5716     */
5717    private boolean handleTouchEventCommon(MotionEvent ev, int action, int x, int y) {
5718        long eventTime = ev.getEventTime();
5719
5720        // Due to the touch screen edge effect, a touch closer to the edge
5721        // always snapped to the edge. As getViewWidth() can be different from
5722        // getWidth() due to the scrollbar, adjusting the point to match
5723        // getViewWidth(). Same applied to the height.
5724        x = Math.min(x, getViewWidth() - 1);
5725        y = Math.min(y, getViewHeightWithTitle() - 1);
5726
5727        int deltaX = mLastTouchX - x;
5728        int deltaY = mLastTouchY - y;
5729        int contentX = viewToContentX(x + mScrollX);
5730        int contentY = viewToContentY(y + mScrollY);
5731
5732        switch (action) {
5733            case MotionEvent.ACTION_DOWN: {
5734                mPreventDefault = PREVENT_DEFAULT_NO;
5735                mConfirmMove = false;
5736                mInitialHitTestResult = null;
5737                if (!mScroller.isFinished()) {
5738                    // stop the current scroll animation, but if this is
5739                    // the start of a fling, allow it to add to the current
5740                    // fling's velocity
5741                    mScroller.abortAnimation();
5742                    mTouchMode = TOUCH_DRAG_START_MODE;
5743                    mConfirmMove = true;
5744                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5745                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
5746                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
5747                    if (getSettings().supportTouchOnly()) {
5748                        removeTouchHighlight(true);
5749                    }
5750                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
5751                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
5752                    } else {
5753                        // commit the short press action for the previous tap
5754                        doShortPress();
5755                        mTouchMode = TOUCH_INIT_MODE;
5756                        mDeferTouchProcess = !mBlockWebkitViewMessages
5757                                && (!inFullScreenMode() && mForwardTouchEvents)
5758                                ? hitFocusedPlugin(contentX, contentY)
5759                                : false;
5760                    }
5761                } else { // the normal case
5762                    mTouchMode = TOUCH_INIT_MODE;
5763                    mDeferTouchProcess = !mBlockWebkitViewMessages
5764                            && (!inFullScreenMode() && mForwardTouchEvents)
5765                            ? hitFocusedPlugin(contentX, contentY)
5766                            : false;
5767                    if (!mBlockWebkitViewMessages) {
5768                        mWebViewCore.sendMessage(
5769                                EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
5770                    }
5771                    if (getSettings().supportTouchOnly()) {
5772                        TouchHighlightData data = new TouchHighlightData();
5773                        data.mX = contentX;
5774                        data.mY = contentY;
5775                        data.mSlop = viewToContentDimension(mNavSlop);
5776                        if (!mBlockWebkitViewMessages) {
5777                            mWebViewCore.sendMessageDelayed(
5778                                    EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
5779                                    ViewConfiguration.getTapTimeout());
5780                        }
5781                        if (DEBUG_TOUCH_HIGHLIGHT) {
5782                            if (getSettings().getNavDump()) {
5783                                mTouchHighlightX = (int) x + mScrollX;
5784                                mTouchHighlightY = (int) y + mScrollY;
5785                                mPrivateHandler.postDelayed(new Runnable() {
5786                                    public void run() {
5787                                        mTouchHighlightX = mTouchHighlightY = 0;
5788                                        invalidate();
5789                                    }
5790                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
5791                            }
5792                        }
5793                    }
5794                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
5795                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
5796                                (eventTime - mLastTouchUpTime), eventTime);
5797                    }
5798                    if (mSelectingText) {
5799                        mDrawSelectionPointer = false;
5800                        mSelectionStarted = nativeStartSelection(contentX, contentY);
5801                        if (DebugFlags.WEB_VIEW) {
5802                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
5803                        }
5804                        invalidate();
5805                    }
5806                }
5807                // Trigger the link
5808                if (!mSelectingText && (mTouchMode == TOUCH_INIT_MODE
5809                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE)) {
5810                    mPrivateHandler.sendEmptyMessageDelayed(
5811                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
5812                    mPrivateHandler.sendEmptyMessageDelayed(
5813                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
5814                    if (inFullScreenMode() || mDeferTouchProcess) {
5815                        mPreventDefault = PREVENT_DEFAULT_YES;
5816                    } else if (!mBlockWebkitViewMessages && mForwardTouchEvents) {
5817                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
5818                    } else {
5819                        mPreventDefault = PREVENT_DEFAULT_NO;
5820                    }
5821                    // pass the touch events from UI thread to WebCore thread
5822                    if (shouldForwardTouchEvent()) {
5823                        TouchEventData ted = new TouchEventData();
5824                        ted.mAction = action;
5825                        ted.mIds = new int[1];
5826                        ted.mIds[0] = ev.getPointerId(0);
5827                        ted.mPoints = new Point[1];
5828                        ted.mPoints[0] = new Point(contentX, contentY);
5829                        ted.mPointsInView = new Point[1];
5830                        ted.mPointsInView[0] = new Point(x, y);
5831                        ted.mMetaState = ev.getMetaState();
5832                        ted.mReprocess = mDeferTouchProcess;
5833                        ted.mNativeLayer = nativeScrollableLayer(
5834                                contentX, contentY, ted.mNativeLayerRect, null);
5835                        ted.mSequence = mTouchEventQueue.nextTouchSequence();
5836                        mTouchEventQueue.preQueueTouchEventData(ted);
5837                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5838                        if (mDeferTouchProcess) {
5839                            // still needs to set them for compute deltaX/Y
5840                            mLastTouchX = x;
5841                            mLastTouchY = y;
5842                            break;
5843                        }
5844                        if (!inFullScreenMode()) {
5845                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
5846                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
5847                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5848                                            action, 0), TAP_TIMEOUT);
5849                        }
5850                    }
5851                }
5852                startTouch(x, y, eventTime);
5853                break;
5854            }
5855            case MotionEvent.ACTION_MOVE: {
5856                boolean firstMove = false;
5857                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
5858                        >= mTouchSlopSquare) {
5859                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5860                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5861                    mConfirmMove = true;
5862                    firstMove = true;
5863                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5864                        mTouchMode = TOUCH_INIT_MODE;
5865                    }
5866                    if (getSettings().supportTouchOnly()) {
5867                        removeTouchHighlight(true);
5868                    }
5869                }
5870                // pass the touch events from UI thread to WebCore thread
5871                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
5872                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
5873                    TouchEventData ted = new TouchEventData();
5874                    ted.mAction = action;
5875                    ted.mIds = new int[1];
5876                    ted.mIds[0] = ev.getPointerId(0);
5877                    ted.mPoints = new Point[1];
5878                    ted.mPoints[0] = new Point(contentX, contentY);
5879                    ted.mPointsInView = new Point[1];
5880                    ted.mPointsInView[0] = new Point(x, y);
5881                    ted.mMetaState = ev.getMetaState();
5882                    ted.mReprocess = mDeferTouchProcess;
5883                    ted.mNativeLayer = mScrollingLayer;
5884                    ted.mNativeLayerRect.set(mScrollingLayerRect);
5885                    ted.mSequence = mTouchEventQueue.nextTouchSequence();
5886                    mTouchEventQueue.preQueueTouchEventData(ted);
5887                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5888                    mLastSentTouchTime = eventTime;
5889                    if (mDeferTouchProcess) {
5890                        break;
5891                    }
5892                    if (firstMove && !inFullScreenMode()) {
5893                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
5894                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5895                                        action, 0), TAP_TIMEOUT);
5896                    }
5897                }
5898                if (mTouchMode == TOUCH_DONE_MODE
5899                        || mPreventDefault == PREVENT_DEFAULT_YES) {
5900                    // no dragging during scroll zoom animation, or when prevent
5901                    // default is yes
5902                    break;
5903                }
5904                if (mVelocityTracker == null) {
5905                    Log.e(LOGTAG, "Got null mVelocityTracker when "
5906                            + "mPreventDefault = " + mPreventDefault
5907                            + " mDeferTouchProcess = " + mDeferTouchProcess
5908                            + " mTouchMode = " + mTouchMode);
5909                } else {
5910                    mVelocityTracker.addMovement(ev);
5911                }
5912                if (mSelectingText && mSelectionStarted) {
5913                    if (DebugFlags.WEB_VIEW) {
5914                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
5915                    }
5916                    ViewParent parent = getParent();
5917                    if (parent != null) {
5918                        parent.requestDisallowInterceptTouchEvent(true);
5919                    }
5920                    mAutoScrollX = x <= mMinAutoScrollX ? -SELECT_SCROLL
5921                            : x >= mMaxAutoScrollX ? SELECT_SCROLL : 0;
5922                    mAutoScrollY = y <= mMinAutoScrollY ? -SELECT_SCROLL
5923                            : y >= mMaxAutoScrollY ? SELECT_SCROLL : 0;
5924                    if ((mAutoScrollX != 0 || mAutoScrollY != 0)
5925                            && !mSentAutoScrollMessage) {
5926                        mSentAutoScrollMessage = true;
5927                        mPrivateHandler.sendEmptyMessageDelayed(
5928                                SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
5929                    }
5930                    if (deltaX != 0 || deltaY != 0) {
5931                        nativeExtendSelection(contentX, contentY);
5932                        invalidate();
5933                    }
5934                    break;
5935                }
5936
5937                if (mTouchMode != TOUCH_DRAG_MODE &&
5938                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5939
5940                    if (!mConfirmMove) {
5941                        break;
5942                    }
5943
5944                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
5945                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
5946                        // track mLastTouchTime as we may need to do fling at
5947                        // ACTION_UP
5948                        mLastTouchTime = eventTime;
5949                        break;
5950                    }
5951
5952                    // Only lock dragging to one axis if we don't have a scale in progress.
5953                    // Scaling implies free-roaming movement. Note this is only ever a question
5954                    // if mZoomManager.supportsPanDuringZoom() is true.
5955                    final ScaleGestureDetector detector =
5956                      mZoomManager.getMultiTouchGestureDetector();
5957                    if (detector == null || !detector.isInProgress()) {
5958                        // if it starts nearly horizontal or vertical, enforce it
5959                        int ax = Math.abs(deltaX);
5960                        int ay = Math.abs(deltaY);
5961                        if (ax > MAX_SLOPE_FOR_DIAG * ay) {
5962                            mSnapScrollMode = SNAP_X;
5963                            mSnapPositive = deltaX > 0;
5964                        } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
5965                            mSnapScrollMode = SNAP_Y;
5966                            mSnapPositive = deltaY > 0;
5967                        }
5968                    }
5969
5970                    mTouchMode = TOUCH_DRAG_MODE;
5971                    mLastTouchX = x;
5972                    mLastTouchY = y;
5973                    deltaX = 0;
5974                    deltaY = 0;
5975
5976                    startScrollingLayer(x, y);
5977                    startDrag();
5978                }
5979
5980                // do pan
5981                boolean done = false;
5982                boolean keepScrollBarsVisible = false;
5983                if (deltaX == 0 && deltaY == 0) {
5984                    keepScrollBarsVisible = done = true;
5985                } else {
5986                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
5987                        int ax = Math.abs(deltaX);
5988                        int ay = Math.abs(deltaY);
5989                        if (mSnapScrollMode == SNAP_X) {
5990                            // radical change means getting out of snap mode
5991                            if (ay > MAX_SLOPE_FOR_DIAG * ax
5992                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5993                                mSnapScrollMode = SNAP_NONE;
5994                            }
5995                            // reverse direction means lock in the snap mode
5996                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
5997                                    (mSnapPositive
5998                                    ? deltaX < -mMinLockSnapReverseDistance
5999                                    : deltaX > mMinLockSnapReverseDistance)) {
6000                                mSnapScrollMode |= SNAP_LOCK;
6001                            }
6002                        } else {
6003                            // radical change means getting out of snap mode
6004                            if (ax > MAX_SLOPE_FOR_DIAG * ay
6005                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
6006                                mSnapScrollMode = SNAP_NONE;
6007                            }
6008                            // reverse direction means lock in the snap mode
6009                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
6010                                    (mSnapPositive
6011                                    ? deltaY < -mMinLockSnapReverseDistance
6012                                    : deltaY > mMinLockSnapReverseDistance)) {
6013                                mSnapScrollMode |= SNAP_LOCK;
6014                            }
6015                        }
6016                    }
6017                    if (mSnapScrollMode != SNAP_NONE) {
6018                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6019                            deltaY = 0;
6020                        } else {
6021                            deltaX = 0;
6022                        }
6023                    }
6024                    if ((deltaX | deltaY) != 0) {
6025                        if (deltaX != 0) {
6026                            mLastTouchX = x;
6027                        }
6028                        if (deltaY != 0) {
6029                            mLastTouchY = y;
6030                        }
6031                        mHeldMotionless = MOTIONLESS_FALSE;
6032                    }
6033                    mLastTouchTime = eventTime;
6034                }
6035
6036                doDrag(deltaX, deltaY);
6037
6038                // Turn off scrollbars when dragging a layer.
6039                if (keepScrollBarsVisible &&
6040                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6041                    if (mHeldMotionless != MOTIONLESS_TRUE) {
6042                        mHeldMotionless = MOTIONLESS_TRUE;
6043                        invalidate();
6044                    }
6045                    // keep the scrollbar on the screen even there is no scroll
6046                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
6047                            false);
6048                    // return false to indicate that we can't pan out of the
6049                    // view space
6050                    return !done;
6051                }
6052                break;
6053            }
6054            case MotionEvent.ACTION_UP: {
6055                if (!isFocused()) requestFocus();
6056                // pass the touch events from UI thread to WebCore thread
6057                if (shouldForwardTouchEvent()) {
6058                    TouchEventData ted = new TouchEventData();
6059                    ted.mIds = new int[1];
6060                    ted.mIds[0] = ev.getPointerId(0);
6061                    ted.mAction = action;
6062                    ted.mPoints = new Point[1];
6063                    ted.mPoints[0] = new Point(contentX, contentY);
6064                    ted.mPointsInView = new Point[1];
6065                    ted.mPointsInView[0] = new Point(x, y);
6066                    ted.mMetaState = ev.getMetaState();
6067                    ted.mReprocess = mDeferTouchProcess;
6068                    ted.mNativeLayer = mScrollingLayer;
6069                    ted.mNativeLayerRect.set(mScrollingLayerRect);
6070                    ted.mSequence = mTouchEventQueue.nextTouchSequence();
6071                    mTouchEventQueue.preQueueTouchEventData(ted);
6072                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6073                }
6074                mLastTouchUpTime = eventTime;
6075                if (mSentAutoScrollMessage) {
6076                    mAutoScrollX = mAutoScrollY = 0;
6077                }
6078                switch (mTouchMode) {
6079                    case TOUCH_DOUBLE_TAP_MODE: // double tap
6080                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6081                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6082                        if (inFullScreenMode() || mDeferTouchProcess) {
6083                            TouchEventData ted = new TouchEventData();
6084                            ted.mIds = new int[1];
6085                            ted.mIds[0] = ev.getPointerId(0);
6086                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
6087                            ted.mPoints = new Point[1];
6088                            ted.mPoints[0] = new Point(contentX, contentY);
6089                            ted.mPointsInView = new Point[1];
6090                            ted.mPointsInView[0] = new Point(x, y);
6091                            ted.mMetaState = ev.getMetaState();
6092                            ted.mReprocess = mDeferTouchProcess;
6093                            ted.mNativeLayer = nativeScrollableLayer(
6094                                    contentX, contentY,
6095                                    ted.mNativeLayerRect, null);
6096                            ted.mSequence = mTouchEventQueue.nextTouchSequence();
6097                            mTouchEventQueue.preQueueTouchEventData(ted);
6098                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6099                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
6100                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
6101                            mTouchMode = TOUCH_DONE_MODE;
6102                        }
6103                        break;
6104                    case TOUCH_INIT_MODE: // tap
6105                    case TOUCH_SHORTPRESS_START_MODE:
6106                    case TOUCH_SHORTPRESS_MODE:
6107                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6108                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6109                        if (mConfirmMove) {
6110                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
6111                                    " WebCore's response for touch down.");
6112                            if (mPreventDefault != PREVENT_DEFAULT_YES
6113                                    && (computeMaxScrollX() > 0
6114                                            || computeMaxScrollY() > 0)) {
6115                                // If the user has performed a very quick touch
6116                                // sequence it is possible that we may get here
6117                                // before WebCore has had a chance to process the events.
6118                                // In this case, any call to preventDefault in the
6119                                // JS touch handler will not have been executed yet.
6120                                // Hence we will see both the UI (now) and WebCore
6121                                // (when context switches) handling the event,
6122                                // regardless of whether the web developer actually
6123                                // doeses preventDefault in their touch handler. This
6124                                // is the nature of our asynchronous touch model.
6125
6126                                // we will not rewrite drag code here, but we
6127                                // will try fling if it applies.
6128                                WebViewCore.reducePriority();
6129                                // to get better performance, pause updating the
6130                                // picture
6131                                WebViewCore.pauseUpdatePicture(mWebViewCore);
6132                                // fall through to TOUCH_DRAG_MODE
6133                            } else {
6134                                // WebKit may consume the touch event and modify
6135                                // DOM. drawContentPicture() will be called with
6136                                // animateSroll as true for better performance.
6137                                // Force redraw in high-quality.
6138                                invalidate();
6139                                break;
6140                            }
6141                        } else {
6142                            if (mSelectingText) {
6143                                // tapping on selection or controls does nothing
6144                                if (!nativeHitSelection(contentX, contentY)) {
6145                                    selectionDone();
6146                                }
6147                                break;
6148                            }
6149                            // only trigger double tap if the WebView is
6150                            // scalable
6151                            if (mTouchMode == TOUCH_INIT_MODE
6152                                    && (canZoomIn() || canZoomOut())) {
6153                                mPrivateHandler.sendEmptyMessageDelayed(
6154                                        RELEASE_SINGLE_TAP, ViewConfiguration
6155                                                .getDoubleTapTimeout());
6156                            } else {
6157                                doShortPress();
6158                            }
6159                            break;
6160                        }
6161                    case TOUCH_DRAG_MODE:
6162                    case TOUCH_DRAG_LAYER_MODE:
6163                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6164                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6165                        // if the user waits a while w/o moving before the
6166                        // up, we don't want to do a fling
6167                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
6168                            if (mVelocityTracker == null) {
6169                                Log.e(LOGTAG, "Got null mVelocityTracker when "
6170                                        + "mPreventDefault = "
6171                                        + mPreventDefault
6172                                        + " mDeferTouchProcess = "
6173                                        + mDeferTouchProcess);
6174                            } else {
6175                                mVelocityTracker.addMovement(ev);
6176                            }
6177                            // set to MOTIONLESS_IGNORE so that it won't keep
6178                            // removing and sending message in
6179                            // drawCoreAndCursorRing()
6180                            mHeldMotionless = MOTIONLESS_IGNORE;
6181                            doFling();
6182                            break;
6183                        } else {
6184                            if (mScroller.springBack(mScrollX, mScrollY, 0,
6185                                    computeMaxScrollX(), 0,
6186                                    computeMaxScrollY())) {
6187                                invalidate();
6188                            }
6189                        }
6190                        // redraw in high-quality, as we're done dragging
6191                        mHeldMotionless = MOTIONLESS_TRUE;
6192                        invalidate();
6193                        // fall through
6194                    case TOUCH_DRAG_START_MODE:
6195                        // TOUCH_DRAG_START_MODE should not happen for the real
6196                        // device as we almost certain will get a MOVE. But this
6197                        // is possible on emulator.
6198                        mLastVelocity = 0;
6199                        WebViewCore.resumePriority();
6200                        if (!mSelectingText) {
6201                            WebViewCore.resumeUpdatePicture(mWebViewCore);
6202                        }
6203                        break;
6204                }
6205                stopTouch();
6206                break;
6207            }
6208            case MotionEvent.ACTION_CANCEL: {
6209                if (mTouchMode == TOUCH_DRAG_MODE) {
6210                    mScroller.springBack(mScrollX, mScrollY, 0,
6211                            computeMaxScrollX(), 0, computeMaxScrollY());
6212                    invalidate();
6213                }
6214                cancelWebCoreTouchEvent(contentX, contentY, false);
6215                cancelTouch();
6216                break;
6217            }
6218        }
6219        return true;
6220    }
6221
6222    private void passMultiTouchToWebKit(MotionEvent ev, long sequence) {
6223        TouchEventData ted = new TouchEventData();
6224        ted.mAction = ev.getActionMasked();
6225        final int count = ev.getPointerCount();
6226        ted.mIds = new int[count];
6227        ted.mPoints = new Point[count];
6228        ted.mPointsInView = new Point[count];
6229        for (int c = 0; c < count; c++) {
6230            ted.mIds[c] = ev.getPointerId(c);
6231            int x = viewToContentX((int) ev.getX(c) + mScrollX);
6232            int y = viewToContentY((int) ev.getY(c) + mScrollY);
6233            ted.mPoints[c] = new Point(x, y);
6234            ted.mPointsInView[c] = new Point((int) ev.getX(c), (int) ev.getY(c));
6235        }
6236        if (ted.mAction == MotionEvent.ACTION_POINTER_DOWN
6237            || ted.mAction == MotionEvent.ACTION_POINTER_UP) {
6238            ted.mActionIndex = ev.getActionIndex();
6239        }
6240        ted.mMetaState = ev.getMetaState();
6241        ted.mReprocess = true;
6242        ted.mMotionEvent = MotionEvent.obtain(ev);
6243        ted.mSequence = sequence;
6244        mTouchEventQueue.preQueueTouchEventData(ted);
6245        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6246        cancelLongPress();
6247        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6248    }
6249
6250    void handleMultiTouchInWebView(MotionEvent ev) {
6251        if (DebugFlags.WEB_VIEW) {
6252            Log.v(LOGTAG, "multi-touch: " + ev + " at " + ev.getEventTime()
6253                + " mTouchMode=" + mTouchMode
6254                + " numPointers=" + ev.getPointerCount()
6255                + " scrolloffset=(" + mScrollX + "," + mScrollY + ")");
6256        }
6257
6258        final ScaleGestureDetector detector =
6259            mZoomManager.getMultiTouchGestureDetector();
6260
6261        // A few apps use WebView but don't instantiate gesture detector.
6262        // We don't need to support multi touch for them.
6263        if (detector == null) return;
6264
6265        float x = ev.getX();
6266        float y = ev.getY();
6267
6268        if (mPreventDefault != PREVENT_DEFAULT_YES) {
6269            detector.onTouchEvent(ev);
6270
6271            if (detector.isInProgress()) {
6272                if (DebugFlags.WEB_VIEW) {
6273                    Log.v(LOGTAG, "detector is in progress");
6274                }
6275                mLastTouchTime = ev.getEventTime();
6276                x = detector.getFocusX();
6277                y = detector.getFocusY();
6278
6279                cancelLongPress();
6280                mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6281                if (!mZoomManager.supportsPanDuringZoom()) {
6282                    return;
6283                }
6284                mTouchMode = TOUCH_DRAG_MODE;
6285                if (mVelocityTracker == null) {
6286                    mVelocityTracker = VelocityTracker.obtain();
6287                }
6288            }
6289        }
6290
6291        int action = ev.getActionMasked();
6292        if (action == MotionEvent.ACTION_POINTER_DOWN) {
6293            cancelTouch();
6294            action = MotionEvent.ACTION_DOWN;
6295        } else if (action == MotionEvent.ACTION_POINTER_UP && ev.getPointerCount() == 2) {
6296            // set mLastTouchX/Y to the remaining point
6297            mLastTouchX = Math.round(x);
6298            mLastTouchY = Math.round(y);
6299        } else if (action == MotionEvent.ACTION_MOVE) {
6300            // negative x or y indicate it is on the edge, skip it.
6301            if (x < 0 || y < 0) {
6302                return;
6303            }
6304        }
6305
6306        handleTouchEventCommon(ev, action, Math.round(x), Math.round(y));
6307    }
6308
6309    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
6310        if (shouldForwardTouchEvent()) {
6311            if (removeEvents) {
6312                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
6313            }
6314            TouchEventData ted = new TouchEventData();
6315            ted.mIds = new int[1];
6316            ted.mIds[0] = 0;
6317            ted.mPoints = new Point[1];
6318            ted.mPoints[0] = new Point(x, y);
6319            ted.mPointsInView = new Point[1];
6320            int viewX = contentToViewX(x) - mScrollX;
6321            int viewY = contentToViewY(y) - mScrollY;
6322            ted.mPointsInView[0] = new Point(viewX, viewY);
6323            ted.mAction = MotionEvent.ACTION_CANCEL;
6324            ted.mNativeLayer = nativeScrollableLayer(
6325                    x, y, ted.mNativeLayerRect, null);
6326            ted.mSequence = mTouchEventQueue.nextTouchSequence();
6327            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6328            mPreventDefault = PREVENT_DEFAULT_IGNORE;
6329
6330            if (removeEvents) {
6331                // Mark this after sending the message above; we should
6332                // be willing to ignore the cancel event that we just sent.
6333                mTouchEventQueue.ignoreCurrentlyMissingEvents();
6334            }
6335        }
6336    }
6337
6338    private void startTouch(float x, float y, long eventTime) {
6339        // Remember where the motion event started
6340        mLastTouchX = Math.round(x);
6341        mLastTouchY = Math.round(y);
6342        mLastTouchTime = eventTime;
6343        mVelocityTracker = VelocityTracker.obtain();
6344        mSnapScrollMode = SNAP_NONE;
6345    }
6346
6347    private void startDrag() {
6348        WebViewCore.reducePriority();
6349        // to get better performance, pause updating the picture
6350        WebViewCore.pauseUpdatePicture(mWebViewCore);
6351        if (!mDragFromTextInput) {
6352            nativeHideCursor();
6353        }
6354
6355        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
6356                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
6357            mZoomManager.invokeZoomPicker();
6358        }
6359    }
6360
6361    private void doDrag(int deltaX, int deltaY) {
6362        if ((deltaX | deltaY) != 0) {
6363            int oldX = mScrollX;
6364            int oldY = mScrollY;
6365            int rangeX = computeMaxScrollX();
6366            int rangeY = computeMaxScrollY();
6367            int overscrollDistance = mOverscrollDistance;
6368
6369            // Check for the original scrolling layer in case we change
6370            // directions.  mTouchMode might be TOUCH_DRAG_MODE if we have
6371            // reached the edge of a layer but mScrollingLayer will be non-zero
6372            // if we initiated the drag on a layer.
6373            if (mScrollingLayer != 0) {
6374                final int contentX = viewToContentDimension(deltaX);
6375                final int contentY = viewToContentDimension(deltaY);
6376
6377                // Check the scrolling bounds to see if we will actually do any
6378                // scrolling.  The rectangle is in document coordinates.
6379                final int maxX = mScrollingLayerRect.right;
6380                final int maxY = mScrollingLayerRect.bottom;
6381                final int resultX = Math.max(0,
6382                        Math.min(mScrollingLayerRect.left + contentX, maxX));
6383                final int resultY = Math.max(0,
6384                        Math.min(mScrollingLayerRect.top + contentY, maxY));
6385
6386                if (resultX != mScrollingLayerRect.left ||
6387                        resultY != mScrollingLayerRect.top) {
6388                    // In case we switched to dragging the page.
6389                    mTouchMode = TOUCH_DRAG_LAYER_MODE;
6390                    deltaX = contentX;
6391                    deltaY = contentY;
6392                    oldX = mScrollingLayerRect.left;
6393                    oldY = mScrollingLayerRect.top;
6394                    rangeX = maxX;
6395                    rangeY = maxY;
6396                } else {
6397                    // Scroll the main page if we are not going to scroll the
6398                    // layer.  This does not reset mScrollingLayer in case the
6399                    // user changes directions and the layer can scroll the
6400                    // other way.
6401                    mTouchMode = TOUCH_DRAG_MODE;
6402                }
6403            }
6404
6405            if (mOverScrollGlow != null) {
6406                mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
6407            }
6408
6409            overScrollBy(deltaX, deltaY, oldX, oldY,
6410                    rangeX, rangeY,
6411                    mOverscrollDistance, mOverscrollDistance, true);
6412            if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
6413                invalidate();
6414            }
6415        }
6416        mZoomManager.keepZoomPickerVisible();
6417    }
6418
6419    private void stopTouch() {
6420        // we also use mVelocityTracker == null to tell us that we are
6421        // not "moving around", so we can take the slower/prettier
6422        // mode in the drawing code
6423        if (mVelocityTracker != null) {
6424            mVelocityTracker.recycle();
6425            mVelocityTracker = null;
6426        }
6427
6428        // Release any pulled glows
6429        if (mOverScrollGlow != null) {
6430            mOverScrollGlow.releaseAll();
6431        }
6432    }
6433
6434    private void cancelTouch() {
6435        // we also use mVelocityTracker == null to tell us that we are
6436        // not "moving around", so we can take the slower/prettier
6437        // mode in the drawing code
6438        if (mVelocityTracker != null) {
6439            mVelocityTracker.recycle();
6440            mVelocityTracker = null;
6441        }
6442
6443        if ((mTouchMode == TOUCH_DRAG_MODE
6444                || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
6445            WebViewCore.resumePriority();
6446            WebViewCore.resumeUpdatePicture(mWebViewCore);
6447        }
6448        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6449        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6450        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6451        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6452        if (getSettings().supportTouchOnly()) {
6453            removeTouchHighlight(true);
6454        }
6455        mHeldMotionless = MOTIONLESS_TRUE;
6456        mTouchMode = TOUCH_DONE_MODE;
6457        nativeHideCursor();
6458    }
6459
6460    @Override
6461    public boolean onGenericMotionEvent(MotionEvent event) {
6462        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6463            switch (event.getAction()) {
6464                case MotionEvent.ACTION_SCROLL: {
6465                    final float vscroll;
6466                    final float hscroll;
6467                    if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
6468                        vscroll = 0;
6469                        hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6470                    } else {
6471                        vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6472                        hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
6473                    }
6474                    if (hscroll != 0 || vscroll != 0) {
6475                        final int vdelta = (int) (vscroll * getVerticalScrollFactor());
6476                        final int hdelta = (int) (hscroll * getHorizontalScrollFactor());
6477                        if (pinScrollBy(hdelta, vdelta, false, 0)) {
6478                            return true;
6479                        }
6480                    }
6481                }
6482            }
6483        }
6484        return super.onGenericMotionEvent(event);
6485    }
6486
6487    private long mTrackballFirstTime = 0;
6488    private long mTrackballLastTime = 0;
6489    private float mTrackballRemainsX = 0.0f;
6490    private float mTrackballRemainsY = 0.0f;
6491    private int mTrackballXMove = 0;
6492    private int mTrackballYMove = 0;
6493    private boolean mSelectingText = false;
6494    private boolean mSelectionStarted = false;
6495    private boolean mExtendSelection = false;
6496    private boolean mDrawSelectionPointer = false;
6497    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
6498    private static final int TRACKBALL_TIMEOUT = 200;
6499    private static final int TRACKBALL_WAIT = 100;
6500    private static final int TRACKBALL_SCALE = 400;
6501    private static final int TRACKBALL_SCROLL_COUNT = 5;
6502    private static final int TRACKBALL_MOVE_COUNT = 10;
6503    private static final int TRACKBALL_MULTIPLIER = 3;
6504    private static final int SELECT_CURSOR_OFFSET = 16;
6505    private static final int SELECT_SCROLL = 5;
6506    private int mSelectX = 0;
6507    private int mSelectY = 0;
6508    private boolean mFocusSizeChanged = false;
6509    private boolean mTrackballDown = false;
6510    private long mTrackballUpTime = 0;
6511    private long mLastCursorTime = 0;
6512    private Rect mLastCursorBounds;
6513
6514    // Set by default; BrowserActivity clears to interpret trackball data
6515    // directly for movement. Currently, the framework only passes
6516    // arrow key events, not trackball events, from one child to the next
6517    private boolean mMapTrackballToArrowKeys = true;
6518
6519    private DrawData mDelaySetPicture;
6520    private DrawData mLoadedPicture;
6521
6522    public void setMapTrackballToArrowKeys(boolean setMap) {
6523        checkThread();
6524        mMapTrackballToArrowKeys = setMap;
6525    }
6526
6527    void resetTrackballTime() {
6528        mTrackballLastTime = 0;
6529    }
6530
6531    @Override
6532    public boolean onTrackballEvent(MotionEvent ev) {
6533        long time = ev.getEventTime();
6534        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
6535            if (ev.getY() > 0) pageDown(true);
6536            if (ev.getY() < 0) pageUp(true);
6537            return true;
6538        }
6539        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
6540            if (mSelectingText) {
6541                return true; // discard press if copy in progress
6542            }
6543            mTrackballDown = true;
6544            if (mNativeClass == 0) {
6545                return false;
6546            }
6547            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
6548            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
6549                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
6550                nativeSelectBestAt(mLastCursorBounds);
6551            }
6552            if (DebugFlags.WEB_VIEW) {
6553                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
6554                        + " time=" + time
6555                        + " mLastCursorTime=" + mLastCursorTime);
6556            }
6557            if (isInTouchMode()) requestFocusFromTouch();
6558            return false; // let common code in onKeyDown at it
6559        }
6560        if (ev.getAction() == MotionEvent.ACTION_UP) {
6561            // LONG_PRESS_CENTER is set in common onKeyDown
6562            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
6563            mTrackballDown = false;
6564            mTrackballUpTime = time;
6565            if (mSelectingText) {
6566                if (mExtendSelection) {
6567                    copySelection();
6568                    selectionDone();
6569                } else {
6570                    mExtendSelection = true;
6571                    nativeSetExtendSelection();
6572                    invalidate(); // draw the i-beam instead of the arrow
6573                }
6574                return true; // discard press if copy in progress
6575            }
6576            if (DebugFlags.WEB_VIEW) {
6577                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
6578                        + " time=" + time
6579                );
6580            }
6581            return false; // let common code in onKeyUp at it
6582        }
6583        if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
6584                AccessibilityManager.getInstance(mContext).isEnabled()) {
6585            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
6586            return false;
6587        }
6588        if (mTrackballDown) {
6589            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
6590            return true; // discard move if trackball is down
6591        }
6592        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
6593            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
6594            return true;
6595        }
6596        // TODO: alternatively we can do panning as touch does
6597        switchOutDrawHistory();
6598        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
6599            if (DebugFlags.WEB_VIEW) {
6600                Log.v(LOGTAG, "onTrackballEvent time="
6601                        + time + " last=" + mTrackballLastTime);
6602            }
6603            mTrackballFirstTime = time;
6604            mTrackballXMove = mTrackballYMove = 0;
6605        }
6606        mTrackballLastTime = time;
6607        if (DebugFlags.WEB_VIEW) {
6608            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
6609        }
6610        mTrackballRemainsX += ev.getX();
6611        mTrackballRemainsY += ev.getY();
6612        doTrackball(time, ev.getMetaState());
6613        return true;
6614    }
6615
6616    void moveSelection(float xRate, float yRate) {
6617        if (mNativeClass == 0)
6618            return;
6619        int width = getViewWidth();
6620        int height = getViewHeight();
6621        mSelectX += xRate;
6622        mSelectY += yRate;
6623        int maxX = width + mScrollX;
6624        int maxY = height + mScrollY;
6625        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
6626                , mSelectX));
6627        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
6628                , mSelectY));
6629        if (DebugFlags.WEB_VIEW) {
6630            Log.v(LOGTAG, "moveSelection"
6631                    + " mSelectX=" + mSelectX
6632                    + " mSelectY=" + mSelectY
6633                    + " mScrollX=" + mScrollX
6634                    + " mScrollY=" + mScrollY
6635                    + " xRate=" + xRate
6636                    + " yRate=" + yRate
6637                    );
6638        }
6639        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
6640        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
6641                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6642                : 0;
6643        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
6644                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6645                : 0;
6646        pinScrollBy(scrollX, scrollY, true, 0);
6647        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
6648        requestRectangleOnScreen(select);
6649        invalidate();
6650   }
6651
6652    private int scaleTrackballX(float xRate, int width) {
6653        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
6654        int nextXMove = xMove;
6655        if (xMove > 0) {
6656            if (xMove > mTrackballXMove) {
6657                xMove -= mTrackballXMove;
6658            }
6659        } else if (xMove < mTrackballXMove) {
6660            xMove -= mTrackballXMove;
6661        }
6662        mTrackballXMove = nextXMove;
6663        return xMove;
6664    }
6665
6666    private int scaleTrackballY(float yRate, int height) {
6667        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
6668        int nextYMove = yMove;
6669        if (yMove > 0) {
6670            if (yMove > mTrackballYMove) {
6671                yMove -= mTrackballYMove;
6672            }
6673        } else if (yMove < mTrackballYMove) {
6674            yMove -= mTrackballYMove;
6675        }
6676        mTrackballYMove = nextYMove;
6677        return yMove;
6678    }
6679
6680    private int keyCodeToSoundsEffect(int keyCode) {
6681        switch(keyCode) {
6682            case KeyEvent.KEYCODE_DPAD_UP:
6683                return SoundEffectConstants.NAVIGATION_UP;
6684            case KeyEvent.KEYCODE_DPAD_RIGHT:
6685                return SoundEffectConstants.NAVIGATION_RIGHT;
6686            case KeyEvent.KEYCODE_DPAD_DOWN:
6687                return SoundEffectConstants.NAVIGATION_DOWN;
6688            case KeyEvent.KEYCODE_DPAD_LEFT:
6689                return SoundEffectConstants.NAVIGATION_LEFT;
6690        }
6691        throw new IllegalArgumentException("keyCode must be one of " +
6692                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
6693                "KEYCODE_DPAD_LEFT}.");
6694    }
6695
6696    private void doTrackball(long time, int metaState) {
6697        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
6698        if (elapsed == 0) {
6699            elapsed = TRACKBALL_TIMEOUT;
6700        }
6701        float xRate = mTrackballRemainsX * 1000 / elapsed;
6702        float yRate = mTrackballRemainsY * 1000 / elapsed;
6703        int viewWidth = getViewWidth();
6704        int viewHeight = getViewHeight();
6705        if (mSelectingText) {
6706            if (!mDrawSelectionPointer) {
6707                // The last selection was made by touch, disabling drawing the
6708                // selection pointer. Allow the trackball to adjust the
6709                // position of the touch control.
6710                mSelectX = contentToViewX(nativeSelectionX());
6711                mSelectY = contentToViewY(nativeSelectionY());
6712                mDrawSelectionPointer = mExtendSelection = true;
6713                nativeSetExtendSelection();
6714            }
6715            moveSelection(scaleTrackballX(xRate, viewWidth),
6716                    scaleTrackballY(yRate, viewHeight));
6717            mTrackballRemainsX = mTrackballRemainsY = 0;
6718            return;
6719        }
6720        float ax = Math.abs(xRate);
6721        float ay = Math.abs(yRate);
6722        float maxA = Math.max(ax, ay);
6723        if (DebugFlags.WEB_VIEW) {
6724            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
6725                    + " xRate=" + xRate
6726                    + " yRate=" + yRate
6727                    + " mTrackballRemainsX=" + mTrackballRemainsX
6728                    + " mTrackballRemainsY=" + mTrackballRemainsY);
6729        }
6730        int width = mContentWidth - viewWidth;
6731        int height = mContentHeight - viewHeight;
6732        if (width < 0) width = 0;
6733        if (height < 0) height = 0;
6734        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
6735        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
6736        maxA = Math.max(ax, ay);
6737        int count = Math.max(0, (int) maxA);
6738        int oldScrollX = mScrollX;
6739        int oldScrollY = mScrollY;
6740        if (count > 0) {
6741            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
6742                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
6743                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
6744                    KeyEvent.KEYCODE_DPAD_RIGHT;
6745            count = Math.min(count, TRACKBALL_MOVE_COUNT);
6746            if (DebugFlags.WEB_VIEW) {
6747                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
6748                        + " count=" + count
6749                        + " mTrackballRemainsX=" + mTrackballRemainsX
6750                        + " mTrackballRemainsY=" + mTrackballRemainsY);
6751            }
6752            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
6753                for (int i = 0; i < count; i++) {
6754                    letPageHandleNavKey(selectKeyCode, time, true, metaState);
6755                }
6756                letPageHandleNavKey(selectKeyCode, time, false, metaState);
6757            } else if (navHandledKey(selectKeyCode, count, false, time)) {
6758                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
6759            }
6760            mTrackballRemainsX = mTrackballRemainsY = 0;
6761        }
6762        if (count >= TRACKBALL_SCROLL_COUNT) {
6763            int xMove = scaleTrackballX(xRate, width);
6764            int yMove = scaleTrackballY(yRate, height);
6765            if (DebugFlags.WEB_VIEW) {
6766                Log.v(LOGTAG, "doTrackball pinScrollBy"
6767                        + " count=" + count
6768                        + " xMove=" + xMove + " yMove=" + yMove
6769                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
6770                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
6771                        );
6772            }
6773            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
6774                xMove = 0;
6775            }
6776            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
6777                yMove = 0;
6778            }
6779            if (xMove != 0 || yMove != 0) {
6780                pinScrollBy(xMove, yMove, true, 0);
6781            }
6782        }
6783    }
6784
6785    /**
6786     * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
6787     * @return Maximum horizontal scroll position within real content
6788     */
6789    int computeMaxScrollX() {
6790        return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
6791    }
6792
6793    /**
6794     * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
6795     * @return Maximum vertical scroll position within real content
6796     */
6797    int computeMaxScrollY() {
6798        return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
6799                - getViewHeightWithTitle(), 0);
6800    }
6801
6802    boolean updateScrollCoordinates(int x, int y) {
6803        int oldX = mScrollX;
6804        int oldY = mScrollY;
6805        mScrollX = x;
6806        mScrollY = y;
6807        if (oldX != mScrollX || oldY != mScrollY) {
6808            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
6809            return true;
6810        } else {
6811            return false;
6812        }
6813    }
6814
6815    public void flingScroll(int vx, int vy) {
6816        checkThread();
6817        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
6818                computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
6819        invalidate();
6820    }
6821
6822    private void doFling() {
6823        if (mVelocityTracker == null) {
6824            return;
6825        }
6826        int maxX = computeMaxScrollX();
6827        int maxY = computeMaxScrollY();
6828
6829        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
6830        int vx = (int) mVelocityTracker.getXVelocity();
6831        int vy = (int) mVelocityTracker.getYVelocity();
6832
6833        int scrollX = mScrollX;
6834        int scrollY = mScrollY;
6835        int overscrollDistance = mOverscrollDistance;
6836        int overflingDistance = mOverflingDistance;
6837
6838        // Use the layer's scroll data if applicable.
6839        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
6840            scrollX = mScrollingLayerRect.left;
6841            scrollY = mScrollingLayerRect.top;
6842            maxX = mScrollingLayerRect.right;
6843            maxY = mScrollingLayerRect.bottom;
6844            // No overscrolling for layers.
6845            overscrollDistance = overflingDistance = 0;
6846        }
6847
6848        if (mSnapScrollMode != SNAP_NONE) {
6849            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6850                vy = 0;
6851            } else {
6852                vx = 0;
6853            }
6854        }
6855        if (true /* EMG release: make our fling more like Maps' */) {
6856            // maps cuts their velocity in half
6857            vx = vx * 3 / 4;
6858            vy = vy * 3 / 4;
6859        }
6860        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
6861            WebViewCore.resumePriority();
6862            if (!mSelectingText) {
6863                WebViewCore.resumeUpdatePicture(mWebViewCore);
6864            }
6865            if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) {
6866                invalidate();
6867            }
6868            return;
6869        }
6870        float currentVelocity = mScroller.getCurrVelocity();
6871        float velocity = (float) Math.hypot(vx, vy);
6872        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
6873                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
6874            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
6875                    - Math.atan2(vy, vx)));
6876            final float circle = (float) (Math.PI) * 2.0f;
6877            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
6878                vx += currentVelocity * mLastVelX / mLastVelocity;
6879                vy += currentVelocity * mLastVelY / mLastVelocity;
6880                velocity = (float) Math.hypot(vx, vy);
6881                if (DebugFlags.WEB_VIEW) {
6882                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
6883                }
6884            } else if (DebugFlags.WEB_VIEW) {
6885                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
6886            }
6887        } else if (DebugFlags.WEB_VIEW) {
6888            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
6889                    + " current=" + currentVelocity
6890                    + " vx=" + vx + " vy=" + vy
6891                    + " maxX=" + maxX + " maxY=" + maxY
6892                    + " scrollX=" + scrollX + " scrollY=" + scrollY
6893                    + " layer=" + mScrollingLayer);
6894        }
6895
6896        // Allow sloppy flings without overscrolling at the edges.
6897        if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
6898            vx = 0;
6899        }
6900        if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
6901            vy = 0;
6902        }
6903
6904        if (overscrollDistance < overflingDistance) {
6905            if ((vx > 0 && scrollX == -overscrollDistance) ||
6906                    (vx < 0 && scrollX == maxX + overscrollDistance)) {
6907                vx = 0;
6908            }
6909            if ((vy > 0 && scrollY == -overscrollDistance) ||
6910                    (vy < 0 && scrollY == maxY + overscrollDistance)) {
6911                vy = 0;
6912            }
6913        }
6914
6915        mLastVelX = vx;
6916        mLastVelY = vy;
6917        mLastVelocity = velocity;
6918
6919        // no horizontal overscroll if the content just fits
6920        mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY,
6921                maxX == 0 ? 0 : overflingDistance, overflingDistance);
6922        // Duration is calculated based on velocity. With range boundaries and overscroll
6923        // we may not know how long the final animation will take. (Hence the deprecation
6924        // warning on the call below.) It's not a big deal for scroll bars but if webcore
6925        // resumes during this effect we will take a performance hit. See computeScroll;
6926        // we resume webcore there when the animation is finished.
6927        final int time = mScroller.getDuration();
6928
6929        // Suppress scrollbars for layer scrolling.
6930        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6931            awakenScrollBars(time);
6932        }
6933
6934        invalidate();
6935    }
6936
6937    /**
6938     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
6939     * in charge of installing this view to the view hierarchy. This view will
6940     * become visible when the user starts scrolling via touch and fade away if
6941     * the user does not interact with it.
6942     * <p/>
6943     * API version 3 introduces a built-in zoom mechanism that is shown
6944     * automatically by the MapView. This is the preferred approach for
6945     * showing the zoom UI.
6946     *
6947     * @deprecated The built-in zoom mechanism is preferred, see
6948     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
6949     */
6950    @Deprecated
6951    public View getZoomControls() {
6952        checkThread();
6953        if (!getSettings().supportZoom()) {
6954            Log.w(LOGTAG, "This WebView doesn't support zoom.");
6955            return null;
6956        }
6957        return mZoomManager.getExternalZoomPicker();
6958    }
6959
6960    void dismissZoomControl() {
6961        mZoomManager.dismissZoomPicker();
6962    }
6963
6964    float getDefaultZoomScale() {
6965        return mZoomManager.getDefaultScale();
6966    }
6967
6968    /**
6969     * @return TRUE if the WebView can be zoomed in.
6970     */
6971    public boolean canZoomIn() {
6972        checkThread();
6973        return mZoomManager.canZoomIn();
6974    }
6975
6976    /**
6977     * @return TRUE if the WebView can be zoomed out.
6978     */
6979    public boolean canZoomOut() {
6980        checkThread();
6981        return mZoomManager.canZoomOut();
6982    }
6983
6984    /**
6985     * Perform zoom in in the webview
6986     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
6987     */
6988    public boolean zoomIn() {
6989        checkThread();
6990        return mZoomManager.zoomIn();
6991    }
6992
6993    /**
6994     * Perform zoom out in the webview
6995     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
6996     */
6997    public boolean zoomOut() {
6998        checkThread();
6999        return mZoomManager.zoomOut();
7000    }
7001
7002    private void updateSelection() {
7003        if (mNativeClass == 0) {
7004            return;
7005        }
7006        // mLastTouchX and mLastTouchY are the point in the current viewport
7007        int contentX = viewToContentX(mLastTouchX + mScrollX);
7008        int contentY = viewToContentY(mLastTouchY + mScrollY);
7009        int slop = viewToContentDimension(mNavSlop);
7010        Rect rect = new Rect(contentX - slop, contentY - slop,
7011                contentX + slop, contentY + slop);
7012        nativeSelectBestAt(rect);
7013        mInitialHitTestResult = hitTestResult(null);
7014    }
7015
7016    /**
7017     * Scroll the focused text field to match the WebTextView
7018     * @param xPercent New x position of the WebTextView from 0 to 1.
7019     */
7020    /*package*/ void scrollFocusedTextInputX(float xPercent) {
7021        if (!inEditingMode() || mWebViewCore == null) {
7022            return;
7023        }
7024        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0,
7025                new Float(xPercent));
7026    }
7027
7028    /**
7029     * Scroll the focused textarea vertically to match the WebTextView
7030     * @param y New y position of the WebTextView in view coordinates
7031     */
7032    /* package */ void scrollFocusedTextInputY(int y) {
7033        if (!inEditingMode() || mWebViewCore == null) {
7034            return;
7035        }
7036        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0, viewToContentDimension(y));
7037    }
7038
7039    /**
7040     * Set our starting point and time for a drag from the WebTextView.
7041     */
7042    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
7043        if (!inEditingMode()) {
7044            return;
7045        }
7046        mLastTouchX = Math.round(x + mWebTextView.getLeft() - mScrollX);
7047        mLastTouchY = Math.round(y + mWebTextView.getTop() - mScrollY);
7048        mLastTouchTime = eventTime;
7049        if (!mScroller.isFinished()) {
7050            abortAnimation();
7051            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
7052        }
7053        mSnapScrollMode = SNAP_NONE;
7054        mVelocityTracker = VelocityTracker.obtain();
7055        mTouchMode = TOUCH_DRAG_START_MODE;
7056    }
7057
7058    /**
7059     * Given a motion event from the WebTextView, set its location to our
7060     * coordinates, and handle the event.
7061     */
7062    /*package*/ boolean textFieldDrag(MotionEvent event) {
7063        if (!inEditingMode()) {
7064            return false;
7065        }
7066        mDragFromTextInput = true;
7067        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
7068                (float) (mWebTextView.getTop() - mScrollY));
7069        boolean result = onTouchEvent(event);
7070        mDragFromTextInput = false;
7071        return result;
7072    }
7073
7074    /**
7075     * Due a touch up from a WebTextView.  This will be handled by webkit to
7076     * change the selection.
7077     * @param event MotionEvent in the WebTextView's coordinates.
7078     */
7079    /*package*/ void touchUpOnTextField(MotionEvent event) {
7080        if (!inEditingMode()) {
7081            return;
7082        }
7083        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
7084        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
7085        int slop = viewToContentDimension(mNavSlop);
7086        nativeMotionUp(x, y, slop);
7087    }
7088
7089    /**
7090     * Called when pressing the center key or trackball on a textfield.
7091     */
7092    /*package*/ void centerKeyPressOnTextField() {
7093        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
7094                    nativeCursorNodePointer());
7095    }
7096
7097    private void doShortPress() {
7098        if (mNativeClass == 0) {
7099            return;
7100        }
7101        if (mPreventDefault == PREVENT_DEFAULT_YES) {
7102            return;
7103        }
7104        mTouchMode = TOUCH_DONE_MODE;
7105        switchOutDrawHistory();
7106        // mLastTouchX and mLastTouchY are the point in the current viewport
7107        int contentX = viewToContentX(mLastTouchX + mScrollX);
7108        int contentY = viewToContentY(mLastTouchY + mScrollY);
7109        int slop = viewToContentDimension(mNavSlop);
7110        if (getSettings().supportTouchOnly()) {
7111            removeTouchHighlight(false);
7112            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7113            // use "0" as generation id to inform WebKit to use the same x/y as
7114            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
7115            touchUpData.mMoveGeneration = 0;
7116            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7117        } else if (nativePointInNavCache(contentX, contentY, slop)) {
7118            WebViewCore.MotionUpData motionUpData = new WebViewCore
7119                    .MotionUpData();
7120            motionUpData.mFrame = nativeCacheHitFramePointer();
7121            motionUpData.mNode = nativeCacheHitNodePointer();
7122            motionUpData.mBounds = nativeCacheHitNodeBounds();
7123            motionUpData.mX = contentX;
7124            motionUpData.mY = contentY;
7125            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
7126                    motionUpData);
7127        } else {
7128            doMotionUp(contentX, contentY);
7129        }
7130    }
7131
7132    private void doMotionUp(int contentX, int contentY) {
7133        int slop = viewToContentDimension(mNavSlop);
7134        if (nativeMotionUp(contentX, contentY, slop) && mLogEvent) {
7135            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
7136        }
7137        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
7138            playSoundEffect(SoundEffectConstants.CLICK);
7139        }
7140    }
7141
7142    /**
7143     * Returns plugin bounds if x/y in content coordinates corresponds to a
7144     * plugin. Otherwise a NULL rectangle is returned.
7145     */
7146    Rect getPluginBounds(int x, int y) {
7147        int slop = viewToContentDimension(mNavSlop);
7148        if (nativePointInNavCache(x, y, slop) && nativeCacheHitIsPlugin()) {
7149            return nativeCacheHitNodeBounds();
7150        } else {
7151            return null;
7152        }
7153    }
7154
7155    /*
7156     * Return true if the rect (e.g. plugin) is fully visible and maximized
7157     * inside the WebView.
7158     */
7159    boolean isRectFitOnScreen(Rect rect) {
7160        final int rectWidth = rect.width();
7161        final int rectHeight = rect.height();
7162        final int viewWidth = getViewWidth();
7163        final int viewHeight = getViewHeightWithTitle();
7164        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight);
7165        scale = mZoomManager.computeScaleWithLimits(scale);
7166        return !mZoomManager.willScaleTriggerZoom(scale)
7167                && contentToViewX(rect.left) >= mScrollX
7168                && contentToViewX(rect.right) <= mScrollX + viewWidth
7169                && contentToViewY(rect.top) >= mScrollY
7170                && contentToViewY(rect.bottom) <= mScrollY + viewHeight;
7171    }
7172
7173    /*
7174     * Maximize and center the rectangle, specified in the document coordinate
7175     * space, inside the WebView. If the zoom doesn't need to be changed, do an
7176     * animated scroll to center it. If the zoom needs to be changed, find the
7177     * zoom center and do a smooth zoom transition. The rect is in document
7178     * coordinates
7179     */
7180    void centerFitRect(Rect rect) {
7181        final int rectWidth = rect.width();
7182        final int rectHeight = rect.height();
7183        final int viewWidth = getViewWidth();
7184        final int viewHeight = getViewHeightWithTitle();
7185        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight
7186                / rectHeight);
7187        scale = mZoomManager.computeScaleWithLimits(scale);
7188        if (!mZoomManager.willScaleTriggerZoom(scale)) {
7189            pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2,
7190                    contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2,
7191                    true, 0);
7192        } else {
7193            float actualScale = mZoomManager.getScale();
7194            float oldScreenX = rect.left * actualScale - mScrollX;
7195            float rectViewX = rect.left * scale;
7196            float rectViewWidth = rectWidth * scale;
7197            float newMaxWidth = mContentWidth * scale;
7198            float newScreenX = (viewWidth - rectViewWidth) / 2;
7199            // pin the newX to the WebView
7200            if (newScreenX > rectViewX) {
7201                newScreenX = rectViewX;
7202            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
7203                newScreenX = viewWidth - (newMaxWidth - rectViewX);
7204            }
7205            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
7206                    / (scale - actualScale);
7207            float oldScreenY = rect.top * actualScale + getTitleHeight()
7208                    - mScrollY;
7209            float rectViewY = rect.top * scale + getTitleHeight();
7210            float rectViewHeight = rectHeight * scale;
7211            float newMaxHeight = mContentHeight * scale + getTitleHeight();
7212            float newScreenY = (viewHeight - rectViewHeight) / 2;
7213            // pin the newY to the WebView
7214            if (newScreenY > rectViewY) {
7215                newScreenY = rectViewY;
7216            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
7217                newScreenY = viewHeight - (newMaxHeight - rectViewY);
7218            }
7219            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
7220                    / (scale - actualScale);
7221            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
7222            mZoomManager.startZoomAnimation(scale, false);
7223        }
7224    }
7225
7226    // Called by JNI to handle a touch on a node representing an email address,
7227    // address, or phone number
7228    private void overrideLoading(String url) {
7229        mCallbackProxy.uiOverrideUrlLoading(url);
7230    }
7231
7232    @Override
7233    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7234        // FIXME: If a subwindow is showing find, and the user touches the
7235        // background window, it can steal focus.
7236        if (mFindIsUp) return false;
7237        boolean result = false;
7238        if (inEditingMode()) {
7239            result = mWebTextView.requestFocus(direction,
7240                    previouslyFocusedRect);
7241        } else {
7242            result = super.requestFocus(direction, previouslyFocusedRect);
7243            if (mWebViewCore.getSettings().getNeedInitialFocus() && !isInTouchMode()) {
7244                // For cases such as GMail, where we gain focus from a direction,
7245                // we want to move to the first available link.
7246                // FIXME: If there are no visible links, we may not want to
7247                int fakeKeyDirection = 0;
7248                switch(direction) {
7249                    case View.FOCUS_UP:
7250                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
7251                        break;
7252                    case View.FOCUS_DOWN:
7253                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
7254                        break;
7255                    case View.FOCUS_LEFT:
7256                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
7257                        break;
7258                    case View.FOCUS_RIGHT:
7259                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
7260                        break;
7261                    default:
7262                        return result;
7263                }
7264                if (mNativeClass != 0 && !nativeHasCursorNode()) {
7265                    navHandledKey(fakeKeyDirection, 1, true, 0);
7266                }
7267            }
7268        }
7269        return result;
7270    }
7271
7272    @Override
7273    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7274        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
7275
7276        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
7277        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
7278        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
7279        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
7280
7281        int measuredHeight = heightSize;
7282        int measuredWidth = widthSize;
7283
7284        // Grab the content size from WebViewCore.
7285        int contentHeight = contentToViewDimension(mContentHeight);
7286        int contentWidth = contentToViewDimension(mContentWidth);
7287
7288//        Log.d(LOGTAG, "------- measure " + heightMode);
7289
7290        if (heightMode != MeasureSpec.EXACTLY) {
7291            mHeightCanMeasure = true;
7292            measuredHeight = contentHeight;
7293            if (heightMode == MeasureSpec.AT_MOST) {
7294                // If we are larger than the AT_MOST height, then our height can
7295                // no longer be measured and we should scroll internally.
7296                if (measuredHeight > heightSize) {
7297                    measuredHeight = heightSize;
7298                    mHeightCanMeasure = false;
7299                } else if (measuredHeight < heightSize) {
7300                    measuredHeight |= MEASURED_STATE_TOO_SMALL;
7301                }
7302            }
7303        } else {
7304            mHeightCanMeasure = false;
7305        }
7306        if (mNativeClass != 0) {
7307            nativeSetHeightCanMeasure(mHeightCanMeasure);
7308        }
7309        // For the width, always use the given size unless unspecified.
7310        if (widthMode == MeasureSpec.UNSPECIFIED) {
7311            mWidthCanMeasure = true;
7312            measuredWidth = contentWidth;
7313        } else {
7314            if (measuredWidth < contentWidth) {
7315                measuredWidth |= MEASURED_STATE_TOO_SMALL;
7316            }
7317            mWidthCanMeasure = false;
7318        }
7319
7320        synchronized (this) {
7321            setMeasuredDimension(measuredWidth, measuredHeight);
7322        }
7323    }
7324
7325    @Override
7326    public boolean requestChildRectangleOnScreen(View child,
7327                                                 Rect rect,
7328                                                 boolean immediate) {
7329        if (mNativeClass == 0) {
7330            return false;
7331        }
7332        // don't scroll while in zoom animation. When it is done, we will adjust
7333        // the necessary components (e.g., WebTextView if it is in editing mode)
7334        if (mZoomManager.isFixedLengthAnimationInProgress()) {
7335            return false;
7336        }
7337
7338        rect.offset(child.getLeft() - child.getScrollX(),
7339                child.getTop() - child.getScrollY());
7340
7341        Rect content = new Rect(viewToContentX(mScrollX),
7342                viewToContentY(mScrollY),
7343                viewToContentX(mScrollX + getWidth()
7344                - getVerticalScrollbarWidth()),
7345                viewToContentY(mScrollY + getViewHeightWithTitle()));
7346        content = nativeSubtractLayers(content);
7347        int screenTop = contentToViewY(content.top);
7348        int screenBottom = contentToViewY(content.bottom);
7349        int height = screenBottom - screenTop;
7350        int scrollYDelta = 0;
7351
7352        if (rect.bottom > screenBottom) {
7353            int oneThirdOfScreenHeight = height / 3;
7354            if (rect.height() > 2 * oneThirdOfScreenHeight) {
7355                // If the rectangle is too tall to fit in the bottom two thirds
7356                // of the screen, place it at the top.
7357                scrollYDelta = rect.top - screenTop;
7358            } else {
7359                // If the rectangle will still fit on screen, we want its
7360                // top to be in the top third of the screen.
7361                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
7362            }
7363        } else if (rect.top < screenTop) {
7364            scrollYDelta = rect.top - screenTop;
7365        }
7366
7367        int screenLeft = contentToViewX(content.left);
7368        int screenRight = contentToViewX(content.right);
7369        int width = screenRight - screenLeft;
7370        int scrollXDelta = 0;
7371
7372        if (rect.right > screenRight && rect.left > screenLeft) {
7373            if (rect.width() > width) {
7374                scrollXDelta += (rect.left - screenLeft);
7375            } else {
7376                scrollXDelta += (rect.right - screenRight);
7377            }
7378        } else if (rect.left < screenLeft) {
7379            scrollXDelta -= (screenLeft - rect.left);
7380        }
7381
7382        if ((scrollYDelta | scrollXDelta) != 0) {
7383            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
7384        }
7385
7386        return false;
7387    }
7388
7389    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
7390            String replace, int newStart, int newEnd) {
7391        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
7392        arg.mReplace = replace;
7393        arg.mNewStart = newStart;
7394        arg.mNewEnd = newEnd;
7395        mTextGeneration++;
7396        arg.mTextGeneration = mTextGeneration;
7397        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
7398    }
7399
7400    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
7401        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
7402        arg.mEvent = event;
7403        arg.mCurrentText = currentText;
7404        // Increase our text generation number, and pass it to webcore thread
7405        mTextGeneration++;
7406        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
7407        // WebKit's document state is not saved until about to leave the page.
7408        // To make sure the host application, like Browser, has the up to date
7409        // document state when it goes to background, we force to save the
7410        // document state.
7411        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
7412        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
7413                cursorData(), 1000);
7414    }
7415
7416    /**
7417     * @hide
7418     */
7419    public synchronized WebViewCore getWebViewCore() {
7420        return mWebViewCore;
7421    }
7422
7423    /**
7424     * Used only by TouchEventQueue to store pending touch events.
7425     */
7426    private static class QueuedTouch {
7427        long mSequence;
7428        MotionEvent mEvent; // Optional
7429        TouchEventData mTed; // Optional
7430
7431        QueuedTouch mNext;
7432
7433        public QueuedTouch set(TouchEventData ted) {
7434            mSequence = ted.mSequence;
7435            mTed = ted;
7436            mEvent = null;
7437            mNext = null;
7438            return this;
7439        }
7440
7441        public QueuedTouch set(MotionEvent ev, long sequence) {
7442            mEvent = MotionEvent.obtain(ev);
7443            mSequence = sequence;
7444            mTed = null;
7445            mNext = null;
7446            return this;
7447        }
7448
7449        public QueuedTouch add(QueuedTouch other) {
7450            if (other.mSequence < mSequence) {
7451                other.mNext = this;
7452                return other;
7453            }
7454
7455            QueuedTouch insertAt = this;
7456            while (insertAt.mNext != null && insertAt.mNext.mSequence < other.mSequence) {
7457                insertAt = insertAt.mNext;
7458            }
7459            other.mNext = insertAt.mNext;
7460            insertAt.mNext = other;
7461            return this;
7462        }
7463    }
7464
7465    /**
7466     * WebView handles touch events asynchronously since some events must be passed to WebKit
7467     * for potentially slower processing. TouchEventQueue serializes touch events regardless
7468     * of which path they take to ensure that no events are ever processed out of order
7469     * by WebView.
7470     */
7471    private class TouchEventQueue {
7472        private long mNextTouchSequence = Long.MIN_VALUE + 1;
7473        private long mLastHandledTouchSequence = Long.MIN_VALUE;
7474        private long mIgnoreUntilSequence = Long.MIN_VALUE + 1;
7475
7476        // Events waiting to be processed.
7477        private QueuedTouch mTouchEventQueue;
7478
7479        // Known events that are waiting on a response before being enqueued.
7480        private QueuedTouch mPreQueue;
7481
7482        // Pool of QueuedTouch objects saved for later use.
7483        private QueuedTouch mQueuedTouchRecycleBin;
7484        private int mQueuedTouchRecycleCount;
7485
7486        private long mLastEventTime = Long.MAX_VALUE;
7487        private static final int MAX_RECYCLED_QUEUED_TOUCH = 15;
7488
7489        // milliseconds until we abandon hope of getting all of a previous gesture
7490        private static final int QUEUED_GESTURE_TIMEOUT = 1000;
7491
7492        private QueuedTouch obtainQueuedTouch() {
7493            if (mQueuedTouchRecycleBin != null) {
7494                QueuedTouch result = mQueuedTouchRecycleBin;
7495                mQueuedTouchRecycleBin = result.mNext;
7496                mQueuedTouchRecycleCount--;
7497                return result;
7498            }
7499            return new QueuedTouch();
7500        }
7501
7502        /**
7503         * Allow events with any currently missing sequence numbers to be skipped in processing.
7504         */
7505        public void ignoreCurrentlyMissingEvents() {
7506            mIgnoreUntilSequence = mNextTouchSequence;
7507
7508            // Run any events we have available and complete, pre-queued or otherwise.
7509            runQueuedAndPreQueuedEvents();
7510        }
7511
7512        private void runQueuedAndPreQueuedEvents() {
7513            QueuedTouch qd = mPreQueue;
7514            boolean fromPreQueue = true;
7515            while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) {
7516                handleQueuedTouch(qd);
7517                QueuedTouch recycleMe = qd;
7518                if (fromPreQueue) {
7519                    mPreQueue = qd.mNext;
7520                } else {
7521                    mTouchEventQueue = qd.mNext;
7522                }
7523                recycleQueuedTouch(recycleMe);
7524                mLastHandledTouchSequence++;
7525
7526                long nextPre = mPreQueue != null ? mPreQueue.mSequence : Long.MAX_VALUE;
7527                long nextQueued = mTouchEventQueue != null ?
7528                        mTouchEventQueue.mSequence : Long.MAX_VALUE;
7529                fromPreQueue = nextPre < nextQueued;
7530                qd = fromPreQueue ? mPreQueue : mTouchEventQueue;
7531            }
7532        }
7533
7534        /**
7535         * Add a TouchEventData to the pre-queue.
7536         *
7537         * An event in the pre-queue is an event that we know about that
7538         * has been sent to webkit, but that we haven't received back and
7539         * enqueued into the normal touch queue yet. If webkit ever times
7540         * out and we need to ignore currently missing events, we'll run
7541         * events from the pre-queue to patch the holes.
7542         *
7543         * @param ted TouchEventData to pre-queue
7544         */
7545        public void preQueueTouchEventData(TouchEventData ted) {
7546            QueuedTouch newTouch = obtainQueuedTouch().set(ted);
7547            if (mPreQueue == null) {
7548                mPreQueue = newTouch;
7549            } else {
7550                QueuedTouch insertionPoint = mPreQueue;
7551                while (insertionPoint.mNext != null &&
7552                        insertionPoint.mNext.mSequence < newTouch.mSequence) {
7553                    insertionPoint = insertionPoint.mNext;
7554                }
7555                newTouch.mNext = insertionPoint.mNext;
7556                insertionPoint.mNext = newTouch;
7557            }
7558        }
7559
7560        private void recycleQueuedTouch(QueuedTouch qd) {
7561            if (mQueuedTouchRecycleCount < MAX_RECYCLED_QUEUED_TOUCH) {
7562                qd.mNext = mQueuedTouchRecycleBin;
7563                mQueuedTouchRecycleBin = qd;
7564                mQueuedTouchRecycleCount++;
7565            }
7566        }
7567
7568        /**
7569         * Reset the touch event queue. This will dump any pending events
7570         * and reset the sequence numbering.
7571         */
7572        public void reset() {
7573            mNextTouchSequence = Long.MIN_VALUE + 1;
7574            mLastHandledTouchSequence = Long.MIN_VALUE;
7575            mIgnoreUntilSequence = Long.MIN_VALUE + 1;
7576            while (mTouchEventQueue != null) {
7577                QueuedTouch recycleMe = mTouchEventQueue;
7578                mTouchEventQueue = mTouchEventQueue.mNext;
7579                recycleQueuedTouch(recycleMe);
7580            }
7581            while (mPreQueue != null) {
7582                QueuedTouch recycleMe = mPreQueue;
7583                mPreQueue = mPreQueue.mNext;
7584                recycleQueuedTouch(recycleMe);
7585            }
7586        }
7587
7588        /**
7589         * Return the next valid sequence number for tagging incoming touch events.
7590         * @return The next touch event sequence number
7591         */
7592        public long nextTouchSequence() {
7593            return mNextTouchSequence++;
7594        }
7595
7596        /**
7597         * Enqueue a touch event in the form of TouchEventData.
7598         * The sequence number will be read from the mSequence field of the argument.
7599         *
7600         * If the touch event's sequence number is the next in line to be processed, it will
7601         * be handled before this method returns. Any subsequent events that have already
7602         * been queued will also be processed in their proper order.
7603         *
7604         * @param ted Touch data to be processed in order.
7605         * @return true if the event was processed before returning, false if it was just enqueued.
7606         */
7607        public boolean enqueueTouchEvent(TouchEventData ted) {
7608            // Remove from the pre-queue if present
7609            QueuedTouch preQueue = mPreQueue;
7610            if (preQueue != null) {
7611                // On exiting this block, preQueue is set to the pre-queued QueuedTouch object
7612                // if it was present in the pre-queue, and removed from the pre-queue itself.
7613                if (preQueue.mSequence == ted.mSequence) {
7614                    mPreQueue = preQueue.mNext;
7615                } else {
7616                    QueuedTouch prev = preQueue;
7617                    preQueue = null;
7618                    while (prev.mNext != null) {
7619                        if (prev.mNext.mSequence == ted.mSequence) {
7620                            preQueue = prev.mNext;
7621                            prev.mNext = preQueue.mNext;
7622                            break;
7623                        } else {
7624                            prev = prev.mNext;
7625                        }
7626                    }
7627                }
7628            }
7629
7630            if (ted.mSequence < mLastHandledTouchSequence) {
7631                // Stale event and we already moved on; drop it. (Should not be common.)
7632                Log.w(LOGTAG, "Stale touch event " + MotionEvent.actionToString(ted.mAction) +
7633                        " received from webcore; ignoring");
7634                return false;
7635            }
7636
7637            if (dropStaleGestures(ted.mMotionEvent, ted.mSequence)) {
7638                return false;
7639            }
7640
7641            // dropStaleGestures above might have fast-forwarded us to
7642            // an event we have already.
7643            runNextQueuedEvents();
7644
7645            if (mLastHandledTouchSequence + 1 == ted.mSequence) {
7646                if (preQueue != null) {
7647                    recycleQueuedTouch(preQueue);
7648                    preQueue = null;
7649                }
7650                handleQueuedTouchEventData(ted);
7651
7652                mLastHandledTouchSequence++;
7653
7654                // Do we have any more? Run them if so.
7655                runNextQueuedEvents();
7656            } else {
7657                // Reuse the pre-queued object if we had it.
7658                QueuedTouch qd = preQueue != null ? preQueue : obtainQueuedTouch().set(ted);
7659                mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd);
7660            }
7661            return true;
7662        }
7663
7664        /**
7665         * Enqueue a touch event in the form of a MotionEvent from the framework.
7666         *
7667         * If the touch event's sequence number is the next in line to be processed, it will
7668         * be handled before this method returns. Any subsequent events that have already
7669         * been queued will also be processed in their proper order.
7670         *
7671         * @param ev MotionEvent to be processed in order
7672         */
7673        public void enqueueTouchEvent(MotionEvent ev) {
7674            final long sequence = nextTouchSequence();
7675
7676            if (dropStaleGestures(ev, sequence)) {
7677                return;
7678            }
7679
7680            // dropStaleGestures above might have fast-forwarded us to
7681            // an event we have already.
7682            runNextQueuedEvents();
7683
7684            if (mLastHandledTouchSequence + 1 == sequence) {
7685                handleQueuedMotionEvent(ev);
7686
7687                mLastHandledTouchSequence++;
7688
7689                // Do we have any more? Run them if so.
7690                runNextQueuedEvents();
7691            } else {
7692                QueuedTouch qd = obtainQueuedTouch().set(ev, sequence);
7693                mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd);
7694            }
7695        }
7696
7697        private void runNextQueuedEvents() {
7698            QueuedTouch qd = mTouchEventQueue;
7699            while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) {
7700                handleQueuedTouch(qd);
7701                QueuedTouch recycleMe = qd;
7702                qd = qd.mNext;
7703                recycleQueuedTouch(recycleMe);
7704                mLastHandledTouchSequence++;
7705            }
7706            mTouchEventQueue = qd;
7707        }
7708
7709        private boolean dropStaleGestures(MotionEvent ev, long sequence) {
7710            if (ev != null && ev.getAction() == MotionEvent.ACTION_MOVE && !mConfirmMove) {
7711                // This is to make sure that we don't attempt to process a tap
7712                // or long press when webkit takes too long to get back to us.
7713                // The movement will be properly confirmed when we process the
7714                // enqueued event later.
7715                final int dx = Math.round(ev.getX()) - mLastTouchX;
7716                final int dy = Math.round(ev.getY()) - mLastTouchY;
7717                if (dx * dx + dy * dy > mTouchSlopSquare) {
7718                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
7719                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
7720                }
7721            }
7722
7723            if (mTouchEventQueue == null) {
7724                return sequence <= mLastHandledTouchSequence;
7725            }
7726
7727            // If we have a new down event and it's been a while since the last event
7728            // we saw, catch up as best we can and keep going.
7729            if (ev != null && ev.getAction() == MotionEvent.ACTION_DOWN) {
7730                long eventTime = ev.getEventTime();
7731                long lastHandledEventTime = mLastEventTime;
7732                if (eventTime > lastHandledEventTime + QUEUED_GESTURE_TIMEOUT) {
7733                    Log.w(LOGTAG, "Got ACTION_DOWN but still waiting on stale event. " +
7734                            "Catching up.");
7735                    runQueuedAndPreQueuedEvents();
7736
7737                    // Drop leftovers that we truly don't have.
7738                    QueuedTouch qd = mTouchEventQueue;
7739                    while (qd != null && qd.mSequence < sequence) {
7740                        QueuedTouch recycleMe = qd;
7741                        qd = qd.mNext;
7742                        recycleQueuedTouch(recycleMe);
7743                    }
7744                    mTouchEventQueue = qd;
7745                    mLastHandledTouchSequence = sequence - 1;
7746                }
7747            }
7748
7749            if (mIgnoreUntilSequence - 1 > mLastHandledTouchSequence) {
7750                QueuedTouch qd = mTouchEventQueue;
7751                while (qd != null && qd.mSequence < mIgnoreUntilSequence) {
7752                    QueuedTouch recycleMe = qd;
7753                    qd = qd.mNext;
7754                    recycleQueuedTouch(recycleMe);
7755                }
7756                mTouchEventQueue = qd;
7757                mLastHandledTouchSequence = mIgnoreUntilSequence - 1;
7758            }
7759
7760            if (mPreQueue != null) {
7761                // Drop stale prequeued events
7762                QueuedTouch qd = mPreQueue;
7763                while (qd != null && qd.mSequence < mIgnoreUntilSequence) {
7764                    QueuedTouch recycleMe = qd;
7765                    qd = qd.mNext;
7766                    recycleQueuedTouch(recycleMe);
7767                }
7768                mPreQueue = qd;
7769            }
7770
7771            return sequence <= mLastHandledTouchSequence;
7772        }
7773
7774        private void handleQueuedTouch(QueuedTouch qt) {
7775            if (qt.mTed != null) {
7776                handleQueuedTouchEventData(qt.mTed);
7777            } else {
7778                handleQueuedMotionEvent(qt.mEvent);
7779                qt.mEvent.recycle();
7780            }
7781        }
7782
7783        private void handleQueuedMotionEvent(MotionEvent ev) {
7784            mLastEventTime = ev.getEventTime();
7785            int action = ev.getActionMasked();
7786            if (ev.getPointerCount() > 1) {  // Multi-touch
7787                handleMultiTouchInWebView(ev);
7788            } else {
7789                final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
7790                if (detector != null && mPreventDefault != PREVENT_DEFAULT_YES) {
7791                    // ScaleGestureDetector needs a consistent event stream to operate properly.
7792                    // It won't take any action with fewer than two pointers, but it needs to
7793                    // update internal bookkeeping state.
7794                    detector.onTouchEvent(ev);
7795                }
7796
7797                handleTouchEventCommon(ev, action, Math.round(ev.getX()), Math.round(ev.getY()));
7798            }
7799        }
7800
7801        private void handleQueuedTouchEventData(TouchEventData ted) {
7802            if (ted.mMotionEvent != null) {
7803                mLastEventTime = ted.mMotionEvent.getEventTime();
7804            }
7805            if (!ted.mReprocess) {
7806                if (ted.mAction == MotionEvent.ACTION_DOWN
7807                        && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
7808                    // if prevent default is called from WebCore, UI
7809                    // will not handle the rest of the touch events any
7810                    // more.
7811                    mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES
7812                            : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
7813                } else if (ted.mAction == MotionEvent.ACTION_MOVE
7814                        && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
7815                    // the return for the first ACTION_MOVE will decide
7816                    // whether UI will handle touch or not. Currently no
7817                    // support for alternating prevent default
7818                    mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES
7819                            : PREVENT_DEFAULT_NO;
7820                }
7821                if (mPreventDefault == PREVENT_DEFAULT_YES) {
7822                    mTouchHighlightRegion.setEmpty();
7823                }
7824            } else {
7825                if (ted.mPoints.length > 1) {  // multi-touch
7826                    if (!ted.mNativeResult && mPreventDefault != PREVENT_DEFAULT_YES) {
7827                        mPreventDefault = PREVENT_DEFAULT_NO;
7828                        handleMultiTouchInWebView(ted.mMotionEvent);
7829                    } else {
7830                        mPreventDefault = PREVENT_DEFAULT_YES;
7831                    }
7832                    return;
7833                }
7834
7835                // prevent default is not called in WebCore, so the
7836                // message needs to be reprocessed in UI
7837                if (!ted.mNativeResult) {
7838                    // Following is for single touch.
7839                    switch (ted.mAction) {
7840                        case MotionEvent.ACTION_DOWN:
7841                            mLastDeferTouchX = ted.mPointsInView[0].x;
7842                            mLastDeferTouchY = ted.mPointsInView[0].y;
7843                            mDeferTouchMode = TOUCH_INIT_MODE;
7844                            break;
7845                        case MotionEvent.ACTION_MOVE: {
7846                            // no snapping in defer process
7847                            int x = ted.mPointsInView[0].x;
7848                            int y = ted.mPointsInView[0].y;
7849
7850                            if (mDeferTouchMode != TOUCH_DRAG_MODE) {
7851                                mDeferTouchMode = TOUCH_DRAG_MODE;
7852                                mLastDeferTouchX = x;
7853                                mLastDeferTouchY = y;
7854                                startScrollingLayer(x, y);
7855                                startDrag();
7856                            }
7857                            int deltaX = pinLocX((int) (mScrollX
7858                                    + mLastDeferTouchX - x))
7859                                    - mScrollX;
7860                            int deltaY = pinLocY((int) (mScrollY
7861                                    + mLastDeferTouchY - y))
7862                                    - mScrollY;
7863                            doDrag(deltaX, deltaY);
7864                            if (deltaX != 0) mLastDeferTouchX = x;
7865                            if (deltaY != 0) mLastDeferTouchY = y;
7866                            break;
7867                        }
7868                        case MotionEvent.ACTION_UP:
7869                        case MotionEvent.ACTION_CANCEL:
7870                            if (mDeferTouchMode == TOUCH_DRAG_MODE) {
7871                                // no fling in defer process
7872                                mScroller.springBack(mScrollX, mScrollY, 0,
7873                                        computeMaxScrollX(), 0,
7874                                        computeMaxScrollY());
7875                                invalidate();
7876                                WebViewCore.resumePriority();
7877                                WebViewCore.resumeUpdatePicture(mWebViewCore);
7878                            }
7879                            mDeferTouchMode = TOUCH_DONE_MODE;
7880                            break;
7881                        case WebViewCore.ACTION_DOUBLETAP:
7882                            // doDoubleTap() needs mLastTouchX/Y as anchor
7883                            mLastDeferTouchX = ted.mPointsInView[0].x;
7884                            mLastDeferTouchY = ted.mPointsInView[0].y;
7885                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
7886                            mDeferTouchMode = TOUCH_DONE_MODE;
7887                            break;
7888                        case WebViewCore.ACTION_LONGPRESS:
7889                            HitTestResult hitTest = getHitTestResult();
7890                            if (hitTest != null && hitTest.mType
7891                                    != HitTestResult.UNKNOWN_TYPE) {
7892                                performLongClick();
7893                            }
7894                            mDeferTouchMode = TOUCH_DONE_MODE;
7895                            break;
7896                    }
7897                }
7898            }
7899        }
7900    }
7901
7902    //-------------------------------------------------------------------------
7903    // Methods can be called from a separate thread, like WebViewCore
7904    // If it needs to call the View system, it has to send message.
7905    //-------------------------------------------------------------------------
7906
7907    /**
7908     * General handler to receive message coming from webkit thread
7909     */
7910    class PrivateHandler extends Handler {
7911        @Override
7912        public void handleMessage(Message msg) {
7913            // exclude INVAL_RECT_MSG_ID since it is frequently output
7914            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
7915                if (msg.what >= FIRST_PRIVATE_MSG_ID
7916                        && msg.what <= LAST_PRIVATE_MSG_ID) {
7917                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
7918                            - FIRST_PRIVATE_MSG_ID]);
7919                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
7920                        && msg.what <= LAST_PACKAGE_MSG_ID) {
7921                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
7922                            - FIRST_PACKAGE_MSG_ID]);
7923                } else {
7924                    Log.v(LOGTAG, Integer.toString(msg.what));
7925                }
7926            }
7927            if (mWebViewCore == null) {
7928                // after WebView's destroy() is called, skip handling messages.
7929                return;
7930            }
7931            if (mBlockWebkitViewMessages
7932                    && msg.what != WEBCORE_INITIALIZED_MSG_ID) {
7933                // Blocking messages from webkit
7934                return;
7935            }
7936            switch (msg.what) {
7937                case REMEMBER_PASSWORD: {
7938                    mDatabase.setUsernamePassword(
7939                            msg.getData().getString("host"),
7940                            msg.getData().getString("username"),
7941                            msg.getData().getString("password"));
7942                    ((Message) msg.obj).sendToTarget();
7943                    break;
7944                }
7945                case NEVER_REMEMBER_PASSWORD: {
7946                    mDatabase.setUsernamePassword(
7947                            msg.getData().getString("host"), null, null);
7948                    ((Message) msg.obj).sendToTarget();
7949                    break;
7950                }
7951                case PREVENT_DEFAULT_TIMEOUT: {
7952                    // if timeout happens, cancel it so that it won't block UI
7953                    // to continue handling touch events
7954                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
7955                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
7956                            || (msg.arg1 == MotionEvent.ACTION_MOVE
7957                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
7958                        cancelWebCoreTouchEvent(
7959                                viewToContentX(mLastTouchX + mScrollX),
7960                                viewToContentY(mLastTouchY + mScrollY),
7961                                true);
7962                    }
7963                    break;
7964                }
7965                case SCROLL_SELECT_TEXT: {
7966                    if (mAutoScrollX == 0 && mAutoScrollY == 0) {
7967                        mSentAutoScrollMessage = false;
7968                        break;
7969                    }
7970                    if (mScrollingLayer == 0) {
7971                        pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
7972                    } else {
7973                        mScrollingLayerRect.left += mAutoScrollX;
7974                        mScrollingLayerRect.top += mAutoScrollY;
7975                        nativeScrollLayer(mScrollingLayer,
7976                                mScrollingLayerRect.left,
7977                                mScrollingLayerRect.top);
7978                        invalidate();
7979                    }
7980                    sendEmptyMessageDelayed(
7981                            SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
7982                    break;
7983                }
7984                case SWITCH_TO_SHORTPRESS: {
7985                    mInitialHitTestResult = null; // set by updateSelection()
7986                    if (mTouchMode == TOUCH_INIT_MODE) {
7987                        if (!getSettings().supportTouchOnly()
7988                                && mPreventDefault != PREVENT_DEFAULT_YES) {
7989                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
7990                            updateSelection();
7991                        } else {
7992                            // set to TOUCH_SHORTPRESS_MODE so that it won't
7993                            // trigger double tap any more
7994                            mTouchMode = TOUCH_SHORTPRESS_MODE;
7995                        }
7996                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
7997                        mTouchMode = TOUCH_DONE_MODE;
7998                    }
7999                    break;
8000                }
8001                case SWITCH_TO_LONGPRESS: {
8002                    if (getSettings().supportTouchOnly()) {
8003                        removeTouchHighlight(false);
8004                    }
8005                    if (inFullScreenMode() || mDeferTouchProcess) {
8006                        TouchEventData ted = new TouchEventData();
8007                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
8008                        ted.mIds = new int[1];
8009                        ted.mIds[0] = 0;
8010                        ted.mPoints = new Point[1];
8011                        ted.mPoints[0] = new Point(viewToContentX(mLastTouchX + mScrollX),
8012                                                   viewToContentY(mLastTouchY + mScrollY));
8013                        ted.mPointsInView = new Point[1];
8014                        ted.mPointsInView[0] = new Point(mLastTouchX, mLastTouchY);
8015                        // metaState for long press is tricky. Should it be the
8016                        // state when the press started or when the press was
8017                        // released? Or some intermediary key state? For
8018                        // simplicity for now, we don't set it.
8019                        ted.mMetaState = 0;
8020                        ted.mReprocess = mDeferTouchProcess;
8021                        ted.mNativeLayer = nativeScrollableLayer(
8022                                ted.mPoints[0].x, ted.mPoints[0].y,
8023                                ted.mNativeLayerRect, null);
8024                        ted.mSequence = mTouchEventQueue.nextTouchSequence();
8025                        mTouchEventQueue.preQueueTouchEventData(ted);
8026                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
8027                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
8028                        mTouchMode = TOUCH_DONE_MODE;
8029                        performLongClick();
8030                    }
8031                    break;
8032                }
8033                case RELEASE_SINGLE_TAP: {
8034                    doShortPress();
8035                    break;
8036                }
8037                case SCROLL_TO_MSG_ID: {
8038                    // arg1 = animate, arg2 = onlyIfImeIsShowing
8039                    // obj = Point(x, y)
8040                    if (msg.arg2 == 1) {
8041                        // This scroll is intended to bring the textfield into
8042                        // view, but is only necessary if the IME is showing
8043                        InputMethodManager imm = InputMethodManager.peekInstance();
8044                        if (imm == null || !imm.isAcceptingText()
8045                                || (!imm.isActive(WebView.this) && (!inEditingMode()
8046                                || !imm.isActive(mWebTextView)))) {
8047                            break;
8048                        }
8049                    }
8050                    final Point p = (Point) msg.obj;
8051                    if (msg.arg1 == 1) {
8052                        spawnContentScrollTo(p.x, p.y);
8053                    } else {
8054                        setContentScrollTo(p.x, p.y);
8055                    }
8056                    break;
8057                }
8058                case UPDATE_ZOOM_RANGE: {
8059                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
8060                    // mScrollX contains the new minPrefWidth
8061                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
8062                    break;
8063                }
8064                case REPLACE_BASE_CONTENT: {
8065                    nativeReplaceBaseContent(msg.arg1);
8066                    break;
8067                }
8068                case NEW_PICTURE_MSG_ID: {
8069                    // called for new content
8070                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
8071                    setNewPicture(draw, true);
8072                    break;
8073                }
8074                case WEBCORE_INITIALIZED_MSG_ID:
8075                    // nativeCreate sets mNativeClass to a non-zero value
8076                    String drawableDir = BrowserFrame.getRawResFilename(
8077                            BrowserFrame.DRAWABLEDIR, mContext);
8078                    AssetManager am = mContext.getAssets();
8079                    nativeCreate(msg.arg1, drawableDir, am);
8080                    if (mDelaySetPicture != null) {
8081                        setNewPicture(mDelaySetPicture, true);
8082                        mDelaySetPicture = null;
8083                    }
8084                    break;
8085                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
8086                    // Make sure that the textfield is currently focused
8087                    // and representing the same node as the pointer.
8088                    if (inEditingMode() &&
8089                            mWebTextView.isSameTextField(msg.arg1)) {
8090                        if (msg.getData().getBoolean("password")) {
8091                            Spannable text = (Spannable) mWebTextView.getText();
8092                            int start = Selection.getSelectionStart(text);
8093                            int end = Selection.getSelectionEnd(text);
8094                            mWebTextView.setInPassword(true);
8095                            // Restore the selection, which may have been
8096                            // ruined by setInPassword.
8097                            Spannable pword =
8098                                    (Spannable) mWebTextView.getText();
8099                            Selection.setSelection(pword, start, end);
8100                        // If the text entry has created more events, ignore
8101                        // this one.
8102                        } else if (msg.arg2 == mTextGeneration) {
8103                            String text = (String) msg.obj;
8104                            if (null == text) {
8105                                text = "";
8106                            }
8107                            mWebTextView.setTextAndKeepSelection(text);
8108                        }
8109                    }
8110                    break;
8111                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
8112                    displaySoftKeyboard(true);
8113                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
8114                case UPDATE_TEXT_SELECTION_MSG_ID:
8115                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
8116                            (WebViewCore.TextSelectionData) msg.obj);
8117                    break;
8118                case FORM_DID_BLUR:
8119                    if (inEditingMode()
8120                            && mWebTextView.isSameTextField(msg.arg1)) {
8121                        hideSoftKeyboard();
8122                    }
8123                    break;
8124                case RETURN_LABEL:
8125                    if (inEditingMode()
8126                            && mWebTextView.isSameTextField(msg.arg1)) {
8127                        mWebTextView.setHint((String) msg.obj);
8128                        InputMethodManager imm
8129                                = InputMethodManager.peekInstance();
8130                        // The hint is propagated to the IME in
8131                        // onCreateInputConnection.  If the IME is already
8132                        // active, restart it so that its hint text is updated.
8133                        if (imm != null && imm.isActive(mWebTextView)) {
8134                            imm.restartInput(mWebTextView);
8135                        }
8136                    }
8137                    break;
8138                case UNHANDLED_NAV_KEY:
8139                    navHandledKey(msg.arg1, 1, false, 0);
8140                    break;
8141                case UPDATE_TEXT_ENTRY_MSG_ID:
8142                    // this is sent after finishing resize in WebViewCore. Make
8143                    // sure the text edit box is still on the  screen.
8144                    if (inEditingMode() && nativeCursorIsTextInput()) {
8145                        rebuildWebTextView();
8146                    }
8147                    break;
8148                case CLEAR_TEXT_ENTRY:
8149                    clearTextEntry();
8150                    break;
8151                case INVAL_RECT_MSG_ID: {
8152                    Rect r = (Rect)msg.obj;
8153                    if (r == null) {
8154                        invalidate();
8155                    } else {
8156                        // we need to scale r from content into view coords,
8157                        // which viewInvalidate() does for us
8158                        viewInvalidate(r.left, r.top, r.right, r.bottom);
8159                    }
8160                    break;
8161                }
8162                case REQUEST_FORM_DATA:
8163                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
8164                    if (mWebTextView.isSameTextField(msg.arg1)) {
8165                        mWebTextView.setAdapterCustom(adapter);
8166                    }
8167                    break;
8168                case RESUME_WEBCORE_PRIORITY:
8169                    WebViewCore.resumePriority();
8170                    WebViewCore.resumeUpdatePicture(mWebViewCore);
8171                    break;
8172
8173                case LONG_PRESS_CENTER:
8174                    // as this is shared by keydown and trackballdown, reset all
8175                    // the states
8176                    mGotCenterDown = false;
8177                    mTrackballDown = false;
8178                    performLongClick();
8179                    break;
8180
8181                case WEBCORE_NEED_TOUCH_EVENTS:
8182                    mForwardTouchEvents = (msg.arg1 != 0);
8183                    break;
8184
8185                case PREVENT_TOUCH_ID:
8186                    if (inFullScreenMode()) {
8187                        break;
8188                    }
8189                    TouchEventData ted = (TouchEventData) msg.obj;
8190
8191                    if (mTouchEventQueue.enqueueTouchEvent(ted)) {
8192                        // WebCore is responding to us; remove pending timeout.
8193                        // It will be re-posted when needed.
8194                        removeMessages(PREVENT_DEFAULT_TIMEOUT);
8195                    }
8196                    break;
8197
8198                case REQUEST_KEYBOARD:
8199                    if (msg.arg1 == 0) {
8200                        hideSoftKeyboard();
8201                    } else {
8202                        displaySoftKeyboard(false);
8203                    }
8204                    break;
8205
8206                case FIND_AGAIN:
8207                    // Ignore if find has been dismissed.
8208                    if (mFindIsUp && mFindCallback != null) {
8209                        mFindCallback.findAll();
8210                    }
8211                    break;
8212
8213                case DRAG_HELD_MOTIONLESS:
8214                    mHeldMotionless = MOTIONLESS_TRUE;
8215                    invalidate();
8216                    // fall through to keep scrollbars awake
8217
8218                case AWAKEN_SCROLL_BARS:
8219                    if (mTouchMode == TOUCH_DRAG_MODE
8220                            && mHeldMotionless == MOTIONLESS_TRUE) {
8221                        awakenScrollBars(ViewConfiguration
8222                                .getScrollDefaultDelay(), false);
8223                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
8224                                .obtainMessage(AWAKEN_SCROLL_BARS),
8225                                ViewConfiguration.getScrollDefaultDelay());
8226                    }
8227                    break;
8228
8229                case DO_MOTION_UP:
8230                    doMotionUp(msg.arg1, msg.arg2);
8231                    break;
8232
8233                case SCREEN_ON:
8234                    setKeepScreenOn(msg.arg1 == 1);
8235                    break;
8236
8237                case ENTER_FULLSCREEN_VIDEO:
8238                    int layerId = msg.arg1;
8239
8240                    String url = (String) msg.obj;
8241                    if (mHTML5VideoViewProxy != null) {
8242                        mHTML5VideoViewProxy.enterFullScreenVideo(layerId, url);
8243                    }
8244                    break;
8245
8246                case SHOW_FULLSCREEN: {
8247                    View view = (View) msg.obj;
8248                    int orientation = msg.arg1;
8249                    int npp = msg.arg2;
8250
8251                    if (inFullScreenMode()) {
8252                        Log.w(LOGTAG, "Should not have another full screen.");
8253                        dismissFullScreenMode();
8254                    }
8255                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, orientation, npp);
8256                    mFullScreenHolder.setContentView(view);
8257                    mFullScreenHolder.show();
8258
8259                    break;
8260                }
8261                case HIDE_FULLSCREEN:
8262                    dismissFullScreenMode();
8263                    break;
8264
8265                case DOM_FOCUS_CHANGED:
8266                    if (inEditingMode()) {
8267                        nativeClearCursor();
8268                        rebuildWebTextView();
8269                    }
8270                    break;
8271
8272                case SHOW_RECT_MSG_ID: {
8273                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
8274                    int x = mScrollX;
8275                    int left = contentToViewX(data.mLeft);
8276                    int width = contentToViewDimension(data.mWidth);
8277                    int maxWidth = contentToViewDimension(data.mContentWidth);
8278                    int viewWidth = getViewWidth();
8279                    if (width < viewWidth) {
8280                        // center align
8281                        x += left + width / 2 - mScrollX - viewWidth / 2;
8282                    } else {
8283                        x += (int) (left + data.mXPercentInDoc * width
8284                                - mScrollX - data.mXPercentInView * viewWidth);
8285                    }
8286                    if (DebugFlags.WEB_VIEW) {
8287                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
8288                              width + ",maxWidth=" + maxWidth +
8289                              ",viewWidth=" + viewWidth + ",x="
8290                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
8291                              ",xPercentInView=" + data.mXPercentInView+ ")");
8292                    }
8293                    // use the passing content width to cap x as the current
8294                    // mContentWidth may not be updated yet
8295                    x = Math.max(0,
8296                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
8297                    int top = contentToViewY(data.mTop);
8298                    int height = contentToViewDimension(data.mHeight);
8299                    int maxHeight = contentToViewDimension(data.mContentHeight);
8300                    int viewHeight = getViewHeight();
8301                    int y = (int) (top + data.mYPercentInDoc * height -
8302                                   data.mYPercentInView * viewHeight);
8303                    if (DebugFlags.WEB_VIEW) {
8304                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
8305                              height + ",maxHeight=" + maxHeight +
8306                              ",viewHeight=" + viewHeight + ",y="
8307                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
8308                              ",yPercentInView=" + data.mYPercentInView+ ")");
8309                    }
8310                    // use the passing content height to cap y as the current
8311                    // mContentHeight may not be updated yet
8312                    y = Math.max(0,
8313                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
8314                    // We need to take into account the visible title height
8315                    // when scrolling since y is an absolute view position.
8316                    y = Math.max(0, y - getVisibleTitleHeight());
8317                    scrollTo(x, y);
8318                    }
8319                    break;
8320
8321                case CENTER_FIT_RECT:
8322                    centerFitRect((Rect)msg.obj);
8323                    break;
8324
8325                case SET_SCROLLBAR_MODES:
8326                    mHorizontalScrollBarMode = msg.arg1;
8327                    mVerticalScrollBarMode = msg.arg2;
8328                    break;
8329
8330                case SELECTION_STRING_CHANGED:
8331                    if (mAccessibilityInjector != null) {
8332                        String selectionString = (String) msg.obj;
8333                        mAccessibilityInjector.onSelectionStringChange(selectionString);
8334                    }
8335                    break;
8336
8337                case SET_TOUCH_HIGHLIGHT_RECTS:
8338                    invalidate(mTouchHighlightRegion.getBounds());
8339                    mTouchHighlightRegion.setEmpty();
8340                    if (msg.obj != null) {
8341                        ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
8342                        for (Rect rect : rects) {
8343                            Rect viewRect = contentToViewRect(rect);
8344                            // some sites, like stories in nytimes.com, set
8345                            // mouse event handler in the top div. It is not
8346                            // user friendly to highlight the div if it covers
8347                            // more than half of the screen.
8348                            if (viewRect.width() < getWidth() >> 1
8349                                    || viewRect.height() < getHeight() >> 1) {
8350                                mTouchHighlightRegion.union(viewRect);
8351                                invalidate(viewRect);
8352                            } else {
8353                                Log.w(LOGTAG, "Skip the huge selection rect:"
8354                                        + viewRect);
8355                            }
8356                        }
8357                    }
8358                    break;
8359
8360                case SAVE_WEBARCHIVE_FINISHED:
8361                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
8362                    if (saveMessage.mCallback != null) {
8363                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
8364                    }
8365                    break;
8366
8367                case SET_AUTOFILLABLE:
8368                    mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
8369                    if (mWebTextView != null) {
8370                        mWebTextView.setAutoFillable(mAutoFillData.getQueryId());
8371                        rebuildWebTextView();
8372                    }
8373                    break;
8374
8375                case AUTOFILL_COMPLETE:
8376                    if (mWebTextView != null) {
8377                        // Clear the WebTextView adapter when AutoFill finishes
8378                        // so that the drop down gets cleared.
8379                        mWebTextView.setAdapterCustom(null);
8380                    }
8381                    break;
8382
8383                case SELECT_AT:
8384                    nativeSelectAt(msg.arg1, msg.arg2);
8385                    break;
8386
8387                default:
8388                    super.handleMessage(msg);
8389                    break;
8390            }
8391        }
8392    }
8393
8394    void setNewPicture(final WebViewCore.DrawData draw, boolean updateBaseLayer) {
8395        if (mNativeClass == 0) {
8396            if (mDelaySetPicture != null) {
8397                throw new IllegalStateException("Tried to setNewPicture with"
8398                        + " a delay picture already set! (memory leak)");
8399            }
8400            // Not initialized yet, delay set
8401            mDelaySetPicture = draw;
8402            return;
8403        }
8404        WebViewCore.ViewState viewState = draw.mViewState;
8405        boolean isPictureAfterFirstLayout = viewState != null;
8406        if (updateBaseLayer) {
8407            setBaseLayer(draw.mBaseLayer, draw.mInvalRegion,
8408                    getSettings().getShowVisualIndicator(),
8409                    isPictureAfterFirstLayout);
8410        }
8411        final Point viewSize = draw.mViewSize;
8412        if (isPictureAfterFirstLayout) {
8413            // Reset the last sent data here since dealing with new page.
8414            mLastWidthSent = 0;
8415            mZoomManager.onFirstLayout(draw);
8416            if (!mDrawHistory) {
8417                // Do not send the scroll event for this particular
8418                // scroll message.  Note that a scroll event may
8419                // still be fired if the user scrolls before the
8420                // message can be handled.
8421                mSendScrollEvent = false;
8422                setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
8423                mSendScrollEvent = true;
8424
8425                // As we are on a new page, remove the WebTextView. This
8426                // is necessary for page loads driven by webkit, and in
8427                // particular when the user was on a password field, so
8428                // the WebTextView was visible.
8429                clearTextEntry();
8430            }
8431        }
8432
8433        // We update the layout (i.e. request a layout from the
8434        // view system) if the last view size that we sent to
8435        // WebCore matches the view size of the picture we just
8436        // received in the fixed dimension.
8437        final boolean updateLayout = viewSize.x == mLastWidthSent
8438                && viewSize.y == mLastHeightSent;
8439        // Don't send scroll event for picture coming from webkit,
8440        // since the new picture may cause a scroll event to override
8441        // the saved history scroll position.
8442        mSendScrollEvent = false;
8443        recordNewContentSize(draw.mContentSize.x,
8444                draw.mContentSize.y, updateLayout);
8445        mSendScrollEvent = true;
8446        if (DebugFlags.WEB_VIEW) {
8447            Rect b = draw.mInvalRegion.getBounds();
8448            Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
8449                    b.left+","+b.top+","+b.right+","+b.bottom+"}");
8450        }
8451        invalidateContentRect(draw.mInvalRegion.getBounds());
8452
8453        if (mPictureListener != null) {
8454            mPictureListener.onNewPicture(WebView.this, capturePicture());
8455        }
8456
8457        // update the zoom information based on the new picture
8458        mZoomManager.onNewPicture(draw);
8459
8460        if (draw.mFocusSizeChanged && inEditingMode()) {
8461            mFocusSizeChanged = true;
8462        }
8463        if (isPictureAfterFirstLayout) {
8464            mViewManager.postReadyToDrawAll();
8465        }
8466    }
8467
8468    /**
8469     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
8470     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
8471     */
8472    private void updateTextSelectionFromMessage(int nodePointer,
8473            int textGeneration, WebViewCore.TextSelectionData data) {
8474        if (inEditingMode()
8475                && mWebTextView.isSameTextField(nodePointer)
8476                && textGeneration == mTextGeneration) {
8477            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
8478        }
8479    }
8480
8481    // Class used to use a dropdown for a <select> element
8482    private class InvokeListBox implements Runnable {
8483        // Whether the listbox allows multiple selection.
8484        private boolean     mMultiple;
8485        // Passed in to a list with multiple selection to tell
8486        // which items are selected.
8487        private int[]       mSelectedArray;
8488        // Passed in to a list with single selection to tell
8489        // where the initial selection is.
8490        private int         mSelection;
8491
8492        private Container[] mContainers;
8493
8494        // Need these to provide stable ids to my ArrayAdapter,
8495        // which normally does not have stable ids. (Bug 1250098)
8496        private class Container extends Object {
8497            /**
8498             * Possible values for mEnabled.  Keep in sync with OptionStatus in
8499             * WebViewCore.cpp
8500             */
8501            final static int OPTGROUP = -1;
8502            final static int OPTION_DISABLED = 0;
8503            final static int OPTION_ENABLED = 1;
8504
8505            String  mString;
8506            int     mEnabled;
8507            int     mId;
8508
8509            @Override
8510            public String toString() {
8511                return mString;
8512            }
8513        }
8514
8515        /**
8516         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
8517         *  and allow filtering.
8518         */
8519        private class MyArrayListAdapter extends ArrayAdapter<Container> {
8520            public MyArrayListAdapter() {
8521                super(mContext,
8522                        mMultiple ? com.android.internal.R.layout.select_dialog_multichoice :
8523                        com.android.internal.R.layout.webview_select_singlechoice,
8524                        mContainers);
8525            }
8526
8527            @Override
8528            public View getView(int position, View convertView,
8529                    ViewGroup parent) {
8530                // Always pass in null so that we will get a new CheckedTextView
8531                // Otherwise, an item which was previously used as an <optgroup>
8532                // element (i.e. has no check), could get used as an <option>
8533                // element, which needs a checkbox/radio, but it would not have
8534                // one.
8535                convertView = super.getView(position, null, parent);
8536                Container c = item(position);
8537                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
8538                    // ListView does not draw dividers between disabled and
8539                    // enabled elements.  Use a LinearLayout to provide dividers
8540                    LinearLayout layout = new LinearLayout(mContext);
8541                    layout.setOrientation(LinearLayout.VERTICAL);
8542                    if (position > 0) {
8543                        View dividerTop = new View(mContext);
8544                        dividerTop.setBackgroundResource(
8545                                android.R.drawable.divider_horizontal_bright);
8546                        layout.addView(dividerTop);
8547                    }
8548
8549                    if (Container.OPTGROUP == c.mEnabled) {
8550                        // Currently select_dialog_multichoice uses CheckedTextViews.
8551                        // If that changes, the class cast will no longer be valid.
8552                        if (mMultiple) {
8553                            Assert.assertTrue(convertView instanceof CheckedTextView);
8554                            ((CheckedTextView) convertView).setCheckMarkDrawable(null);
8555                        }
8556                    } else {
8557                        // c.mEnabled == Container.OPTION_DISABLED
8558                        // Draw the disabled element in a disabled state.
8559                        convertView.setEnabled(false);
8560                    }
8561
8562                    layout.addView(convertView);
8563                    if (position < getCount() - 1) {
8564                        View dividerBottom = new View(mContext);
8565                        dividerBottom.setBackgroundResource(
8566                                android.R.drawable.divider_horizontal_bright);
8567                        layout.addView(dividerBottom);
8568                    }
8569                    return layout;
8570                }
8571                return convertView;
8572            }
8573
8574            @Override
8575            public boolean hasStableIds() {
8576                // AdapterView's onChanged method uses this to determine whether
8577                // to restore the old state.  Return false so that the old (out
8578                // of date) state does not replace the new, valid state.
8579                return false;
8580            }
8581
8582            private Container item(int position) {
8583                if (position < 0 || position >= getCount()) {
8584                    return null;
8585                }
8586                return (Container) getItem(position);
8587            }
8588
8589            @Override
8590            public long getItemId(int position) {
8591                Container item = item(position);
8592                if (item == null) {
8593                    return -1;
8594                }
8595                return item.mId;
8596            }
8597
8598            @Override
8599            public boolean areAllItemsEnabled() {
8600                return false;
8601            }
8602
8603            @Override
8604            public boolean isEnabled(int position) {
8605                Container item = item(position);
8606                if (item == null) {
8607                    return false;
8608                }
8609                return Container.OPTION_ENABLED == item.mEnabled;
8610            }
8611        }
8612
8613        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
8614            mMultiple = true;
8615            mSelectedArray = selected;
8616
8617            int length = array.length;
8618            mContainers = new Container[length];
8619            for (int i = 0; i < length; i++) {
8620                mContainers[i] = new Container();
8621                mContainers[i].mString = array[i];
8622                mContainers[i].mEnabled = enabled[i];
8623                mContainers[i].mId = i;
8624            }
8625        }
8626
8627        private InvokeListBox(String[] array, int[] enabled, int selection) {
8628            mSelection = selection;
8629            mMultiple = false;
8630
8631            int length = array.length;
8632            mContainers = new Container[length];
8633            for (int i = 0; i < length; i++) {
8634                mContainers[i] = new Container();
8635                mContainers[i].mString = array[i];
8636                mContainers[i].mEnabled = enabled[i];
8637                mContainers[i].mId = i;
8638            }
8639        }
8640
8641        /*
8642         * Whenever the data set changes due to filtering, this class ensures
8643         * that the checked item remains checked.
8644         */
8645        private class SingleDataSetObserver extends DataSetObserver {
8646            private long        mCheckedId;
8647            private ListView    mListView;
8648            private Adapter     mAdapter;
8649
8650            /*
8651             * Create a new observer.
8652             * @param id The ID of the item to keep checked.
8653             * @param l ListView for getting and clearing the checked states
8654             * @param a Adapter for getting the IDs
8655             */
8656            public SingleDataSetObserver(long id, ListView l, Adapter a) {
8657                mCheckedId = id;
8658                mListView = l;
8659                mAdapter = a;
8660            }
8661
8662            @Override
8663            public void onChanged() {
8664                // The filter may have changed which item is checked.  Find the
8665                // item that the ListView thinks is checked.
8666                int position = mListView.getCheckedItemPosition();
8667                long id = mAdapter.getItemId(position);
8668                if (mCheckedId != id) {
8669                    // Clear the ListView's idea of the checked item, since
8670                    // it is incorrect
8671                    mListView.clearChoices();
8672                    // Search for mCheckedId.  If it is in the filtered list,
8673                    // mark it as checked
8674                    int count = mAdapter.getCount();
8675                    for (int i = 0; i < count; i++) {
8676                        if (mAdapter.getItemId(i) == mCheckedId) {
8677                            mListView.setItemChecked(i, true);
8678                            break;
8679                        }
8680                    }
8681                }
8682            }
8683        }
8684
8685        public void run() {
8686            final ListView listView = (ListView) LayoutInflater.from(mContext)
8687                    .inflate(com.android.internal.R.layout.select_dialog, null);
8688            final MyArrayListAdapter adapter = new MyArrayListAdapter();
8689            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
8690                    .setView(listView).setCancelable(true)
8691                    .setInverseBackgroundForced(true);
8692
8693            if (mMultiple) {
8694                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
8695                    public void onClick(DialogInterface dialog, int which) {
8696                        mWebViewCore.sendMessage(
8697                                EventHub.LISTBOX_CHOICES,
8698                                adapter.getCount(), 0,
8699                                listView.getCheckedItemPositions());
8700                    }});
8701                b.setNegativeButton(android.R.string.cancel,
8702                        new DialogInterface.OnClickListener() {
8703                    public void onClick(DialogInterface dialog, int which) {
8704                        mWebViewCore.sendMessage(
8705                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
8706                }});
8707            }
8708            mListBoxDialog = b.create();
8709            listView.setAdapter(adapter);
8710            listView.setFocusableInTouchMode(true);
8711            // There is a bug (1250103) where the checks in a ListView with
8712            // multiple items selected are associated with the positions, not
8713            // the ids, so the items do not properly retain their checks when
8714            // filtered.  Do not allow filtering on multiple lists until
8715            // that bug is fixed.
8716
8717            listView.setTextFilterEnabled(!mMultiple);
8718            if (mMultiple) {
8719                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
8720                int length = mSelectedArray.length;
8721                for (int i = 0; i < length; i++) {
8722                    listView.setItemChecked(mSelectedArray[i], true);
8723                }
8724            } else {
8725                listView.setOnItemClickListener(new OnItemClickListener() {
8726                    public void onItemClick(AdapterView<?> parent, View v,
8727                            int position, long id) {
8728                        // Rather than sending the message right away, send it
8729                        // after the page regains focus.
8730                        mListBoxMessage = Message.obtain(null,
8731                                EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0);
8732                        mListBoxDialog.dismiss();
8733                        mListBoxDialog = null;
8734                    }
8735                });
8736                if (mSelection != -1) {
8737                    listView.setSelection(mSelection);
8738                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
8739                    listView.setItemChecked(mSelection, true);
8740                    DataSetObserver observer = new SingleDataSetObserver(
8741                            adapter.getItemId(mSelection), listView, adapter);
8742                    adapter.registerDataSetObserver(observer);
8743                }
8744            }
8745            mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
8746                public void onCancel(DialogInterface dialog) {
8747                    mWebViewCore.sendMessage(
8748                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
8749                    mListBoxDialog = null;
8750                }
8751            });
8752            mListBoxDialog.show();
8753        }
8754    }
8755
8756    private Message mListBoxMessage;
8757
8758    /*
8759     * Request a dropdown menu for a listbox with multiple selection.
8760     *
8761     * @param array Labels for the listbox.
8762     * @param enabledArray  State for each element in the list.  See static
8763     *      integers in Container class.
8764     * @param selectedArray Which positions are initally selected.
8765     */
8766    void requestListBox(String[] array, int[] enabledArray, int[]
8767            selectedArray) {
8768        mPrivateHandler.post(
8769                new InvokeListBox(array, enabledArray, selectedArray));
8770    }
8771
8772    /*
8773     * Request a dropdown menu for a listbox with single selection or a single
8774     * <select> element.
8775     *
8776     * @param array Labels for the listbox.
8777     * @param enabledArray  State for each element in the list.  See static
8778     *      integers in Container class.
8779     * @param selection Which position is initally selected.
8780     */
8781    void requestListBox(String[] array, int[] enabledArray, int selection) {
8782        mPrivateHandler.post(
8783                new InvokeListBox(array, enabledArray, selection));
8784    }
8785
8786    // called by JNI
8787    private void sendMoveFocus(int frame, int node) {
8788        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
8789                new WebViewCore.CursorData(frame, node, 0, 0));
8790    }
8791
8792    // called by JNI
8793    private void sendMoveMouse(int frame, int node, int x, int y) {
8794        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
8795                new WebViewCore.CursorData(frame, node, x, y));
8796    }
8797
8798    /*
8799     * Send a mouse move event to the webcore thread.
8800     *
8801     * @param removeFocus Pass true to remove the WebTextView, if present.
8802     * @param stopPaintingCaret Stop drawing the blinking caret if true.
8803     * called by JNI
8804     */
8805    @SuppressWarnings("unused")
8806    private void sendMoveMouseIfLatest(boolean removeFocus, boolean stopPaintingCaret) {
8807        if (removeFocus) {
8808            clearTextEntry();
8809        }
8810        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
8811                stopPaintingCaret ? 1 : 0, 0,
8812                cursorData());
8813    }
8814
8815    /**
8816     * Called by JNI to send a message to the webcore thread that the user
8817     * touched the webpage.
8818     * @param touchGeneration Generation number of the touch, to ignore touches
8819     *      after a new one has been generated.
8820     * @param frame Pointer to the frame holding the node that was touched.
8821     * @param node Pointer to the node touched.
8822     * @param x x-position of the touch.
8823     * @param y y-position of the touch.
8824     */
8825    private void sendMotionUp(int touchGeneration,
8826            int frame, int node, int x, int y) {
8827        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
8828        touchUpData.mMoveGeneration = touchGeneration;
8829        touchUpData.mFrame = frame;
8830        touchUpData.mNode = node;
8831        touchUpData.mX = x;
8832        touchUpData.mY = y;
8833        touchUpData.mNativeLayer = nativeScrollableLayer(
8834                x, y, touchUpData.mNativeLayerRect, null);
8835        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
8836    }
8837
8838
8839    private int getScaledMaxXScroll() {
8840        int width;
8841        if (mHeightCanMeasure == false) {
8842            width = getViewWidth() / 4;
8843        } else {
8844            Rect visRect = new Rect();
8845            calcOurVisibleRect(visRect);
8846            width = visRect.width() / 2;
8847        }
8848        // FIXME the divisor should be retrieved from somewhere
8849        return viewToContentX(width);
8850    }
8851
8852    private int getScaledMaxYScroll() {
8853        int height;
8854        if (mHeightCanMeasure == false) {
8855            height = getViewHeight() / 4;
8856        } else {
8857            Rect visRect = new Rect();
8858            calcOurVisibleRect(visRect);
8859            height = visRect.height() / 2;
8860        }
8861        // FIXME the divisor should be retrieved from somewhere
8862        // the closest thing today is hard-coded into ScrollView.java
8863        // (from ScrollView.java, line 363)   int maxJump = height/2;
8864        return Math.round(height * mZoomManager.getInvScale());
8865    }
8866
8867    /**
8868     * Called by JNI to invalidate view
8869     */
8870    private void viewInvalidate() {
8871        invalidate();
8872    }
8873
8874    /**
8875     * Pass the key directly to the page.  This assumes that
8876     * nativePageShouldHandleShiftAndArrows() returned true.
8877     */
8878    private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
8879        int keyEventAction;
8880        int eventHubAction;
8881        if (down) {
8882            keyEventAction = KeyEvent.ACTION_DOWN;
8883            eventHubAction = EventHub.KEY_DOWN;
8884            playSoundEffect(keyCodeToSoundsEffect(keyCode));
8885        } else {
8886            keyEventAction = KeyEvent.ACTION_UP;
8887            eventHubAction = EventHub.KEY_UP;
8888        }
8889
8890        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
8891                1, (metaState & KeyEvent.META_SHIFT_ON)
8892                | (metaState & KeyEvent.META_ALT_ON)
8893                | (metaState & KeyEvent.META_SYM_ON)
8894                , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
8895        mWebViewCore.sendMessage(eventHubAction, event);
8896    }
8897
8898    // return true if the key was handled
8899    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
8900            long time) {
8901        if (mNativeClass == 0) {
8902            return false;
8903        }
8904        mInitialHitTestResult = null;
8905        mLastCursorTime = time;
8906        mLastCursorBounds = nativeGetCursorRingBounds();
8907        boolean keyHandled
8908                = nativeMoveCursor(keyCode, count, noScroll) == false;
8909        if (DebugFlags.WEB_VIEW) {
8910            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
8911                    + " mLastCursorTime=" + mLastCursorTime
8912                    + " handled=" + keyHandled);
8913        }
8914        if (keyHandled == false) {
8915            return keyHandled;
8916        }
8917        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
8918        if (contentCursorRingBounds.isEmpty()) return keyHandled;
8919        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
8920        // set last touch so that context menu related functions will work
8921        mLastTouchX = (viewCursorRingBounds.left + viewCursorRingBounds.right) / 2;
8922        mLastTouchY = (viewCursorRingBounds.top + viewCursorRingBounds.bottom) / 2;
8923        if (mHeightCanMeasure == false) {
8924            return keyHandled;
8925        }
8926        Rect visRect = new Rect();
8927        calcOurVisibleRect(visRect);
8928        Rect outset = new Rect(visRect);
8929        int maxXScroll = visRect.width() / 2;
8930        int maxYScroll = visRect.height() / 2;
8931        outset.inset(-maxXScroll, -maxYScroll);
8932        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
8933            return keyHandled;
8934        }
8935        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
8936        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
8937                maxXScroll);
8938        if (maxH > 0) {
8939            pinScrollBy(maxH, 0, true, 0);
8940        } else {
8941            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
8942                    -maxXScroll);
8943            if (maxH < 0) {
8944                pinScrollBy(maxH, 0, true, 0);
8945            }
8946        }
8947        if (mLastCursorBounds.isEmpty()) return keyHandled;
8948        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
8949            return keyHandled;
8950        }
8951        if (DebugFlags.WEB_VIEW) {
8952            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
8953                    + contentCursorRingBounds);
8954        }
8955        requestRectangleOnScreen(viewCursorRingBounds);
8956        return keyHandled;
8957    }
8958
8959    /**
8960     * @return Whether accessibility script has been injected.
8961     */
8962    private boolean accessibilityScriptInjected() {
8963        // TODO: Maybe the injected script should announce its presence in
8964        // the page meta-tag so the nativePageShouldHandleShiftAndArrows
8965        // will check that as one of the conditions it looks for
8966        return mAccessibilityScriptInjected;
8967    }
8968
8969    /**
8970     * Set the background color. It's white by default. Pass
8971     * zero to make the view transparent.
8972     * @param color   the ARGB color described by Color.java
8973     */
8974    @Override
8975    public void setBackgroundColor(int color) {
8976        mBackgroundColor = color;
8977        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
8978    }
8979
8980    /**
8981     * @deprecated This method is now obsolete.
8982     */
8983    @Deprecated
8984    public void debugDump() {
8985        checkThread();
8986        nativeDebugDump();
8987        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
8988    }
8989
8990    /**
8991     * Draw the HTML page into the specified canvas. This call ignores any
8992     * view-specific zoom, scroll offset, or other changes. It does not draw
8993     * any view-specific chrome, such as progress or URL bars.
8994     *
8995     * @hide only needs to be accessible to Browser and testing
8996     */
8997    public void drawPage(Canvas canvas) {
8998        nativeDraw(canvas, 0, 0, false);
8999    }
9000
9001    /**
9002     * Enable the communication b/t the webView and VideoViewProxy
9003     *
9004     * @hide only used by the Browser
9005     */
9006    public void setHTML5VideoViewProxy(HTML5VideoViewProxy proxy) {
9007        mHTML5VideoViewProxy = proxy;
9008    }
9009
9010    /**
9011     * Enable expanded tiles bound for smoother scrolling.
9012     *
9013     * @hide only used by the Browser
9014     */
9015    public void setExpandedTileBounds(boolean enabled) {
9016        nativeSetExpandedTileBounds(enabled);
9017    }
9018
9019    /**
9020     * Set the time to wait between passing touches to WebCore. See also the
9021     * TOUCH_SENT_INTERVAL member for further discussion.
9022     *
9023     * @hide This is only used by the DRT test application.
9024     */
9025    public void setTouchInterval(int interval) {
9026        mCurrentTouchInterval = interval;
9027    }
9028
9029    /**
9030     *  Update our cache with updatedText.
9031     *  @param updatedText  The new text to put in our cache.
9032     */
9033    /* package */ void updateCachedTextfield(String updatedText) {
9034        // Also place our generation number so that when we look at the cache
9035        // we recognize that it is up to date.
9036        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
9037    }
9038
9039    /*package*/ void autoFillForm(int autoFillQueryId) {
9040        mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0);
9041    }
9042
9043    /* package */ ViewManager getViewManager() {
9044        return mViewManager;
9045    }
9046
9047    private static void checkThread() {
9048        if (Looper.myLooper() != Looper.getMainLooper()) {
9049            RuntimeException exception = new RuntimeException(
9050                    "A WebView method was called on thread '" +
9051                    Thread.currentThread().getName() + "'. " +
9052                    "All WebView methods must be called on the UI thread. " +
9053                    "Future versions of WebView may not support use on other threads.");
9054            Log.e(LOGTAG, Log.getStackTraceString(exception));
9055            StrictMode.onWebViewMethodCalledOnWrongThread(exception);
9056        }
9057    }
9058
9059    private native int nativeCacheHitFramePointer();
9060    private native boolean  nativeCacheHitIsPlugin();
9061    private native Rect nativeCacheHitNodeBounds();
9062    private native int nativeCacheHitNodePointer();
9063    /* package */ native void nativeClearCursor();
9064    private native void     nativeCreate(int ptr, String drawableDir, AssetManager am);
9065    private native int      nativeCursorFramePointer();
9066    private native Rect     nativeCursorNodeBounds();
9067    private native int nativeCursorNodePointer();
9068    private native boolean  nativeCursorIntersects(Rect visibleRect);
9069    private native boolean  nativeCursorIsAnchor();
9070    private native boolean  nativeCursorIsTextInput();
9071    private native Point    nativeCursorPosition();
9072    private native String   nativeCursorText();
9073    /**
9074     * Returns true if the native cursor node says it wants to handle key events
9075     * (ala plugins). This can only be called if mNativeClass is non-zero!
9076     */
9077    private native boolean  nativeCursorWantsKeyEvents();
9078    private native void     nativeDebugDump();
9079    private native void     nativeDestroy();
9080
9081    /**
9082     * Draw the picture set with a background color and extra. If
9083     * "splitIfNeeded" is true and the return value is not 0, the return value
9084     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
9085     * native allocation can be freed.
9086     */
9087    private native int nativeDraw(Canvas canvas, int color, int extra,
9088            boolean splitIfNeeded);
9089    private native void     nativeDumpDisplayTree(String urlOrNull);
9090    private native boolean  nativeEvaluateLayersAnimations();
9091    private native int      nativeGetDrawGLFunction(Rect rect, Rect viewRect,
9092            float scale, int extras);
9093    private native void     nativeUpdateDrawGLFunction(Rect rect, Rect viewRect);
9094    private native void     nativeExtendSelection(int x, int y);
9095    private native int      nativeFindAll(String findLower, String findUpper,
9096            boolean sameAsLastSearch);
9097    private native void     nativeFindNext(boolean forward);
9098    /* package */ native int      nativeFocusCandidateFramePointer();
9099    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
9100    /* package */ native boolean  nativeFocusCandidateIsPassword();
9101    private native boolean  nativeFocusCandidateIsRtlText();
9102    private native boolean  nativeFocusCandidateIsTextInput();
9103    /* package */ native int      nativeFocusCandidateMaxLength();
9104    /* package */ native boolean  nativeFocusCandidateIsAutoComplete();
9105    /* package */ native String   nativeFocusCandidateName();
9106    private native Rect     nativeFocusCandidateNodeBounds();
9107    /**
9108     * @return A Rect with left, top, right, bottom set to the corresponding
9109     * padding values in the focus candidate, if it is a textfield/textarea with
9110     * a style.  Otherwise return null.  This is not actually a rectangle; Rect
9111     * is being used to pass four integers.
9112     */
9113    private native Rect     nativeFocusCandidatePaddingRect();
9114    /* package */ native int      nativeFocusCandidatePointer();
9115    private native String   nativeFocusCandidateText();
9116    /* package */ native float    nativeFocusCandidateTextSize();
9117    /* package */ native int nativeFocusCandidateLineHeight();
9118    /**
9119     * Returns an integer corresponding to WebView.cpp::type.
9120     * See WebTextView.setType()
9121     */
9122    private native int      nativeFocusCandidateType();
9123    private native boolean  nativeFocusIsPlugin();
9124    private native Rect     nativeFocusNodeBounds();
9125    /* package */ native int nativeFocusNodePointer();
9126    private native Rect     nativeGetCursorRingBounds();
9127    private native String   nativeGetSelection();
9128    private native boolean  nativeHasCursorNode();
9129    private native boolean  nativeHasFocusNode();
9130    private native void     nativeHideCursor();
9131    private native boolean  nativeHitSelection(int x, int y);
9132    private native String   nativeImageURI(int x, int y);
9133    private native void     nativeInstrumentReport();
9134    private native Rect     nativeLayerBounds(int layer);
9135    /* package */ native boolean nativeMoveCursorToNextTextInput();
9136    // return true if the page has been scrolled
9137    private native boolean  nativeMotionUp(int x, int y, int slop);
9138    // returns false if it handled the key
9139    private native boolean  nativeMoveCursor(int keyCode, int count,
9140            boolean noScroll);
9141    private native int      nativeMoveGeneration();
9142    private native void     nativeMoveSelection(int x, int y);
9143    /**
9144     * @return true if the page should get the shift and arrow keys, rather
9145     * than select text/navigation.
9146     *
9147     * If the focus is a plugin, or if the focus and cursor match and are
9148     * a contentEditable element, then the page should handle these keys.
9149     */
9150    private native boolean  nativePageShouldHandleShiftAndArrows();
9151    private native boolean  nativePointInNavCache(int x, int y, int slop);
9152    // Like many other of our native methods, you must make sure that
9153    // mNativeClass is not null before calling this method.
9154    private native void     nativeRecordButtons(boolean focused,
9155            boolean pressed, boolean invalidate);
9156    private native void     nativeResetSelection();
9157    private native Point    nativeSelectableText();
9158    private native void     nativeSelectAll();
9159    private native void     nativeSelectBestAt(Rect rect);
9160    private native void     nativeSelectAt(int x, int y);
9161    private native int      nativeSelectionX();
9162    private native int      nativeSelectionY();
9163    private native int      nativeFindIndex();
9164    private native void     nativeSetExtendSelection();
9165    private native void     nativeSetFindIsEmpty();
9166    private native void     nativeSetFindIsUp(boolean isUp);
9167    private native void     nativeSetHeightCanMeasure(boolean measure);
9168    private native void     nativeSetBaseLayer(int layer, Region invalRegion,
9169            boolean showVisualIndicator, boolean isPictureAfterFirstLayout);
9170    private native int      nativeGetBaseLayer();
9171    private native void     nativeShowCursorTimed();
9172    private native void     nativeReplaceBaseContent(int content);
9173    private native void     nativeCopyBaseContentToPicture(Picture pict);
9174    private native boolean  nativeHasContent();
9175    private native void     nativeSetSelectionPointer(boolean set,
9176            float scale, int x, int y);
9177    private native boolean  nativeStartSelection(int x, int y);
9178    private native void     nativeStopGL();
9179    private native Rect     nativeSubtractLayers(Rect content);
9180    private native int      nativeTextGeneration();
9181    // Never call this version except by updateCachedTextfield(String) -
9182    // we always want to pass in our generation number.
9183    private native void     nativeUpdateCachedTextfield(String updatedText,
9184            int generation);
9185    private native boolean  nativeWordSelection(int x, int y);
9186    // return NO_LEFTEDGE means failure.
9187    static final int NO_LEFTEDGE = -1;
9188    native int nativeGetBlockLeftEdge(int x, int y, float scale);
9189
9190    private native void nativeSetExpandedTileBounds(boolean enabled);
9191
9192    // Returns a pointer to the scrollable LayerAndroid at the given point.
9193    private native int      nativeScrollableLayer(int x, int y, Rect scrollRect,
9194            Rect scrollBounds);
9195    /**
9196     * Scroll the specified layer.
9197     * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer.
9198     * @param newX Destination x position to which to scroll.
9199     * @param newY Destination y position to which to scroll.
9200     * @return True if the layer is successfully scrolled.
9201     */
9202    private native boolean  nativeScrollLayer(int layer, int newX, int newY);
9203}
9204