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