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