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