WebView.java revision a3ebcc9d2ea15614529e112880e1d16e81a178e1
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.Context;
22import android.content.DialogInterface;
23import android.content.Intent;
24import android.content.DialogInterface.OnCancelListener;
25import android.database.DataSetObserver;
26import android.graphics.Bitmap;
27import android.graphics.Canvas;
28import android.graphics.Color;
29import android.graphics.CornerPathEffect;
30import android.graphics.DrawFilter;
31import android.graphics.Interpolator;
32import android.graphics.Paint;
33import android.graphics.PaintFlagsDrawFilter;
34import android.graphics.Picture;
35import android.graphics.Point;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.drawable.Drawable;
40import android.net.Uri;
41import android.net.http.SslCertificate;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.Message;
45import android.os.ServiceManager;
46import android.os.SystemClock;
47import android.speech.tts.TextToSpeech;
48import android.text.IClipboard;
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            try {
4057                IClipboard clip = IClipboard.Stub.asInterface(
4058                        ServiceManager.getService("clipboard"));
4059                        clip.setClipboardText(selection);
4060            } catch (android.os.RemoteException e) {
4061                Log.e(LOGTAG, "Clipboard failed", e);
4062            }
4063        }
4064        invalidate(); // remove selection region and pointer
4065        return copiedSomething;
4066    }
4067
4068    /**
4069     * @hide pending API council approval.
4070     */
4071    public String getSelection() {
4072        if (mNativeClass == 0) return "";
4073        return nativeGetSelection();
4074    }
4075
4076    @Override
4077    protected void onAttachedToWindow() {
4078        super.onAttachedToWindow();
4079        if (hasWindowFocus()) setActive(true);
4080    }
4081
4082    @Override
4083    protected void onDetachedFromWindow() {
4084        clearTextEntry(false);
4085        mZoomManager.dismissZoomPicker();
4086        if (hasWindowFocus()) setActive(false);
4087        super.onDetachedFromWindow();
4088    }
4089
4090    @Override
4091    protected void onVisibilityChanged(View changedView, int visibility) {
4092        super.onVisibilityChanged(changedView, visibility);
4093        // The zoomManager may be null if the webview is created from XML that
4094        // specifies the view's visibility param as not visible (see http://b/2794841)
4095        if (visibility != View.VISIBLE && mZoomManager != null) {
4096            mZoomManager.dismissZoomPicker();
4097        }
4098    }
4099
4100    /**
4101     * @deprecated WebView no longer needs to implement
4102     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4103     */
4104    @Deprecated
4105    public void onChildViewAdded(View parent, View child) {}
4106
4107    /**
4108     * @deprecated WebView no longer needs to implement
4109     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4110     */
4111    @Deprecated
4112    public void onChildViewRemoved(View p, View child) {}
4113
4114    /**
4115     * @deprecated WebView should not have implemented
4116     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
4117     * does nothing now.
4118     */
4119    @Deprecated
4120    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
4121    }
4122
4123    private void setActive(boolean active) {
4124        if (active) {
4125            if (hasFocus()) {
4126                // If our window regained focus, and we have focus, then begin
4127                // drawing the cursor ring
4128                mDrawCursorRing = true;
4129                if (mNativeClass != 0) {
4130                    nativeRecordButtons(true, false, true);
4131                    if (inEditingMode()) {
4132                        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0);
4133                    }
4134                }
4135            } else {
4136                // If our window gained focus, but we do not have it, do not
4137                // draw the cursor ring.
4138                mDrawCursorRing = false;
4139                // We do not call nativeRecordButtons here because we assume
4140                // that when we lost focus, or window focus, it got called with
4141                // false for the first parameter
4142            }
4143        } else {
4144            if (!mZoomManager.isZoomPickerVisible()) {
4145                /*
4146                 * The external zoom controls come in their own window, so our
4147                 * window loses focus. Our policy is to not draw the cursor ring
4148                 * if our window is not focused, but this is an exception since
4149                 * the user can still navigate the web page with the zoom
4150                 * controls showing.
4151                 */
4152                mDrawCursorRing = false;
4153            }
4154            mGotKeyDown = false;
4155            mShiftIsPressed = false;
4156            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4157            mTouchMode = TOUCH_DONE_MODE;
4158            if (mNativeClass != 0) {
4159                nativeRecordButtons(false, false, true);
4160            }
4161            setFocusControllerInactive();
4162        }
4163        invalidate();
4164    }
4165
4166    // To avoid drawing the cursor ring, and remove the TextView when our window
4167    // loses focus.
4168    @Override
4169    public void onWindowFocusChanged(boolean hasWindowFocus) {
4170        setActive(hasWindowFocus);
4171        if (hasWindowFocus) {
4172            BrowserFrame.sJavaBridge.setActiveWebView(this);
4173        } else {
4174            BrowserFrame.sJavaBridge.removeActiveWebView(this);
4175        }
4176        super.onWindowFocusChanged(hasWindowFocus);
4177    }
4178
4179    /*
4180     * Pass a message to WebCore Thread, telling the WebCore::Page's
4181     * FocusController to be  "inactive" so that it will
4182     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
4183     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
4184     */
4185    /* package */ void setFocusControllerInactive() {
4186        // Do not need to also check whether mWebViewCore is null, because
4187        // mNativeClass is only set if mWebViewCore is non null
4188        if (mNativeClass == 0) return;
4189        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
4190    }
4191
4192    @Override
4193    protected void onFocusChanged(boolean focused, int direction,
4194            Rect previouslyFocusedRect) {
4195        if (DebugFlags.WEB_VIEW) {
4196            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
4197        }
4198        if (focused) {
4199            // When we regain focus, if we have window focus, resume drawing
4200            // the cursor ring
4201            if (hasWindowFocus()) {
4202                mDrawCursorRing = true;
4203                if (mNativeClass != 0) {
4204                    nativeRecordButtons(true, false, true);
4205                }
4206            //} else {
4207                // The WebView has gained focus while we do not have
4208                // windowfocus.  When our window lost focus, we should have
4209                // called nativeRecordButtons(false...)
4210            }
4211        } else {
4212            // When we lost focus, unless focus went to the TextView (which is
4213            // true if we are in editing mode), stop drawing the cursor ring.
4214            if (!inEditingMode()) {
4215                mDrawCursorRing = false;
4216                if (mNativeClass != 0) {
4217                    nativeRecordButtons(false, false, true);
4218                }
4219                setFocusControllerInactive();
4220            }
4221            mGotKeyDown = false;
4222        }
4223
4224        super.onFocusChanged(focused, direction, previouslyFocusedRect);
4225    }
4226
4227    /**
4228     * @hide
4229     */
4230    @Override
4231    protected boolean setFrame(int left, int top, int right, int bottom) {
4232        boolean changed = super.setFrame(left, top, right, bottom);
4233        if (!changed && mHeightCanMeasure) {
4234            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
4235            // in WebViewCore after we get the first layout. We do call
4236            // requestLayout() when we get contentSizeChanged(). But the View
4237            // system won't call onSizeChanged if the dimension is not changed.
4238            // In this case, we need to call sendViewSizeZoom() explicitly to
4239            // notify the WebKit about the new dimensions.
4240            sendViewSizeZoom(false);
4241        }
4242        return changed;
4243    }
4244
4245    @Override
4246    protected void onSizeChanged(int w, int h, int ow, int oh) {
4247        super.onSizeChanged(w, h, ow, oh);
4248
4249        // adjust the max viewport width depending on the view dimensions. This
4250        // is to ensure the scaling is not going insane. So do not shrink it if
4251        // the view size is temporarily smaller, e.g. when soft keyboard is up.
4252        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
4253        if (newMaxViewportWidth > sMaxViewportWidth) {
4254            sMaxViewportWidth = newMaxViewportWidth;
4255        }
4256
4257        mZoomManager.onSizeChanged(w, h, ow, oh);
4258    }
4259
4260    @Override
4261    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4262        super.onScrollChanged(l, t, oldl, oldt);
4263        sendOurVisibleRect();
4264        // update WebKit if visible title bar height changed. The logic is same
4265        // as getVisibleTitleHeight.
4266        int titleHeight = getTitleHeight();
4267        if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
4268            sendViewSizeZoom(false);
4269        }
4270    }
4271
4272    @Override
4273    public boolean dispatchKeyEvent(KeyEvent event) {
4274        boolean dispatch = true;
4275
4276        // Textfields, plugins, and contentEditable nodes need to receive the
4277        // shift up key even if another key was released while the shift key
4278        // was held down.
4279        if (!inEditingMode() && (mNativeClass == 0
4280                || !nativePageShouldHandleShiftAndArrows())) {
4281            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4282                mGotKeyDown = true;
4283            } else {
4284                if (!mGotKeyDown) {
4285                    /*
4286                     * We got a key up for which we were not the recipient of
4287                     * the original key down. Don't give it to the view.
4288                     */
4289                    dispatch = false;
4290                }
4291                mGotKeyDown = false;
4292            }
4293        }
4294
4295        if (dispatch) {
4296            return super.dispatchKeyEvent(event);
4297        } else {
4298            // We didn't dispatch, so let something else handle the key
4299            return false;
4300        }
4301    }
4302
4303    // Here are the snap align logic:
4304    // 1. If it starts nearly horizontally or vertically, snap align;
4305    // 2. If there is a dramitic direction change, let it go;
4306    // 3. If there is a same direction back and forth, lock it.
4307
4308    // adjustable parameters
4309    private int mMinLockSnapReverseDistance;
4310    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
4311    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
4312
4313    private static int sign(float x) {
4314        return x > 0 ? 1 : (x < 0 ? -1 : 0);
4315    }
4316
4317    // if the page can scroll <= this value, we won't allow the drag tracker
4318    // to have any effect.
4319    private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4;
4320
4321    private class DragTrackerHandler {
4322        private final DragTracker mProxy;
4323        private final float mStartY, mStartX;
4324        private final float mMinDY, mMinDX;
4325        private final float mMaxDY, mMaxDX;
4326        private float mCurrStretchY, mCurrStretchX;
4327        private int mSX, mSY;
4328        private Interpolator mInterp;
4329        private float[] mXY = new float[2];
4330
4331        // inner (non-state) classes can't have enums :(
4332        private static final int DRAGGING_STATE = 0;
4333        private static final int ANIMATING_STATE = 1;
4334        private static final int FINISHED_STATE = 2;
4335        private int mState;
4336
4337        public DragTrackerHandler(float x, float y, DragTracker proxy) {
4338            mProxy = proxy;
4339
4340            int docBottom = computeVerticalScrollRange() + getTitleHeight();
4341            int viewTop = getScrollY();
4342            int viewBottom = viewTop + getHeight();
4343
4344            mStartY = y;
4345            mMinDY = -viewTop;
4346            mMaxDY = docBottom - viewBottom;
4347
4348            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4349                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y +
4350                      " up/down= " + mMinDY + " " + mMaxDY);
4351            }
4352
4353            int docRight = computeHorizontalScrollRange();
4354            int viewLeft = getScrollX();
4355            int viewRight = viewLeft + getWidth();
4356            mStartX = x;
4357            mMinDX = -viewLeft;
4358            mMaxDX = docRight - viewRight;
4359
4360            mState = DRAGGING_STATE;
4361            mProxy.onStartDrag(x, y);
4362
4363            // ensure we buildBitmap at least once
4364            mSX = -99999;
4365        }
4366
4367        private float computeStretch(float delta, float min, float max) {
4368            float stretch = 0;
4369            if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) {
4370                if (delta < min) {
4371                    stretch = delta - min;
4372                } else if (delta > max) {
4373                    stretch = delta - max;
4374                }
4375            }
4376            return stretch;
4377        }
4378
4379        public void dragTo(float x, float y) {
4380            float sy = computeStretch(mStartY - y, mMinDY, mMaxDY);
4381            float sx = computeStretch(mStartX - x, mMinDX, mMaxDX);
4382
4383            if ((mSnapScrollMode & SNAP_X) != 0) {
4384                sy = 0;
4385            } else if ((mSnapScrollMode & SNAP_Y) != 0) {
4386                sx = 0;
4387            }
4388
4389            if (mCurrStretchX != sx || mCurrStretchY != sy) {
4390                mCurrStretchX = sx;
4391                mCurrStretchY = sy;
4392                if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4393                    Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx +
4394                          " " + sy);
4395                }
4396                if (mProxy.onStretchChange(sx, sy)) {
4397                    invalidate();
4398                }
4399            }
4400        }
4401
4402        public void stopDrag() {
4403            final int DURATION = 200;
4404            int now = (int)SystemClock.uptimeMillis();
4405            mInterp = new Interpolator(2);
4406            mXY[0] = mCurrStretchX;
4407            mXY[1] = mCurrStretchY;
4408         //   float[] blend = new float[] { 0.5f, 0, 0.75f, 1 };
4409            float[] blend = new float[] { 0, 0.5f, 0.75f, 1 };
4410            mInterp.setKeyFrame(0, now, mXY, blend);
4411            float[] zerozero = new float[] { 0, 0 };
4412            mInterp.setKeyFrame(1, now + DURATION, zerozero, null);
4413            mState = ANIMATING_STATE;
4414
4415            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4416                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation");
4417            }
4418        }
4419
4420        // Call this after each draw. If it ruturns null, the tracker is done
4421        public boolean isFinished() {
4422            return mState == FINISHED_STATE;
4423        }
4424
4425        private int hiddenHeightOfTitleBar() {
4426            return getTitleHeight() - getVisibleTitleHeight();
4427        }
4428
4429        // need a way to know if 565 or 8888 is the right config for
4430        // capturing the display and giving it to the drag proxy
4431        private Bitmap.Config offscreenBitmapConfig() {
4432            // hard code 565 for now
4433            return Bitmap.Config.RGB_565;
4434        }
4435
4436        /*  If the tracker draws, then this returns true, otherwise it will
4437            return false, and draw nothing.
4438         */
4439        public boolean draw(Canvas canvas) {
4440            if (mCurrStretchX != 0 || mCurrStretchY != 0) {
4441                int sx = getScrollX();
4442                int sy = getScrollY() - hiddenHeightOfTitleBar();
4443                if (mSX != sx || mSY != sy) {
4444                    buildBitmap(sx, sy);
4445                    mSX = sx;
4446                    mSY = sy;
4447                }
4448
4449                if (mState == ANIMATING_STATE) {
4450                    Interpolator.Result result = mInterp.timeToValues(mXY);
4451                    if (result == Interpolator.Result.FREEZE_END) {
4452                        mState = FINISHED_STATE;
4453                        return false;
4454                    } else {
4455                        mProxy.onStretchChange(mXY[0], mXY[1]);
4456                        invalidate();
4457                        // fall through to the draw
4458                    }
4459                }
4460                int count = canvas.save(Canvas.MATRIX_SAVE_FLAG);
4461                canvas.translate(sx, sy);
4462                mProxy.onDraw(canvas);
4463                canvas.restoreToCount(count);
4464                return true;
4465            }
4466            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4467                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " +
4468                      mCurrStretchX + " " + mCurrStretchY);
4469            }
4470            return false;
4471        }
4472
4473        private void buildBitmap(int sx, int sy) {
4474            int w = getWidth();
4475            int h = getViewHeight();
4476            Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig());
4477            Canvas canvas = new Canvas(bm);
4478            canvas.translate(-sx, -sy);
4479            drawContent(canvas);
4480
4481            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4482                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx +
4483                      " " + sy + " " + w + " " + h);
4484            }
4485            mProxy.onBitmapChange(bm);
4486        }
4487    }
4488
4489    /** @hide */
4490    public static class DragTracker {
4491        public void onStartDrag(float x, float y) {}
4492        public boolean onStretchChange(float sx, float sy) {
4493            // return true to have us inval the view
4494            return false;
4495        }
4496        public void onStopDrag() {}
4497        public void onBitmapChange(Bitmap bm) {}
4498        public void onDraw(Canvas canvas) {}
4499    }
4500
4501    /** @hide */
4502    public DragTracker getDragTracker() {
4503        return mDragTracker;
4504    }
4505
4506    /** @hide */
4507    public void setDragTracker(DragTracker tracker) {
4508        mDragTracker = tracker;
4509    }
4510
4511    private DragTracker mDragTracker;
4512    private DragTrackerHandler mDragTrackerHandler;
4513
4514    private boolean hitFocusedPlugin(int contentX, int contentY) {
4515        if (DebugFlags.WEB_VIEW) {
4516            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
4517            Rect r = nativeFocusNodeBounds();
4518            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
4519                    + ", " + r.right + ", " + r.bottom + ")");
4520        }
4521        return nativeFocusIsPlugin()
4522                && nativeFocusNodeBounds().contains(contentX, contentY);
4523    }
4524
4525    private boolean shouldForwardTouchEvent() {
4526        return mFullScreenHolder != null || (mForwardTouchEvents
4527                && !mSelectingText
4528                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
4529    }
4530
4531    private boolean inFullScreenMode() {
4532        return mFullScreenHolder != null;
4533    }
4534
4535    void onPinchToZoomAnimationStart() {
4536        // cancel the single touch handling
4537        cancelTouch();
4538        onZoomAnimationStart();
4539    }
4540
4541    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
4542        onZoomAnimationEnd();
4543        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
4544        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
4545        // as it may trigger the unwanted fling.
4546        mTouchMode = TOUCH_PINCH_DRAG;
4547        mConfirmMove = true;
4548        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
4549    }
4550
4551    private void startScrollingLayer(float gestureX, float gestureY) {
4552        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4553            int contentX = viewToContentX((int) gestureX + mScrollX);
4554            int contentY = viewToContentY((int) gestureY + mScrollY);
4555            mScrollingLayer = nativeScrollableLayer(contentX, contentY);
4556            if (mScrollingLayer != 0) {
4557                mTouchMode = TOUCH_DRAG_LAYER_MODE;
4558            }
4559        }
4560    }
4561
4562    // 1/(density * density) used to compute the distance between points.
4563    // Computed in init().
4564    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
4565
4566    // The distance between two points reported in onTouchEvent scaled by the
4567    // density of the screen.
4568    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
4569
4570    @Override
4571    public boolean onTouchEvent(MotionEvent ev) {
4572        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
4573            return false;
4574        }
4575
4576        if (DebugFlags.WEB_VIEW) {
4577            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
4578                    + mTouchMode);
4579        }
4580
4581        int action = ev.getAction();
4582        float x = ev.getX();
4583        float y = ev.getY();
4584        long eventTime = ev.getEventTime();
4585
4586        final ScaleGestureDetector detector =
4587                mZoomManager.getMultiTouchGestureDetector();
4588        boolean skipScaleGesture = false;
4589        // Set to the mid-point of a two-finger gesture used to detect if the
4590        // user has touched a layer.
4591        float gestureX = x;
4592        float gestureY = y;
4593        if (!detector.isInProgress()) {
4594            // The gesture for scrolling a layer is two fingers close together.
4595            // FIXME: we may consider giving WebKit an option to handle
4596            // multi-touch events later.
4597            if (ev.getPointerCount() > 1) {
4598                float dx = ev.getX(1) - ev.getX(0);
4599                float dy = ev.getY(1) - ev.getY(0);
4600                float dist = (dx * dx + dy * dy) *
4601                        DRAG_LAYER_INVERSE_DENSITY_SQUARED;
4602                // Use the approximate center to determine if the gesture is in
4603                // a layer.
4604                gestureX = ev.getX(0) + (dx * .5f);
4605                gestureY = ev.getY(0) + (dy * .5f);
4606                // Now use a consistent point for tracking movement.
4607                if (ev.getX(0) < ev.getX(1)) {
4608                    x = ev.getX(0);
4609                    y = ev.getY(0);
4610                } else {
4611                    x = ev.getX(1);
4612                    y = ev.getY(1);
4613                }
4614                action = ev.getActionMasked();
4615                if (dist < DRAG_LAYER_FINGER_DISTANCE) {
4616                    skipScaleGesture = true;
4617                } else if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
4618                    // Fingers moved too far apart while dragging, the user
4619                    // might be trying to zoom.
4620                    mTouchMode = TOUCH_INIT_MODE;
4621                }
4622            }
4623        }
4624
4625        // FIXME: we may consider to give WebKit an option to handle multi-touch
4626        // events later.
4627        if (mZoomManager.supportsMultiTouchZoom() && ev.getPointerCount() > 1 &&
4628                mTouchMode != TOUCH_DRAG_LAYER_MODE && !skipScaleGesture) {
4629
4630            // if the page disallows zoom, skip multi-pointer action
4631            if (mZoomManager.isZoomScaleFixed()) {
4632                return true;
4633            }
4634
4635            if (!detector.isInProgress() &&
4636                    ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
4637                // Insert a fake pointer down event in order to start
4638                // the zoom scale detector.
4639                MotionEvent temp = MotionEvent.obtain(ev);
4640                // Clear the original event and set it to
4641                // ACTION_POINTER_DOWN.
4642                temp.setAction(temp.getAction() &
4643                        ~MotionEvent.ACTION_MASK |
4644                        MotionEvent.ACTION_POINTER_DOWN);
4645                detector.onTouchEvent(temp);
4646            }
4647
4648            detector.onTouchEvent(ev);
4649
4650            if (detector.isInProgress()) {
4651                mLastTouchTime = eventTime;
4652                return true;
4653            }
4654
4655            x = detector.getFocusX();
4656            y = detector.getFocusY();
4657            action = ev.getAction() & MotionEvent.ACTION_MASK;
4658            if (action == MotionEvent.ACTION_POINTER_DOWN) {
4659                cancelTouch();
4660                action = MotionEvent.ACTION_DOWN;
4661            } else if (action == MotionEvent.ACTION_POINTER_UP) {
4662                // set mLastTouchX/Y to the remaining point
4663                mLastTouchX = x;
4664                mLastTouchY = y;
4665            } else if (action == MotionEvent.ACTION_MOVE) {
4666                // negative x or y indicate it is on the edge, skip it.
4667                if (x < 0 || y < 0) {
4668                    return true;
4669                }
4670            }
4671        }
4672
4673        // Due to the touch screen edge effect, a touch closer to the edge
4674        // always snapped to the edge. As getViewWidth() can be different from
4675        // getWidth() due to the scrollbar, adjusting the point to match
4676        // getViewWidth(). Same applied to the height.
4677        x = Math.min(x, getViewWidth() - 1);
4678        y = Math.min(y, getViewHeightWithTitle() - 1);
4679
4680        float fDeltaX = mLastTouchX - x;
4681        float fDeltaY = mLastTouchY - y;
4682        int deltaX = (int) fDeltaX;
4683        int deltaY = (int) fDeltaY;
4684        int contentX = viewToContentX((int) x + mScrollX);
4685        int contentY = viewToContentY((int) y + mScrollY);
4686
4687        switch (action) {
4688            case MotionEvent.ACTION_DOWN: {
4689                mPreventDefault = PREVENT_DEFAULT_NO;
4690                mConfirmMove = false;
4691                if (!mScroller.isFinished()) {
4692                    // stop the current scroll animation, but if this is
4693                    // the start of a fling, allow it to add to the current
4694                    // fling's velocity
4695                    mScroller.abortAnimation();
4696                    mTouchMode = TOUCH_DRAG_START_MODE;
4697                    mConfirmMove = true;
4698                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
4699                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
4700                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
4701                    if (getSettings().supportTouchOnly()) {
4702                        removeTouchHighlight(true);
4703                    }
4704                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
4705                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
4706                    } else {
4707                        // commit the short press action for the previous tap
4708                        doShortPress();
4709                        mTouchMode = TOUCH_INIT_MODE;
4710                        mDeferTouchProcess = (!inFullScreenMode()
4711                                && mForwardTouchEvents) ? hitFocusedPlugin(
4712                                contentX, contentY) : false;
4713                    }
4714                } else { // the normal case
4715                    mTouchMode = TOUCH_INIT_MODE;
4716                    mDeferTouchProcess = (!inFullScreenMode()
4717                            && mForwardTouchEvents) ? hitFocusedPlugin(
4718                            contentX, contentY) : false;
4719                    mWebViewCore.sendMessage(
4720                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
4721                    if (getSettings().supportTouchOnly()) {
4722                        TouchHighlightData data = new TouchHighlightData();
4723                        data.mX = contentX;
4724                        data.mY = contentY;
4725                        data.mSlop = viewToContentDimension(mNavSlop);
4726                        mWebViewCore.sendMessageDelayed(
4727                                EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
4728                                ViewConfiguration.getTapTimeout());
4729                        if (DEBUG_TOUCH_HIGHLIGHT) {
4730                            if (getSettings().getNavDump()) {
4731                                mTouchHighlightX = (int) x + mScrollX;
4732                                mTouchHighlightY = (int) y + mScrollY;
4733                                mPrivateHandler.postDelayed(new Runnable() {
4734                                    public void run() {
4735                                        mTouchHighlightX = mTouchHighlightY = 0;
4736                                        invalidate();
4737                                    }
4738                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
4739                            }
4740                        }
4741                    }
4742                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
4743                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
4744                                (eventTime - mLastTouchUpTime), eventTime);
4745                    }
4746                    if (mSelectingText) {
4747                        mDrawSelectionPointer = false;
4748                        mSelectionStarted = nativeStartSelection(contentX, contentY);
4749                        if (DebugFlags.WEB_VIEW) {
4750                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
4751                        }
4752                        invalidate();
4753                    }
4754                }
4755                // Trigger the link
4756                if (mTouchMode == TOUCH_INIT_MODE
4757                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4758                    mPrivateHandler.sendEmptyMessageDelayed(
4759                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
4760                    mPrivateHandler.sendEmptyMessageDelayed(
4761                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
4762                    if (inFullScreenMode() || mDeferTouchProcess) {
4763                        mPreventDefault = PREVENT_DEFAULT_YES;
4764                    } else if (mForwardTouchEvents) {
4765                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
4766                    } else {
4767                        mPreventDefault = PREVENT_DEFAULT_NO;
4768                    }
4769                    // pass the touch events from UI thread to WebCore thread
4770                    if (shouldForwardTouchEvent()) {
4771                        TouchEventData ted = new TouchEventData();
4772                        ted.mAction = action;
4773                        ted.mX = contentX;
4774                        ted.mY = contentY;
4775                        ted.mMetaState = ev.getMetaState();
4776                        ted.mReprocess = mDeferTouchProcess;
4777                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4778                        if (mDeferTouchProcess) {
4779                            // still needs to set them for compute deltaX/Y
4780                            mLastTouchX = x;
4781                            mLastTouchY = y;
4782                            break;
4783                        }
4784                        if (!inFullScreenMode()) {
4785                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
4786                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
4787                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
4788                                            action, 0), TAP_TIMEOUT);
4789                        }
4790                    }
4791                }
4792                startTouch(x, y, eventTime);
4793                break;
4794            }
4795            case MotionEvent.ACTION_MOVE: {
4796                boolean firstMove = false;
4797                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
4798                        >= mTouchSlopSquare) {
4799                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4800                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4801                    mConfirmMove = true;
4802                    firstMove = true;
4803                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4804                        mTouchMode = TOUCH_INIT_MODE;
4805                    }
4806                    if (getSettings().supportTouchOnly()) {
4807                        removeTouchHighlight(true);
4808                    }
4809                }
4810                // pass the touch events from UI thread to WebCore thread
4811                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
4812                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
4813                    TouchEventData ted = new TouchEventData();
4814                    ted.mAction = action;
4815                    ted.mX = contentX;
4816                    ted.mY = contentY;
4817                    ted.mMetaState = ev.getMetaState();
4818                    ted.mReprocess = mDeferTouchProcess;
4819                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4820                    mLastSentTouchTime = eventTime;
4821                    if (mDeferTouchProcess) {
4822                        break;
4823                    }
4824                    if (firstMove && !inFullScreenMode()) {
4825                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
4826                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
4827                                        action, 0), TAP_TIMEOUT);
4828                    }
4829                }
4830                if (mTouchMode == TOUCH_DONE_MODE
4831                        || mPreventDefault == PREVENT_DEFAULT_YES) {
4832                    // no dragging during scroll zoom animation, or when prevent
4833                    // default is yes
4834                    break;
4835                }
4836                if (mVelocityTracker == null) {
4837                    Log.e(LOGTAG, "Got null mVelocityTracker when "
4838                            + "mPreventDefault = " + mPreventDefault
4839                            + " mDeferTouchProcess = " + mDeferTouchProcess
4840                            + " mTouchMode = " + mTouchMode);
4841                }
4842                mVelocityTracker.addMovement(ev);
4843                if (mSelectingText && mSelectionStarted) {
4844                    if (DebugFlags.WEB_VIEW) {
4845                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
4846                    }
4847                    nativeExtendSelection(contentX, contentY);
4848                    invalidate();
4849                    break;
4850                }
4851
4852                if (mTouchMode != TOUCH_DRAG_MODE &&
4853                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4854
4855                    if (!mConfirmMove) {
4856                        break;
4857                    }
4858
4859                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
4860                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
4861                        // track mLastTouchTime as we may need to do fling at
4862                        // ACTION_UP
4863                        mLastTouchTime = eventTime;
4864                        break;
4865                    }
4866                    // if it starts nearly horizontal or vertical, enforce it
4867                    int ax = Math.abs(deltaX);
4868                    int ay = Math.abs(deltaY);
4869                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
4870                        mSnapScrollMode = SNAP_X;
4871                        mSnapPositive = deltaX > 0;
4872                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
4873                        mSnapScrollMode = SNAP_Y;
4874                        mSnapPositive = deltaY > 0;
4875                    }
4876
4877                    mTouchMode = TOUCH_DRAG_MODE;
4878                    mLastTouchX = x;
4879                    mLastTouchY = y;
4880                    fDeltaX = 0.0f;
4881                    fDeltaY = 0.0f;
4882                    deltaX = 0;
4883                    deltaY = 0;
4884
4885                    if (skipScaleGesture) {
4886                        startScrollingLayer(gestureX, gestureY);
4887                    }
4888                    startDrag();
4889                }
4890
4891                if (mDragTrackerHandler != null) {
4892                    mDragTrackerHandler.dragTo(x, y);
4893                }
4894
4895                // do pan
4896                if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4897                    int newScrollX = pinLocX(mScrollX + deltaX);
4898                    int newDeltaX = newScrollX - mScrollX;
4899                    if (deltaX != newDeltaX) {
4900                        deltaX = newDeltaX;
4901                        fDeltaX = (float) newDeltaX;
4902                    }
4903                    int newScrollY = pinLocY(mScrollY + deltaY);
4904                    int newDeltaY = newScrollY - mScrollY;
4905                    if (deltaY != newDeltaY) {
4906                        deltaY = newDeltaY;
4907                        fDeltaY = (float) newDeltaY;
4908                    }
4909                }
4910                boolean done = false;
4911                boolean keepScrollBarsVisible = false;
4912                if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
4913                    mLastTouchX = x;
4914                    mLastTouchY = y;
4915                    keepScrollBarsVisible = done = true;
4916                } else {
4917                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
4918                        int ax = Math.abs(deltaX);
4919                        int ay = Math.abs(deltaY);
4920                        if (mSnapScrollMode == SNAP_X) {
4921                            // radical change means getting out of snap mode
4922                            if (ay > MAX_SLOPE_FOR_DIAG * ax
4923                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
4924                                mSnapScrollMode = SNAP_NONE;
4925                            }
4926                            // reverse direction means lock in the snap mode
4927                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
4928                                    (mSnapPositive
4929                                    ? deltaX < -mMinLockSnapReverseDistance
4930                                    : deltaX > mMinLockSnapReverseDistance)) {
4931                                mSnapScrollMode |= SNAP_LOCK;
4932                            }
4933                        } else {
4934                            // radical change means getting out of snap mode
4935                            if (ax > MAX_SLOPE_FOR_DIAG * ay
4936                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
4937                                mSnapScrollMode = SNAP_NONE;
4938                            }
4939                            // reverse direction means lock in the snap mode
4940                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
4941                                    (mSnapPositive
4942                                    ? deltaY < -mMinLockSnapReverseDistance
4943                                    : deltaY > mMinLockSnapReverseDistance)) {
4944                                mSnapScrollMode |= SNAP_LOCK;
4945                            }
4946                        }
4947                    }
4948                    if (mSnapScrollMode != SNAP_NONE) {
4949                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
4950                            deltaY = 0;
4951                        } else {
4952                            deltaX = 0;
4953                        }
4954                    }
4955                    if ((deltaX | deltaY) != 0) {
4956                        if (deltaX != 0) {
4957                            mLastTouchX = x;
4958                        }
4959                        if (deltaY != 0) {
4960                            mLastTouchY = y;
4961                        }
4962                        mHeldMotionless = MOTIONLESS_FALSE;
4963                    } else {
4964                        // keep the scrollbar on the screen even there is no
4965                        // scroll
4966                        mLastTouchX = x;
4967                        mLastTouchY = y;
4968                        keepScrollBarsVisible = true;
4969                    }
4970                    mLastTouchTime = eventTime;
4971                    mUserScroll = true;
4972                }
4973
4974                doDrag(deltaX, deltaY);
4975
4976                // Turn off scrollbars when dragging a layer.
4977                if (keepScrollBarsVisible &&
4978                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4979                    if (mHeldMotionless != MOTIONLESS_TRUE) {
4980                        mHeldMotionless = MOTIONLESS_TRUE;
4981                        invalidate();
4982                    }
4983                    // keep the scrollbar on the screen even there is no scroll
4984                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
4985                            false);
4986                    // return false to indicate that we can't pan out of the
4987                    // view space
4988                    return !done;
4989                }
4990                break;
4991            }
4992            case MotionEvent.ACTION_UP: {
4993                if (!isFocused()) requestFocus();
4994                // pass the touch events from UI thread to WebCore thread
4995                if (shouldForwardTouchEvent()) {
4996                    TouchEventData ted = new TouchEventData();
4997                    ted.mAction = action;
4998                    ted.mX = contentX;
4999                    ted.mY = contentY;
5000                    ted.mMetaState = ev.getMetaState();
5001                    ted.mReprocess = mDeferTouchProcess;
5002                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5003                }
5004                mLastTouchUpTime = eventTime;
5005                switch (mTouchMode) {
5006                    case TOUCH_DOUBLE_TAP_MODE: // double tap
5007                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5008                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5009                        if (inFullScreenMode() || mDeferTouchProcess) {
5010                            TouchEventData ted = new TouchEventData();
5011                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
5012                            ted.mX = contentX;
5013                            ted.mY = contentY;
5014                            ted.mMetaState = ev.getMetaState();
5015                            ted.mReprocess = mDeferTouchProcess;
5016                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5017                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
5018                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
5019                            mTouchMode = TOUCH_DONE_MODE;
5020                        }
5021                        break;
5022                    case TOUCH_INIT_MODE: // tap
5023                    case TOUCH_SHORTPRESS_START_MODE:
5024                    case TOUCH_SHORTPRESS_MODE:
5025                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5026                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5027                        if (mConfirmMove) {
5028                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
5029                                    " WebCore's response for touch down.");
5030                            if (mPreventDefault != PREVENT_DEFAULT_YES
5031                                    && (computeMaxScrollX() > 0
5032                                            || computeMaxScrollY() > 0)) {
5033                                // If the user has performed a very quick touch
5034                                // sequence it is possible that we may get here
5035                                // before WebCore has had a chance to process the events.
5036                                // In this case, any call to preventDefault in the
5037                                // JS touch handler will not have been executed yet.
5038                                // Hence we will see both the UI (now) and WebCore
5039                                // (when context switches) handling the event,
5040                                // regardless of whether the web developer actually
5041                                // doeses preventDefault in their touch handler. This
5042                                // is the nature of our asynchronous touch model.
5043
5044                                // we will not rewrite drag code here, but we
5045                                // will try fling if it applies.
5046                                WebViewCore.reducePriority();
5047                                // to get better performance, pause updating the
5048                                // picture
5049                                WebViewCore.pauseUpdatePicture(mWebViewCore);
5050                                // fall through to TOUCH_DRAG_MODE
5051                            } else {
5052                                // WebKit may consume the touch event and modify
5053                                // DOM. drawContentPicture() will be called with
5054                                // animateSroll as true for better performance.
5055                                // Force redraw in high-quality.
5056                                invalidate();
5057                                break;
5058                            }
5059                        } else {
5060                            if (mSelectingText) {
5061                                // tapping on selection or controls does nothing
5062                                if (!nativeHitSelection(contentX, contentY)) {
5063                                    selectionDone();
5064                                }
5065                                break;
5066                            }
5067                            // only trigger double tap if the WebView is
5068                            // scalable
5069                            if (mTouchMode == TOUCH_INIT_MODE
5070                                    && (canZoomIn() || canZoomOut())) {
5071                                mPrivateHandler.sendEmptyMessageDelayed(
5072                                        RELEASE_SINGLE_TAP, ViewConfiguration
5073                                                .getDoubleTapTimeout());
5074                            } else {
5075                                doShortPress();
5076                            }
5077                            break;
5078                        }
5079                    case TOUCH_DRAG_MODE:
5080                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5081                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5082                        // if the user waits a while w/o moving before the
5083                        // up, we don't want to do a fling
5084                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
5085                            if (mVelocityTracker == null) {
5086                                Log.e(LOGTAG, "Got null mVelocityTracker when "
5087                                        + "mPreventDefault = "
5088                                        + mPreventDefault
5089                                        + " mDeferTouchProcess = "
5090                                        + mDeferTouchProcess);
5091                            }
5092                            mVelocityTracker.addMovement(ev);
5093                            // set to MOTIONLESS_IGNORE so that it won't keep
5094                            // removing and sending message in
5095                            // drawCoreAndCursorRing()
5096                            mHeldMotionless = MOTIONLESS_IGNORE;
5097                            doFling();
5098                            break;
5099                        }
5100                        // redraw in high-quality, as we're done dragging
5101                        mHeldMotionless = MOTIONLESS_TRUE;
5102                        invalidate();
5103                        // fall through
5104                    case TOUCH_DRAG_START_MODE:
5105                    case TOUCH_DRAG_LAYER_MODE:
5106                        // TOUCH_DRAG_START_MODE should not happen for the real
5107                        // device as we almost certain will get a MOVE. But this
5108                        // is possible on emulator.
5109                        mLastVelocity = 0;
5110                        WebViewCore.resumePriority();
5111                        WebViewCore.resumeUpdatePicture(mWebViewCore);
5112                        break;
5113                }
5114                stopTouch();
5115                break;
5116            }
5117            case MotionEvent.ACTION_CANCEL: {
5118                if (mTouchMode == TOUCH_DRAG_MODE) {
5119                    invalidate();
5120                }
5121                cancelWebCoreTouchEvent(contentX, contentY, false);
5122                cancelTouch();
5123                break;
5124            }
5125        }
5126        return true;
5127    }
5128
5129    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
5130        if (shouldForwardTouchEvent()) {
5131            if (removeEvents) {
5132                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5133            }
5134            TouchEventData ted = new TouchEventData();
5135            ted.mX = x;
5136            ted.mY = y;
5137            ted.mAction = MotionEvent.ACTION_CANCEL;
5138            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5139            mPreventDefault = PREVENT_DEFAULT_IGNORE;
5140        }
5141    }
5142
5143    private void startTouch(float x, float y, long eventTime) {
5144        // Remember where the motion event started
5145        mLastTouchX = x;
5146        mLastTouchY = y;
5147        mLastTouchTime = eventTime;
5148        mVelocityTracker = VelocityTracker.obtain();
5149        mSnapScrollMode = SNAP_NONE;
5150        if (mDragTracker != null) {
5151            mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker);
5152        }
5153    }
5154
5155    private void startDrag() {
5156        WebViewCore.reducePriority();
5157        // to get better performance, pause updating the picture
5158        WebViewCore.pauseUpdatePicture(mWebViewCore);
5159        if (!mDragFromTextInput) {
5160            nativeHideCursor();
5161        }
5162
5163        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
5164                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
5165            mZoomManager.invokeZoomPicker();
5166        }
5167    }
5168
5169    private void doDrag(int deltaX, int deltaY) {
5170        if ((deltaX | deltaY) != 0) {
5171            if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
5172                deltaX = viewToContentDimension(deltaX);
5173                deltaY = viewToContentDimension(deltaY);
5174                if (nativeScrollLayer(mScrollingLayer, deltaX, deltaY)) {
5175                    invalidate();
5176                }
5177                return;
5178            }
5179            scrollBy(deltaX, deltaY);
5180        }
5181        mZoomManager.keepZoomPickerVisible();
5182    }
5183
5184    private void stopTouch() {
5185        if (mDragTrackerHandler != null) {
5186            mDragTrackerHandler.stopDrag();
5187        }
5188        // we also use mVelocityTracker == null to tell us that we are
5189        // not "moving around", so we can take the slower/prettier
5190        // mode in the drawing code
5191        if (mVelocityTracker != null) {
5192            mVelocityTracker.recycle();
5193            mVelocityTracker = null;
5194        }
5195    }
5196
5197    private void cancelTouch() {
5198        if (mDragTrackerHandler != null) {
5199            mDragTrackerHandler.stopDrag();
5200        }
5201        // we also use mVelocityTracker == null to tell us that we are
5202        // not "moving around", so we can take the slower/prettier
5203        // mode in the drawing code
5204        if (mVelocityTracker != null) {
5205            mVelocityTracker.recycle();
5206            mVelocityTracker = null;
5207        }
5208        if (mTouchMode == TOUCH_DRAG_MODE ||
5209                mTouchMode == TOUCH_DRAG_LAYER_MODE) {
5210            WebViewCore.resumePriority();
5211            WebViewCore.resumeUpdatePicture(mWebViewCore);
5212        }
5213        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5214        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5215        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5216        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5217        if (getSettings().supportTouchOnly()) {
5218            removeTouchHighlight(true);
5219        }
5220        mHeldMotionless = MOTIONLESS_TRUE;
5221        mTouchMode = TOUCH_DONE_MODE;
5222        nativeHideCursor();
5223    }
5224
5225    private long mTrackballFirstTime = 0;
5226    private long mTrackballLastTime = 0;
5227    private float mTrackballRemainsX = 0.0f;
5228    private float mTrackballRemainsY = 0.0f;
5229    private int mTrackballXMove = 0;
5230    private int mTrackballYMove = 0;
5231    private boolean mSelectingText = false;
5232    private boolean mSelectionStarted = false;
5233    private boolean mExtendSelection = false;
5234    private boolean mDrawSelectionPointer = false;
5235    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
5236    private static final int TRACKBALL_TIMEOUT = 200;
5237    private static final int TRACKBALL_WAIT = 100;
5238    private static final int TRACKBALL_SCALE = 400;
5239    private static final int TRACKBALL_SCROLL_COUNT = 5;
5240    private static final int TRACKBALL_MOVE_COUNT = 10;
5241    private static final int TRACKBALL_MULTIPLIER = 3;
5242    private static final int SELECT_CURSOR_OFFSET = 16;
5243    private int mSelectX = 0;
5244    private int mSelectY = 0;
5245    private boolean mFocusSizeChanged = false;
5246    private boolean mShiftIsPressed = false;
5247    private boolean mTrackballDown = false;
5248    private long mTrackballUpTime = 0;
5249    private long mLastCursorTime = 0;
5250    private Rect mLastCursorBounds;
5251
5252    // Set by default; BrowserActivity clears to interpret trackball data
5253    // directly for movement. Currently, the framework only passes
5254    // arrow key events, not trackball events, from one child to the next
5255    private boolean mMapTrackballToArrowKeys = true;
5256
5257    public void setMapTrackballToArrowKeys(boolean setMap) {
5258        mMapTrackballToArrowKeys = setMap;
5259    }
5260
5261    void resetTrackballTime() {
5262        mTrackballLastTime = 0;
5263    }
5264
5265    @Override
5266    public boolean onTrackballEvent(MotionEvent ev) {
5267        long time = ev.getEventTime();
5268        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
5269            if (ev.getY() > 0) pageDown(true);
5270            if (ev.getY() < 0) pageUp(true);
5271            return true;
5272        }
5273        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
5274            if (mSelectingText) {
5275                return true; // discard press if copy in progress
5276            }
5277            mTrackballDown = true;
5278            if (mNativeClass == 0) {
5279                return false;
5280            }
5281            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
5282            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
5283                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
5284                nativeSelectBestAt(mLastCursorBounds);
5285            }
5286            if (DebugFlags.WEB_VIEW) {
5287                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
5288                        + " time=" + time
5289                        + " mLastCursorTime=" + mLastCursorTime);
5290            }
5291            if (isInTouchMode()) requestFocusFromTouch();
5292            return false; // let common code in onKeyDown at it
5293        }
5294        if (ev.getAction() == MotionEvent.ACTION_UP) {
5295            // LONG_PRESS_CENTER is set in common onKeyDown
5296            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5297            mTrackballDown = false;
5298            mTrackballUpTime = time;
5299            if (mSelectingText) {
5300                if (mExtendSelection) {
5301                    copySelection();
5302                    selectionDone();
5303                } else {
5304                    mExtendSelection = true;
5305                    nativeSetExtendSelection();
5306                    invalidate(); // draw the i-beam instead of the arrow
5307                }
5308                return true; // discard press if copy in progress
5309            }
5310            if (DebugFlags.WEB_VIEW) {
5311                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
5312                        + " time=" + time
5313                );
5314            }
5315            return false; // let common code in onKeyUp at it
5316        }
5317        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
5318            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
5319            return false;
5320        }
5321        if (mTrackballDown) {
5322            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
5323            return true; // discard move if trackball is down
5324        }
5325        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
5326            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
5327            return true;
5328        }
5329        // TODO: alternatively we can do panning as touch does
5330        switchOutDrawHistory();
5331        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
5332            if (DebugFlags.WEB_VIEW) {
5333                Log.v(LOGTAG, "onTrackballEvent time="
5334                        + time + " last=" + mTrackballLastTime);
5335            }
5336            mTrackballFirstTime = time;
5337            mTrackballXMove = mTrackballYMove = 0;
5338        }
5339        mTrackballLastTime = time;
5340        if (DebugFlags.WEB_VIEW) {
5341            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
5342        }
5343        mTrackballRemainsX += ev.getX();
5344        mTrackballRemainsY += ev.getY();
5345        doTrackball(time);
5346        return true;
5347    }
5348
5349    void moveSelection(float xRate, float yRate) {
5350        if (mNativeClass == 0)
5351            return;
5352        int width = getViewWidth();
5353        int height = getViewHeight();
5354        mSelectX += xRate;
5355        mSelectY += yRate;
5356        int maxX = width + mScrollX;
5357        int maxY = height + mScrollY;
5358        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
5359                , mSelectX));
5360        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
5361                , mSelectY));
5362        if (DebugFlags.WEB_VIEW) {
5363            Log.v(LOGTAG, "moveSelection"
5364                    + " mSelectX=" + mSelectX
5365                    + " mSelectY=" + mSelectY
5366                    + " mScrollX=" + mScrollX
5367                    + " mScrollY=" + mScrollY
5368                    + " xRate=" + xRate
5369                    + " yRate=" + yRate
5370                    );
5371        }
5372        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
5373        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
5374                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5375                : 0;
5376        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
5377                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5378                : 0;
5379        pinScrollBy(scrollX, scrollY, true, 0);
5380        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
5381        requestRectangleOnScreen(select);
5382        invalidate();
5383   }
5384
5385    private int scaleTrackballX(float xRate, int width) {
5386        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
5387        int nextXMove = xMove;
5388        if (xMove > 0) {
5389            if (xMove > mTrackballXMove) {
5390                xMove -= mTrackballXMove;
5391            }
5392        } else if (xMove < mTrackballXMove) {
5393            xMove -= mTrackballXMove;
5394        }
5395        mTrackballXMove = nextXMove;
5396        return xMove;
5397    }
5398
5399    private int scaleTrackballY(float yRate, int height) {
5400        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
5401        int nextYMove = yMove;
5402        if (yMove > 0) {
5403            if (yMove > mTrackballYMove) {
5404                yMove -= mTrackballYMove;
5405            }
5406        } else if (yMove < mTrackballYMove) {
5407            yMove -= mTrackballYMove;
5408        }
5409        mTrackballYMove = nextYMove;
5410        return yMove;
5411    }
5412
5413    private int keyCodeToSoundsEffect(int keyCode) {
5414        switch(keyCode) {
5415            case KeyEvent.KEYCODE_DPAD_UP:
5416                return SoundEffectConstants.NAVIGATION_UP;
5417            case KeyEvent.KEYCODE_DPAD_RIGHT:
5418                return SoundEffectConstants.NAVIGATION_RIGHT;
5419            case KeyEvent.KEYCODE_DPAD_DOWN:
5420                return SoundEffectConstants.NAVIGATION_DOWN;
5421            case KeyEvent.KEYCODE_DPAD_LEFT:
5422                return SoundEffectConstants.NAVIGATION_LEFT;
5423        }
5424        throw new IllegalArgumentException("keyCode must be one of " +
5425                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
5426                "KEYCODE_DPAD_LEFT}.");
5427    }
5428
5429    private void doTrackball(long time) {
5430        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
5431        if (elapsed == 0) {
5432            elapsed = TRACKBALL_TIMEOUT;
5433        }
5434        float xRate = mTrackballRemainsX * 1000 / elapsed;
5435        float yRate = mTrackballRemainsY * 1000 / elapsed;
5436        int viewWidth = getViewWidth();
5437        int viewHeight = getViewHeight();
5438        if (mSelectingText) {
5439            if (!mDrawSelectionPointer) {
5440                // The last selection was made by touch, disabling drawing the
5441                // selection pointer. Allow the trackball to adjust the
5442                // position of the touch control.
5443                mSelectX = contentToViewX(nativeSelectionX());
5444                mSelectY = contentToViewY(nativeSelectionY());
5445                mDrawSelectionPointer = mExtendSelection = true;
5446                nativeSetExtendSelection();
5447            }
5448            moveSelection(scaleTrackballX(xRate, viewWidth),
5449                    scaleTrackballY(yRate, viewHeight));
5450            mTrackballRemainsX = mTrackballRemainsY = 0;
5451            return;
5452        }
5453        float ax = Math.abs(xRate);
5454        float ay = Math.abs(yRate);
5455        float maxA = Math.max(ax, ay);
5456        if (DebugFlags.WEB_VIEW) {
5457            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
5458                    + " xRate=" + xRate
5459                    + " yRate=" + yRate
5460                    + " mTrackballRemainsX=" + mTrackballRemainsX
5461                    + " mTrackballRemainsY=" + mTrackballRemainsY);
5462        }
5463        int width = mContentWidth - viewWidth;
5464        int height = mContentHeight - viewHeight;
5465        if (width < 0) width = 0;
5466        if (height < 0) height = 0;
5467        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
5468        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
5469        maxA = Math.max(ax, ay);
5470        int count = Math.max(0, (int) maxA);
5471        int oldScrollX = mScrollX;
5472        int oldScrollY = mScrollY;
5473        if (count > 0) {
5474            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
5475                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
5476                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
5477                    KeyEvent.KEYCODE_DPAD_RIGHT;
5478            count = Math.min(count, TRACKBALL_MOVE_COUNT);
5479            if (DebugFlags.WEB_VIEW) {
5480                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
5481                        + " count=" + count
5482                        + " mTrackballRemainsX=" + mTrackballRemainsX
5483                        + " mTrackballRemainsY=" + mTrackballRemainsY);
5484            }
5485            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
5486                for (int i = 0; i < count; i++) {
5487                    letPageHandleNavKey(selectKeyCode, time, true);
5488                }
5489                letPageHandleNavKey(selectKeyCode, time, false);
5490            } else if (navHandledKey(selectKeyCode, count, false, time)) {
5491                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
5492            }
5493            mTrackballRemainsX = mTrackballRemainsY = 0;
5494        }
5495        if (count >= TRACKBALL_SCROLL_COUNT) {
5496            int xMove = scaleTrackballX(xRate, width);
5497            int yMove = scaleTrackballY(yRate, height);
5498            if (DebugFlags.WEB_VIEW) {
5499                Log.v(LOGTAG, "doTrackball pinScrollBy"
5500                        + " count=" + count
5501                        + " xMove=" + xMove + " yMove=" + yMove
5502                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
5503                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
5504                        );
5505            }
5506            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
5507                xMove = 0;
5508            }
5509            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
5510                yMove = 0;
5511            }
5512            if (xMove != 0 || yMove != 0) {
5513                pinScrollBy(xMove, yMove, true, 0);
5514            }
5515            mUserScroll = true;
5516        }
5517    }
5518
5519    private int computeMaxScrollX() {
5520        return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
5521    }
5522
5523    private int computeMaxScrollY() {
5524        return Math.max(computeVerticalScrollRange() + getTitleHeight()
5525                - getViewHeightWithTitle(), 0);
5526    }
5527
5528    boolean updateScrollCoordinates(int x, int y) {
5529        int oldX = mScrollX;
5530        int oldY = mScrollY;
5531        mScrollX = x;
5532        mScrollY = y;
5533        if (oldX != mScrollX || oldY != mScrollY) {
5534            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
5535            return true;
5536        } else {
5537            return false;
5538        }
5539    }
5540
5541    public void flingScroll(int vx, int vy) {
5542        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
5543                computeMaxScrollY());
5544        invalidate();
5545    }
5546
5547    private void doFling() {
5548        if (mVelocityTracker == null) {
5549            return;
5550        }
5551        int maxX = computeMaxScrollX();
5552        int maxY = computeMaxScrollY();
5553
5554        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
5555        int vx = (int) mVelocityTracker.getXVelocity();
5556        int vy = (int) mVelocityTracker.getYVelocity();
5557
5558        if (mSnapScrollMode != SNAP_NONE) {
5559            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5560                vy = 0;
5561            } else {
5562                vx = 0;
5563            }
5564        }
5565        if (true /* EMG release: make our fling more like Maps' */) {
5566            // maps cuts their velocity in half
5567            vx = vx * 3 / 4;
5568            vy = vy * 3 / 4;
5569        }
5570        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
5571            WebViewCore.resumePriority();
5572            WebViewCore.resumeUpdatePicture(mWebViewCore);
5573            return;
5574        }
5575        float currentVelocity = mScroller.getCurrVelocity();
5576        float velocity = (float) Math.hypot(vx, vy);
5577        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
5578                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
5579            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
5580                    - Math.atan2(vy, vx)));
5581            final float circle = (float) (Math.PI) * 2.0f;
5582            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
5583                vx += currentVelocity * mLastVelX / mLastVelocity;
5584                vy += currentVelocity * mLastVelY / mLastVelocity;
5585                velocity = (float) Math.hypot(vx, vy);
5586                if (DebugFlags.WEB_VIEW) {
5587                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
5588                }
5589            } else if (DebugFlags.WEB_VIEW) {
5590                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
5591            }
5592        } else if (DebugFlags.WEB_VIEW) {
5593            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
5594                    + " current=" + currentVelocity
5595                    + " vx=" + vx + " vy=" + vy
5596                    + " maxX=" + maxX + " maxY=" + maxY
5597                    + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
5598        }
5599        mLastVelX = vx;
5600        mLastVelY = vy;
5601        mLastVelocity = velocity;
5602
5603        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
5604        final int time = mScroller.getDuration();
5605        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time);
5606        awakenScrollBars(time);
5607        invalidate();
5608    }
5609
5610    /**
5611     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
5612     * in charge of installing this view to the view hierarchy. This view will
5613     * become visible when the user starts scrolling via touch and fade away if
5614     * the user does not interact with it.
5615     * <p/>
5616     * API version 3 introduces a built-in zoom mechanism that is shown
5617     * automatically by the MapView. This is the preferred approach for
5618     * showing the zoom UI.
5619     *
5620     * @deprecated The built-in zoom mechanism is preferred, see
5621     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
5622     */
5623    @Deprecated
5624    public View getZoomControls() {
5625        if (!getSettings().supportZoom()) {
5626            Log.w(LOGTAG, "This WebView doesn't support zoom.");
5627            return null;
5628        }
5629        return mZoomManager.getExternalZoomPicker();
5630    }
5631
5632    void dismissZoomControl() {
5633        mZoomManager.dismissZoomPicker();
5634    }
5635
5636    float getDefaultZoomScale() {
5637        return mZoomManager.getDefaultScale();
5638    }
5639
5640    /**
5641     * @return TRUE if the WebView can be zoomed in.
5642     */
5643    public boolean canZoomIn() {
5644        return mZoomManager.canZoomIn();
5645    }
5646
5647    /**
5648     * @return TRUE if the WebView can be zoomed out.
5649     */
5650    public boolean canZoomOut() {
5651        return mZoomManager.canZoomOut();
5652    }
5653
5654    /**
5655     * Perform zoom in in the webview
5656     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
5657     */
5658    public boolean zoomIn() {
5659        return mZoomManager.zoomIn();
5660    }
5661
5662    /**
5663     * Perform zoom out in the webview
5664     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
5665     */
5666    public boolean zoomOut() {
5667        return mZoomManager.zoomOut();
5668    }
5669
5670    private void updateSelection() {
5671        if (mNativeClass == 0) {
5672            return;
5673        }
5674        // mLastTouchX and mLastTouchY are the point in the current viewport
5675        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5676        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5677        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
5678                contentX + mNavSlop, contentY + mNavSlop);
5679        nativeSelectBestAt(rect);
5680    }
5681
5682    /**
5683     * Scroll the focused text field/area to match the WebTextView
5684     * @param xPercent New x position of the WebTextView from 0 to 1.
5685     * @param y New y position of the WebTextView in view coordinates
5686     */
5687    /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
5688        if (!inEditingMode() || mWebViewCore == null) {
5689            return;
5690        }
5691        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
5692                // Since this position is relative to the top of the text input
5693                // field, we do not need to take the title bar's height into
5694                // consideration.
5695                viewToContentDimension(y),
5696                new Float(xPercent));
5697    }
5698
5699    /**
5700     * Set our starting point and time for a drag from the WebTextView.
5701     */
5702    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
5703        if (!inEditingMode()) {
5704            return;
5705        }
5706        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
5707        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
5708        mLastTouchTime = eventTime;
5709        if (!mScroller.isFinished()) {
5710            abortAnimation();
5711            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5712        }
5713        mSnapScrollMode = SNAP_NONE;
5714        mVelocityTracker = VelocityTracker.obtain();
5715        mTouchMode = TOUCH_DRAG_START_MODE;
5716    }
5717
5718    /**
5719     * Given a motion event from the WebTextView, set its location to our
5720     * coordinates, and handle the event.
5721     */
5722    /*package*/ boolean textFieldDrag(MotionEvent event) {
5723        if (!inEditingMode()) {
5724            return false;
5725        }
5726        mDragFromTextInput = true;
5727        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
5728                (float) (mWebTextView.getTop() - mScrollY));
5729        boolean result = onTouchEvent(event);
5730        mDragFromTextInput = false;
5731        return result;
5732    }
5733
5734    /**
5735     * Due a touch up from a WebTextView.  This will be handled by webkit to
5736     * change the selection.
5737     * @param event MotionEvent in the WebTextView's coordinates.
5738     */
5739    /*package*/ void touchUpOnTextField(MotionEvent event) {
5740        if (!inEditingMode()) {
5741            return;
5742        }
5743        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
5744        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
5745        nativeMotionUp(x, y, mNavSlop);
5746    }
5747
5748    /**
5749     * Called when pressing the center key or trackball on a textfield.
5750     */
5751    /*package*/ void centerKeyPressOnTextField() {
5752        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
5753                    nativeCursorNodePointer());
5754    }
5755
5756    private void doShortPress() {
5757        if (mNativeClass == 0) {
5758            return;
5759        }
5760        if (mPreventDefault == PREVENT_DEFAULT_YES) {
5761            return;
5762        }
5763        mTouchMode = TOUCH_DONE_MODE;
5764        switchOutDrawHistory();
5765        // mLastTouchX and mLastTouchY are the point in the current viewport
5766        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5767        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5768        if (getSettings().supportTouchOnly()) {
5769            removeTouchHighlight(false);
5770            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
5771            // use "0" as generation id to inform WebKit to use the same x/y as
5772            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
5773            touchUpData.mMoveGeneration = 0;
5774            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
5775        } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
5776            WebViewCore.MotionUpData motionUpData = new WebViewCore
5777                    .MotionUpData();
5778            motionUpData.mFrame = nativeCacheHitFramePointer();
5779            motionUpData.mNode = nativeCacheHitNodePointer();
5780            motionUpData.mBounds = nativeCacheHitNodeBounds();
5781            motionUpData.mX = contentX;
5782            motionUpData.mY = contentY;
5783            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
5784                    motionUpData);
5785        } else {
5786            doMotionUp(contentX, contentY);
5787        }
5788    }
5789
5790    private void doMotionUp(int contentX, int contentY) {
5791        if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) {
5792            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
5793        }
5794        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
5795            playSoundEffect(SoundEffectConstants.CLICK);
5796        }
5797    }
5798
5799    /*
5800     * Return true if the view (Plugin) is fully visible and maximized inside
5801     * the WebView.
5802     */
5803    boolean isPluginFitOnScreen(ViewManager.ChildView view) {
5804        final int viewWidth = getViewWidth();
5805        final int viewHeight = getViewHeightWithTitle();
5806        float scale = Math.min((float) viewWidth / view.width, (float) viewHeight / view.height);
5807        scale = mZoomManager.computeScaleWithLimits(scale);
5808        return !mZoomManager.willScaleTriggerZoom(scale)
5809                && contentToViewX(view.x) >= mScrollX
5810                && contentToViewX(view.x + view.width) <= mScrollX + viewWidth
5811                && contentToViewY(view.y) >= mScrollY
5812                && contentToViewY(view.y + view.height) <= mScrollY + viewHeight;
5813    }
5814
5815    /*
5816     * Maximize and center the rectangle, specified in the document coordinate
5817     * space, inside the WebView. If the zoom doesn't need to be changed, do an
5818     * animated scroll to center it. If the zoom needs to be changed, find the
5819     * zoom center and do a smooth zoom transition.
5820     */
5821    void centerFitRect(int docX, int docY, int docWidth, int docHeight) {
5822        int viewWidth = getViewWidth();
5823        int viewHeight = getViewHeightWithTitle();
5824        float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight
5825                / docHeight);
5826        scale = mZoomManager.computeScaleWithLimits(scale);
5827        if (!mZoomManager.willScaleTriggerZoom(scale)) {
5828            pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2,
5829                    contentToViewY(docY + docHeight / 2) - viewHeight / 2,
5830                    true, 0);
5831        } else {
5832            float actualScale = mZoomManager.getScale();
5833            float oldScreenX = docX * actualScale - mScrollX;
5834            float rectViewX = docX * scale;
5835            float rectViewWidth = docWidth * scale;
5836            float newMaxWidth = mContentWidth * scale;
5837            float newScreenX = (viewWidth - rectViewWidth) / 2;
5838            // pin the newX to the WebView
5839            if (newScreenX > rectViewX) {
5840                newScreenX = rectViewX;
5841            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
5842                newScreenX = viewWidth - (newMaxWidth - rectViewX);
5843            }
5844            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
5845                    / (scale - actualScale);
5846            float oldScreenY = docY * actualScale + getTitleHeight()
5847                    - mScrollY;
5848            float rectViewY = docY * scale + getTitleHeight();
5849            float rectViewHeight = docHeight * scale;
5850            float newMaxHeight = mContentHeight * scale + getTitleHeight();
5851            float newScreenY = (viewHeight - rectViewHeight) / 2;
5852            // pin the newY to the WebView
5853            if (newScreenY > rectViewY) {
5854                newScreenY = rectViewY;
5855            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
5856                newScreenY = viewHeight - (newMaxHeight - rectViewY);
5857            }
5858            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
5859                    / (scale - actualScale);
5860            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
5861            mZoomManager.startZoomAnimation(scale, false);
5862        }
5863    }
5864
5865    // Called by JNI to handle a touch on a node representing an email address,
5866    // address, or phone number
5867    private void overrideLoading(String url) {
5868        mCallbackProxy.uiOverrideUrlLoading(url);
5869    }
5870
5871    @Override
5872    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5873        // FIXME: If a subwindow is showing find, and the user touches the
5874        // background window, it can steal focus.
5875        if (mFindIsUp) return false;
5876        boolean result = false;
5877        if (inEditingMode()) {
5878            result = mWebTextView.requestFocus(direction,
5879                    previouslyFocusedRect);
5880        } else {
5881            result = super.requestFocus(direction, previouslyFocusedRect);
5882            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
5883                // For cases such as GMail, where we gain focus from a direction,
5884                // we want to move to the first available link.
5885                // FIXME: If there are no visible links, we may not want to
5886                int fakeKeyDirection = 0;
5887                switch(direction) {
5888                    case View.FOCUS_UP:
5889                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
5890                        break;
5891                    case View.FOCUS_DOWN:
5892                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
5893                        break;
5894                    case View.FOCUS_LEFT:
5895                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
5896                        break;
5897                    case View.FOCUS_RIGHT:
5898                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
5899                        break;
5900                    default:
5901                        return result;
5902                }
5903                if (mNativeClass != 0 && !nativeHasCursorNode()) {
5904                    navHandledKey(fakeKeyDirection, 1, true, 0);
5905                }
5906            }
5907        }
5908        return result;
5909    }
5910
5911    @Override
5912    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5913        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
5914
5915        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5916        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5917        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5918        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5919
5920        int measuredHeight = heightSize;
5921        int measuredWidth = widthSize;
5922
5923        // Grab the content size from WebViewCore.
5924        int contentHeight = contentToViewDimension(mContentHeight);
5925        int contentWidth = contentToViewDimension(mContentWidth);
5926
5927//        Log.d(LOGTAG, "------- measure " + heightMode);
5928
5929        if (heightMode != MeasureSpec.EXACTLY) {
5930            mHeightCanMeasure = true;
5931            measuredHeight = contentHeight;
5932            if (heightMode == MeasureSpec.AT_MOST) {
5933                // If we are larger than the AT_MOST height, then our height can
5934                // no longer be measured and we should scroll internally.
5935                if (measuredHeight > heightSize) {
5936                    measuredHeight = heightSize;
5937                    mHeightCanMeasure = false;
5938                }
5939            }
5940        } else {
5941            mHeightCanMeasure = false;
5942        }
5943        if (mNativeClass != 0) {
5944            nativeSetHeightCanMeasure(mHeightCanMeasure);
5945        }
5946        // For the width, always use the given size unless unspecified.
5947        if (widthMode == MeasureSpec.UNSPECIFIED) {
5948            mWidthCanMeasure = true;
5949            measuredWidth = contentWidth;
5950        } else {
5951            mWidthCanMeasure = false;
5952        }
5953
5954        synchronized (this) {
5955            setMeasuredDimension(measuredWidth, measuredHeight);
5956        }
5957    }
5958
5959    @Override
5960    public boolean requestChildRectangleOnScreen(View child,
5961                                                 Rect rect,
5962                                                 boolean immediate) {
5963        // don't scroll while in zoom animation. When it is done, we will adjust
5964        // the necessary components (e.g., WebTextView if it is in editing mode)
5965        if (mZoomManager.isFixedLengthAnimationInProgress()) {
5966            return false;
5967        }
5968
5969        rect.offset(child.getLeft() - child.getScrollX(),
5970                child.getTop() - child.getScrollY());
5971
5972        Rect content = new Rect(viewToContentX(mScrollX),
5973                viewToContentY(mScrollY),
5974                viewToContentX(mScrollX + getWidth()
5975                - getVerticalScrollbarWidth()),
5976                viewToContentY(mScrollY + getViewHeightWithTitle()));
5977        content = nativeSubtractLayers(content);
5978        int screenTop = contentToViewY(content.top);
5979        int screenBottom = contentToViewY(content.bottom);
5980        int height = screenBottom - screenTop;
5981        int scrollYDelta = 0;
5982
5983        if (rect.bottom > screenBottom) {
5984            int oneThirdOfScreenHeight = height / 3;
5985            if (rect.height() > 2 * oneThirdOfScreenHeight) {
5986                // If the rectangle is too tall to fit in the bottom two thirds
5987                // of the screen, place it at the top.
5988                scrollYDelta = rect.top - screenTop;
5989            } else {
5990                // If the rectangle will still fit on screen, we want its
5991                // top to be in the top third of the screen.
5992                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
5993            }
5994        } else if (rect.top < screenTop) {
5995            scrollYDelta = rect.top - screenTop;
5996        }
5997
5998        int screenLeft = contentToViewX(content.left);
5999        int screenRight = contentToViewX(content.right);
6000        int width = screenRight - screenLeft;
6001        int scrollXDelta = 0;
6002
6003        if (rect.right > screenRight && rect.left > screenLeft) {
6004            if (rect.width() > width) {
6005                scrollXDelta += (rect.left - screenLeft);
6006            } else {
6007                scrollXDelta += (rect.right - screenRight);
6008            }
6009        } else if (rect.left < screenLeft) {
6010            scrollXDelta -= (screenLeft - rect.left);
6011        }
6012
6013        if ((scrollYDelta | scrollXDelta) != 0) {
6014            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
6015        }
6016
6017        return false;
6018    }
6019
6020    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
6021            String replace, int newStart, int newEnd) {
6022        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
6023        arg.mReplace = replace;
6024        arg.mNewStart = newStart;
6025        arg.mNewEnd = newEnd;
6026        mTextGeneration++;
6027        arg.mTextGeneration = mTextGeneration;
6028        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
6029    }
6030
6031    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
6032        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
6033        arg.mEvent = event;
6034        arg.mCurrentText = currentText;
6035        // Increase our text generation number, and pass it to webcore thread
6036        mTextGeneration++;
6037        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
6038        // WebKit's document state is not saved until about to leave the page.
6039        // To make sure the host application, like Browser, has the up to date
6040        // document state when it goes to background, we force to save the
6041        // document state.
6042        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
6043        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
6044                cursorData(), 1000);
6045    }
6046
6047    /* package */ synchronized WebViewCore getWebViewCore() {
6048        return mWebViewCore;
6049    }
6050
6051    //-------------------------------------------------------------------------
6052    // Methods can be called from a separate thread, like WebViewCore
6053    // If it needs to call the View system, it has to send message.
6054    //-------------------------------------------------------------------------
6055
6056    /**
6057     * General handler to receive message coming from webkit thread
6058     */
6059    class PrivateHandler extends Handler {
6060        @Override
6061        public void handleMessage(Message msg) {
6062            // exclude INVAL_RECT_MSG_ID since it is frequently output
6063            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
6064                if (msg.what >= FIRST_PRIVATE_MSG_ID
6065                        && msg.what <= LAST_PRIVATE_MSG_ID) {
6066                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
6067                            - FIRST_PRIVATE_MSG_ID]);
6068                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
6069                        && msg.what <= LAST_PACKAGE_MSG_ID) {
6070                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
6071                            - FIRST_PACKAGE_MSG_ID]);
6072                } else {
6073                    Log.v(LOGTAG, Integer.toString(msg.what));
6074                }
6075            }
6076            if (mWebViewCore == null) {
6077                // after WebView's destroy() is called, skip handling messages.
6078                return;
6079            }
6080            switch (msg.what) {
6081                case REMEMBER_PASSWORD: {
6082                    mDatabase.setUsernamePassword(
6083                            msg.getData().getString("host"),
6084                            msg.getData().getString("username"),
6085                            msg.getData().getString("password"));
6086                    ((Message) msg.obj).sendToTarget();
6087                    break;
6088                }
6089                case NEVER_REMEMBER_PASSWORD: {
6090                    mDatabase.setUsernamePassword(
6091                            msg.getData().getString("host"), null, null);
6092                    ((Message) msg.obj).sendToTarget();
6093                    break;
6094                }
6095                case PREVENT_DEFAULT_TIMEOUT: {
6096                    // if timeout happens, cancel it so that it won't block UI
6097                    // to continue handling touch events
6098                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
6099                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
6100                            || (msg.arg1 == MotionEvent.ACTION_MOVE
6101                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
6102                        cancelWebCoreTouchEvent(
6103                                viewToContentX((int) mLastTouchX + mScrollX),
6104                                viewToContentY((int) mLastTouchY + mScrollY),
6105                                true);
6106                    }
6107                    break;
6108                }
6109                case SWITCH_TO_SHORTPRESS: {
6110                    if (mTouchMode == TOUCH_INIT_MODE) {
6111                        if (!getSettings().supportTouchOnly()
6112                                && mPreventDefault != PREVENT_DEFAULT_YES) {
6113                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
6114                            updateSelection();
6115                        } else {
6116                            // set to TOUCH_SHORTPRESS_MODE so that it won't
6117                            // trigger double tap any more
6118                            mTouchMode = TOUCH_SHORTPRESS_MODE;
6119                        }
6120                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
6121                        mTouchMode = TOUCH_DONE_MODE;
6122                    }
6123                    break;
6124                }
6125                case SWITCH_TO_LONGPRESS: {
6126                    if (getSettings().supportTouchOnly()) {
6127                        removeTouchHighlight(false);
6128                    }
6129                    if (inFullScreenMode() || mDeferTouchProcess) {
6130                        TouchEventData ted = new TouchEventData();
6131                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
6132                        ted.mX = viewToContentX((int) mLastTouchX + mScrollX);
6133                        ted.mY = viewToContentY((int) mLastTouchY + mScrollY);
6134                        // metaState for long press is tricky. Should it be the
6135                        // state when the press started or when the press was
6136                        // released? Or some intermediary key state? For
6137                        // simplicity for now, we don't set it.
6138                        ted.mMetaState = 0;
6139                        ted.mReprocess = mDeferTouchProcess;
6140                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6141                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
6142                        mTouchMode = TOUCH_DONE_MODE;
6143                        performLongClick();
6144                    }
6145                    break;
6146                }
6147                case RELEASE_SINGLE_TAP: {
6148                    doShortPress();
6149                    break;
6150                }
6151                case SCROLL_BY_MSG_ID:
6152                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
6153                    break;
6154                case SYNC_SCROLL_TO_MSG_ID:
6155                    if (mUserScroll) {
6156                        // if user has scrolled explicitly, don't sync the
6157                        // scroll position any more
6158                        mUserScroll = false;
6159                        break;
6160                    }
6161                    // fall through
6162                case SCROLL_TO_MSG_ID:
6163                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
6164                        // if we can't scroll to the exact position due to pin,
6165                        // send a message to WebCore to re-scroll when we get a
6166                        // new picture
6167                        mUserScroll = false;
6168                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
6169                                msg.arg1, msg.arg2);
6170                    }
6171                    break;
6172                case SPAWN_SCROLL_TO_MSG_ID:
6173                    spawnContentScrollTo(msg.arg1, msg.arg2);
6174                    break;
6175                case UPDATE_ZOOM_RANGE: {
6176                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
6177                    // mScrollX contains the new minPrefWidth
6178                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
6179                    break;
6180                }
6181                case REPLACE_BASE_CONTENT: {
6182                    nativeReplaceBaseContent(msg.arg1);
6183                    break;
6184                }
6185                case NEW_PICTURE_MSG_ID: {
6186                    // called for new content
6187                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
6188                    nativeSetBaseLayer(draw.mBaseLayer);
6189                    final Point viewSize = draw.mViewPoint;
6190                    WebViewCore.ViewState viewState = draw.mViewState;
6191                    boolean isPictureAfterFirstLayout = viewState != null;
6192                    if (isPictureAfterFirstLayout) {
6193                        // Reset the last sent data here since dealing with new page.
6194                        mLastWidthSent = 0;
6195                        mZoomManager.onFirstLayout(draw);
6196                        if (!mDrawHistory) {
6197                            setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
6198                            // As we are on a new page, remove the WebTextView. This
6199                            // is necessary for page loads driven by webkit, and in
6200                            // particular when the user was on a password field, so
6201                            // the WebTextView was visible.
6202                            clearTextEntry(false);
6203                        }
6204                    }
6205
6206                    // We update the layout (i.e. request a layout from the
6207                    // view system) if the last view size that we sent to
6208                    // WebCore matches the view size of the picture we just
6209                    // received in the fixed dimension.
6210                    final boolean updateLayout = viewSize.x == mLastWidthSent
6211                            && viewSize.y == mLastHeightSent;
6212                    recordNewContentSize(draw.mWidthHeight.x,
6213                            draw.mWidthHeight.y, updateLayout);
6214                    if (DebugFlags.WEB_VIEW) {
6215                        Rect b = draw.mInvalRegion.getBounds();
6216                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
6217                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
6218                    }
6219                    invalidateContentRect(draw.mInvalRegion.getBounds());
6220
6221                    if (mPictureListener != null) {
6222                        mPictureListener.onNewPicture(WebView.this, capturePicture());
6223                    }
6224
6225                    // update the zoom information based on the new picture
6226                    mZoomManager.onNewPicture(draw);
6227
6228                    if (draw.mFocusSizeChanged && inEditingMode()) {
6229                        mFocusSizeChanged = true;
6230                    }
6231                    if (isPictureAfterFirstLayout) {
6232                        mViewManager.postReadyToDrawAll();
6233                    }
6234                    break;
6235                }
6236                case WEBCORE_INITIALIZED_MSG_ID:
6237                    // nativeCreate sets mNativeClass to a non-zero value
6238                    nativeCreate(msg.arg1);
6239                    break;
6240                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
6241                    // Make sure that the textfield is currently focused
6242                    // and representing the same node as the pointer.
6243                    if (inEditingMode() &&
6244                            mWebTextView.isSameTextField(msg.arg1)) {
6245                        if (msg.getData().getBoolean("password")) {
6246                            Spannable text = (Spannable) mWebTextView.getText();
6247                            int start = Selection.getSelectionStart(text);
6248                            int end = Selection.getSelectionEnd(text);
6249                            mWebTextView.setInPassword(true);
6250                            // Restore the selection, which may have been
6251                            // ruined by setInPassword.
6252                            Spannable pword =
6253                                    (Spannable) mWebTextView.getText();
6254                            Selection.setSelection(pword, start, end);
6255                        // If the text entry has created more events, ignore
6256                        // this one.
6257                        } else if (msg.arg2 == mTextGeneration) {
6258                            mWebTextView.setTextAndKeepSelection(
6259                                    (String) msg.obj);
6260                        }
6261                    }
6262                    break;
6263                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
6264                    displaySoftKeyboard(true);
6265                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
6266                case UPDATE_TEXT_SELECTION_MSG_ID:
6267                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
6268                            (WebViewCore.TextSelectionData) msg.obj);
6269                    break;
6270                case RETURN_LABEL:
6271                    if (inEditingMode()
6272                            && mWebTextView.isSameTextField(msg.arg1)) {
6273                        mWebTextView.setHint((String) msg.obj);
6274                        InputMethodManager imm
6275                                = InputMethodManager.peekInstance();
6276                        // The hint is propagated to the IME in
6277                        // onCreateInputConnection.  If the IME is already
6278                        // active, restart it so that its hint text is updated.
6279                        if (imm != null && imm.isActive(mWebTextView)) {
6280                            imm.restartInput(mWebTextView);
6281                        }
6282                    }
6283                    break;
6284                case UNHANDLED_NAV_KEY:
6285                    navHandledKey(msg.arg1, 1, false, 0);
6286                    break;
6287                case UPDATE_TEXT_ENTRY_MSG_ID:
6288                    // this is sent after finishing resize in WebViewCore. Make
6289                    // sure the text edit box is still on the  screen.
6290                    if (inEditingMode() && nativeCursorIsTextInput()) {
6291                        mWebTextView.bringIntoView();
6292                        rebuildWebTextView();
6293                    }
6294                    break;
6295                case CLEAR_TEXT_ENTRY:
6296                    clearTextEntry(false);
6297                    break;
6298                case INVAL_RECT_MSG_ID: {
6299                    Rect r = (Rect)msg.obj;
6300                    if (r == null) {
6301                        invalidate();
6302                    } else {
6303                        // we need to scale r from content into view coords,
6304                        // which viewInvalidate() does for us
6305                        viewInvalidate(r.left, r.top, r.right, r.bottom);
6306                    }
6307                    break;
6308                }
6309                case REQUEST_FORM_DATA:
6310                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
6311                    if (mWebTextView.isSameTextField(msg.arg1)) {
6312                        mWebTextView.setAdapterCustom(adapter);
6313                    }
6314                    break;
6315                case RESUME_WEBCORE_PRIORITY:
6316                    WebViewCore.resumePriority();
6317                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6318                    break;
6319
6320                case LONG_PRESS_CENTER:
6321                    // as this is shared by keydown and trackballdown, reset all
6322                    // the states
6323                    mGotCenterDown = false;
6324                    mTrackballDown = false;
6325                    performLongClick();
6326                    break;
6327
6328                case WEBCORE_NEED_TOUCH_EVENTS:
6329                    mForwardTouchEvents = (msg.arg1 != 0);
6330                    break;
6331
6332                case PREVENT_TOUCH_ID:
6333                    if (inFullScreenMode()) {
6334                        break;
6335                    }
6336                    if (msg.obj == null) {
6337                        if (msg.arg1 == MotionEvent.ACTION_DOWN
6338                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
6339                            // if prevent default is called from WebCore, UI
6340                            // will not handle the rest of the touch events any
6341                            // more.
6342                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6343                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
6344                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
6345                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
6346                            // the return for the first ACTION_MOVE will decide
6347                            // whether UI will handle touch or not. Currently no
6348                            // support for alternating prevent default
6349                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6350                                    : PREVENT_DEFAULT_NO;
6351                        }
6352                        if (mPreventDefault == PREVENT_DEFAULT_YES) {
6353                            mTouchHighlightRegion.setEmpty();
6354                        }
6355                    } else if (msg.arg2 == 0) {
6356                        // prevent default is not called in WebCore, so the
6357                        // message needs to be reprocessed in UI
6358                        TouchEventData ted = (TouchEventData) msg.obj;
6359                        switch (ted.mAction) {
6360                            case MotionEvent.ACTION_DOWN:
6361                                mLastDeferTouchX = contentToViewX(ted.mX)
6362                                        - mScrollX;
6363                                mLastDeferTouchY = contentToViewY(ted.mY)
6364                                        - mScrollY;
6365                                mDeferTouchMode = TOUCH_INIT_MODE;
6366                                break;
6367                            case MotionEvent.ACTION_MOVE: {
6368                                // no snapping in defer process
6369                                int x = contentToViewX(ted.mX) - mScrollX;
6370                                int y = contentToViewY(ted.mY) - mScrollY;
6371                                if (mDeferTouchMode != TOUCH_DRAG_MODE) {
6372                                    mDeferTouchMode = TOUCH_DRAG_MODE;
6373                                    mLastDeferTouchX = x;
6374                                    mLastDeferTouchY = y;
6375                                    startDrag();
6376                                }
6377                                int deltaX = pinLocX((int) (mScrollX
6378                                        + mLastDeferTouchX - x))
6379                                        - mScrollX;
6380                                int deltaY = pinLocY((int) (mScrollY
6381                                        + mLastDeferTouchY - y))
6382                                        - mScrollY;
6383                                doDrag(deltaX, deltaY);
6384                                if (deltaX != 0) mLastDeferTouchX = x;
6385                                if (deltaY != 0) mLastDeferTouchY = y;
6386                                break;
6387                            }
6388                            case MotionEvent.ACTION_UP:
6389                            case MotionEvent.ACTION_CANCEL:
6390                                if (mDeferTouchMode == TOUCH_DRAG_MODE) {
6391                                    // no fling in defer process
6392                                    WebViewCore.resumePriority();
6393                                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6394                                }
6395                                mDeferTouchMode = TOUCH_DONE_MODE;
6396                                break;
6397                            case WebViewCore.ACTION_DOUBLETAP:
6398                                // doDoubleTap() needs mLastTouchX/Y as anchor
6399                                mLastTouchX = contentToViewX(ted.mX) - mScrollX;
6400                                mLastTouchY = contentToViewY(ted.mY) - mScrollY;
6401                                mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
6402                                mDeferTouchMode = TOUCH_DONE_MODE;
6403                                break;
6404                            case WebViewCore.ACTION_LONGPRESS:
6405                                HitTestResult hitTest = getHitTestResult();
6406                                if (hitTest != null && hitTest.mType
6407                                        != HitTestResult.UNKNOWN_TYPE) {
6408                                    performLongClick();
6409                                }
6410                                mDeferTouchMode = TOUCH_DONE_MODE;
6411                                break;
6412                        }
6413                    }
6414                    break;
6415
6416                case REQUEST_KEYBOARD:
6417                    if (msg.arg1 == 0) {
6418                        hideSoftKeyboard();
6419                    } else {
6420                        displaySoftKeyboard(false);
6421                    }
6422                    break;
6423
6424                case FIND_AGAIN:
6425                    // Ignore if find has been dismissed.
6426                    if (mFindIsUp) {
6427                        findAll(mLastFind);
6428                    }
6429                    break;
6430
6431                case DRAG_HELD_MOTIONLESS:
6432                    mHeldMotionless = MOTIONLESS_TRUE;
6433                    invalidate();
6434                    // fall through to keep scrollbars awake
6435
6436                case AWAKEN_SCROLL_BARS:
6437                    if (mTouchMode == TOUCH_DRAG_MODE
6438                            && mHeldMotionless == MOTIONLESS_TRUE) {
6439                        awakenScrollBars(ViewConfiguration
6440                                .getScrollDefaultDelay(), false);
6441                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
6442                                .obtainMessage(AWAKEN_SCROLL_BARS),
6443                                ViewConfiguration.getScrollDefaultDelay());
6444                    }
6445                    break;
6446
6447                case DO_MOTION_UP:
6448                    doMotionUp(msg.arg1, msg.arg2);
6449                    break;
6450
6451                case SHOW_FULLSCREEN: {
6452                    View view = (View) msg.obj;
6453                    int npp = msg.arg1;
6454
6455                    if (mFullScreenHolder != null) {
6456                        Log.w(LOGTAG, "Should not have another full screen.");
6457                        mFullScreenHolder.dismiss();
6458                    }
6459                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp);
6460                    mFullScreenHolder.setContentView(view);
6461                    mFullScreenHolder.setCancelable(false);
6462                    mFullScreenHolder.setCanceledOnTouchOutside(false);
6463                    mFullScreenHolder.show();
6464
6465                    break;
6466                }
6467                case HIDE_FULLSCREEN:
6468                    if (inFullScreenMode()) {
6469                        mFullScreenHolder.dismiss();
6470                        mFullScreenHolder = null;
6471                    }
6472                    break;
6473
6474                case DOM_FOCUS_CHANGED:
6475                    if (inEditingMode()) {
6476                        nativeClearCursor();
6477                        rebuildWebTextView();
6478                    }
6479                    break;
6480
6481                case SHOW_RECT_MSG_ID: {
6482                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
6483                    int x = mScrollX;
6484                    int left = contentToViewX(data.mLeft);
6485                    int width = contentToViewDimension(data.mWidth);
6486                    int maxWidth = contentToViewDimension(data.mContentWidth);
6487                    int viewWidth = getViewWidth();
6488                    if (width < viewWidth) {
6489                        // center align
6490                        x += left + width / 2 - mScrollX - viewWidth / 2;
6491                    } else {
6492                        x += (int) (left + data.mXPercentInDoc * width
6493                                - mScrollX - data.mXPercentInView * viewWidth);
6494                    }
6495                    if (DebugFlags.WEB_VIEW) {
6496                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
6497                              width + ",maxWidth=" + maxWidth +
6498                              ",viewWidth=" + viewWidth + ",x="
6499                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
6500                              ",xPercentInView=" + data.mXPercentInView+ ")");
6501                    }
6502                    // use the passing content width to cap x as the current
6503                    // mContentWidth may not be updated yet
6504                    x = Math.max(0,
6505                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
6506                    int top = contentToViewY(data.mTop);
6507                    int height = contentToViewDimension(data.mHeight);
6508                    int maxHeight = contentToViewDimension(data.mContentHeight);
6509                    int viewHeight = getViewHeight();
6510                    int y = (int) (top + data.mYPercentInDoc * height -
6511                                   data.mYPercentInView * viewHeight);
6512                    if (DebugFlags.WEB_VIEW) {
6513                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
6514                              height + ",maxHeight=" + maxHeight +
6515                              ",viewHeight=" + viewHeight + ",y="
6516                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
6517                              ",yPercentInView=" + data.mYPercentInView+ ")");
6518                    }
6519                    // use the passing content height to cap y as the current
6520                    // mContentHeight may not be updated yet
6521                    y = Math.max(0,
6522                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
6523                    // We need to take into account the visible title height
6524                    // when scrolling since y is an absolute view position.
6525                    y = Math.max(0, y - getVisibleTitleHeight());
6526                    scrollTo(x, y);
6527                    }
6528                    break;
6529
6530                case CENTER_FIT_RECT:
6531                    Rect r = (Rect)msg.obj;
6532                    centerFitRect(r.left, r.top, r.width(), r.height());
6533                    break;
6534
6535                case SET_SCROLLBAR_MODES:
6536                    mHorizontalScrollBarMode = msg.arg1;
6537                    mVerticalScrollBarMode = msg.arg2;
6538                    break;
6539
6540                case SELECTION_STRING_CHANGED:
6541                    if (mAccessibilityInjector != null) {
6542                        String selectionString = (String) msg.obj;
6543                        mAccessibilityInjector.onSelectionStringChange(selectionString);
6544                    }
6545                    break;
6546
6547                case SET_TOUCH_HIGHLIGHT_RECTS:
6548                    invalidate(mTouchHighlightRegion.getBounds());
6549                    mTouchHighlightRegion.setEmpty();
6550                    if (msg.obj != null) {
6551                        ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
6552                        for (Rect rect : rects) {
6553                            Rect viewRect = contentToViewRect(rect);
6554                            // some sites, like stories in nytimes.com, set
6555                            // mouse event handler in the top div. It is not
6556                            // user friendly to highlight the div if it covers
6557                            // more than half of the screen.
6558                            if (viewRect.width() < getWidth() >> 1
6559                                    || viewRect.height() < getHeight() >> 1) {
6560                                mTouchHighlightRegion.union(viewRect);
6561                                invalidate(viewRect);
6562                            } else {
6563                                Log.w(LOGTAG, "Skip the huge selection rect:"
6564                                        + viewRect);
6565                            }
6566                        }
6567                    }
6568                    break;
6569
6570                case SAVE_WEBARCHIVE_FINISHED:
6571                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
6572                    if (saveMessage.mCallback != null) {
6573                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
6574                    }
6575                    break;
6576
6577                default:
6578                    super.handleMessage(msg);
6579                    break;
6580            }
6581        }
6582    }
6583
6584    /**
6585     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
6586     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
6587     */
6588    private void updateTextSelectionFromMessage(int nodePointer,
6589            int textGeneration, WebViewCore.TextSelectionData data) {
6590        if (inEditingMode()
6591                && mWebTextView.isSameTextField(nodePointer)
6592                && textGeneration == mTextGeneration) {
6593            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
6594        }
6595    }
6596
6597    // Class used to use a dropdown for a <select> element
6598    private class InvokeListBox implements Runnable {
6599        // Whether the listbox allows multiple selection.
6600        private boolean     mMultiple;
6601        // Passed in to a list with multiple selection to tell
6602        // which items are selected.
6603        private int[]       mSelectedArray;
6604        // Passed in to a list with single selection to tell
6605        // where the initial selection is.
6606        private int         mSelection;
6607
6608        private Container[] mContainers;
6609
6610        // Need these to provide stable ids to my ArrayAdapter,
6611        // which normally does not have stable ids. (Bug 1250098)
6612        private class Container extends Object {
6613            /**
6614             * Possible values for mEnabled.  Keep in sync with OptionStatus in
6615             * WebViewCore.cpp
6616             */
6617            final static int OPTGROUP = -1;
6618            final static int OPTION_DISABLED = 0;
6619            final static int OPTION_ENABLED = 1;
6620
6621            String  mString;
6622            int     mEnabled;
6623            int     mId;
6624
6625            public String toString() {
6626                return mString;
6627            }
6628        }
6629
6630        /**
6631         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
6632         *  and allow filtering.
6633         */
6634        private class MyArrayListAdapter extends ArrayAdapter<Container> {
6635            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
6636                super(context,
6637                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
6638                            com.android.internal.R.layout.select_dialog_singlechoice,
6639                            objects);
6640            }
6641
6642            @Override
6643            public View getView(int position, View convertView,
6644                    ViewGroup parent) {
6645                // Always pass in null so that we will get a new CheckedTextView
6646                // Otherwise, an item which was previously used as an <optgroup>
6647                // element (i.e. has no check), could get used as an <option>
6648                // element, which needs a checkbox/radio, but it would not have
6649                // one.
6650                convertView = super.getView(position, null, parent);
6651                Container c = item(position);
6652                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
6653                    // ListView does not draw dividers between disabled and
6654                    // enabled elements.  Use a LinearLayout to provide dividers
6655                    LinearLayout layout = new LinearLayout(mContext);
6656                    layout.setOrientation(LinearLayout.VERTICAL);
6657                    if (position > 0) {
6658                        View dividerTop = new View(mContext);
6659                        dividerTop.setBackgroundResource(
6660                                android.R.drawable.divider_horizontal_bright);
6661                        layout.addView(dividerTop);
6662                    }
6663
6664                    if (Container.OPTGROUP == c.mEnabled) {
6665                        // Currently select_dialog_multichoice and
6666                        // select_dialog_singlechoice are CheckedTextViews.  If
6667                        // that changes, the class cast will no longer be valid.
6668                        Assert.assertTrue(
6669                                convertView instanceof CheckedTextView);
6670                        ((CheckedTextView) convertView).setCheckMarkDrawable(
6671                                null);
6672                    } else {
6673                        // c.mEnabled == Container.OPTION_DISABLED
6674                        // Draw the disabled element in a disabled state.
6675                        convertView.setEnabled(false);
6676                    }
6677
6678                    layout.addView(convertView);
6679                    if (position < getCount() - 1) {
6680                        View dividerBottom = new View(mContext);
6681                        dividerBottom.setBackgroundResource(
6682                                android.R.drawable.divider_horizontal_bright);
6683                        layout.addView(dividerBottom);
6684                    }
6685                    return layout;
6686                }
6687                return convertView;
6688            }
6689
6690            @Override
6691            public boolean hasStableIds() {
6692                // AdapterView's onChanged method uses this to determine whether
6693                // to restore the old state.  Return false so that the old (out
6694                // of date) state does not replace the new, valid state.
6695                return false;
6696            }
6697
6698            private Container item(int position) {
6699                if (position < 0 || position >= getCount()) {
6700                    return null;
6701                }
6702                return (Container) getItem(position);
6703            }
6704
6705            @Override
6706            public long getItemId(int position) {
6707                Container item = item(position);
6708                if (item == null) {
6709                    return -1;
6710                }
6711                return item.mId;
6712            }
6713
6714            @Override
6715            public boolean areAllItemsEnabled() {
6716                return false;
6717            }
6718
6719            @Override
6720            public boolean isEnabled(int position) {
6721                Container item = item(position);
6722                if (item == null) {
6723                    return false;
6724                }
6725                return Container.OPTION_ENABLED == item.mEnabled;
6726            }
6727        }
6728
6729        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
6730            mMultiple = true;
6731            mSelectedArray = selected;
6732
6733            int length = array.length;
6734            mContainers = new Container[length];
6735            for (int i = 0; i < length; i++) {
6736                mContainers[i] = new Container();
6737                mContainers[i].mString = array[i];
6738                mContainers[i].mEnabled = enabled[i];
6739                mContainers[i].mId = i;
6740            }
6741        }
6742
6743        private InvokeListBox(String[] array, int[] enabled, int selection) {
6744            mSelection = selection;
6745            mMultiple = false;
6746
6747            int length = array.length;
6748            mContainers = new Container[length];
6749            for (int i = 0; i < length; i++) {
6750                mContainers[i] = new Container();
6751                mContainers[i].mString = array[i];
6752                mContainers[i].mEnabled = enabled[i];
6753                mContainers[i].mId = i;
6754            }
6755        }
6756
6757        /*
6758         * Whenever the data set changes due to filtering, this class ensures
6759         * that the checked item remains checked.
6760         */
6761        private class SingleDataSetObserver extends DataSetObserver {
6762            private long        mCheckedId;
6763            private ListView    mListView;
6764            private Adapter     mAdapter;
6765
6766            /*
6767             * Create a new observer.
6768             * @param id The ID of the item to keep checked.
6769             * @param l ListView for getting and clearing the checked states
6770             * @param a Adapter for getting the IDs
6771             */
6772            public SingleDataSetObserver(long id, ListView l, Adapter a) {
6773                mCheckedId = id;
6774                mListView = l;
6775                mAdapter = a;
6776            }
6777
6778            public void onChanged() {
6779                // The filter may have changed which item is checked.  Find the
6780                // item that the ListView thinks is checked.
6781                int position = mListView.getCheckedItemPosition();
6782                long id = mAdapter.getItemId(position);
6783                if (mCheckedId != id) {
6784                    // Clear the ListView's idea of the checked item, since
6785                    // it is incorrect
6786                    mListView.clearChoices();
6787                    // Search for mCheckedId.  If it is in the filtered list,
6788                    // mark it as checked
6789                    int count = mAdapter.getCount();
6790                    for (int i = 0; i < count; i++) {
6791                        if (mAdapter.getItemId(i) == mCheckedId) {
6792                            mListView.setItemChecked(i, true);
6793                            break;
6794                        }
6795                    }
6796                }
6797            }
6798
6799            public void onInvalidate() {}
6800        }
6801
6802        public void run() {
6803            final ListView listView = (ListView) LayoutInflater.from(mContext)
6804                    .inflate(com.android.internal.R.layout.select_dialog, null);
6805            final MyArrayListAdapter adapter = new
6806                    MyArrayListAdapter(mContext, mContainers, mMultiple);
6807            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
6808                    .setView(listView).setCancelable(true)
6809                    .setInverseBackgroundForced(true);
6810
6811            if (mMultiple) {
6812                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
6813                    public void onClick(DialogInterface dialog, int which) {
6814                        mWebViewCore.sendMessage(
6815                                EventHub.LISTBOX_CHOICES,
6816                                adapter.getCount(), 0,
6817                                listView.getCheckedItemPositions());
6818                    }});
6819                b.setNegativeButton(android.R.string.cancel,
6820                        new DialogInterface.OnClickListener() {
6821                    public void onClick(DialogInterface dialog, int which) {
6822                        mWebViewCore.sendMessage(
6823                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6824                }});
6825            }
6826            final AlertDialog dialog = b.create();
6827            listView.setAdapter(adapter);
6828            listView.setFocusableInTouchMode(true);
6829            // There is a bug (1250103) where the checks in a ListView with
6830            // multiple items selected are associated with the positions, not
6831            // the ids, so the items do not properly retain their checks when
6832            // filtered.  Do not allow filtering on multiple lists until
6833            // that bug is fixed.
6834
6835            listView.setTextFilterEnabled(!mMultiple);
6836            if (mMultiple) {
6837                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
6838                int length = mSelectedArray.length;
6839                for (int i = 0; i < length; i++) {
6840                    listView.setItemChecked(mSelectedArray[i], true);
6841                }
6842            } else {
6843                listView.setOnItemClickListener(new OnItemClickListener() {
6844                    public void onItemClick(AdapterView parent, View v,
6845                            int position, long id) {
6846                        mWebViewCore.sendMessage(
6847                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
6848                        dialog.dismiss();
6849                    }
6850                });
6851                if (mSelection != -1) {
6852                    listView.setSelection(mSelection);
6853                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
6854                    listView.setItemChecked(mSelection, true);
6855                    DataSetObserver observer = new SingleDataSetObserver(
6856                            adapter.getItemId(mSelection), listView, adapter);
6857                    adapter.registerDataSetObserver(observer);
6858                }
6859            }
6860            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
6861                public void onCancel(DialogInterface dialog) {
6862                    mWebViewCore.sendMessage(
6863                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6864                }
6865            });
6866            dialog.show();
6867        }
6868    }
6869
6870    /*
6871     * Request a dropdown menu for a listbox with multiple selection.
6872     *
6873     * @param array Labels for the listbox.
6874     * @param enabledArray  State for each element in the list.  See static
6875     *      integers in Container class.
6876     * @param selectedArray Which positions are initally selected.
6877     */
6878    void requestListBox(String[] array, int[] enabledArray, int[]
6879            selectedArray) {
6880        mPrivateHandler.post(
6881                new InvokeListBox(array, enabledArray, selectedArray));
6882    }
6883
6884    /*
6885     * Request a dropdown menu for a listbox with single selection or a single
6886     * <select> element.
6887     *
6888     * @param array Labels for the listbox.
6889     * @param enabledArray  State for each element in the list.  See static
6890     *      integers in Container class.
6891     * @param selection Which position is initally selected.
6892     */
6893    void requestListBox(String[] array, int[] enabledArray, int selection) {
6894        mPrivateHandler.post(
6895                new InvokeListBox(array, enabledArray, selection));
6896    }
6897
6898    // called by JNI
6899    private void sendMoveFocus(int frame, int node) {
6900        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
6901                new WebViewCore.CursorData(frame, node, 0, 0));
6902    }
6903
6904    // called by JNI
6905    private void sendMoveMouse(int frame, int node, int x, int y) {
6906        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
6907                new WebViewCore.CursorData(frame, node, x, y));
6908    }
6909
6910    /*
6911     * Send a mouse move event to the webcore thread.
6912     *
6913     * @param removeFocus Pass true if the "mouse" cursor is now over a node
6914     *                    which wants key events, but it is not the focus. This
6915     *                    will make the visual appear as though nothing is in
6916     *                    focus.  Remove the WebTextView, if present, and stop
6917     *                    drawing the blinking caret.
6918     * called by JNI
6919     */
6920    private void sendMoveMouseIfLatest(boolean removeFocus) {
6921        if (removeFocus) {
6922            clearTextEntry(true);
6923        }
6924        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
6925                cursorData());
6926    }
6927
6928    // called by JNI
6929    private void sendMotionUp(int touchGeneration,
6930            int frame, int node, int x, int y) {
6931        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
6932        touchUpData.mMoveGeneration = touchGeneration;
6933        touchUpData.mFrame = frame;
6934        touchUpData.mNode = node;
6935        touchUpData.mX = x;
6936        touchUpData.mY = y;
6937        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
6938    }
6939
6940
6941    private int getScaledMaxXScroll() {
6942        int width;
6943        if (mHeightCanMeasure == false) {
6944            width = getViewWidth() / 4;
6945        } else {
6946            Rect visRect = new Rect();
6947            calcOurVisibleRect(visRect);
6948            width = visRect.width() / 2;
6949        }
6950        // FIXME the divisor should be retrieved from somewhere
6951        return viewToContentX(width);
6952    }
6953
6954    private int getScaledMaxYScroll() {
6955        int height;
6956        if (mHeightCanMeasure == false) {
6957            height = getViewHeight() / 4;
6958        } else {
6959            Rect visRect = new Rect();
6960            calcOurVisibleRect(visRect);
6961            height = visRect.height() / 2;
6962        }
6963        // FIXME the divisor should be retrieved from somewhere
6964        // the closest thing today is hard-coded into ScrollView.java
6965        // (from ScrollView.java, line 363)   int maxJump = height/2;
6966        return Math.round(height * mZoomManager.getInvScale());
6967    }
6968
6969    /**
6970     * Called by JNI to invalidate view
6971     */
6972    private void viewInvalidate() {
6973        invalidate();
6974    }
6975
6976    /**
6977     * Pass the key directly to the page.  This assumes that
6978     * nativePageShouldHandleShiftAndArrows() returned true.
6979     */
6980    private void letPageHandleNavKey(int keyCode, long time, boolean down) {
6981        int keyEventAction;
6982        int eventHubAction;
6983        if (down) {
6984            keyEventAction = KeyEvent.ACTION_DOWN;
6985            eventHubAction = EventHub.KEY_DOWN;
6986            playSoundEffect(keyCodeToSoundsEffect(keyCode));
6987        } else {
6988            keyEventAction = KeyEvent.ACTION_UP;
6989            eventHubAction = EventHub.KEY_UP;
6990        }
6991        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
6992                1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
6993                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
6994                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
6995                , 0, 0, 0);
6996        mWebViewCore.sendMessage(eventHubAction, event);
6997    }
6998
6999    // return true if the key was handled
7000    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
7001            long time) {
7002        if (mNativeClass == 0) {
7003            return false;
7004        }
7005        mLastCursorTime = time;
7006        mLastCursorBounds = nativeGetCursorRingBounds();
7007        boolean keyHandled
7008                = nativeMoveCursor(keyCode, count, noScroll) == false;
7009        if (DebugFlags.WEB_VIEW) {
7010            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
7011                    + " mLastCursorTime=" + mLastCursorTime
7012                    + " handled=" + keyHandled);
7013        }
7014        if (keyHandled == false || mHeightCanMeasure == false) {
7015            return keyHandled;
7016        }
7017        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
7018        if (contentCursorRingBounds.isEmpty()) return keyHandled;
7019        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
7020        Rect visRect = new Rect();
7021        calcOurVisibleRect(visRect);
7022        Rect outset = new Rect(visRect);
7023        int maxXScroll = visRect.width() / 2;
7024        int maxYScroll = visRect.height() / 2;
7025        outset.inset(-maxXScroll, -maxYScroll);
7026        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
7027            return keyHandled;
7028        }
7029        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
7030        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
7031                maxXScroll);
7032        if (maxH > 0) {
7033            pinScrollBy(maxH, 0, true, 0);
7034        } else {
7035            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
7036                    -maxXScroll);
7037            if (maxH < 0) {
7038                pinScrollBy(maxH, 0, true, 0);
7039            }
7040        }
7041        if (mLastCursorBounds.isEmpty()) return keyHandled;
7042        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
7043            return keyHandled;
7044        }
7045        if (DebugFlags.WEB_VIEW) {
7046            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
7047                    + contentCursorRingBounds);
7048        }
7049        requestRectangleOnScreen(viewCursorRingBounds);
7050        mUserScroll = true;
7051        return keyHandled;
7052    }
7053
7054    /**
7055     * Set the background color. It's white by default. Pass
7056     * zero to make the view transparent.
7057     * @param color   the ARGB color described by Color.java
7058     */
7059    public void setBackgroundColor(int color) {
7060        mBackgroundColor = color;
7061        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
7062    }
7063
7064    public void debugDump() {
7065        nativeDebugDump();
7066        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
7067    }
7068
7069    /**
7070     * Draw the HTML page into the specified canvas. This call ignores any
7071     * view-specific zoom, scroll offset, or other changes. It does not draw
7072     * any view-specific chrome, such as progress or URL bars.
7073     *
7074     * @hide only needs to be accessible to Browser and testing
7075     */
7076    public void drawPage(Canvas canvas) {
7077        nativeDraw(canvas, 0, 0, false);
7078    }
7079
7080    /**
7081     * Set the time to wait between passing touches to WebCore. See also the
7082     * TOUCH_SENT_INTERVAL member for further discussion.
7083     *
7084     * @hide This is only used by the DRT test application.
7085     */
7086    public void setTouchInterval(int interval) {
7087        mCurrentTouchInterval = interval;
7088    }
7089
7090    /**
7091     *  Update our cache with updatedText.
7092     *  @param updatedText  The new text to put in our cache.
7093     */
7094    /* package */ void updateCachedTextfield(String updatedText) {
7095        // Also place our generation number so that when we look at the cache
7096        // we recognize that it is up to date.
7097        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
7098    }
7099
7100    private native int nativeCacheHitFramePointer();
7101    private native Rect nativeCacheHitNodeBounds();
7102    private native int nativeCacheHitNodePointer();
7103    /* package */ native void nativeClearCursor();
7104    private native void     nativeCreate(int ptr);
7105    private native int      nativeCursorFramePointer();
7106    private native Rect     nativeCursorNodeBounds();
7107    private native int nativeCursorNodePointer();
7108    /* package */ native boolean nativeCursorMatchesFocus();
7109    private native boolean  nativeCursorIntersects(Rect visibleRect);
7110    private native boolean  nativeCursorIsAnchor();
7111    private native boolean  nativeCursorIsTextInput();
7112    private native Point    nativeCursorPosition();
7113    private native String   nativeCursorText();
7114    /**
7115     * Returns true if the native cursor node says it wants to handle key events
7116     * (ala plugins). This can only be called if mNativeClass is non-zero!
7117     */
7118    private native boolean  nativeCursorWantsKeyEvents();
7119    private native void     nativeDebugDump();
7120    private native void     nativeDestroy();
7121
7122    /**
7123     * Draw the picture set with a background color and extra. If
7124     * "splitIfNeeded" is true and the return value is not 0, the return value
7125     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
7126     * native allocation can be freed.
7127     */
7128    private native int nativeDraw(Canvas canvas, int color, int extra,
7129            boolean splitIfNeeded);
7130    private native void     nativeDumpDisplayTree(String urlOrNull);
7131    private native boolean  nativeEvaluateLayersAnimations();
7132    private native void     nativeExtendSelection(int x, int y);
7133    private native int      nativeFindAll(String findLower, String findUpper);
7134    private native void     nativeFindNext(boolean forward);
7135    /* package */ native int      nativeFocusCandidateFramePointer();
7136    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
7137    /* package */ native boolean  nativeFocusCandidateIsPassword();
7138    private native boolean  nativeFocusCandidateIsRtlText();
7139    private native boolean  nativeFocusCandidateIsTextInput();
7140    /* package */ native int      nativeFocusCandidateMaxLength();
7141    /* package */ native String   nativeFocusCandidateName();
7142    private native Rect     nativeFocusCandidateNodeBounds();
7143    /* package */ native int      nativeFocusCandidatePointer();
7144    private native String   nativeFocusCandidateText();
7145    private native int      nativeFocusCandidateTextSize();
7146    /**
7147     * Returns an integer corresponding to WebView.cpp::type.
7148     * See WebTextView.setType()
7149     */
7150    private native int      nativeFocusCandidateType();
7151    private native boolean  nativeFocusIsPlugin();
7152    private native Rect     nativeFocusNodeBounds();
7153    /* package */ native int nativeFocusNodePointer();
7154    private native Rect     nativeGetCursorRingBounds();
7155    private native String   nativeGetSelection();
7156    private native boolean  nativeHasCursorNode();
7157    private native boolean  nativeHasFocusNode();
7158    private native void     nativeHideCursor();
7159    private native boolean  nativeHitSelection(int x, int y);
7160    private native String   nativeImageURI(int x, int y);
7161    private native void     nativeInstrumentReport();
7162    /* package */ native boolean nativeMoveCursorToNextTextInput();
7163    // return true if the page has been scrolled
7164    private native boolean  nativeMotionUp(int x, int y, int slop);
7165    // returns false if it handled the key
7166    private native boolean  nativeMoveCursor(int keyCode, int count,
7167            boolean noScroll);
7168    private native int      nativeMoveGeneration();
7169    private native void     nativeMoveSelection(int x, int y);
7170    /**
7171     * @return true if the page should get the shift and arrow keys, rather
7172     * than select text/navigation.
7173     *
7174     * If the focus is a plugin, or if the focus and cursor match and are
7175     * a contentEditable element, then the page should handle these keys.
7176     */
7177    private native boolean  nativePageShouldHandleShiftAndArrows();
7178    private native boolean  nativePointInNavCache(int x, int y, int slop);
7179    // Like many other of our native methods, you must make sure that
7180    // mNativeClass is not null before calling this method.
7181    private native void     nativeRecordButtons(boolean focused,
7182            boolean pressed, boolean invalidate);
7183    private native void     nativeResetSelection();
7184    private native void     nativeSelectAll();
7185    private native void     nativeSelectBestAt(Rect rect);
7186    private native int      nativeSelectionX();
7187    private native int      nativeSelectionY();
7188    private native int      nativeFindIndex();
7189    private native void     nativeSetExtendSelection();
7190    private native void     nativeSetFindIsEmpty();
7191    private native void     nativeSetFindIsUp(boolean isUp);
7192    private native void     nativeSetFollowedLink(boolean followed);
7193    private native void     nativeSetHeightCanMeasure(boolean measure);
7194    private native void     nativeSetBaseLayer(int layer);
7195    private native void     nativeReplaceBaseContent(int content);
7196    private native void     nativeCopyBaseContentToPicture(Picture pict);
7197    private native boolean  nativeHasContent();
7198    private native void     nativeSetSelectionPointer(boolean set,
7199            float scale, int x, int y);
7200    private native boolean  nativeStartSelection(int x, int y);
7201    private native Rect     nativeSubtractLayers(Rect content);
7202    private native int      nativeTextGeneration();
7203    // Never call this version except by updateCachedTextfield(String) -
7204    // we always want to pass in our generation number.
7205    private native void     nativeUpdateCachedTextfield(String updatedText,
7206            int generation);
7207    private native boolean  nativeWordSelection(int x, int y);
7208    // return NO_LEFTEDGE means failure.
7209    static final int NO_LEFTEDGE = -1;
7210    native int nativeGetBlockLeftEdge(int x, int y, float scale);
7211
7212    // Returns a pointer to the scrollable LayerAndroid at the given point.
7213    private native int      nativeScrollableLayer(int x, int y);
7214    private native boolean  nativeScrollLayer(int layer, int dx, int dy);
7215}
7216