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