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