WebView.java revision 5de6389f2252cb6e39918e21f80a08918e0c2c02
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.app.AlertDialog;
20import android.content.Context;
21import android.content.DialogInterface;
22import android.content.Intent;
23import android.content.DialogInterface.OnCancelListener;
24import android.database.DataSetObserver;
25import android.graphics.Bitmap;
26import android.graphics.Canvas;
27import android.graphics.Color;
28import android.graphics.Picture;
29import android.graphics.Point;
30import android.graphics.Rect;
31import android.graphics.Region;
32import android.graphics.drawable.Drawable;
33import android.net.http.SslCertificate;
34import android.net.Uri;
35import android.os.Bundle;
36import android.os.Handler;
37import android.os.Message;
38import android.os.ServiceManager;
39import android.os.SystemClock;
40import android.provider.Checkin;
41import android.text.IClipboard;
42import android.text.Selection;
43import android.text.Spannable;
44import android.util.AttributeSet;
45import android.util.EventLog;
46import android.util.Log;
47import android.util.TypedValue;
48import android.view.Gravity;
49import android.view.KeyEvent;
50import android.view.LayoutInflater;
51import android.view.MotionEvent;
52import android.view.SoundEffectConstants;
53import android.view.VelocityTracker;
54import android.view.View;
55import android.view.ViewConfiguration;
56import android.view.ViewGroup;
57import android.view.ViewParent;
58import android.view.ViewTreeObserver;
59import android.view.animation.AlphaAnimation;
60import android.view.inputmethod.InputMethodManager;
61import android.webkit.WebTextView.AutoCompleteAdapter;
62import android.webkit.WebViewCore.EventHub;
63import android.widget.AbsoluteLayout;
64import android.widget.Adapter;
65import android.widget.AdapterView;
66import android.widget.ArrayAdapter;
67import android.widget.CheckedTextView;
68import android.widget.FrameLayout;
69import android.widget.LinearLayout;
70import android.widget.ListView;
71import android.widget.Scroller;
72import android.widget.Toast;
73import android.widget.ZoomButtonsController;
74import android.widget.ZoomControls;
75import android.widget.AdapterView.OnItemClickListener;
76
77import java.io.File;
78import java.io.FileInputStream;
79import java.io.FileNotFoundException;
80import java.io.FileOutputStream;
81import java.io.IOException;
82import java.net.URLDecoder;
83import java.util.ArrayList;
84import java.util.List;
85import java.util.Map;
86
87import junit.framework.Assert;
88
89/**
90 * <p>A View that displays web pages. This class is the basis upon which you
91 * can roll your own web browser or simply display some online content within your Activity.
92 * It uses the WebKit rendering engine to display
93 * web pages and includes methods to navigate forward and backward
94 * through a history, zoom in and out, perform text searches and more.</p>
95 * <p>To enable the built-in zoom, set
96 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
97 * (introduced in API version 3).
98 * <p>Note that, in order for your Activity to access the Internet and load web pages
99 * in a WebView, you must add the <var>INTERNET</var> permissions to your
100 * Android Manifest file:</p>
101 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
102 *
103 * <p>This must be a child of the <code>&lt;manifest></code> element.</p>
104 *
105 * <h3>Basic usage</h3>
106 *
107 * <p>By default, a WebView provides no browser-like widgets, does not
108 * enable JavaScript and errors will be ignored. If your goal is only
109 * to display some HTML as a part of your UI, this is probably fine;
110 * the user won't need to interact with the web page beyond reading
111 * it, and the web page won't need to interact with the user. If you
112 * actually want a fully blown web browser, then you probably want to
113 * invoke the Browser application with your URL rather than show it
114 * with a WebView. See {@link android.content.Intent} for more information.</p>
115 *
116 * <pre class="prettyprint">
117 * WebView webview = new WebView(this);
118 * setContentView(webview);
119 *
120 * // Simplest usage: note that an exception will NOT be thrown
121 * // if there is an error loading this page (see below).
122 * webview.loadUrl("http://slashdot.org/");
123 *
124 * // Of course you can also load from any string:
125 * String summary = "&lt;html>&lt;body>You scored &lt;b>192</b> points.&lt;/body>&lt;/html>";
126 * webview.loadData(summary, "text/html", "utf-8");
127 * // ... although note that there are restrictions on what this HTML can do.
128 * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info.
129 * </pre>
130 *
131 * <p>A WebView has several customization points where you can add your
132 * own behavior. These are:</p>
133 *
134 * <ul>
135 *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
136 *       This class is called when something that might impact a
137 *       browser UI happens, for instance, progress updates and
138 *       JavaScript alerts are sent here.
139 *   </li>
140 *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
141 *       It will be called when things happen that impact the
142 *       rendering of the content, eg, errors or form submissions. You
143 *       can also intercept URL loading here.</li>
144 *   <li>Via the {@link android.webkit.WebSettings} class, which contains
145 *       miscellaneous configuration. </li>
146 *   <li>With the {@link android.webkit.WebView#addJavascriptInterface} method.
147 *       This lets you bind Java objects into the WebView so they can be
148 *       controlled from the web pages JavaScript.</li>
149 * </ul>
150 *
151 * <p>Here's a more complicated example, showing error handling,
152 *    settings, and progress notification:</p>
153 *
154 * <pre class="prettyprint">
155 * // Let's display the progress in the activity title bar, like the
156 * // browser app does.
157 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
158 *
159 * webview.getSettings().setJavaScriptEnabled(true);
160 *
161 * final Activity activity = this;
162 * webview.setWebChromeClient(new WebChromeClient() {
163 *   public void onProgressChanged(WebView view, int progress) {
164 *     // Activities and WebViews measure progress with different scales.
165 *     // The progress meter will automatically disappear when we reach 100%
166 *     activity.setProgress(progress * 1000);
167 *   }
168 * });
169 * webview.setWebViewClient(new WebViewClient() {
170 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
171 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
172 *   }
173 * });
174 *
175 * webview.loadUrl("http://slashdot.org/");
176 * </pre>
177 *
178 * <h3>Cookie and window management</h3>
179 *
180 * <p>For obvious security reasons, your application has its own
181 * cache, cookie store etc - it does not share the Browser
182 * applications data. Cookies are managed on a separate thread, so
183 * operations like index building don't block the UI
184 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
185 * if you want to use cookies in your application.
186 * </p>
187 *
188 * <p>By default, requests by the HTML to open new windows are
189 * ignored. This is true whether they be opened by JavaScript or by
190 * the target attribute on a link. You can customize your
191 * WebChromeClient to provide your own behaviour for opening multiple windows,
192 * and render them in whatever manner you want.</p>
193 *
194 * <p>Standard behavior for an Activity is to be destroyed and
195 * recreated when the devices orientation is changed. This will cause
196 * the WebView to reload the current page. If you don't want that, you
197 * can set your Activity to handle the orientation and keyboardHidden
198 * changes, and then just leave the WebView alone. It'll automatically
199 * re-orient itself as appropriate.</p>
200 */
201public class WebView extends AbsoluteLayout
202        implements ViewTreeObserver.OnGlobalFocusChangeListener,
203        ViewGroup.OnHierarchyChangeListener {
204
205    // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
206    // the screen all-the-time. Good for profiling our drawing code
207    static private final boolean AUTO_REDRAW_HACK = false;
208    // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
209    private boolean mAutoRedraw;
210
211    static final String LOGTAG = "webview";
212
213    private static class ExtendedZoomControls extends FrameLayout {
214        public ExtendedZoomControls(Context context, AttributeSet attrs) {
215            super(context, attrs);
216            LayoutInflater inflater = (LayoutInflater)
217                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
218            inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true);
219            mPlusMinusZoomControls = (ZoomControls) findViewById(
220                    com.android.internal.R.id.zoomControls);
221            findViewById(com.android.internal.R.id.zoomMagnify).setVisibility(
222                    View.GONE);
223        }
224
225        public void show(boolean showZoom, boolean canZoomOut) {
226            mPlusMinusZoomControls.setVisibility(
227                    showZoom ? View.VISIBLE : View.GONE);
228            fade(View.VISIBLE, 0.0f, 1.0f);
229        }
230
231        public void hide() {
232            fade(View.GONE, 1.0f, 0.0f);
233        }
234
235        private void fade(int visibility, float startAlpha, float endAlpha) {
236            AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha);
237            anim.setDuration(500);
238            startAnimation(anim);
239            setVisibility(visibility);
240        }
241
242        public boolean hasFocus() {
243            return mPlusMinusZoomControls.hasFocus();
244        }
245
246        public void setOnZoomInClickListener(OnClickListener listener) {
247            mPlusMinusZoomControls.setOnZoomInClickListener(listener);
248        }
249
250        public void setOnZoomOutClickListener(OnClickListener listener) {
251            mPlusMinusZoomControls.setOnZoomOutClickListener(listener);
252        }
253
254        ZoomControls    mPlusMinusZoomControls;
255    }
256
257    /**
258     *  Transportation object for returning WebView across thread boundaries.
259     */
260    public class WebViewTransport {
261        private WebView mWebview;
262
263        /**
264         * Set the WebView to the transportation object.
265         * @param webview The WebView to transport.
266         */
267        public synchronized void setWebView(WebView webview) {
268            mWebview = webview;
269        }
270
271        /**
272         * Return the WebView object.
273         * @return WebView The transported WebView object.
274         */
275        public synchronized WebView getWebView() {
276            return mWebview;
277        }
278    }
279
280    // A final CallbackProxy shared by WebViewCore and BrowserFrame.
281    private final CallbackProxy mCallbackProxy;
282
283    private final WebViewDatabase mDatabase;
284
285    // SSL certificate for the main top-level page (if secure)
286    private SslCertificate mCertificate;
287
288    // Native WebView pointer that is 0 until the native object has been
289    // created.
290    private int mNativeClass;
291    // This would be final but it needs to be set to null when the WebView is
292    // destroyed.
293    private WebViewCore mWebViewCore;
294    // Handler for dispatching UI messages.
295    /* package */ final Handler mPrivateHandler = new PrivateHandler();
296    private WebTextView mWebTextView;
297    // Used to ignore changes to webkit text that arrives to the UI side after
298    // more key events.
299    private int mTextGeneration;
300
301    // Used by WebViewCore to create child views.
302    /* package */ final ViewManager mViewManager;
303
304    /**
305     * Position of the last touch event.
306     */
307    private float mLastTouchX;
308    private float mLastTouchY;
309
310    /**
311     * Time of the last touch event.
312     */
313    private long mLastTouchTime;
314
315    /**
316     * Time of the last time sending touch event to WebViewCore
317     */
318    private long mLastSentTouchTime;
319
320    /**
321     * The minimum elapsed time before sending another ACTION_MOVE event to
322     * WebViewCore. This really should be tuned for each type of the devices.
323     * For example in Google Map api test case, it takes Dream device at least
324     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
325     * triggering the layout and drawing the picture. While the same process
326     * takes 60+ms on the current high speed device. If we make
327     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
328     * to WebViewCore queue and the real layout and draw events will be pushed
329     * to further, which slows down the refresh rate. Choose 50 to favor the
330     * current high speed devices. For Dream like devices, 100 is a better
331     * choice. Maybe make this in the buildspec later.
332     */
333    private static final int TOUCH_SENT_INTERVAL = 50;
334
335    /**
336     * Helper class to get velocity for fling
337     */
338    VelocityTracker mVelocityTracker;
339    private int mMaximumFling;
340    private float mLastVelocity;
341    private float mLastVelX;
342    private float mLastVelY;
343
344    /**
345     * Touch mode
346     */
347    private int mTouchMode = TOUCH_DONE_MODE;
348    private static final int TOUCH_INIT_MODE = 1;
349    private static final int TOUCH_DRAG_START_MODE = 2;
350    private static final int TOUCH_DRAG_MODE = 3;
351    private static final int TOUCH_SHORTPRESS_START_MODE = 4;
352    private static final int TOUCH_SHORTPRESS_MODE = 5;
353    private static final int TOUCH_DOUBLE_TAP_MODE = 6;
354    private static final int TOUCH_DONE_MODE = 7;
355    private static final int TOUCH_SELECT_MODE = 8;
356
357    // Whether to forward the touch events to WebCore
358    private boolean mForwardTouchEvents = false;
359
360    // Whether to prevent drag during touch. The initial value depends on
361    // mForwardTouchEvents. If WebCore wants touch events, we assume it will
362    // take control of touch events unless it says no for touch down event.
363    private static final int PREVENT_DRAG_NO = 0;
364    private static final int PREVENT_DRAG_MAYBE_YES = 1;
365    private static final int PREVENT_DRAG_YES = 2;
366    private int mPreventDrag = PREVENT_DRAG_NO;
367
368    // To keep track of whether the current drag was initiated by a WebTextView,
369    // so that we know not to hide the cursor
370    boolean mDragFromTextInput;
371
372    // Whether or not to draw the cursor ring.
373    private boolean mDrawCursorRing = true;
374
375    // true if onPause has been called (and not onResume)
376    private boolean mIsPaused;
377
378    /**
379     * Customizable constant
380     */
381    // pre-computed square of ViewConfiguration.getScaledTouchSlop()
382    private int mTouchSlopSquare;
383    // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
384    private int mDoubleTapSlopSquare;
385    // pre-computed density adjusted navigation slop
386    private int mNavSlop;
387    // This should be ViewConfiguration.getTapTimeout()
388    // But system time out is 100ms, which is too short for the browser.
389    // In the browser, if it switches out of tap too soon, jump tap won't work.
390    private static final int TAP_TIMEOUT = 200;
391    // This should be ViewConfiguration.getLongPressTimeout()
392    // But system time out is 500ms, which is too short for the browser.
393    // With a short timeout, it's difficult to treat trigger a short press.
394    private static final int LONG_PRESS_TIMEOUT = 1000;
395    // needed to avoid flinging after a pause of no movement
396    private static final int MIN_FLING_TIME = 250;
397    // draw unfiltered after drag is held without movement
398    private static final int MOTIONLESS_TIME = 100;
399    // The time that the Zoom Controls are visible before fading away
400    private static final long ZOOM_CONTROLS_TIMEOUT =
401            ViewConfiguration.getZoomControlsTimeout();
402    // The amount of content to overlap between two screens when going through
403    // pages with the space bar, in pixels.
404    private static final int PAGE_SCROLL_OVERLAP = 24;
405
406    /**
407     * These prevent calling requestLayout if either dimension is fixed. This
408     * depends on the layout parameters and the measure specs.
409     */
410    boolean mWidthCanMeasure;
411    boolean mHeightCanMeasure;
412
413    // Remember the last dimensions we sent to the native side so we can avoid
414    // sending the same dimensions more than once.
415    int mLastWidthSent;
416    int mLastHeightSent;
417
418    private int mContentWidth;   // cache of value from WebViewCore
419    private int mContentHeight;  // cache of value from WebViewCore
420
421    // Need to have the separate control for horizontal and vertical scrollbar
422    // style than the View's single scrollbar style
423    private boolean mOverlayHorizontalScrollbar = true;
424    private boolean mOverlayVerticalScrollbar = false;
425
426    // our standard speed. this way small distances will be traversed in less
427    // time than large distances, but we cap the duration, so that very large
428    // distances won't take too long to get there.
429    private static final int STD_SPEED = 480;  // pixels per second
430    // time for the longest scroll animation
431    private static final int MAX_DURATION = 750;   // milliseconds
432    private static final int SLIDE_TITLE_DURATION = 500;   // milliseconds
433    private Scroller mScroller;
434
435    private boolean mWrapContent;
436    private static final int MOTIONLESS_FALSE           = 0;
437    private static final int MOTIONLESS_PENDING         = 1;
438    private static final int MOTIONLESS_TRUE            = 2;
439    private int mHeldMotionless;
440
441    /**
442     * Private message ids
443     */
444    private static final int REMEMBER_PASSWORD          = 1;
445    private static final int NEVER_REMEMBER_PASSWORD    = 2;
446    private static final int SWITCH_TO_SHORTPRESS       = 3;
447    private static final int SWITCH_TO_LONGPRESS        = 4;
448    private static final int RELEASE_SINGLE_TAP         = 5;
449    private static final int REQUEST_FORM_DATA          = 6;
450    private static final int RESUME_WEBCORE_UPDATE      = 7;
451    private static final int DRAG_HELD_MOTIONLESS       = 8;
452    private static final int AWAKEN_SCROLL_BARS         = 9;
453
454    //! arg1=x, arg2=y
455    static final int SCROLL_TO_MSG_ID                   = 10;
456    static final int SCROLL_BY_MSG_ID                   = 11;
457    //! arg1=x, arg2=y
458    static final int SPAWN_SCROLL_TO_MSG_ID             = 12;
459    //! arg1=x, arg2=y
460    static final int SYNC_SCROLL_TO_MSG_ID              = 13;
461    static final int NEW_PICTURE_MSG_ID                 = 14;
462    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 15;
463    static final int WEBCORE_INITIALIZED_MSG_ID         = 16;
464    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 17;
465    static final int FIND_AGAIN                         = 18;
466    static final int MOVE_OUT_OF_PLUGIN                 = 19;
467    static final int CLEAR_TEXT_ENTRY                   = 20;
468    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 21;
469    static final int UPDATE_CLIPBOARD                   = 22;
470    static final int LONG_PRESS_CENTER                  = 23;
471    static final int PREVENT_TOUCH_ID                   = 24;
472    static final int WEBCORE_NEED_TOUCH_EVENTS          = 25;
473    // obj=Rect in doc coordinates
474    static final int INVAL_RECT_MSG_ID                  = 26;
475    static final int REQUEST_KEYBOARD                   = 27;
476
477    static final String[] HandlerDebugString = {
478        "REMEMBER_PASSWORD", //              = 1;
479        "NEVER_REMEMBER_PASSWORD", //        = 2;
480        "SWITCH_TO_SHORTPRESS", //           = 3;
481        "SWITCH_TO_LONGPRESS", //            = 4;
482        "RELEASE_SINGLE_TAP", //             = 5;
483        "REQUEST_FORM_DATA", //              = 6;
484        "RESUME_WEBCORE_UPDATE", //          = 7;
485        "DRAG_HELD_MOTIONLESS", //           = 8;
486        "AWAKEN_SCROLL_BARS", //             = 9;
487        "SCROLL_TO_MSG_ID", //               = 10;
488        "SCROLL_BY_MSG_ID", //               = 11;
489        "SPAWN_SCROLL_TO_MSG_ID", //         = 12;
490        "SYNC_SCROLL_TO_MSG_ID", //          = 13;
491        "NEW_PICTURE_MSG_ID", //             = 14;
492        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 15;
493        "WEBCORE_INITIALIZED_MSG_ID", //     = 16;
494        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 17;
495        "FIND_AGAIN", //                     = 18;
496        "MOVE_OUT_OF_PLUGIN", //             = 19;
497        "CLEAR_TEXT_ENTRY", //               = 20;
498        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 21;
499        "UPDATE_CLIPBOARD", //               = 22;
500        "LONG_PRESS_CENTER", //              = 23;
501        "PREVENT_TOUCH_ID", //               = 24;
502        "WEBCORE_NEED_TOUCH_EVENTS", //      = 25;
503        "INVAL_RECT_MSG_ID", //              = 26;
504        "REQUEST_KEYBOARD" //                = 27;
505    };
506
507    // default scale limit. Depending on the display density
508    private static float DEFAULT_MAX_ZOOM_SCALE;
509    private static float DEFAULT_MIN_ZOOM_SCALE;
510    // scale limit, which can be set through viewport meta tag in the web page
511    private float mMaxZoomScale;
512    private float mMinZoomScale;
513    private boolean mMinZoomScaleFixed = true;
514
515    // initial scale in percent. 0 means using default.
516    private int mInitialScale = 0;
517
518    // while in the zoom overview mode, the page's width is fully fit to the
519    // current window. The page is alive, in another words, you can click to
520    // follow the links. Double tap will toggle between zoom overview mode and
521    // the last zoom scale.
522    boolean mInZoomOverview = false;
523
524    // ideally mZoomOverviewWidth should be mContentWidth. But sites like espn,
525    // engadget always have wider mContentWidth no matter what viewport size is.
526    int mZoomOverviewWidth = WebViewCore.DEFAULT_VIEWPORT_WIDTH;
527    float mLastScale;
528
529    // default scale. Depending on the display density.
530    static int DEFAULT_SCALE_PERCENT;
531    private float mDefaultScale;
532
533    // set to true temporarily while the zoom control is being dragged
534    private boolean mPreviewZoomOnly = false;
535
536    // computed scale and inverse, from mZoomWidth.
537    private float mActualScale;
538    private float mInvActualScale;
539    // if this is non-zero, it is used on drawing rather than mActualScale
540    private float mZoomScale;
541    private float mInvInitialZoomScale;
542    private float mInvFinalZoomScale;
543    private int mInitialScrollX;
544    private int mInitialScrollY;
545    private long mZoomStart;
546    private static final int ZOOM_ANIMATION_LENGTH = 500;
547
548    private boolean mUserScroll = false;
549
550    private int mSnapScrollMode = SNAP_NONE;
551    private static final int SNAP_NONE = 0;
552    private static final int SNAP_LOCK = 1; // not a separate state
553    private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
554    private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
555    private boolean mSnapPositive;
556
557    // Used to match key downs and key ups
558    private boolean mGotKeyDown;
559
560    /* package */ static boolean mLogEvent = true;
561    private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101;
562    private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102;
563
564    // for event log
565    private long mLastTouchUpTime = 0;
566
567    /**
568     * URI scheme for telephone number
569     */
570    public static final String SCHEME_TEL = "tel:";
571    /**
572     * URI scheme for email address
573     */
574    public static final String SCHEME_MAILTO = "mailto:";
575    /**
576     * URI scheme for map address
577     */
578    public static final String SCHEME_GEO = "geo:0,0?q=";
579
580    private int mBackgroundColor = Color.WHITE;
581
582    // Used to notify listeners of a new picture.
583    private PictureListener mPictureListener;
584    /**
585     * Interface to listen for new pictures as they change.
586     */
587    public interface PictureListener {
588        /**
589         * Notify the listener that the picture has changed.
590         * @param view The WebView that owns the picture.
591         * @param picture The new picture.
592         */
593        public void onNewPicture(WebView view, Picture picture);
594    }
595
596    // FIXME: Want to make this public, but need to change the API file.
597    public /*static*/ class HitTestResult {
598        /**
599         * Default HitTestResult, where the target is unknown
600         */
601        public static final int UNKNOWN_TYPE = 0;
602        /**
603         * HitTestResult for hitting a HTML::a tag
604         */
605        public static final int ANCHOR_TYPE = 1;
606        /**
607         * HitTestResult for hitting a phone number
608         */
609        public static final int PHONE_TYPE = 2;
610        /**
611         * HitTestResult for hitting a map address
612         */
613        public static final int GEO_TYPE = 3;
614        /**
615         * HitTestResult for hitting an email address
616         */
617        public static final int EMAIL_TYPE = 4;
618        /**
619         * HitTestResult for hitting an HTML::img tag
620         */
621        public static final int IMAGE_TYPE = 5;
622        /**
623         * HitTestResult for hitting a HTML::a tag which contains HTML::img
624         */
625        public static final int IMAGE_ANCHOR_TYPE = 6;
626        /**
627         * HitTestResult for hitting a HTML::a tag with src=http
628         */
629        public static final int SRC_ANCHOR_TYPE = 7;
630        /**
631         * HitTestResult for hitting a HTML::a tag with src=http + HTML::img
632         */
633        public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
634        /**
635         * HitTestResult for hitting an edit text area
636         */
637        public static final int EDIT_TEXT_TYPE = 9;
638
639        private int mType;
640        private String mExtra;
641
642        HitTestResult() {
643            mType = UNKNOWN_TYPE;
644        }
645
646        private void setType(int type) {
647            mType = type;
648        }
649
650        private void setExtra(String extra) {
651            mExtra = extra;
652        }
653
654        public int getType() {
655            return mType;
656        }
657
658        public String getExtra() {
659            return mExtra;
660        }
661    }
662
663    // The View containing the zoom controls
664    private ExtendedZoomControls mZoomControls;
665    private Runnable mZoomControlRunnable;
666
667    private ZoomButtonsController mZoomButtonsController;
668
669    // These keep track of the center point of the zoom.  They are used to
670    // determine the point around which we should zoom.
671    private float mZoomCenterX;
672    private float mZoomCenterY;
673
674    private ZoomButtonsController.OnZoomListener mZoomListener =
675            new ZoomButtonsController.OnZoomListener() {
676
677        public void onVisibilityChanged(boolean visible) {
678            if (visible) {
679                switchOutDrawHistory();
680                updateZoomButtonsEnabled();
681            }
682        }
683
684        public void onZoom(boolean zoomIn) {
685            if (zoomIn) {
686                zoomIn();
687            } else {
688                zoomOut();
689            }
690
691            updateZoomButtonsEnabled();
692        }
693    };
694
695    /**
696     * Construct a new WebView with a Context object.
697     * @param context A Context object used to access application assets.
698     */
699    public WebView(Context context) {
700        this(context, null);
701    }
702
703    /**
704     * Construct a new WebView with layout parameters.
705     * @param context A Context object used to access application assets.
706     * @param attrs An AttributeSet passed to our parent.
707     */
708    public WebView(Context context, AttributeSet attrs) {
709        this(context, attrs, com.android.internal.R.attr.webViewStyle);
710    }
711
712    /**
713     * Construct a new WebView with layout parameters and a default style.
714     * @param context A Context object used to access application assets.
715     * @param attrs An AttributeSet passed to our parent.
716     * @param defStyle The default style resource ID.
717     */
718    public WebView(Context context, AttributeSet attrs, int defStyle) {
719        this(context, attrs, defStyle, null);
720    }
721
722    /**
723     * Construct a new WebView with layout parameters, a default style and a set
724     * of custom Javscript interfaces to be added to the WebView at initialization
725     * time. This guraratees that these interfaces will be available when the JS
726     * context is initialized.
727     * @param context A Context object used to access application assets.
728     * @param attrs An AttributeSet passed to our parent.
729     * @param defStyle The default style resource ID.
730     * @param javascriptInterfaces is a Map of intareface names, as keys, and
731     * object implementing those interfaces, as values.
732     * @hide pending API council approval.
733     */
734    protected WebView(Context context, AttributeSet attrs, int defStyle,
735            Map<String, Object> javascriptInterfaces) {
736        super(context, attrs, defStyle);
737        init();
738
739        mCallbackProxy = new CallbackProxy(context, this);
740        mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces);
741        mDatabase = WebViewDatabase.getInstance(context);
742        mScroller = new Scroller(context);
743
744        mViewManager = new ViewManager(this);
745
746        mZoomButtonsController = new ZoomButtonsController(this);
747        mZoomButtonsController.setOnZoomListener(mZoomListener);
748        // ZoomButtonsController positions the buttons at the bottom, but in
749        // the middle.  Change their layout parameters so they appear on the
750        // right.
751        View controls = mZoomButtonsController.getZoomControls();
752        ViewGroup.LayoutParams params = controls.getLayoutParams();
753        if (params instanceof FrameLayout.LayoutParams) {
754            FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams)
755                    params;
756            frameParams.gravity = Gravity.RIGHT;
757        }
758    }
759
760    private void updateZoomButtonsEnabled() {
761        boolean canZoomIn = mActualScale < mMaxZoomScale;
762        boolean canZoomOut = mActualScale > mMinZoomScale && !mInZoomOverview;
763        if (!canZoomIn && !canZoomOut) {
764            // Hide the zoom in and out buttons, as well as the fit to page
765            // button, if the page cannot zoom
766            mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
767        } else {
768            // Bring back the hidden zoom controls.
769            mZoomButtonsController.getZoomControls()
770                    .setVisibility(View.VISIBLE);
771            // Set each one individually, as a page may be able to zoom in
772            // or out.
773            mZoomButtonsController.setZoomInEnabled(canZoomIn);
774            mZoomButtonsController.setZoomOutEnabled(canZoomOut);
775        }
776    }
777
778    private void init() {
779        setWillNotDraw(false);
780        setFocusable(true);
781        setFocusableInTouchMode(true);
782        setClickable(true);
783        setLongClickable(true);
784
785        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
786        int slop = configuration.getScaledTouchSlop();
787        mTouchSlopSquare = slop * slop;
788        mMinLockSnapReverseDistance = slop;
789        slop = configuration.getScaledDoubleTapSlop();
790        mDoubleTapSlopSquare = slop * slop;
791        final float density = getContext().getResources().getDisplayMetrics().density;
792        // use one line height, 16 based on our current default font, for how
793        // far we allow a touch be away from the edge of a link
794        mNavSlop = (int) (16 * density);
795        // density adjusted scale factors
796        DEFAULT_SCALE_PERCENT = (int) (100 * density);
797        mDefaultScale = density;
798        mActualScale = density;
799        mInvActualScale = 1 / density;
800        DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
801        DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
802        mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
803        mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
804        mMaximumFling = configuration.getScaledMaximumFlingVelocity();
805    }
806
807    /* package */void updateDefaultZoomDensity(int zoomDensity) {
808        final float density = getContext().getResources().getDisplayMetrics().density
809                * 100 / zoomDensity;
810        if (Math.abs(density - mDefaultScale) > 0.01) {
811            float scaleFactor = density / mDefaultScale;
812            // adjust the limits
813            mNavSlop = (int) (16 * density);
814            DEFAULT_SCALE_PERCENT = (int) (100 * density);
815            DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
816            DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
817            mDefaultScale = density;
818            mMaxZoomScale *= scaleFactor;
819            mMinZoomScale *= scaleFactor;
820            setNewZoomScale(mActualScale * scaleFactor, false);
821        }
822    }
823
824    /* package */ boolean onSavePassword(String schemePlusHost, String username,
825            String password, final Message resumeMsg) {
826       boolean rVal = false;
827       if (resumeMsg == null) {
828           // null resumeMsg implies saving password silently
829           mDatabase.setUsernamePassword(schemePlusHost, username, password);
830       } else {
831            final Message remember = mPrivateHandler.obtainMessage(
832                    REMEMBER_PASSWORD);
833            remember.getData().putString("host", schemePlusHost);
834            remember.getData().putString("username", username);
835            remember.getData().putString("password", password);
836            remember.obj = resumeMsg;
837
838            final Message neverRemember = mPrivateHandler.obtainMessage(
839                    NEVER_REMEMBER_PASSWORD);
840            neverRemember.getData().putString("host", schemePlusHost);
841            neverRemember.getData().putString("username", username);
842            neverRemember.getData().putString("password", password);
843            neverRemember.obj = resumeMsg;
844
845            new AlertDialog.Builder(getContext())
846                    .setTitle(com.android.internal.R.string.save_password_label)
847                    .setMessage(com.android.internal.R.string.save_password_message)
848                    .setPositiveButton(com.android.internal.R.string.save_password_notnow,
849                    new DialogInterface.OnClickListener() {
850                        public void onClick(DialogInterface dialog, int which) {
851                            resumeMsg.sendToTarget();
852                        }
853                    })
854                    .setNeutralButton(com.android.internal.R.string.save_password_remember,
855                    new DialogInterface.OnClickListener() {
856                        public void onClick(DialogInterface dialog, int which) {
857                            remember.sendToTarget();
858                        }
859                    })
860                    .setNegativeButton(com.android.internal.R.string.save_password_never,
861                    new DialogInterface.OnClickListener() {
862                        public void onClick(DialogInterface dialog, int which) {
863                            neverRemember.sendToTarget();
864                        }
865                    })
866                    .setOnCancelListener(new OnCancelListener() {
867                        public void onCancel(DialogInterface dialog) {
868                            resumeMsg.sendToTarget();
869                        }
870                    }).show();
871            // Return true so that WebViewCore will pause while the dialog is
872            // up.
873            rVal = true;
874        }
875       return rVal;
876    }
877
878    @Override
879    public void setScrollBarStyle(int style) {
880        if (style == View.SCROLLBARS_INSIDE_INSET
881                || style == View.SCROLLBARS_OUTSIDE_INSET) {
882            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
883        } else {
884            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
885        }
886        super.setScrollBarStyle(style);
887    }
888
889    /**
890     * Specify whether the horizontal scrollbar has overlay style.
891     * @param overlay TRUE if horizontal scrollbar should have overlay style.
892     */
893    public void setHorizontalScrollbarOverlay(boolean overlay) {
894        mOverlayHorizontalScrollbar = overlay;
895    }
896
897    /**
898     * Specify whether the vertical scrollbar has overlay style.
899     * @param overlay TRUE if vertical scrollbar should have overlay style.
900     */
901    public void setVerticalScrollbarOverlay(boolean overlay) {
902        mOverlayVerticalScrollbar = overlay;
903    }
904
905    /**
906     * Return whether horizontal scrollbar has overlay style
907     * @return TRUE if horizontal scrollbar has overlay style.
908     */
909    public boolean overlayHorizontalScrollbar() {
910        return mOverlayHorizontalScrollbar;
911    }
912
913    /**
914     * Return whether vertical scrollbar has overlay style
915     * @return TRUE if vertical scrollbar has overlay style.
916     */
917    public boolean overlayVerticalScrollbar() {
918        return mOverlayVerticalScrollbar;
919    }
920
921    /*
922     * Return the width of the view where the content of WebView should render
923     * to.
924     * Note: this can be called from WebCoreThread.
925     */
926    /* package */ int getViewWidth() {
927        if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
928            return getWidth();
929        } else {
930            return getWidth() - getVerticalScrollbarWidth();
931        }
932    }
933
934    /*
935     * returns the height of the titlebarview (if any). Does not care about
936     * scrolling
937     */
938    private int getTitleHeight() {
939        return mTitleBar != null ? mTitleBar.getHeight() : 0;
940    }
941
942    /*
943     * Return the amount of the titlebarview (if any) that is visible
944     */
945    private int getVisibleTitleHeight() {
946        return Math.max(getTitleHeight() - mScrollY, 0);
947    }
948
949    /*
950     * Return the height of the view where the content of WebView should render
951     * to.  Note that this excludes mTitleBar, if there is one.
952     * Note: this can be called from WebCoreThread.
953     */
954    /* package */ int getViewHeight() {
955        return getViewHeightWithTitle() - getVisibleTitleHeight();
956    }
957
958    private int getViewHeightWithTitle() {
959        int height = getHeight();
960        if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
961            height -= getHorizontalScrollbarHeight();
962        }
963        return height;
964    }
965
966    /**
967     * @return The SSL certificate for the main top-level page or null if
968     * there is no certificate (the site is not secure).
969     */
970    public SslCertificate getCertificate() {
971        return mCertificate;
972    }
973
974    /**
975     * Sets the SSL certificate for the main top-level page.
976     */
977    public void setCertificate(SslCertificate certificate) {
978        // here, the certificate can be null (if the site is not secure)
979        mCertificate = certificate;
980    }
981
982    //-------------------------------------------------------------------------
983    // Methods called by activity
984    //-------------------------------------------------------------------------
985
986    /**
987     * Save the username and password for a particular host in the WebView's
988     * internal database.
989     * @param host The host that required the credentials.
990     * @param username The username for the given host.
991     * @param password The password for the given host.
992     */
993    public void savePassword(String host, String username, String password) {
994        mDatabase.setUsernamePassword(host, username, password);
995    }
996
997    /**
998     * Set the HTTP authentication credentials for a given host and realm.
999     *
1000     * @param host The host for the credentials.
1001     * @param realm The realm for the credentials.
1002     * @param username The username for the password. If it is null, it means
1003     *                 password can't be saved.
1004     * @param password The password
1005     */
1006    public void setHttpAuthUsernamePassword(String host, String realm,
1007            String username, String password) {
1008        mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
1009    }
1010
1011    /**
1012     * Retrieve the HTTP authentication username and password for a given
1013     * host & realm pair
1014     *
1015     * @param host The host for which the credentials apply.
1016     * @param realm The realm for which the credentials apply.
1017     * @return String[] if found, String[0] is username, which can be null and
1018     *         String[1] is password. Return null if it can't find anything.
1019     */
1020    public String[] getHttpAuthUsernamePassword(String host, String realm) {
1021        return mDatabase.getHttpAuthUsernamePassword(host, realm);
1022    }
1023
1024    /**
1025     * Destroy the internal state of the WebView. This method should be called
1026     * after the WebView has been removed from the view system. No other
1027     * methods may be called on a WebView after destroy.
1028     */
1029    public void destroy() {
1030        clearTextEntry();
1031        if (mWebViewCore != null) {
1032            // Set the handlers to null before destroying WebViewCore so no
1033            // more messages will be posted.
1034            mCallbackProxy.setWebViewClient(null);
1035            mCallbackProxy.setWebChromeClient(null);
1036            // Tell WebViewCore to destroy itself
1037            WebViewCore webViewCore = mWebViewCore;
1038            mWebViewCore = null; // prevent using partial webViewCore
1039            webViewCore.destroy();
1040            // Remove any pending messages that might not be serviced yet.
1041            mPrivateHandler.removeCallbacksAndMessages(null);
1042            mCallbackProxy.removeCallbacksAndMessages(null);
1043            // Wake up the WebCore thread just in case it is waiting for a
1044            // javascript dialog.
1045            synchronized (mCallbackProxy) {
1046                mCallbackProxy.notify();
1047            }
1048        }
1049        if (mNativeClass != 0) {
1050            nativeDestroy();
1051            mNativeClass = 0;
1052        }
1053    }
1054
1055    /**
1056     * Enables platform notifications of data state and proxy changes.
1057     */
1058    public static void enablePlatformNotifications() {
1059        Network.enablePlatformNotifications();
1060    }
1061
1062    /**
1063     * If platform notifications are enabled, this should be called
1064     * from the Activity's onPause() or onStop().
1065     */
1066    public static void disablePlatformNotifications() {
1067        Network.disablePlatformNotifications();
1068    }
1069
1070    /**
1071     * Sets JavaScript engine flags.
1072     *
1073     * @param flags JS engine flags in a String
1074     *
1075     * @hide pending API solidification
1076     */
1077    public void setJsFlags(String flags) {
1078        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
1079    }
1080
1081    /**
1082     * Inform WebView of the network state. This is used to set
1083     * the javascript property window.navigator.isOnline and
1084     * generates the online/offline event as specified in HTML5, sec. 5.7.7
1085     * @param networkUp boolean indicating if network is available
1086     */
1087    public void setNetworkAvailable(boolean networkUp) {
1088        mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
1089                networkUp ? 1 : 0, 0);
1090    }
1091
1092    /**
1093     * Save the state of this WebView used in
1094     * {@link android.app.Activity#onSaveInstanceState}. Please note that this
1095     * method no longer stores the display data for this WebView. The previous
1096     * behavior could potentially leak files if {@link #restoreState} was never
1097     * called. See {@link #savePicture} and {@link #restorePicture} for saving
1098     * and restoring the display data.
1099     * @param outState The Bundle to store the WebView state.
1100     * @return The same copy of the back/forward list used to save the state. If
1101     *         saveState fails, the returned list will be null.
1102     * @see #savePicture
1103     * @see #restorePicture
1104     */
1105    public WebBackForwardList saveState(Bundle outState) {
1106        if (outState == null) {
1107            return null;
1108        }
1109        // We grab a copy of the back/forward list because a client of WebView
1110        // may have invalidated the history list by calling clearHistory.
1111        WebBackForwardList list = copyBackForwardList();
1112        final int currentIndex = list.getCurrentIndex();
1113        final int size = list.getSize();
1114        // We should fail saving the state if the list is empty or the index is
1115        // not in a valid range.
1116        if (currentIndex < 0 || currentIndex >= size || size == 0) {
1117            return null;
1118        }
1119        outState.putInt("index", currentIndex);
1120        // FIXME: This should just be a byte[][] instead of ArrayList but
1121        // Parcel.java does not have the code to handle multi-dimensional
1122        // arrays.
1123        ArrayList<byte[]> history = new ArrayList<byte[]>(size);
1124        for (int i = 0; i < size; i++) {
1125            WebHistoryItem item = list.getItemAtIndex(i);
1126            if (null == item) {
1127                // FIXME: this shouldn't happen
1128                // need to determine how item got set to null
1129                Log.w(LOGTAG, "saveState: Unexpected null history item.");
1130                return null;
1131            }
1132            byte[] data = item.getFlattenedData();
1133            if (data == null) {
1134                // It would be very odd to not have any data for a given history
1135                // item. And we will fail to rebuild the history list without
1136                // flattened data.
1137                return null;
1138            }
1139            history.add(data);
1140        }
1141        outState.putSerializable("history", history);
1142        if (mCertificate != null) {
1143            outState.putBundle("certificate",
1144                               SslCertificate.saveState(mCertificate));
1145        }
1146        return list;
1147    }
1148
1149    /**
1150     * Save the current display data to the Bundle given. Used in conjunction
1151     * with {@link #saveState}.
1152     * @param b A Bundle to store the display data.
1153     * @param dest The file to store the serialized picture data. Will be
1154     *             overwritten with this WebView's picture data.
1155     * @return True if the picture was successfully saved.
1156     */
1157    public boolean savePicture(Bundle b, File dest) {
1158        if (dest == null || b == null) {
1159            return false;
1160        }
1161        final Picture p = capturePicture();
1162        try {
1163            final FileOutputStream out = new FileOutputStream(dest);
1164            p.writeToStream(out);
1165            out.close();
1166        } catch (FileNotFoundException e){
1167            e.printStackTrace();
1168        } catch (IOException e) {
1169            e.printStackTrace();
1170        } catch (RuntimeException e) {
1171            e.printStackTrace();
1172        }
1173        if (dest.length() > 0) {
1174            b.putInt("scrollX", mScrollX);
1175            b.putInt("scrollY", mScrollY);
1176            b.putFloat("scale", mActualScale);
1177            if (mInZoomOverview) {
1178                b.putFloat("lastScale", mLastScale);
1179            }
1180            return true;
1181        }
1182        return false;
1183    }
1184
1185    /**
1186     * Restore the display data that was save in {@link #savePicture}. Used in
1187     * conjunction with {@link #restoreState}.
1188     * @param b A Bundle containing the saved display data.
1189     * @param src The file where the picture data was stored.
1190     * @return True if the picture was successfully restored.
1191     */
1192    public boolean restorePicture(Bundle b, File src) {
1193        if (src == null || b == null) {
1194            return false;
1195        }
1196        if (src.exists()) {
1197            Picture p = null;
1198            try {
1199                final FileInputStream in = new FileInputStream(src);
1200                p = Picture.createFromStream(in);
1201                in.close();
1202            } catch (FileNotFoundException e){
1203                e.printStackTrace();
1204            } catch (RuntimeException e) {
1205                e.printStackTrace();
1206            } catch (IOException e) {
1207                e.printStackTrace();
1208            }
1209            if (p != null) {
1210                int sx = b.getInt("scrollX", 0);
1211                int sy = b.getInt("scrollY", 0);
1212                float scale = b.getFloat("scale", 1.0f);
1213                mDrawHistory = true;
1214                mHistoryPicture = p;
1215                mScrollX = sx;
1216                mScrollY = sy;
1217                mHistoryWidth = Math.round(p.getWidth() * scale);
1218                mHistoryHeight = Math.round(p.getHeight() * scale);
1219                // as getWidth() / getHeight() of the view are not
1220                // available yet, set up mActualScale, so that when
1221                // onSizeChanged() is called, the rest will be set
1222                // correctly
1223                mActualScale = scale;
1224                float lastScale = b.getFloat("lastScale", -1.0f);
1225                if (lastScale > 0) {
1226                    mInZoomOverview = true;
1227                    mLastScale = lastScale;
1228                } else {
1229                    mInZoomOverview = false;
1230                }
1231                invalidate();
1232                return true;
1233            }
1234        }
1235        return false;
1236    }
1237
1238    /**
1239     * Restore the state of this WebView from the given map used in
1240     * {@link android.app.Activity#onRestoreInstanceState}. This method should
1241     * be called to restore the state of the WebView before using the object. If
1242     * it is called after the WebView has had a chance to build state (load
1243     * pages, create a back/forward list, etc.) there may be undesirable
1244     * side-effects. Please note that this method no longer restores the
1245     * display data for this WebView. See {@link #savePicture} and {@link
1246     * #restorePicture} for saving and restoring the display data.
1247     * @param inState The incoming Bundle of state.
1248     * @return The restored back/forward list or null if restoreState failed.
1249     * @see #savePicture
1250     * @see #restorePicture
1251     */
1252    public WebBackForwardList restoreState(Bundle inState) {
1253        WebBackForwardList returnList = null;
1254        if (inState == null) {
1255            return returnList;
1256        }
1257        if (inState.containsKey("index") && inState.containsKey("history")) {
1258            mCertificate = SslCertificate.restoreState(
1259                inState.getBundle("certificate"));
1260
1261            final WebBackForwardList list = mCallbackProxy.getBackForwardList();
1262            final int index = inState.getInt("index");
1263            // We can't use a clone of the list because we need to modify the
1264            // shared copy, so synchronize instead to prevent concurrent
1265            // modifications.
1266            synchronized (list) {
1267                final List<byte[]> history =
1268                        (List<byte[]>) inState.getSerializable("history");
1269                final int size = history.size();
1270                // Check the index bounds so we don't crash in native code while
1271                // restoring the history index.
1272                if (index < 0 || index >= size) {
1273                    return null;
1274                }
1275                for (int i = 0; i < size; i++) {
1276                    byte[] data = history.remove(0);
1277                    if (data == null) {
1278                        // If we somehow have null data, we cannot reconstruct
1279                        // the item and thus our history list cannot be rebuilt.
1280                        return null;
1281                    }
1282                    WebHistoryItem item = new WebHistoryItem(data);
1283                    list.addHistoryItem(item);
1284                }
1285                // Grab the most recent copy to return to the caller.
1286                returnList = copyBackForwardList();
1287                // Update the copy to have the correct index.
1288                returnList.setCurrentIndex(index);
1289            }
1290            // Remove all pending messages because we are restoring previous
1291            // state.
1292            mWebViewCore.removeMessages();
1293            // Send a restore state message.
1294            mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
1295        }
1296        return returnList;
1297    }
1298
1299    /**
1300     * Load the given url.
1301     * @param url The url of the resource to load.
1302     */
1303    public void loadUrl(String url) {
1304        if (url == null) {
1305            return;
1306        }
1307        switchOutDrawHistory();
1308        mWebViewCore.sendMessage(EventHub.LOAD_URL, url);
1309        clearTextEntry();
1310    }
1311
1312    /**
1313     * Load the url with postData using "POST" method into the WebView. If url
1314     * is not a network url, it will be loaded with {link
1315     * {@link #loadUrl(String)} instead.
1316     *
1317     * @param url The url of the resource to load.
1318     * @param postData The data will be passed to "POST" request.
1319     */
1320    public void postUrl(String url, byte[] postData) {
1321        if (URLUtil.isNetworkUrl(url)) {
1322            switchOutDrawHistory();
1323            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
1324            arg.mUrl = url;
1325            arg.mPostData = postData;
1326            mWebViewCore.sendMessage(EventHub.POST_URL, arg);
1327            clearTextEntry();
1328        } else {
1329            loadUrl(url);
1330        }
1331    }
1332
1333    /**
1334     * Load the given data into the WebView. This will load the data into
1335     * WebView using the data: scheme. Content loaded through this mechanism
1336     * does not have the ability to load content from the network.
1337     * @param data A String of data in the given encoding.
1338     * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg
1339     * @param encoding The encoding of the data. i.e. utf-8, base64
1340     */
1341    public void loadData(String data, String mimeType, String encoding) {
1342        loadUrl("data:" + mimeType + ";" + encoding + "," + data);
1343    }
1344
1345    /**
1346     * Load the given data into the WebView, use the provided URL as the base
1347     * URL for the content. The base URL is the URL that represents the page
1348     * that is loaded through this interface. As such, it is used for the
1349     * history entry and to resolve any relative URLs. The failUrl is used if
1350     * browser fails to load the data provided. If it is empty or null, and the
1351     * load fails, then no history entry is created.
1352     * <p>
1353     * Note for post 1.0. Due to the change in the WebKit, the access to asset
1354     * files through "file:///android_asset/" for the sub resources is more
1355     * restricted. If you provide null or empty string as baseUrl, you won't be
1356     * able to access asset files. If the baseUrl is anything other than
1357     * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for
1358     * sub resources.
1359     *
1360     * @param baseUrl Url to resolve relative paths with, if null defaults to
1361     *            "about:blank"
1362     * @param data A String of data in the given encoding.
1363     * @param mimeType The MIMEType of the data. i.e. text/html. If null,
1364     *            defaults to "text/html"
1365     * @param encoding The encoding of the data. i.e. utf-8, us-ascii
1366     * @param failUrl URL to use if the content fails to load or null.
1367     */
1368    public void loadDataWithBaseURL(String baseUrl, String data,
1369            String mimeType, String encoding, String failUrl) {
1370
1371        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
1372            loadData(data, mimeType, encoding);
1373            return;
1374        }
1375        switchOutDrawHistory();
1376        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
1377        arg.mBaseUrl = baseUrl;
1378        arg.mData = data;
1379        arg.mMimeType = mimeType;
1380        arg.mEncoding = encoding;
1381        arg.mFailUrl = failUrl;
1382        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
1383        clearTextEntry();
1384    }
1385
1386    /**
1387     * Stop the current load.
1388     */
1389    public void stopLoading() {
1390        // TODO: should we clear all the messages in the queue before sending
1391        // STOP_LOADING?
1392        switchOutDrawHistory();
1393        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
1394    }
1395
1396    /**
1397     * Reload the current url.
1398     */
1399    public void reload() {
1400        clearTextEntry();
1401        switchOutDrawHistory();
1402        mWebViewCore.sendMessage(EventHub.RELOAD);
1403    }
1404
1405    /**
1406     * Return true if this WebView has a back history item.
1407     * @return True iff this WebView has a back history item.
1408     */
1409    public boolean canGoBack() {
1410        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1411        synchronized (l) {
1412            if (l.getClearPending()) {
1413                return false;
1414            } else {
1415                return l.getCurrentIndex() > 0;
1416            }
1417        }
1418    }
1419
1420    /**
1421     * Go back in the history of this WebView.
1422     */
1423    public void goBack() {
1424        goBackOrForward(-1);
1425    }
1426
1427    /**
1428     * Return true if this WebView has a forward history item.
1429     * @return True iff this Webview has a forward history item.
1430     */
1431    public boolean canGoForward() {
1432        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1433        synchronized (l) {
1434            if (l.getClearPending()) {
1435                return false;
1436            } else {
1437                return l.getCurrentIndex() < l.getSize() - 1;
1438            }
1439        }
1440    }
1441
1442    /**
1443     * Go forward in the history of this WebView.
1444     */
1445    public void goForward() {
1446        goBackOrForward(1);
1447    }
1448
1449    /**
1450     * Return true if the page can go back or forward the given
1451     * number of steps.
1452     * @param steps The negative or positive number of steps to move the
1453     *              history.
1454     */
1455    public boolean canGoBackOrForward(int steps) {
1456        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1457        synchronized (l) {
1458            if (l.getClearPending()) {
1459                return false;
1460            } else {
1461                int newIndex = l.getCurrentIndex() + steps;
1462                return newIndex >= 0 && newIndex < l.getSize();
1463            }
1464        }
1465    }
1466
1467    /**
1468     * Go to the history item that is the number of steps away from
1469     * the current item. Steps is negative if backward and positive
1470     * if forward.
1471     * @param steps The number of steps to take back or forward in the back
1472     *              forward list.
1473     */
1474    public void goBackOrForward(int steps) {
1475        goBackOrForward(steps, false);
1476    }
1477
1478    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
1479        // every time we go back or forward, we want to reset the
1480        // WebView certificate:
1481        // if the new site is secure, we will reload it and get a
1482        // new certificate set;
1483        // if the new site is not secure, the certificate must be
1484        // null, and that will be the case
1485        mCertificate = null;
1486        if (steps != 0) {
1487            clearTextEntry();
1488            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
1489                    ignoreSnapshot ? 1 : 0);
1490        }
1491    }
1492
1493    private boolean extendScroll(int y) {
1494        int finalY = mScroller.getFinalY();
1495        int newY = pinLocY(finalY + y);
1496        if (newY == finalY) return false;
1497        mScroller.setFinalY(newY);
1498        mScroller.extendDuration(computeDuration(0, y));
1499        return true;
1500    }
1501
1502    /**
1503     * Scroll the contents of the view up by half the view size
1504     * @param top true to jump to the top of the page
1505     * @return true if the page was scrolled
1506     */
1507    public boolean pageUp(boolean top) {
1508        if (mNativeClass == 0) {
1509            return false;
1510        }
1511        nativeClearCursor(); // start next trackball movement from page edge
1512        if (top) {
1513            // go to the top of the document
1514            return pinScrollTo(mScrollX, 0, true, 0);
1515        }
1516        // Page up
1517        int h = getHeight();
1518        int y;
1519        if (h > 2 * PAGE_SCROLL_OVERLAP) {
1520            y = -h + PAGE_SCROLL_OVERLAP;
1521        } else {
1522            y = -h / 2;
1523        }
1524        mUserScroll = true;
1525        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
1526                : extendScroll(y);
1527    }
1528
1529    /**
1530     * Scroll the contents of the view down by half the page size
1531     * @param bottom true to jump to bottom of page
1532     * @return true if the page was scrolled
1533     */
1534    public boolean pageDown(boolean bottom) {
1535        if (mNativeClass == 0) {
1536            return false;
1537        }
1538        nativeClearCursor(); // start next trackball movement from page edge
1539        if (bottom) {
1540            return pinScrollTo(mScrollX, mContentHeight, true, 0);
1541        }
1542        // Page down.
1543        int h = getHeight();
1544        int y;
1545        if (h > 2 * PAGE_SCROLL_OVERLAP) {
1546            y = h - PAGE_SCROLL_OVERLAP;
1547        } else {
1548            y = h / 2;
1549        }
1550        mUserScroll = true;
1551        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
1552                : extendScroll(y);
1553    }
1554
1555    /**
1556     * Clear the view so that onDraw() will draw nothing but white background,
1557     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
1558     */
1559    public void clearView() {
1560        mContentWidth = 0;
1561        mContentHeight = 0;
1562        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
1563    }
1564
1565    /**
1566     * Return a new picture that captures the current display of the webview.
1567     * This is a copy of the display, and will be unaffected if the webview
1568     * later loads a different URL.
1569     *
1570     * @return a picture containing the current contents of the view. Note this
1571     *         picture is of the entire document, and is not restricted to the
1572     *         bounds of the view.
1573     */
1574    public Picture capturePicture() {
1575        if (null == mWebViewCore) return null; // check for out of memory tab
1576        return mWebViewCore.copyContentPicture();
1577    }
1578
1579    /**
1580     *  Return true if the browser is displaying a TextView for text input.
1581     */
1582    private boolean inEditingMode() {
1583        return mWebTextView != null && mWebTextView.getParent() != null
1584                && mWebTextView.hasFocus();
1585    }
1586
1587    private void clearTextEntry() {
1588        if (inEditingMode()) {
1589            mWebTextView.remove();
1590        }
1591    }
1592
1593    /**
1594     * Return the current scale of the WebView
1595     * @return The current scale.
1596     */
1597    public float getScale() {
1598        return mActualScale;
1599    }
1600
1601    /**
1602     * Set the initial scale for the WebView. 0 means default. If
1603     * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
1604     * way. Otherwise it starts with 100%. If initial scale is greater than 0,
1605     * WebView starts will this value as initial scale.
1606     *
1607     * @param scaleInPercent The initial scale in percent.
1608     */
1609    public void setInitialScale(int scaleInPercent) {
1610        mInitialScale = scaleInPercent;
1611    }
1612
1613    /**
1614     * Invoke the graphical zoom picker widget for this WebView. This will
1615     * result in the zoom widget appearing on the screen to control the zoom
1616     * level of this WebView.
1617     */
1618    public void invokeZoomPicker() {
1619        if (!getSettings().supportZoom()) {
1620            Log.w(LOGTAG, "This WebView doesn't support zoom.");
1621            return;
1622        }
1623        clearTextEntry();
1624        if (getSettings().getBuiltInZoomControls()) {
1625            mZoomButtonsController.setVisible(true);
1626        } else {
1627            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
1628            mPrivateHandler.postDelayed(mZoomControlRunnable,
1629                    ZOOM_CONTROLS_TIMEOUT);
1630        }
1631    }
1632
1633    /**
1634     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
1635     * is found and the anchor has a non-javascript url, the HitTestResult type
1636     * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
1637     * anchor does not have a url or if it is a javascript url, the type will
1638     * be UNKNOWN_TYPE and the url has to be retrieved through
1639     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1640     * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
1641     * the "extra" field. A type of
1642     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
1643     * a child node. If a phone number is found, the HitTestResult type is set
1644     * to PHONE_TYPE and the phone number is set in the "extra" field of
1645     * HitTestResult. If a map address is found, the HitTestResult type is set
1646     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1647     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1648     * and the email is set in the "extra" field of HitTestResult. Otherwise,
1649     * HitTestResult type is set to UNKNOWN_TYPE.
1650     */
1651    public HitTestResult getHitTestResult() {
1652        if (mNativeClass == 0) {
1653            return null;
1654        }
1655
1656        HitTestResult result = new HitTestResult();
1657        if (nativeHasCursorNode()) {
1658            if (nativeCursorIsTextInput()) {
1659                result.setType(HitTestResult.EDIT_TEXT_TYPE);
1660            } else {
1661                String text = nativeCursorText();
1662                if (text != null) {
1663                    if (text.startsWith(SCHEME_TEL)) {
1664                        result.setType(HitTestResult.PHONE_TYPE);
1665                        result.setExtra(text.substring(SCHEME_TEL.length()));
1666                    } else if (text.startsWith(SCHEME_MAILTO)) {
1667                        result.setType(HitTestResult.EMAIL_TYPE);
1668                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
1669                    } else if (text.startsWith(SCHEME_GEO)) {
1670                        result.setType(HitTestResult.GEO_TYPE);
1671                        result.setExtra(URLDecoder.decode(text
1672                                .substring(SCHEME_GEO.length())));
1673                    } else if (nativeCursorIsAnchor()) {
1674                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
1675                        result.setExtra(text);
1676                    }
1677                }
1678            }
1679        }
1680        int type = result.getType();
1681        if (type == HitTestResult.UNKNOWN_TYPE
1682                || type == HitTestResult.SRC_ANCHOR_TYPE) {
1683            // Now check to see if it is an image.
1684            int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1685            int contentY = viewToContentY((int) mLastTouchY + mScrollY);
1686            String text = nativeImageURI(contentX, contentY);
1687            if (text != null) {
1688                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
1689                        HitTestResult.IMAGE_TYPE :
1690                        HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1691                result.setExtra(text);
1692            }
1693        }
1694        return result;
1695    }
1696
1697    /**
1698     * Request the href of an anchor element due to getFocusNodePath returning
1699     * "href." If hrefMsg is null, this method returns immediately and does not
1700     * dispatch hrefMsg to its target.
1701     *
1702     * @param hrefMsg This message will be dispatched with the result of the
1703     *            request as the data member with "url" as key. The result can
1704     *            be null.
1705     */
1706    // FIXME: API change required to change the name of this function.  We now
1707    // look at the cursor node, and not the focus node.  Also, what is
1708    // getFocusNodePath?
1709    public void requestFocusNodeHref(Message hrefMsg) {
1710        if (hrefMsg == null || mNativeClass == 0) {
1711            return;
1712        }
1713        if (nativeCursorIsAnchor()) {
1714            mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
1715                    nativeCursorFramePointer(), nativeCursorNodePointer(),
1716                    hrefMsg);
1717        }
1718    }
1719
1720    /**
1721     * Request the url of the image last touched by the user. msg will be sent
1722     * to its target with a String representing the url as its object.
1723     *
1724     * @param msg This message will be dispatched with the result of the request
1725     *            as the data member with "url" as key. The result can be null.
1726     */
1727    public void requestImageRef(Message msg) {
1728        if (0 == mNativeClass) return; // client isn't initialized
1729        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1730        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
1731        String ref = nativeImageURI(contentX, contentY);
1732        Bundle data = msg.getData();
1733        data.putString("url", ref);
1734        msg.setData(data);
1735        msg.sendToTarget();
1736    }
1737
1738    private static int pinLoc(int x, int viewMax, int docMax) {
1739//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
1740        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
1741            // pin the short document to the top/left of the screen
1742            x = 0;
1743//            Log.d(LOGTAG, "--- center " + x);
1744        } else if (x < 0) {
1745            x = 0;
1746//            Log.d(LOGTAG, "--- zero");
1747        } else if (x + viewMax > docMax) {
1748            x = docMax - viewMax;
1749//            Log.d(LOGTAG, "--- pin " + x);
1750        }
1751        return x;
1752    }
1753
1754    // Expects x in view coordinates
1755    private int pinLocX(int x) {
1756        return pinLoc(x, getViewWidth(), computeHorizontalScrollRange());
1757    }
1758
1759    // Expects y in view coordinates
1760    private int pinLocY(int y) {
1761        int titleH = getTitleHeight();
1762        // if the titlebar is still visible, just pin against 0
1763        if (y <= titleH) {
1764            return Math.max(y, 0);
1765        }
1766        // convert to 0-based coordinate (subtract the title height)
1767        // pin(), and then add the title height back in
1768        return pinLoc(y - titleH, getViewHeight(),
1769                      computeVerticalScrollRange()) + titleH;
1770    }
1771
1772    /**
1773     * A title bar which is embedded in this WebView, and scrolls along with it
1774     * vertically, but not horizontally.
1775     */
1776    private View mTitleBar;
1777
1778    /**
1779     * Since we draw the title bar ourselves, we removed the shadow from the
1780     * browser's activity.  We do want a shadow at the bottom of the title bar,
1781     * or at the top of the screen if the title bar is not visible.  This
1782     * drawable serves that purpose.
1783     */
1784    private Drawable mTitleShadow;
1785
1786    /**
1787     * Add or remove a title bar to be embedded into the WebView, and scroll
1788     * along with it vertically, while remaining in view horizontally. Pass
1789     * null to remove the title bar from the WebView, and return to drawing
1790     * the WebView normally without translating to account for the title bar.
1791     * @hide
1792     */
1793    public void setEmbeddedTitleBar(View v) {
1794        if (mTitleBar == v) return;
1795        if (mTitleBar != null) {
1796            removeView(mTitleBar);
1797        }
1798        if (null != v) {
1799            addView(v, new AbsoluteLayout.LayoutParams(
1800                    ViewGroup.LayoutParams.FILL_PARENT,
1801                    ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
1802            if (mTitleShadow == null) {
1803                mTitleShadow = (Drawable) mContext.getResources().getDrawable(
1804                        com.android.internal.R.drawable.title_bar_shadow);
1805            }
1806        }
1807        mTitleBar = v;
1808    }
1809
1810    /**
1811     * Given a distance in view space, convert it to content space. Note: this
1812     * does not reflect translation, just scaling, so this should not be called
1813     * with coordinates, but should be called for dimensions like width or
1814     * height.
1815     */
1816    private int viewToContentDimension(int d) {
1817        return Math.round(d * mInvActualScale);
1818    }
1819
1820    /**
1821     * Given an x coordinate in view space, convert it to content space.  Also
1822     * may be used for absolute heights (such as for the WebTextView's
1823     * textSize, which is unaffected by the height of the title bar).
1824     */
1825    /*package*/ int viewToContentX(int x) {
1826        return viewToContentDimension(x);
1827    }
1828
1829    /**
1830     * Given a y coordinate in view space, convert it to content space.
1831     * Takes into account the height of the title bar if there is one
1832     * embedded into the WebView.
1833     */
1834    /*package*/ int viewToContentY(int y) {
1835        return viewToContentDimension(y - getTitleHeight());
1836    }
1837
1838    /**
1839     * Given a distance in content space, convert it to view space. Note: this
1840     * does not reflect translation, just scaling, so this should not be called
1841     * with coordinates, but should be called for dimensions like width or
1842     * height.
1843     */
1844    /*package*/ int contentToViewDimension(int d) {
1845        return Math.round(d * mActualScale);
1846    }
1847
1848    /**
1849     * Given an x coordinate in content space, convert it to view
1850     * space.
1851     */
1852    /*package*/ int contentToViewX(int x) {
1853        return contentToViewDimension(x);
1854    }
1855
1856    /**
1857     * Given a y coordinate in content space, convert it to view
1858     * space.  Takes into account the height of the title bar.
1859     */
1860    /*package*/ int contentToViewY(int y) {
1861        return contentToViewDimension(y) + getTitleHeight();
1862    }
1863
1864    private Rect contentToViewRect(Rect x) {
1865        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
1866                        contentToViewX(x.right), contentToViewY(x.bottom));
1867    }
1868
1869    /*  To invalidate a rectangle in content coordinates, we need to transform
1870        the rect into view coordinates, so we can then call invalidate(...).
1871
1872        Normally, we would just call contentToView[XY](...), which eventually
1873        calls Math.round(coordinate * mActualScale). However, for invalidates,
1874        we need to account for the slop that occurs with antialiasing. To
1875        address that, we are a little more liberal in the size of the rect that
1876        we invalidate.
1877
1878        This liberal calculation calls floor() for the top/left, and ceil() for
1879        the bottom/right coordinates. This catches the possible extra pixels of
1880        antialiasing that we might have missed with just round().
1881     */
1882
1883    // Called by JNI to invalidate the View, given rectangle coordinates in
1884    // content space
1885    private void viewInvalidate(int l, int t, int r, int b) {
1886        final float scale = mActualScale;
1887        final int dy = getTitleHeight();
1888        invalidate((int)Math.floor(l * scale),
1889                   (int)Math.floor(t * scale) + dy,
1890                   (int)Math.ceil(r * scale),
1891                   (int)Math.ceil(b * scale) + dy);
1892    }
1893
1894    // Called by JNI to invalidate the View after a delay, given rectangle
1895    // coordinates in content space
1896    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
1897        final float scale = mActualScale;
1898        final int dy = getTitleHeight();
1899        postInvalidateDelayed(delay,
1900                              (int)Math.floor(l * scale),
1901                              (int)Math.floor(t * scale) + dy,
1902                              (int)Math.ceil(r * scale),
1903                              (int)Math.ceil(b * scale) + dy);
1904    }
1905
1906    private void invalidateContentRect(Rect r) {
1907        viewInvalidate(r.left, r.top, r.right, r.bottom);
1908    }
1909
1910    // stop the scroll animation, and don't let a subsequent fling add
1911    // to the existing velocity
1912    private void abortAnimation() {
1913        mScroller.abortAnimation();
1914        mLastVelocity = 0;
1915    }
1916
1917    /* call from webcoreview.draw(), so we're still executing in the UI thread
1918    */
1919    private void recordNewContentSize(int w, int h, boolean updateLayout) {
1920
1921        // premature data from webkit, ignore
1922        if ((w | h) == 0) {
1923            return;
1924        }
1925
1926        // don't abort a scroll animation if we didn't change anything
1927        if (mContentWidth != w || mContentHeight != h) {
1928            // record new dimensions
1929            mContentWidth = w;
1930            mContentHeight = h;
1931            // If history Picture is drawn, don't update scroll. They will be
1932            // updated when we get out of that mode.
1933            if (!mDrawHistory) {
1934                // repin our scroll, taking into account the new content size
1935                int oldX = mScrollX;
1936                int oldY = mScrollY;
1937                mScrollX = pinLocX(mScrollX);
1938                mScrollY = pinLocY(mScrollY);
1939                if (oldX != mScrollX || oldY != mScrollY) {
1940                    sendOurVisibleRect();
1941                }
1942                if (!mScroller.isFinished()) {
1943                    // We are in the middle of a scroll.  Repin the final scroll
1944                    // position.
1945                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
1946                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
1947                }
1948            }
1949        }
1950        contentSizeChanged(updateLayout);
1951    }
1952
1953    private void setNewZoomScale(float scale, boolean force) {
1954        if (scale < mMinZoomScale) {
1955            scale = mMinZoomScale;
1956        } else if (scale > mMaxZoomScale) {
1957            scale = mMaxZoomScale;
1958        }
1959        if (scale != mActualScale || force) {
1960            if (mDrawHistory) {
1961                // If history Picture is drawn, don't update scroll. They will
1962                // be updated when we get out of that mode.
1963                if (scale != mActualScale && !mPreviewZoomOnly) {
1964                    mCallbackProxy.onScaleChanged(mActualScale, scale);
1965                }
1966                mActualScale = scale;
1967                mInvActualScale = 1 / scale;
1968                if (!mPreviewZoomOnly) {
1969                    sendViewSizeZoom();
1970                }
1971            } else {
1972                // update our scroll so we don't appear to jump
1973                // i.e. keep the center of the doc in the center of the view
1974
1975                int oldX = mScrollX;
1976                int oldY = mScrollY;
1977                float ratio = scale * mInvActualScale;   // old inverse
1978                float sx = ratio * oldX + (ratio - 1) * mZoomCenterX;
1979                float sy = ratio * oldY + (ratio - 1)
1980                        * (mZoomCenterY - getTitleHeight());
1981
1982                // now update our new scale and inverse
1983                if (scale != mActualScale && !mPreviewZoomOnly) {
1984                    mCallbackProxy.onScaleChanged(mActualScale, scale);
1985                }
1986                mActualScale = scale;
1987                mInvActualScale = 1 / scale;
1988
1989                // Scale all the child views
1990                mViewManager.scaleAll();
1991
1992                // as we don't have animation for scaling, don't do animation
1993                // for scrolling, as it causes weird intermediate state
1994                //        pinScrollTo(Math.round(sx), Math.round(sy));
1995                mScrollX = pinLocX(Math.round(sx));
1996                mScrollY = pinLocY(Math.round(sy));
1997
1998                if (!mPreviewZoomOnly) {
1999                    sendViewSizeZoom();
2000                    sendOurVisibleRect();
2001                }
2002            }
2003        }
2004    }
2005
2006    // Used to avoid sending many visible rect messages.
2007    private Rect mLastVisibleRectSent;
2008    private Rect mLastGlobalRect;
2009
2010    private Rect sendOurVisibleRect() {
2011        Rect rect = new Rect();
2012        calcOurContentVisibleRect(rect);
2013        // Rect.equals() checks for null input.
2014        if (!rect.equals(mLastVisibleRectSent)) {
2015            Point pos = new Point(rect.left, rect.top);
2016            mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
2017                    nativeMoveGeneration(), 0, pos);
2018            mLastVisibleRectSent = rect;
2019        }
2020        Rect globalRect = new Rect();
2021        if (getGlobalVisibleRect(globalRect)
2022                && !globalRect.equals(mLastGlobalRect)) {
2023            if (DebugFlags.WEB_VIEW) {
2024                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2025                        + globalRect.top + ",r=" + globalRect.right + ",b="
2026                        + globalRect.bottom);
2027            }
2028            // TODO: the global offset is only used by windowRect()
2029            // in ChromeClientAndroid ; other clients such as touch
2030            // and mouse events could return view + screen relative points.
2031            mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2032            mLastGlobalRect = globalRect;
2033        }
2034        return rect;
2035    }
2036
2037    // Sets r to be the visible rectangle of our webview in view coordinates
2038    private void calcOurVisibleRect(Rect r) {
2039        Point p = new Point();
2040        getGlobalVisibleRect(r, p);
2041        r.offset(-p.x, -p.y);
2042        if (mFindIsUp) {
2043            r.bottom -= mFindHeight;
2044        }
2045    }
2046
2047    // Sets r to be our visible rectangle in content coordinates
2048    private void calcOurContentVisibleRect(Rect r) {
2049        calcOurVisibleRect(r);
2050        r.left = viewToContentX(r.left);
2051        // viewToContentY will remove the total height of the title bar.  Add
2052        // the visible height back in to account for the fact that if the title
2053        // bar is partially visible, the part of the visible rect which is
2054        // displaying our content is displaced by that amount.
2055        r.top = viewToContentY(r.top + getVisibleTitleHeight());
2056        r.right = viewToContentX(r.right);
2057        r.bottom = viewToContentY(r.bottom);
2058    }
2059
2060    static class ViewSizeData {
2061        int mWidth;
2062        int mHeight;
2063        int mTextWrapWidth;
2064        float mScale;
2065        boolean mIgnoreHeight;
2066    }
2067
2068    /**
2069     * Compute unzoomed width and height, and if they differ from the last
2070     * values we sent, send them to webkit (to be used has new viewport)
2071     *
2072     * @return true if new values were sent
2073     */
2074    private boolean sendViewSizeZoom() {
2075        int viewWidth = getViewWidth();
2076        int newWidth = Math.round(viewWidth * mInvActualScale);
2077        int newHeight = Math.round(getViewHeight() * mInvActualScale);
2078        /*
2079         * Because the native side may have already done a layout before the
2080         * View system was able to measure us, we have to send a height of 0 to
2081         * remove excess whitespace when we grow our width. This will trigger a
2082         * layout and a change in content size. This content size change will
2083         * mean that contentSizeChanged will either call this method directly or
2084         * indirectly from onSizeChanged.
2085         */
2086        if (newWidth > mLastWidthSent && mWrapContent) {
2087            newHeight = 0;
2088        }
2089        // Avoid sending another message if the dimensions have not changed.
2090        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) {
2091            ViewSizeData data = new ViewSizeData();
2092            data.mWidth = newWidth;
2093            data.mHeight = newHeight;
2094            // while in zoom overview mode, the text are wrapped to the screen
2095            // width matching mLastScale. So that we don't trigger re-flow while
2096            // toggling between overview mode and normal mode.
2097            data.mTextWrapWidth = mInZoomOverview ? Math.round(viewWidth
2098                    / mLastScale) : newWidth;
2099            data.mScale = mActualScale;
2100            data.mIgnoreHeight = mZoomScale != 0 && !mHeightCanMeasure;
2101            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
2102            mLastWidthSent = newWidth;
2103            mLastHeightSent = newHeight;
2104            return true;
2105        }
2106        return false;
2107    }
2108
2109    @Override
2110    protected int computeHorizontalScrollRange() {
2111        if (mDrawHistory) {
2112            return mHistoryWidth;
2113        } else {
2114            // to avoid rounding error caused unnecessary scrollbar, use floor
2115            return (int) Math.floor(mContentWidth * mActualScale);
2116        }
2117    }
2118
2119    @Override
2120    protected int computeVerticalScrollRange() {
2121        if (mDrawHistory) {
2122            return mHistoryHeight;
2123        } else {
2124            // to avoid rounding error caused unnecessary scrollbar, use floor
2125            return (int) Math.floor(mContentHeight * mActualScale);
2126        }
2127    }
2128
2129    @Override
2130    protected int computeVerticalScrollOffset() {
2131        return Math.max(mScrollY - getTitleHeight(), 0);
2132    }
2133
2134    @Override
2135    protected int computeVerticalScrollExtent() {
2136        return getViewHeight();
2137    }
2138
2139    /** @hide */
2140    @Override
2141    protected void onDrawVerticalScrollBar(Canvas canvas,
2142                                           Drawable scrollBar,
2143                                           int l, int t, int r, int b) {
2144        scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b);
2145        scrollBar.draw(canvas);
2146    }
2147
2148    /**
2149     * Get the url for the current page. This is not always the same as the url
2150     * passed to WebViewClient.onPageStarted because although the load for
2151     * that url has begun, the current page may not have changed.
2152     * @return The url for the current page.
2153     */
2154    public String getUrl() {
2155        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2156        return h != null ? h.getUrl() : null;
2157    }
2158
2159    /**
2160     * Get the original url for the current page. This is not always the same
2161     * as the url passed to WebViewClient.onPageStarted because although the
2162     * load for that url has begun, the current page may not have changed.
2163     * Also, there may have been redirects resulting in a different url to that
2164     * originally requested.
2165     * @return The url that was originally requested for the current page.
2166     */
2167    public String getOriginalUrl() {
2168        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2169        return h != null ? h.getOriginalUrl() : null;
2170    }
2171
2172    /**
2173     * Get the title for the current page. This is the title of the current page
2174     * until WebViewClient.onReceivedTitle is called.
2175     * @return The title for the current page.
2176     */
2177    public String getTitle() {
2178        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2179        return h != null ? h.getTitle() : null;
2180    }
2181
2182    /**
2183     * Get the favicon for the current page. This is the favicon of the current
2184     * page until WebViewClient.onReceivedIcon is called.
2185     * @return The favicon for the current page.
2186     */
2187    public Bitmap getFavicon() {
2188        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2189        return h != null ? h.getFavicon() : null;
2190    }
2191
2192    /**
2193     * Get the touch icon url for the apple-touch-icon <link> element.
2194     * @hide
2195     */
2196    public String getTouchIconUrl() {
2197        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2198        return h != null ? h.getTouchIconUrl() : null;
2199    }
2200
2201    /**
2202     * Get the progress for the current page.
2203     * @return The progress for the current page between 0 and 100.
2204     */
2205    public int getProgress() {
2206        return mCallbackProxy.getProgress();
2207    }
2208
2209    /**
2210     * @return the height of the HTML content.
2211     */
2212    public int getContentHeight() {
2213        return mContentHeight;
2214    }
2215
2216    /**
2217     * @return the width of the HTML content.
2218     * @hide
2219     */
2220    public int getContentWidth() {
2221        return mContentWidth;
2222    }
2223
2224    /**
2225     * Pause all layout, parsing, and javascript timers for all webviews. This
2226     * is a global requests, not restricted to just this webview. This can be
2227     * useful if the application has been paused.
2228     */
2229    public void pauseTimers() {
2230        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
2231    }
2232
2233    /**
2234     * Resume all layout, parsing, and javascript timers for all webviews.
2235     * This will resume dispatching all timers.
2236     */
2237    public void resumeTimers() {
2238        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
2239    }
2240
2241    /**
2242     * Call this to pause any extra processing associated with this view and
2243     * its associated DOM/plugins/javascript/etc. For example, if the view is
2244     * taken offscreen, this could be called to reduce unnecessary CPU and/or
2245     * network traffic. When the view is again "active", call onResume().
2246     *
2247     * Note that this differs from pauseTimers(), which affects all views/DOMs
2248     * @hide
2249     */
2250    public void onPause() {
2251        if (!mIsPaused) {
2252            mIsPaused = true;
2253            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
2254        }
2255    }
2256
2257    /**
2258     * Call this to balanace a previous call to onPause()
2259     * @hide
2260     */
2261    public void onResume() {
2262        if (mIsPaused) {
2263            mIsPaused = false;
2264            mWebViewCore.sendMessage(EventHub.ON_RESUME);
2265        }
2266    }
2267
2268    /**
2269     * Returns true if the view is paused, meaning onPause() was called. Calling
2270     * onResume() sets the paused state back to false.
2271     * @hide
2272     */
2273    public boolean isPaused() {
2274        return mIsPaused;
2275    }
2276
2277    /**
2278     * Call this to inform the view that memory is low so that it can
2279     * free any available memory.
2280     * @hide
2281     */
2282    public void freeMemory() {
2283        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
2284    }
2285
2286    /**
2287     * Clear the resource cache. Note that the cache is per-application, so
2288     * this will clear the cache for all WebViews used.
2289     *
2290     * @param includeDiskFiles If false, only the RAM cache is cleared.
2291     */
2292    public void clearCache(boolean includeDiskFiles) {
2293        // Note: this really needs to be a static method as it clears cache for all
2294        // WebView. But we need mWebViewCore to send message to WebCore thread, so
2295        // we can't make this static.
2296        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
2297                includeDiskFiles ? 1 : 0, 0);
2298    }
2299
2300    /**
2301     * Make sure that clearing the form data removes the adapter from the
2302     * currently focused textfield if there is one.
2303     */
2304    public void clearFormData() {
2305        if (inEditingMode()) {
2306            AutoCompleteAdapter adapter = null;
2307            mWebTextView.setAdapterCustom(adapter);
2308        }
2309    }
2310
2311    /**
2312     * Tell the WebView to clear its internal back/forward list.
2313     */
2314    public void clearHistory() {
2315        mCallbackProxy.getBackForwardList().setClearPending();
2316        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
2317    }
2318
2319    /**
2320     * Clear the SSL preferences table stored in response to proceeding with SSL
2321     * certificate errors.
2322     */
2323    public void clearSslPreferences() {
2324        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
2325    }
2326
2327    /**
2328     * Return the WebBackForwardList for this WebView. This contains the
2329     * back/forward list for use in querying each item in the history stack.
2330     * This is a copy of the private WebBackForwardList so it contains only a
2331     * snapshot of the current state. Multiple calls to this method may return
2332     * different objects. The object returned from this method will not be
2333     * updated to reflect any new state.
2334     */
2335    public WebBackForwardList copyBackForwardList() {
2336        return mCallbackProxy.getBackForwardList().clone();
2337    }
2338
2339    /*
2340     * Highlight and scroll to the next occurance of String in findAll.
2341     * Wraps the page infinitely, and scrolls.  Must be called after
2342     * calling findAll.
2343     *
2344     * @param forward Direction to search.
2345     */
2346    public void findNext(boolean forward) {
2347        if (0 == mNativeClass) return; // client isn't initialized
2348        nativeFindNext(forward);
2349    }
2350
2351    /*
2352     * Find all instances of find on the page and highlight them.
2353     * @param find  String to find.
2354     * @return int  The number of occurances of the String "find"
2355     *              that were found.
2356     */
2357    public int findAll(String find) {
2358        if (0 == mNativeClass) return 0; // client isn't initialized
2359        if (mFindIsUp == false) {
2360            recordNewContentSize(mContentWidth, mContentHeight + mFindHeight,
2361                    false);
2362            mFindIsUp = true;
2363        }
2364        int result = nativeFindAll(find.toLowerCase(), find.toUpperCase());
2365        invalidate();
2366        mLastFind = find;
2367        return result;
2368    }
2369
2370    // Used to know whether the find dialog is open.  Affects whether
2371    // or not we draw the highlights for matches.
2372    private boolean mFindIsUp;
2373    private int mFindHeight;
2374    // Keep track of the last string sent, so we can search again after an
2375    // orientation change or the dismissal of the soft keyboard.
2376    private String mLastFind;
2377
2378    /**
2379     * Return the first substring consisting of the address of a physical
2380     * location. Currently, only addresses in the United States are detected,
2381     * and consist of:
2382     * - a house number
2383     * - a street name
2384     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2385     * - a city name
2386     * - a state or territory, either spelled out or two-letter abbr.
2387     * - an optional 5 digit or 9 digit zip code.
2388     *
2389     * All names must be correctly capitalized, and the zip code, if present,
2390     * must be valid for the state. The street type must be a standard USPS
2391     * spelling or abbreviation. The state or territory must also be spelled
2392     * or abbreviated using USPS standards. The house number may not exceed
2393     * five digits.
2394     * @param addr The string to search for addresses.
2395     *
2396     * @return the address, or if no address is found, return null.
2397     */
2398    public static String findAddress(String addr) {
2399        return findAddress(addr, false);
2400    }
2401
2402    /**
2403     * @hide
2404     * Return the first substring consisting of the address of a physical
2405     * location. Currently, only addresses in the United States are detected,
2406     * and consist of:
2407     * - a house number
2408     * - a street name
2409     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2410     * - a city name
2411     * - a state or territory, either spelled out or two-letter abbr.
2412     * - an optional 5 digit or 9 digit zip code.
2413     *
2414     * Names are optionally capitalized, and the zip code, if present,
2415     * must be valid for the state. The street type must be a standard USPS
2416     * spelling or abbreviation. The state or territory must also be spelled
2417     * or abbreviated using USPS standards. The house number may not exceed
2418     * five digits.
2419     * @param addr The string to search for addresses.
2420     * @param caseInsensitive addr Set to true to make search ignore case.
2421     *
2422     * @return the address, or if no address is found, return null.
2423     */
2424    public static String findAddress(String addr, boolean caseInsensitive) {
2425        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
2426    }
2427
2428    /*
2429     * Clear the highlighting surrounding text matches created by findAll.
2430     */
2431    public void clearMatches() {
2432        if (mFindIsUp) {
2433            recordNewContentSize(mContentWidth, mContentHeight - mFindHeight,
2434                    false);
2435            mFindIsUp = false;
2436        }
2437        nativeSetFindIsDown();
2438        // Now that the dialog has been removed, ensure that we scroll to a
2439        // location that is not beyond the end of the page.
2440        pinScrollTo(mScrollX, mScrollY, false, 0);
2441        invalidate();
2442    }
2443
2444    /**
2445     * @hide
2446     */
2447    public void setFindDialogHeight(int height) {
2448        if (DebugFlags.WEB_VIEW) {
2449            Log.v(LOGTAG, "setFindDialogHeight height=" + height);
2450        }
2451        mFindHeight = height;
2452    }
2453
2454    /**
2455     * Query the document to see if it contains any image references. The
2456     * message object will be dispatched with arg1 being set to 1 if images
2457     * were found and 0 if the document does not reference any images.
2458     * @param response The message that will be dispatched with the result.
2459     */
2460    public void documentHasImages(Message response) {
2461        if (response == null) {
2462            return;
2463        }
2464        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
2465    }
2466
2467    @Override
2468    public void computeScroll() {
2469        if (mScroller.computeScrollOffset()) {
2470            int oldX = mScrollX;
2471            int oldY = mScrollY;
2472            mScrollX = mScroller.getCurrX();
2473            mScrollY = mScroller.getCurrY();
2474            postInvalidate();  // So we draw again
2475            if (oldX != mScrollX || oldY != mScrollY) {
2476                // as onScrollChanged() is not called, sendOurVisibleRect()
2477                // needs to be call explicitly
2478                sendOurVisibleRect();
2479            }
2480        } else {
2481            super.computeScroll();
2482        }
2483    }
2484
2485    private static int computeDuration(int dx, int dy) {
2486        int distance = Math.max(Math.abs(dx), Math.abs(dy));
2487        int duration = distance * 1000 / STD_SPEED;
2488        return Math.min(duration, MAX_DURATION);
2489    }
2490
2491    // helper to pin the scrollBy parameters (already in view coordinates)
2492    // returns true if the scroll was changed
2493    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
2494        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
2495    }
2496    // helper to pin the scrollTo parameters (already in view coordinates)
2497    // returns true if the scroll was changed
2498    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
2499        x = pinLocX(x);
2500        y = pinLocY(y);
2501        int dx = x - mScrollX;
2502        int dy = y - mScrollY;
2503
2504        if ((dx | dy) == 0) {
2505            return false;
2506        }
2507        if (animate) {
2508            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
2509            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
2510                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
2511            awakenScrollBars(mScroller.getDuration());
2512            invalidate();
2513        } else {
2514            abortAnimation(); // just in case
2515            scrollTo(x, y);
2516        }
2517        return true;
2518    }
2519
2520    // Scale from content to view coordinates, and pin.
2521    // Also called by jni webview.cpp
2522    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
2523        if (mDrawHistory) {
2524            // disallow WebView to change the scroll position as History Picture
2525            // is used in the view system.
2526            // TODO: as we switchOutDrawHistory when trackball or navigation
2527            // keys are hit, this should be safe. Right?
2528            return false;
2529        }
2530        cx = contentToViewDimension(cx);
2531        cy = contentToViewDimension(cy);
2532        if (mHeightCanMeasure) {
2533            // move our visible rect according to scroll request
2534            if (cy != 0) {
2535                Rect tempRect = new Rect();
2536                calcOurVisibleRect(tempRect);
2537                tempRect.offset(cx, cy);
2538                requestRectangleOnScreen(tempRect);
2539            }
2540            // FIXME: We scroll horizontally no matter what because currently
2541            // ScrollView and ListView will not scroll horizontally.
2542            // FIXME: Why do we only scroll horizontally if there is no
2543            // vertical scroll?
2544//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
2545            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
2546        } else {
2547            return pinScrollBy(cx, cy, animate, 0);
2548        }
2549    }
2550
2551    // scale from content to view coordinates, and pin
2552    // return true if pin caused the final x/y different than the request cx/cy,
2553    // and a future scroll may reach the request cx/cy after our size has
2554    // changed
2555    // return false if the view scroll to the exact position as it is requested,
2556    // where negative numbers are taken to mean 0
2557    private boolean setContentScrollTo(int cx, int cy) {
2558        if (mDrawHistory) {
2559            // disallow WebView to change the scroll position as History Picture
2560            // is used in the view system.
2561            // One known case where this is called is that WebCore tries to
2562            // restore the scroll position. As history Picture already uses the
2563            // saved scroll position, it is ok to skip this.
2564            return false;
2565        }
2566        int vx;
2567        int vy;
2568        if ((cx | cy) == 0) {
2569            // If the page is being scrolled to (0,0), do not add in the title
2570            // bar's height, and simply scroll to (0,0). (The only other work
2571            // in contentToView_ is to multiply, so this would not change 0.)
2572            vx = 0;
2573            vy = 0;
2574        } else {
2575            vx = contentToViewX(cx);
2576            vy = contentToViewY(cy);
2577        }
2578//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
2579//                      vx + " " + vy + "]");
2580        // Some mobile sites attempt to scroll the title bar off the page by
2581        // scrolling to (0,1).  If we are at the top left corner of the
2582        // page, assume this is an attempt to scroll off the title bar, and
2583        // animate the title bar off screen slowly enough that the user can see
2584        // it.
2585        if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0) {
2586            pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
2587            // Since we are animating, we have not yet reached the desired
2588            // scroll position.  Do not return true to request another attempt
2589            return false;
2590        }
2591        pinScrollTo(vx, vy, false, 0);
2592        // If the request was to scroll to a negative coordinate, treat it as if
2593        // it was a request to scroll to 0
2594        if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
2595            return true;
2596        } else {
2597            return false;
2598        }
2599    }
2600
2601    // scale from content to view coordinates, and pin
2602    private void spawnContentScrollTo(int cx, int cy) {
2603        if (mDrawHistory) {
2604            // disallow WebView to change the scroll position as History Picture
2605            // is used in the view system.
2606            return;
2607        }
2608        int vx = contentToViewX(cx);
2609        int vy = contentToViewY(cy);
2610        pinScrollTo(vx, vy, true, 0);
2611    }
2612
2613    /**
2614     * These are from webkit, and are in content coordinate system (unzoomed)
2615     */
2616    private void contentSizeChanged(boolean updateLayout) {
2617        // suppress 0,0 since we usually see real dimensions soon after
2618        // this avoids drawing the prev content in a funny place. If we find a
2619        // way to consolidate these notifications, this check may become
2620        // obsolete
2621        if ((mContentWidth | mContentHeight) == 0) {
2622            return;
2623        }
2624
2625        if (mHeightCanMeasure) {
2626            if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
2627                    || updateLayout) {
2628                requestLayout();
2629            }
2630        } else if (mWidthCanMeasure) {
2631            if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
2632                    || updateLayout) {
2633                requestLayout();
2634            }
2635        } else {
2636            // If we don't request a layout, try to send our view size to the
2637            // native side to ensure that WebCore has the correct dimensions.
2638            sendViewSizeZoom();
2639        }
2640    }
2641
2642    /**
2643     * Set the WebViewClient that will receive various notifications and
2644     * requests. This will replace the current handler.
2645     * @param client An implementation of WebViewClient.
2646     */
2647    public void setWebViewClient(WebViewClient client) {
2648        mCallbackProxy.setWebViewClient(client);
2649    }
2650
2651    /**
2652     * Gets the WebViewClient
2653     * @return the current WebViewClient instance.
2654     *
2655     *@hide pending API council approval.
2656     */
2657    public WebViewClient getWebViewClient() {
2658        return mCallbackProxy.getWebViewClient();
2659    }
2660
2661    /**
2662     * Register the interface to be used when content can not be handled by
2663     * the rendering engine, and should be downloaded instead. This will replace
2664     * the current handler.
2665     * @param listener An implementation of DownloadListener.
2666     */
2667    public void setDownloadListener(DownloadListener listener) {
2668        mCallbackProxy.setDownloadListener(listener);
2669    }
2670
2671    /**
2672     * Set the chrome handler. This is an implementation of WebChromeClient for
2673     * use in handling Javascript dialogs, favicons, titles, and the progress.
2674     * This will replace the current handler.
2675     * @param client An implementation of WebChromeClient.
2676     */
2677    public void setWebChromeClient(WebChromeClient client) {
2678        mCallbackProxy.setWebChromeClient(client);
2679    }
2680
2681    /**
2682     * Gets the chrome handler.
2683     * @return the current WebChromeClient instance.
2684     *
2685     * @hide API council approval.
2686     */
2687    public WebChromeClient getWebChromeClient() {
2688        return mCallbackProxy.getWebChromeClient();
2689    }
2690
2691    /**
2692     * Set the Picture listener. This is an interface used to receive
2693     * notifications of a new Picture.
2694     * @param listener An implementation of WebView.PictureListener.
2695     */
2696    public void setPictureListener(PictureListener listener) {
2697        mPictureListener = listener;
2698    }
2699
2700    /**
2701     * {@hide}
2702     */
2703    /* FIXME: Debug only! Remove for SDK! */
2704    public void externalRepresentation(Message callback) {
2705        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
2706    }
2707
2708    /**
2709     * {@hide}
2710     */
2711    /* FIXME: Debug only! Remove for SDK! */
2712    public void documentAsText(Message callback) {
2713        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
2714    }
2715
2716    /**
2717     * Use this function to bind an object to Javascript so that the
2718     * methods can be accessed from Javascript.
2719     * <p><strong>IMPORTANT:</strong>
2720     * <ul>
2721     * <li> Using addJavascriptInterface() allows JavaScript to control your
2722     * application. This can be a very useful feature or a dangerous security
2723     * issue. When the HTML in the WebView is untrustworthy (for example, part
2724     * or all of the HTML is provided by some person or process), then an
2725     * attacker could inject HTML that will execute your code and possibly any
2726     * code of the attacker's choosing.<br>
2727     * Do not use addJavascriptInterface() unless all of the HTML in this
2728     * WebView was written by you.</li>
2729     * <li> The Java object that is bound runs in another thread and not in
2730     * the thread that it was constructed in.</li>
2731     * </ul></p>
2732     * @param obj The class instance to bind to Javascript
2733     * @param interfaceName The name to used to expose the class in Javascript
2734     */
2735    public void addJavascriptInterface(Object obj, String interfaceName) {
2736        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
2737        arg.mObject = obj;
2738        arg.mInterfaceName = interfaceName;
2739        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
2740    }
2741
2742    /**
2743     * Return the WebSettings object used to control the settings for this
2744     * WebView.
2745     * @return A WebSettings object that can be used to control this WebView's
2746     *         settings.
2747     */
2748    public WebSettings getSettings() {
2749        return mWebViewCore.getSettings();
2750    }
2751
2752   /**
2753    * Return the list of currently loaded plugins.
2754    * @return The list of currently loaded plugins.
2755    *
2756    * @deprecated This was used for Gears, which has been deprecated.
2757    */
2758    @Deprecated
2759    public static synchronized PluginList getPluginList() {
2760        return null;
2761    }
2762
2763   /**
2764    * @deprecated This was used for Gears, which has been deprecated.
2765    */
2766    @Deprecated
2767    public void refreshPlugins(boolean reloadOpenPages) { }
2768
2769    //-------------------------------------------------------------------------
2770    // Override View methods
2771    //-------------------------------------------------------------------------
2772
2773    @Override
2774    protected void finalize() throws Throwable {
2775        try {
2776            destroy();
2777        } finally {
2778            super.finalize();
2779        }
2780    }
2781
2782    @Override
2783    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
2784        if (child == mTitleBar) {
2785            // When drawing the title bar, move it horizontally to always show
2786            // at the top of the WebView.
2787            mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
2788        }
2789        return super.drawChild(canvas, child, drawingTime);
2790    }
2791
2792    @Override
2793    protected void onDraw(Canvas canvas) {
2794        // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
2795        if (mNativeClass == 0) {
2796            return;
2797        }
2798        int saveCount = canvas.save();
2799        if (mTitleBar != null) {
2800            canvas.translate(0, (int) mTitleBar.getHeight());
2801        }
2802        // Update the buttons in the picture, so when we draw the picture
2803        // to the screen, they are in the correct state.
2804        // Tell the native side if user is a) touching the screen,
2805        // b) pressing the trackball down, or c) pressing the enter key
2806        // If the cursor is on a button, we need to draw it in the pressed
2807        // state.
2808        // If mNativeClass is 0, we should not reach here, so we do not
2809        // need to check it again.
2810        nativeRecordButtons(hasFocus() && hasWindowFocus(),
2811                mTouchMode == TOUCH_SHORTPRESS_START_MODE
2812                || mTrackballDown || mGotCenterDown, false);
2813        drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
2814        canvas.restoreToCount(saveCount);
2815
2816        // Now draw the shadow.
2817        if (mTitleBar != null) {
2818            int y = mScrollY + getVisibleTitleHeight();
2819            int height = (int) (5f * getContext().getResources()
2820                    .getDisplayMetrics().density);
2821            mTitleShadow.setBounds(mScrollX, y, mScrollX + getWidth(),
2822                    y + height);
2823            mTitleShadow.draw(canvas);
2824        }
2825        if (AUTO_REDRAW_HACK && mAutoRedraw) {
2826            invalidate();
2827        }
2828    }
2829
2830    @Override
2831    public void setLayoutParams(ViewGroup.LayoutParams params) {
2832        if (params.height == LayoutParams.WRAP_CONTENT) {
2833            mWrapContent = true;
2834        }
2835        super.setLayoutParams(params);
2836    }
2837
2838    @Override
2839    public boolean performLongClick() {
2840        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
2841            // Send the click so that the textfield is in focus
2842            centerKeyPressOnTextField();
2843            rebuildWebTextView();
2844        }
2845        if (inEditingMode()) {
2846            return mWebTextView.performLongClick();
2847        } else {
2848            return super.performLongClick();
2849        }
2850    }
2851
2852    boolean inAnimateZoom() {
2853        return mZoomScale != 0;
2854    }
2855
2856    /**
2857     * Need to adjust the WebTextView after a change in zoom, since mActualScale
2858     * has changed.  This is especially important for password fields, which are
2859     * drawn by the WebTextView, since it conveys more information than what
2860     * webkit draws.  Thus we need to reposition it to show in the correct
2861     * place.
2862     */
2863    private boolean mNeedToAdjustWebTextView;
2864
2865    private boolean didUpdateTextViewBounds(boolean allowIntersect) {
2866        Rect contentBounds = nativeFocusCandidateNodeBounds();
2867        Rect vBox = contentToViewRect(contentBounds);
2868        Rect visibleRect = new Rect();
2869        calcOurVisibleRect(visibleRect);
2870        if (allowIntersect ? Rect.intersects(visibleRect, vBox) :
2871                visibleRect.contains(vBox)) {
2872            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
2873                    vBox.height());
2874            return true;
2875        } else {
2876            return false;
2877        }
2878    }
2879
2880    private void drawCoreAndCursorRing(Canvas canvas, int color,
2881        boolean drawCursorRing) {
2882        if (mDrawHistory) {
2883            canvas.scale(mActualScale, mActualScale);
2884            canvas.drawPicture(mHistoryPicture);
2885            return;
2886        }
2887
2888        boolean animateZoom = mZoomScale != 0;
2889        boolean animateScroll = (!mScroller.isFinished()
2890                || mVelocityTracker != null)
2891                && (mTouchMode != TOUCH_DRAG_MODE ||
2892                mHeldMotionless != MOTIONLESS_TRUE);
2893        if (mTouchMode == TOUCH_DRAG_MODE) {
2894            if (mHeldMotionless == MOTIONLESS_PENDING) {
2895                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
2896                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
2897                mHeldMotionless = MOTIONLESS_FALSE;
2898            }
2899            if (mHeldMotionless == MOTIONLESS_FALSE) {
2900                mPrivateHandler.sendMessageDelayed(mPrivateHandler
2901                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
2902                mHeldMotionless = MOTIONLESS_PENDING;
2903            }
2904        }
2905        if (animateZoom) {
2906            float zoomScale;
2907            int interval = (int) (SystemClock.uptimeMillis() - mZoomStart);
2908            if (interval < ZOOM_ANIMATION_LENGTH) {
2909                float ratio = (float) interval / ZOOM_ANIMATION_LENGTH;
2910                zoomScale = 1.0f / (mInvInitialZoomScale
2911                        + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio);
2912                invalidate();
2913            } else {
2914                zoomScale = mZoomScale;
2915                // set mZoomScale to be 0 as we have done animation
2916                mZoomScale = 0;
2917                // call invalidate() again to draw with the final filters
2918                invalidate();
2919                if (mNeedToAdjustWebTextView) {
2920                    mNeedToAdjustWebTextView = false;
2921                    // As a result of the zoom, the textfield is now on
2922                    // screen.  Place the WebTextView in its new place,
2923                    // accounting for our new scroll/zoom values.
2924                    if (didUpdateTextViewBounds(false)) {
2925                        mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
2926                                contentToViewDimension(
2927                                nativeFocusCandidateTextSize()));
2928                        // If it is a password field, start drawing the
2929                        // WebTextView once again.
2930                        if (nativeFocusCandidateIsPassword()) {
2931                            mWebTextView.setInPassword(true);
2932                        }
2933                    } else {
2934                        // The textfield is now off screen.  The user probably
2935                        // was not zooming to see the textfield better.  Remove
2936                        // the WebTextView.  If the user types a key, and the
2937                        // textfield is still in focus, we will reconstruct
2938                        // the WebTextView and scroll it back on screen.
2939                        mWebTextView.remove();
2940                    }
2941                }
2942            }
2943            // calculate the intermediate scroll position. As we need to use
2944            // zoomScale, we can't use pinLocX/Y directly. Copy the logic here.
2945            float scale = zoomScale * mInvInitialZoomScale;
2946            int tx = Math.round(scale * (mInitialScrollX + mZoomCenterX)
2947                    - mZoomCenterX);
2948            tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth
2949                    * zoomScale)) + mScrollX;
2950            int titleHeight = getTitleHeight();
2951            int ty = Math.round(scale
2952                    * (mInitialScrollY + mZoomCenterY - titleHeight)
2953                    - (mZoomCenterY - titleHeight));
2954            ty = -(ty <= titleHeight ? Math.max(ty, 0) : pinLoc(ty
2955                    - titleHeight, getViewHeight(), Math.round(mContentHeight
2956                    * zoomScale)) + titleHeight) + mScrollY;
2957            canvas.translate(tx, ty);
2958            canvas.scale(zoomScale, zoomScale);
2959            if (inEditingMode() && !mNeedToAdjustWebTextView
2960                    && mZoomScale != 0) {
2961                // The WebTextView is up.  Keep track of this so we can adjust
2962                // its size and placement when we finish zooming
2963                mNeedToAdjustWebTextView = true;
2964                // If it is in password mode, turn it off so it does not draw
2965                // misplaced.
2966                if (nativeFocusCandidateIsPassword()) {
2967                    mWebTextView.setInPassword(false);
2968                }
2969            }
2970        } else {
2971            canvas.scale(mActualScale, mActualScale);
2972        }
2973
2974        mWebViewCore.drawContentPicture(canvas, color, animateZoom,
2975                animateScroll);
2976
2977        if (mNativeClass == 0) return;
2978        if (mShiftIsPressed && !animateZoom) {
2979            if (mTouchSelection || mExtendSelection) {
2980                nativeDrawSelectionRegion(canvas);
2981            }
2982            if (!mTouchSelection) {
2983                nativeDrawSelectionPointer(canvas, mInvActualScale, mSelectX,
2984                        mSelectY - getTitleHeight(), mExtendSelection);
2985            }
2986        } else if (drawCursorRing) {
2987            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
2988                mTouchMode = TOUCH_SHORTPRESS_MODE;
2989                HitTestResult hitTest = getHitTestResult();
2990                if (hitTest != null &&
2991                        hitTest.mType != HitTestResult.UNKNOWN_TYPE) {
2992                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
2993                            .obtainMessage(SWITCH_TO_LONGPRESS),
2994                            LONG_PRESS_TIMEOUT);
2995                }
2996            }
2997            nativeDrawCursorRing(canvas);
2998        }
2999        // When the FindDialog is up, only draw the matches if we are not in
3000        // the process of scrolling them into view.
3001        if (mFindIsUp && !animateScroll) {
3002            nativeDrawMatches(canvas);
3003        }
3004        if (mFocusSizeChanged) {
3005            mFocusSizeChanged = false;
3006            didUpdateTextViewBounds(true);
3007        }
3008    }
3009
3010    // draw history
3011    private boolean mDrawHistory = false;
3012    private Picture mHistoryPicture = null;
3013    private int mHistoryWidth = 0;
3014    private int mHistoryHeight = 0;
3015
3016    // Only check the flag, can be called from WebCore thread
3017    boolean drawHistory() {
3018        return mDrawHistory;
3019    }
3020
3021    // Should only be called in UI thread
3022    void switchOutDrawHistory() {
3023        if (null == mWebViewCore) return; // CallbackProxy may trigger this
3024        if (mDrawHistory && mWebViewCore.pictureReady()) {
3025            mDrawHistory = false;
3026            invalidate();
3027            int oldScrollX = mScrollX;
3028            int oldScrollY = mScrollY;
3029            mScrollX = pinLocX(mScrollX);
3030            mScrollY = pinLocY(mScrollY);
3031            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
3032                mUserScroll = false;
3033                mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
3034                        oldScrollY);
3035            }
3036            sendOurVisibleRect();
3037        }
3038    }
3039
3040    WebViewCore.CursorData cursorData() {
3041        WebViewCore.CursorData result = new WebViewCore.CursorData();
3042        result.mMoveGeneration = nativeMoveGeneration();
3043        result.mFrame = nativeCursorFramePointer();
3044        Point position = nativeCursorPosition();
3045        result.mX = position.x;
3046        result.mY = position.y;
3047        return result;
3048    }
3049
3050    /**
3051     *  Delete text from start to end in the focused textfield. If there is no
3052     *  focus, or if start == end, silently fail.  If start and end are out of
3053     *  order, swap them.
3054     *  @param  start   Beginning of selection to delete.
3055     *  @param  end     End of selection to delete.
3056     */
3057    /* package */ void deleteSelection(int start, int end) {
3058        mTextGeneration++;
3059        WebViewCore.TextSelectionData data
3060                = new WebViewCore.TextSelectionData(start, end);
3061        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
3062                data);
3063    }
3064
3065    /**
3066     *  Set the selection to (start, end) in the focused textfield. If start and
3067     *  end are out of order, swap them.
3068     *  @param  start   Beginning of selection.
3069     *  @param  end     End of selection.
3070     */
3071    /* package */ void setSelection(int start, int end) {
3072        mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
3073    }
3074
3075    // Called by JNI when a touch event puts a textfield into focus.
3076    private void displaySoftKeyboard(boolean isTextView) {
3077        InputMethodManager imm = (InputMethodManager)
3078                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3079
3080        if (isTextView) {
3081            if (mWebTextView == null) return;
3082
3083            imm.showSoftInput(mWebTextView, 0);
3084            if (mInZoomOverview) {
3085                // if in zoom overview mode, call doDoubleTap() to bring it back
3086                // to normal mode so that user can enter text.
3087                doDoubleTap();
3088            }
3089        }
3090        else { // used by plugins
3091            imm.showSoftInput(this, 0);
3092        }
3093    }
3094
3095    // Called by WebKit to instruct the UI to hide the keyboard
3096    private void hideSoftKeyboard() {
3097        InputMethodManager imm = (InputMethodManager)
3098                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3099
3100        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
3101    }
3102
3103    /**
3104     * Only for calling from JNI.  Allows a click on an unfocused textfield to
3105     * put the textfield in focus.
3106     */
3107    private void setOkayNotToMatch() {
3108        if (inEditingMode()) {
3109            mWebTextView.mOkayForFocusNotToMatch = true;
3110        }
3111    }
3112
3113    /*
3114     * This method checks the current focus and cursor and potentially rebuilds
3115     * mWebTextView to have the appropriate properties, such as password,
3116     * multiline, and what text it contains.  It also removes it if necessary.
3117     */
3118    /* package */ void rebuildWebTextView() {
3119        // If the WebView does not have focus, do nothing until it gains focus.
3120        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
3121            return;
3122        }
3123        boolean alreadyThere = inEditingMode();
3124        // inEditingMode can only return true if mWebTextView is non-null,
3125        // so we can safely call remove() if (alreadyThere)
3126        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
3127            if (alreadyThere) {
3128                mWebTextView.remove();
3129            }
3130            return;
3131        }
3132        // At this point, we know we have found an input field, so go ahead
3133        // and create the WebTextView if necessary.
3134        if (mWebTextView == null) {
3135            mWebTextView = new WebTextView(mContext, WebView.this);
3136            // Initialize our generation number.
3137            mTextGeneration = 0;
3138        }
3139        mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
3140                contentToViewDimension(nativeFocusCandidateTextSize()));
3141        Rect visibleRect = new Rect();
3142        calcOurContentVisibleRect(visibleRect);
3143        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
3144        // should be in content coordinates.
3145        Rect bounds = nativeFocusCandidateNodeBounds();
3146        if (!Rect.intersects(bounds, visibleRect)) {
3147            mWebTextView.bringIntoView();
3148        }
3149        String text = nativeFocusCandidateText();
3150        int nodePointer = nativeFocusCandidatePointer();
3151        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
3152            // It is possible that we have the same textfield, but it has moved,
3153            // i.e. In the case of opening/closing the screen.
3154            // In that case, we need to set the dimensions, but not the other
3155            // aspects.
3156            // We also need to restore the selection, which gets wrecked by
3157            // calling setTextEntryRect.
3158            Spannable spannable = (Spannable) mWebTextView.getText();
3159            int start = Selection.getSelectionStart(spannable);
3160            int end = Selection.getSelectionEnd(spannable);
3161            // If the text has been changed by webkit, update it.  However, if
3162            // there has been more UI text input, ignore it.  We will receive
3163            // another update when that text is recognized.
3164            if (text != null && !text.equals(spannable.toString())
3165                    && nativeTextGeneration() == mTextGeneration) {
3166                mWebTextView.setTextAndKeepSelection(text);
3167            } else {
3168                // FIXME: Determine whether this is necessary.
3169                Selection.setSelection(spannable, start, end);
3170            }
3171        } else {
3172            Rect vBox = contentToViewRect(bounds);
3173            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3174                    vBox.height());
3175            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
3176                    Gravity.RIGHT : Gravity.NO_GRAVITY);
3177            // this needs to be called before update adapter thread starts to
3178            // ensure the mWebTextView has the same node pointer
3179            mWebTextView.setNodePointer(nodePointer);
3180            int maxLength = -1;
3181            boolean isTextField = nativeFocusCandidateIsTextField();
3182            if (isTextField) {
3183                maxLength = nativeFocusCandidateMaxLength();
3184                String name = nativeFocusCandidateName();
3185                if (mWebViewCore.getSettings().getSaveFormData()
3186                        && name != null) {
3187                    Message update = mPrivateHandler.obtainMessage(
3188                            REQUEST_FORM_DATA, nodePointer);
3189                    RequestFormData updater = new RequestFormData(name,
3190                            getUrl(), update);
3191                    Thread t = new Thread(updater);
3192                    t.start();
3193                }
3194            }
3195            mWebTextView.setMaxLength(maxLength);
3196            AutoCompleteAdapter adapter = null;
3197            mWebTextView.setAdapterCustom(adapter);
3198            mWebTextView.setSingleLine(isTextField);
3199            mWebTextView.setInPassword(nativeFocusCandidateIsPassword());
3200            if (null == text) {
3201                if (DebugFlags.WEB_VIEW) {
3202                    Log.v(LOGTAG, "rebuildWebTextView null == text");
3203                }
3204                text = "";
3205            }
3206            mWebTextView.setTextAndKeepSelection(text);
3207            mWebTextView.requestFocus();
3208        }
3209    }
3210
3211    /*
3212     * This class requests an Adapter for the WebTextView which shows past
3213     * entries stored in the database.  It is a Runnable so that it can be done
3214     * in its own thread, without slowing down the UI.
3215     */
3216    private class RequestFormData implements Runnable {
3217        private String mName;
3218        private String mUrl;
3219        private Message mUpdateMessage;
3220
3221        public RequestFormData(String name, String url, Message msg) {
3222            mName = name;
3223            mUrl = url;
3224            mUpdateMessage = msg;
3225        }
3226
3227        public void run() {
3228            ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName);
3229            if (pastEntries.size() > 0) {
3230                AutoCompleteAdapter adapter = new
3231                        AutoCompleteAdapter(mContext, pastEntries);
3232                mUpdateMessage.obj = adapter;
3233                mUpdateMessage.sendToTarget();
3234            }
3235        }
3236    }
3237
3238    // This is used to determine long press with the center key.  Does not
3239    // affect long press with the trackball/touch.
3240    private boolean mGotCenterDown = false;
3241
3242    @Override
3243    public boolean onKeyDown(int keyCode, KeyEvent event) {
3244        if (DebugFlags.WEB_VIEW) {
3245            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
3246                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3247        }
3248
3249        if (mNativeClass == 0) {
3250            return false;
3251        }
3252
3253        // do this hack up front, so it always works, regardless of touch-mode
3254        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
3255            mAutoRedraw = !mAutoRedraw;
3256            if (mAutoRedraw) {
3257                invalidate();
3258            }
3259            return true;
3260        }
3261
3262        // Bubble up the key event if
3263        // 1. it is a system key; or
3264        // 2. the host application wants to handle it;
3265        if (event.isSystem()
3266                || mCallbackProxy.uiOverrideKeyEvent(event)) {
3267            return false;
3268        }
3269
3270        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
3271                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3272                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
3273            setUpSelectXY();
3274        }
3275
3276        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3277                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3278            // always handle the navigation keys in the UI thread
3279            switchOutDrawHistory();
3280            if (mShiftIsPressed) {
3281                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
3282                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
3283                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
3284                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
3285                int multiplier = event.getRepeatCount() + 1;
3286                moveSelection(xRate * multiplier, yRate * multiplier);
3287                return true;
3288            }
3289            if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) {
3290                playSoundEffect(keyCodeToSoundsEffect(keyCode));
3291                return true;
3292            }
3293            // Bubble up the key event as WebView doesn't handle it
3294            return false;
3295        }
3296
3297        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3298            switchOutDrawHistory();
3299            if (event.getRepeatCount() == 0) {
3300                if (mShiftIsPressed) {
3301                    return true; // discard press if copy in progress
3302                }
3303                mGotCenterDown = true;
3304                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3305                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
3306                // Already checked mNativeClass, so we do not need to check it
3307                // again.
3308                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
3309                return true;
3310            }
3311            // Bubble up the key event as WebView doesn't handle it
3312            return false;
3313        }
3314
3315        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
3316                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
3317            // turn off copy select if a shift-key combo is pressed
3318            mExtendSelection = mShiftIsPressed = false;
3319            if (mTouchMode == TOUCH_SELECT_MODE) {
3320                mTouchMode = TOUCH_INIT_MODE;
3321            }
3322        }
3323
3324        if (getSettings().getNavDump()) {
3325            switch (keyCode) {
3326                case KeyEvent.KEYCODE_4:
3327                    // "/data/data/com.android.browser/displayTree.txt"
3328                    nativeDumpDisplayTree(getUrl());
3329                    break;
3330                case KeyEvent.KEYCODE_5:
3331                case KeyEvent.KEYCODE_6:
3332                    // 5: dump the dom tree to the file
3333                    // "/data/data/com.android.browser/domTree.txt"
3334                    // 6: dump the dom tree to the adb log
3335                    mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE,
3336                            (keyCode == KeyEvent.KEYCODE_5) ? 1 : 0, 0);
3337                    break;
3338                case KeyEvent.KEYCODE_7:
3339                case KeyEvent.KEYCODE_8:
3340                    // 7: dump the render tree to the file
3341                    // "/data/data/com.android.browser/renderTree.txt"
3342                    // 8: dump the render tree to the adb log
3343                    mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE,
3344                            (keyCode == KeyEvent.KEYCODE_7) ? 1 : 0, 0);
3345                    break;
3346                case KeyEvent.KEYCODE_9:
3347                    nativeInstrumentReport();
3348                    return true;
3349            }
3350        }
3351
3352        if (nativeCursorIsTextInput()) {
3353            // This message will put the node in focus, for the DOM's notion
3354            // of focus, and make the focuscontroller active
3355            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
3356                    nativeCursorNodePointer());
3357            // This will bring up the WebTextView and put it in focus, for
3358            // our view system's notion of focus
3359            rebuildWebTextView();
3360            // Now we need to pass the event to it
3361            if (inEditingMode()) {
3362                mWebTextView.setDefaultSelection();
3363                mWebTextView.mOkayForFocusNotToMatch = true;
3364                return mWebTextView.dispatchKeyEvent(event);
3365            }
3366        } else if (nativeHasFocusNode()) {
3367            // In this case, the cursor is not on a text input, but the focus
3368            // might be.  Check it, and if so, hand over to the WebTextView.
3369            rebuildWebTextView();
3370            if (inEditingMode()) {
3371                return mWebTextView.dispatchKeyEvent(event);
3372            }
3373        }
3374
3375        // TODO: should we pass all the keys to DOM or check the meta tag
3376        if (nativeCursorWantsKeyEvents() || true) {
3377            // pass the key to DOM
3378            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3379            // return true as DOM handles the key
3380            return true;
3381        }
3382
3383        // Bubble up the key event as WebView doesn't handle it
3384        return false;
3385    }
3386
3387    @Override
3388    public boolean onKeyUp(int keyCode, KeyEvent event) {
3389        if (DebugFlags.WEB_VIEW) {
3390            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
3391                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3392        }
3393
3394        if (mNativeClass == 0) {
3395            return false;
3396        }
3397
3398        // special CALL handling when cursor node's href is "tel:XXX"
3399        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
3400            String text = nativeCursorText();
3401            if (!nativeCursorIsTextInput() && text != null
3402                    && text.startsWith(SCHEME_TEL)) {
3403                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
3404                getContext().startActivity(intent);
3405                return true;
3406            }
3407        }
3408
3409        // Bubble up the key event if
3410        // 1. it is a system key; or
3411        // 2. the host application wants to handle it;
3412        if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) {
3413            return false;
3414        }
3415
3416        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3417                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3418            if (commitCopy()) {
3419                return true;
3420            }
3421        }
3422
3423        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3424                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3425            // always handle the navigation keys in the UI thread
3426            // Bubble up the key event as WebView doesn't handle it
3427            return false;
3428        }
3429
3430        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3431            // remove the long press message first
3432            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
3433            mGotCenterDown = false;
3434
3435            if (mShiftIsPressed) {
3436                if (mExtendSelection) {
3437                    commitCopy();
3438                } else {
3439                    mExtendSelection = true;
3440                    invalidate(); // draw the i-beam instead of the arrow
3441                }
3442                return true; // discard press if copy in progress
3443            }
3444
3445            // perform the single click
3446            Rect visibleRect = sendOurVisibleRect();
3447            // Note that sendOurVisibleRect calls viewToContent, so the
3448            // coordinates should be in content coordinates.
3449            if (!nativeCursorIntersects(visibleRect)) {
3450                return false;
3451            }
3452            WebViewCore.CursorData data = cursorData();
3453            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
3454            playSoundEffect(SoundEffectConstants.CLICK);
3455            if (nativeCursorIsTextInput()) {
3456                rebuildWebTextView();
3457                centerKeyPressOnTextField();
3458                if (inEditingMode()) {
3459                    mWebTextView.setDefaultSelection();
3460                    mWebTextView.mOkayForFocusNotToMatch = true;
3461                }
3462                return true;
3463            }
3464            nativeSetFollowedLink(true);
3465            if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
3466                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
3467                        nativeCursorNodePointer());
3468            }
3469            return true;
3470        }
3471
3472        // TODO: should we pass all the keys to DOM or check the meta tag
3473        if (nativeCursorWantsKeyEvents() || true) {
3474            // pass the key to DOM
3475            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
3476            // return true as DOM handles the key
3477            return true;
3478        }
3479
3480        // Bubble up the key event as WebView doesn't handle it
3481        return false;
3482    }
3483
3484    private void setUpSelectXY() {
3485        mExtendSelection = false;
3486        mShiftIsPressed = true;
3487        if (nativeHasCursorNode()) {
3488            Rect rect = nativeCursorNodeBounds();
3489            mSelectX = contentToViewX(rect.left);
3490            mSelectY = contentToViewY(rect.top);
3491        } else if (mLastTouchY > getVisibleTitleHeight()) {
3492            mSelectX = mScrollX + (int) mLastTouchX;
3493            mSelectY = mScrollY + (int) mLastTouchY;
3494        } else {
3495            mSelectX = mScrollX + getViewWidth() / 2;
3496            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
3497        }
3498        nativeHideCursor();
3499    }
3500
3501    /**
3502     * @hide
3503     */
3504    public void emulateShiftHeld() {
3505        if (0 == mNativeClass) return; // client isn't initialized
3506        setUpSelectXY();
3507    }
3508
3509    private boolean commitCopy() {
3510        boolean copiedSomething = false;
3511        if (mExtendSelection) {
3512            // copy region so core operates on copy without touching orig.
3513            Region selection = new Region(nativeGetSelection());
3514            if (selection.isEmpty() == false) {
3515                Toast.makeText(mContext
3516                        , com.android.internal.R.string.text_copied
3517                        , Toast.LENGTH_SHORT).show();
3518                mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection);
3519                copiedSomething = true;
3520            }
3521            mExtendSelection = false;
3522        }
3523        mShiftIsPressed = false;
3524        invalidate(); // remove selection region and pointer
3525        if (mTouchMode == TOUCH_SELECT_MODE) {
3526            mTouchMode = TOUCH_INIT_MODE;
3527        }
3528        return copiedSomething;
3529    }
3530
3531    // Set this as a hierarchy change listener so we can know when this view
3532    // is removed and still have access to our parent.
3533    @Override
3534    protected void onAttachedToWindow() {
3535        super.onAttachedToWindow();
3536        ViewParent parent = getParent();
3537        if (parent instanceof ViewGroup) {
3538            ViewGroup p = (ViewGroup) parent;
3539            p.setOnHierarchyChangeListener(this);
3540        }
3541    }
3542
3543    @Override
3544    protected void onDetachedFromWindow() {
3545        super.onDetachedFromWindow();
3546        ViewParent parent = getParent();
3547        if (parent instanceof ViewGroup) {
3548            ViewGroup p = (ViewGroup) parent;
3549            p.setOnHierarchyChangeListener(null);
3550        }
3551
3552        // Clean up the zoom controller
3553        mZoomButtonsController.setVisible(false);
3554    }
3555
3556    // Implementation for OnHierarchyChangeListener
3557    public void onChildViewAdded(View parent, View child) {}
3558
3559    public void onChildViewRemoved(View p, View child) {
3560        if (child == this) {
3561            clearTextEntry();
3562        }
3563    }
3564
3565    /**
3566     * @deprecated WebView should not have implemented
3567     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
3568     * does nothing now.
3569     */
3570    @Deprecated
3571    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
3572    }
3573
3574    // To avoid drawing the cursor ring, and remove the TextView when our window
3575    // loses focus.
3576    @Override
3577    public void onWindowFocusChanged(boolean hasWindowFocus) {
3578        if (hasWindowFocus) {
3579            if (hasFocus()) {
3580                // If our window regained focus, and we have focus, then begin
3581                // drawing the cursor ring
3582                mDrawCursorRing = true;
3583                if (mNativeClass != 0) {
3584                    nativeRecordButtons(true, false, true);
3585                    if (inEditingMode()) {
3586                        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0);
3587                    }
3588                }
3589            } else {
3590                // If our window gained focus, but we do not have it, do not
3591                // draw the cursor ring.
3592                mDrawCursorRing = false;
3593                // We do not call nativeRecordButtons here because we assume
3594                // that when we lost focus, or window focus, it got called with
3595                // false for the first parameter
3596            }
3597        } else {
3598            if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) {
3599                /*
3600                 * The zoom controls come in their own window, so our window
3601                 * loses focus. Our policy is to not draw the cursor ring if
3602                 * our window is not focused, but this is an exception since
3603                 * the user can still navigate the web page with the zoom
3604                 * controls showing.
3605                 */
3606                // If our window has lost focus, stop drawing the cursor ring
3607                mDrawCursorRing = false;
3608            }
3609            mGotKeyDown = false;
3610            mShiftIsPressed = false;
3611            if (mNativeClass != 0) {
3612                nativeRecordButtons(false, false, true);
3613            }
3614            setFocusControllerInactive();
3615        }
3616        invalidate();
3617        super.onWindowFocusChanged(hasWindowFocus);
3618    }
3619
3620    /*
3621     * Pass a message to WebCore Thread, telling the WebCore::Page's
3622     * FocusController to be  "inactive" so that it will
3623     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
3624     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
3625     */
3626    /* package */ void setFocusControllerInactive() {
3627        // Do not need to also check whether mWebViewCore is null, because
3628        // mNativeClass is only set if mWebViewCore is non null
3629        if (mNativeClass == 0) return;
3630        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
3631    }
3632
3633    @Override
3634    protected void onFocusChanged(boolean focused, int direction,
3635            Rect previouslyFocusedRect) {
3636        if (DebugFlags.WEB_VIEW) {
3637            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
3638        }
3639        if (focused) {
3640            // When we regain focus, if we have window focus, resume drawing
3641            // the cursor ring
3642            if (hasWindowFocus()) {
3643                mDrawCursorRing = true;
3644                if (mNativeClass != 0) {
3645                    nativeRecordButtons(true, false, true);
3646                }
3647            //} else {
3648                // The WebView has gained focus while we do not have
3649                // windowfocus.  When our window lost focus, we should have
3650                // called nativeRecordButtons(false...)
3651            }
3652        } else {
3653            // When we lost focus, unless focus went to the TextView (which is
3654            // true if we are in editing mode), stop drawing the cursor ring.
3655            if (!inEditingMode()) {
3656                mDrawCursorRing = false;
3657                if (mNativeClass != 0) {
3658                    nativeRecordButtons(false, false, true);
3659                }
3660                setFocusControllerInactive();
3661            }
3662            mGotKeyDown = false;
3663        }
3664
3665        super.onFocusChanged(focused, direction, previouslyFocusedRect);
3666    }
3667
3668    /**
3669     * @hide
3670     */
3671    @Override
3672    protected boolean setFrame(int left, int top, int right, int bottom) {
3673        boolean changed = super.setFrame(left, top, right, bottom);
3674        if (!changed && mHeightCanMeasure) {
3675            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
3676            // in WebViewCore after we get the first layout. We do call
3677            // requestLayout() when we get contentSizeChanged(). But the View
3678            // system won't call onSizeChanged if the dimension is not changed.
3679            // In this case, we need to call sendViewSizeZoom() explicitly to
3680            // notify the WebKit about the new dimensions.
3681            sendViewSizeZoom();
3682        }
3683        return changed;
3684    }
3685
3686    @Override
3687    protected void onSizeChanged(int w, int h, int ow, int oh) {
3688        super.onSizeChanged(w, h, ow, oh);
3689        // Center zooming to the center of the screen.
3690        if (mZoomScale == 0) { // unless we're already zooming
3691            mZoomCenterX = getViewWidth() * .5f;
3692            mZoomCenterY = getViewHeight() * .5f;
3693        }
3694
3695        // update mMinZoomScale if the minimum zoom scale is not fixed
3696        if (!mMinZoomScaleFixed) {
3697            // when change from narrow screen to wide screen, the new viewWidth
3698            // can be wider than the old content width. We limit the minimum
3699            // scale to 1.0f. The proper minimum scale will be calculated when
3700            // the new picture shows up.
3701            mMinZoomScale = Math.min(1.0f, (float) getViewWidth()
3702                    / (mDrawHistory ? mHistoryPicture.getWidth()
3703                            : mZoomOverviewWidth));
3704        }
3705
3706        // we always force, in case our height changed, in which case we still
3707        // want to send the notification over to webkit
3708        setNewZoomScale(mActualScale, true);
3709    }
3710
3711    @Override
3712    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
3713        super.onScrollChanged(l, t, oldl, oldt);
3714
3715        sendOurVisibleRect();
3716    }
3717
3718
3719    @Override
3720    public boolean dispatchKeyEvent(KeyEvent event) {
3721        boolean dispatch = true;
3722
3723        if (!inEditingMode()) {
3724            if (event.getAction() == KeyEvent.ACTION_DOWN) {
3725                mGotKeyDown = true;
3726            } else {
3727                if (!mGotKeyDown) {
3728                    /*
3729                     * We got a key up for which we were not the recipient of
3730                     * the original key down. Don't give it to the view.
3731                     */
3732                    dispatch = false;
3733                }
3734                mGotKeyDown = false;
3735            }
3736        }
3737
3738        if (dispatch) {
3739            return super.dispatchKeyEvent(event);
3740        } else {
3741            // We didn't dispatch, so let something else handle the key
3742            return false;
3743        }
3744    }
3745
3746    // Here are the snap align logic:
3747    // 1. If it starts nearly horizontally or vertically, snap align;
3748    // 2. If there is a dramitic direction change, let it go;
3749    // 3. If there is a same direction back and forth, lock it.
3750
3751    // adjustable parameters
3752    private int mMinLockSnapReverseDistance;
3753    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
3754    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
3755
3756    @Override
3757    public boolean onTouchEvent(MotionEvent ev) {
3758        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
3759            return false;
3760        }
3761
3762        if (DebugFlags.WEB_VIEW) {
3763            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
3764                    + mTouchMode);
3765        }
3766
3767        int action = ev.getAction();
3768        float x = ev.getX();
3769        float y = ev.getY();
3770        long eventTime = ev.getEventTime();
3771
3772        // Due to the touch screen edge effect, a touch closer to the edge
3773        // always snapped to the edge. As getViewWidth() can be different from
3774        // getWidth() due to the scrollbar, adjusting the point to match
3775        // getViewWidth(). Same applied to the height.
3776        if (x > getViewWidth() - 1) {
3777            x = getViewWidth() - 1;
3778        }
3779        if (y > getViewHeightWithTitle() - 1) {
3780            y = getViewHeightWithTitle() - 1;
3781        }
3782
3783        // pass the touch events from UI thread to WebCore thread
3784        if (mForwardTouchEvents && (action != MotionEvent.ACTION_MOVE
3785                || eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) {
3786            WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
3787            ted.mAction = action;
3788            ted.mX = viewToContentX((int) x + mScrollX);
3789            ted.mY = viewToContentY((int) y + mScrollY);
3790            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
3791            mLastSentTouchTime = eventTime;
3792        }
3793
3794        float fDeltaX = mLastTouchX - x;
3795        float fDeltaY = mLastTouchY - y;
3796        int deltaX = (int) fDeltaX;
3797        int deltaY = (int) fDeltaY;
3798
3799        switch (action) {
3800            case MotionEvent.ACTION_DOWN: {
3801                mPreventDrag = PREVENT_DRAG_NO;
3802                if (!mScroller.isFinished()) {
3803                    // stop the current scroll animation, but if this is
3804                    // the start of a fling, allow it to add to the current
3805                    // fling's velocity
3806                    mScroller.abortAnimation();
3807                    mTouchMode = TOUCH_DRAG_START_MODE;
3808                    mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
3809                } else if (mShiftIsPressed) {
3810                    mSelectX = mScrollX + (int) x;
3811                    mSelectY = mScrollY + (int) y;
3812                    mTouchMode = TOUCH_SELECT_MODE;
3813                    if (DebugFlags.WEB_VIEW) {
3814                        Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
3815                    }
3816                    nativeMoveSelection(viewToContentX(mSelectX),
3817                            viewToContentY(mSelectY), false);
3818                    mTouchSelection = mExtendSelection = true;
3819                    invalidate(); // draw the i-beam instead of the arrow
3820                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
3821                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
3822                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
3823                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
3824                    } else {
3825                        // commit the short press action for the previous tap
3826                        doShortPress();
3827                        // continue, mTouchMode should be still TOUCH_INIT_MODE
3828                    }
3829                } else {
3830                    mTouchMode = TOUCH_INIT_MODE;
3831                    mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES
3832                            : PREVENT_DRAG_NO;
3833                    mWebViewCore.sendMessage(
3834                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
3835                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
3836                        EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION,
3837                                (eventTime - mLastTouchUpTime), eventTime);
3838                    }
3839                }
3840                // Trigger the link
3841                if (mTouchMode == TOUCH_INIT_MODE
3842                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
3843                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
3844                            .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT);
3845                }
3846                // Remember where the motion event started
3847                mLastTouchX = x;
3848                mLastTouchY = y;
3849                mLastTouchTime = eventTime;
3850                mVelocityTracker = VelocityTracker.obtain();
3851                mSnapScrollMode = SNAP_NONE;
3852                break;
3853            }
3854            case MotionEvent.ACTION_MOVE: {
3855                if (mTouchMode == TOUCH_DONE_MODE) {
3856                    // no dragging during scroll zoom animation
3857                    break;
3858                }
3859                mVelocityTracker.addMovement(ev);
3860
3861                if (mTouchMode != TOUCH_DRAG_MODE) {
3862                    if (mTouchMode == TOUCH_SELECT_MODE) {
3863                        mSelectX = mScrollX + (int) x;
3864                        mSelectY = mScrollY + (int) y;
3865                        if (DebugFlags.WEB_VIEW) {
3866                            Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
3867                        }
3868                        nativeMoveSelection(viewToContentX(mSelectX),
3869                               viewToContentY(mSelectY), true);
3870                        invalidate();
3871                        break;
3872                    }
3873                    if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) {
3874                        break;
3875                    }
3876                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
3877                        // track mLastTouchTime as we may need to do fling at
3878                        // ACTION_UP
3879                        mLastTouchTime = eventTime;
3880                        break;
3881                    }
3882                    if (mTouchMode == TOUCH_SHORTPRESS_MODE
3883                            || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
3884                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3885                    } else if (mTouchMode == TOUCH_INIT_MODE
3886                            || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
3887                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3888                    }
3889
3890                    // if it starts nearly horizontal or vertical, enforce it
3891                    int ax = Math.abs(deltaX);
3892                    int ay = Math.abs(deltaY);
3893                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
3894                        mSnapScrollMode = SNAP_X;
3895                        mSnapPositive = deltaX > 0;
3896                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
3897                        mSnapScrollMode = SNAP_Y;
3898                        mSnapPositive = deltaY > 0;
3899                    }
3900
3901                    mTouchMode = TOUCH_DRAG_MODE;
3902                    WebViewCore.pauseUpdate(mWebViewCore);
3903                    if (!mDragFromTextInput) {
3904                        nativeHideCursor();
3905                    }
3906                    WebSettings settings = getSettings();
3907                    if (settings.supportZoom()
3908                            && settings.getBuiltInZoomControls()
3909                            && !mZoomButtonsController.isVisible()
3910                            && mMinZoomScale < mMaxZoomScale) {
3911                        mZoomButtonsController.setVisible(true);
3912                        int count = settings.getDoubleTapToastCount();
3913                        if (mInZoomOverview && count > 0) {
3914                            settings.setDoubleTapToastCount(--count);
3915                            Toast.makeText(mContext,
3916                                    com.android.internal.R.string.double_tap_toast,
3917                                    Toast.LENGTH_LONG).show();
3918                        }
3919                    }
3920                }
3921
3922                // do pan
3923                int newScrollX = pinLocX(mScrollX + deltaX);
3924                int newDeltaX = newScrollX - mScrollX;
3925                if (deltaX != newDeltaX) {
3926                    deltaX = newDeltaX;
3927                    fDeltaX = (float) newDeltaX;
3928                }
3929                int newScrollY = pinLocY(mScrollY + deltaY);
3930                int newDeltaY = newScrollY - mScrollY;
3931                if (deltaY != newDeltaY) {
3932                    deltaY = newDeltaY;
3933                    fDeltaY = (float) newDeltaY;
3934                }
3935                boolean done = false;
3936                boolean keepScrollBarsVisible = false;
3937                if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
3938                    keepScrollBarsVisible = done = true;
3939                } else {
3940                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
3941                        int ax = Math.abs(deltaX);
3942                        int ay = Math.abs(deltaY);
3943                        if (mSnapScrollMode == SNAP_X) {
3944                            // radical change means getting out of snap mode
3945                            if (ay > MAX_SLOPE_FOR_DIAG * ax
3946                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3947                                mSnapScrollMode = SNAP_NONE;
3948                            }
3949                            // reverse direction means lock in the snap mode
3950                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
3951                                    (mSnapPositive
3952                                    ? deltaX < -mMinLockSnapReverseDistance
3953                                    : deltaX > mMinLockSnapReverseDistance)) {
3954                                mSnapScrollMode |= SNAP_LOCK;
3955                            }
3956                        } else {
3957                            // radical change means getting out of snap mode
3958                            if (ax > MAX_SLOPE_FOR_DIAG * ay
3959                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3960                                mSnapScrollMode = SNAP_NONE;
3961                            }
3962                            // reverse direction means lock in the snap mode
3963                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
3964                                    (mSnapPositive
3965                                    ? deltaY < -mMinLockSnapReverseDistance
3966                                    : deltaY > mMinLockSnapReverseDistance)) {
3967                                mSnapScrollMode |= SNAP_LOCK;
3968                            }
3969                        }
3970                    }
3971                    if (mSnapScrollMode != SNAP_NONE) {
3972                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
3973                            deltaY = 0;
3974                        } else {
3975                            deltaX = 0;
3976                        }
3977                    }
3978                    if ((deltaX | deltaY) != 0) {
3979                        scrollBy(deltaX, deltaY);
3980                        if (deltaX != 0) {
3981                            mLastTouchX = x;
3982                        }
3983                        if (deltaY != 0) {
3984                            mLastTouchY = y;
3985                        }
3986                        mHeldMotionless = MOTIONLESS_FALSE;
3987                    } else {
3988                        // keep the scrollbar on the screen even there is no
3989                        // scroll
3990                        keepScrollBarsVisible = true;
3991                    }
3992                    mLastTouchTime = eventTime;
3993                    mUserScroll = true;
3994                }
3995
3996                if (!getSettings().getBuiltInZoomControls()) {
3997                    boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
3998                    if (mZoomControls != null && showPlusMinus) {
3999                        if (mZoomControls.getVisibility() == View.VISIBLE) {
4000                            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4001                        } else {
4002                            mZoomControls.show(showPlusMinus, false);
4003                        }
4004                        mPrivateHandler.postDelayed(mZoomControlRunnable,
4005                                ZOOM_CONTROLS_TIMEOUT);
4006                    }
4007                }
4008
4009                if (keepScrollBarsVisible) {
4010                    if (mHeldMotionless != MOTIONLESS_TRUE) {
4011                        mHeldMotionless = MOTIONLESS_TRUE;
4012                        invalidate();
4013                    }
4014                    // keep the scrollbar on the screen even there is no scroll
4015                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
4016                            false);
4017                    // return false to indicate that we can't pan out of the
4018                    // view space
4019                    return !done;
4020                }
4021                break;
4022            }
4023            case MotionEvent.ACTION_UP: {
4024                mLastTouchUpTime = eventTime;
4025                switch (mTouchMode) {
4026                    case TOUCH_DOUBLE_TAP_MODE: // double tap
4027                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4028                        mTouchMode = TOUCH_DONE_MODE;
4029                        doDoubleTap();
4030                        break;
4031                    case TOUCH_SELECT_MODE:
4032                        commitCopy();
4033                        mTouchSelection = false;
4034                        break;
4035                    case TOUCH_INIT_MODE: // tap
4036                    case TOUCH_SHORTPRESS_START_MODE:
4037                    case TOUCH_SHORTPRESS_MODE:
4038                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4039                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4040                        if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) {
4041                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
4042                                    " WebCore's response for touch down.");
4043                            if (computeHorizontalScrollExtent() < computeHorizontalScrollRange()
4044                                    || computeVerticalScrollExtent() < computeVerticalScrollRange()) {
4045                                // we will not rewrite drag code here, but we
4046                                // will try fling if it applies.
4047                                WebViewCore.pauseUpdate(mWebViewCore);
4048                                // fall through to TOUCH_DRAG_MODE
4049                            } else {
4050                                break;
4051                            }
4052                        } else {
4053                            if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
4054                                // if mPreventDrag is not confirmed, treat it as
4055                                // no so that it won't block tap or double tap.
4056                                mPreventDrag = PREVENT_DRAG_NO;
4057                            }
4058                            if (mPreventDrag == PREVENT_DRAG_NO) {
4059                                if (mTouchMode == TOUCH_INIT_MODE) {
4060                                    mPrivateHandler.sendMessageDelayed(
4061                                            mPrivateHandler.obtainMessage(
4062                                            RELEASE_SINGLE_TAP),
4063                                            ViewConfiguration.getDoubleTapTimeout());
4064                                } else {
4065                                    mTouchMode = TOUCH_DONE_MODE;
4066                                    doShortPress();
4067                                }
4068                            }
4069                            break;
4070                        }
4071                    case TOUCH_DRAG_MODE:
4072                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4073                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4074                        mHeldMotionless = MOTIONLESS_TRUE;
4075                        // redraw in high-quality, as we're done dragging
4076                        invalidate();
4077                        // if the user waits a while w/o moving before the
4078                        // up, we don't want to do a fling
4079                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
4080                            mVelocityTracker.addMovement(ev);
4081                            doFling();
4082                            break;
4083                        }
4084                        mLastVelocity = 0;
4085                        WebViewCore.resumeUpdate(mWebViewCore);
4086                        break;
4087                    case TOUCH_DRAG_START_MODE:
4088                    case TOUCH_DONE_MODE:
4089                        // do nothing
4090                        break;
4091                }
4092                // we also use mVelocityTracker == null to tell us that we are
4093                // not "moving around", so we can take the slower/prettier
4094                // mode in the drawing code
4095                if (mVelocityTracker != null) {
4096                    mVelocityTracker.recycle();
4097                    mVelocityTracker = null;
4098                }
4099                break;
4100            }
4101            case MotionEvent.ACTION_CANCEL: {
4102                // we also use mVelocityTracker == null to tell us that we are
4103                // not "moving around", so we can take the slower/prettier
4104                // mode in the drawing code
4105                if (mVelocityTracker != null) {
4106                    mVelocityTracker.recycle();
4107                    mVelocityTracker = null;
4108                }
4109                if (mTouchMode == TOUCH_DRAG_MODE) {
4110                    WebViewCore.resumeUpdate(mWebViewCore);
4111                }
4112                mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4113                mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4114                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4115                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4116                mHeldMotionless = MOTIONLESS_TRUE;
4117                mTouchMode = TOUCH_DONE_MODE;
4118                nativeHideCursor();
4119                break;
4120            }
4121        }
4122        return true;
4123    }
4124
4125    private long mTrackballFirstTime = 0;
4126    private long mTrackballLastTime = 0;
4127    private float mTrackballRemainsX = 0.0f;
4128    private float mTrackballRemainsY = 0.0f;
4129    private int mTrackballXMove = 0;
4130    private int mTrackballYMove = 0;
4131    private boolean mExtendSelection = false;
4132    private boolean mTouchSelection = false;
4133    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
4134    private static final int TRACKBALL_TIMEOUT = 200;
4135    private static final int TRACKBALL_WAIT = 100;
4136    private static final int TRACKBALL_SCALE = 400;
4137    private static final int TRACKBALL_SCROLL_COUNT = 5;
4138    private static final int TRACKBALL_MOVE_COUNT = 10;
4139    private static final int TRACKBALL_MULTIPLIER = 3;
4140    private static final int SELECT_CURSOR_OFFSET = 16;
4141    private int mSelectX = 0;
4142    private int mSelectY = 0;
4143    private boolean mFocusSizeChanged = false;
4144    private boolean mShiftIsPressed = false;
4145    private boolean mTrackballDown = false;
4146    private long mTrackballUpTime = 0;
4147    private long mLastCursorTime = 0;
4148    private Rect mLastCursorBounds;
4149
4150    // Set by default; BrowserActivity clears to interpret trackball data
4151    // directly for movement. Currently, the framework only passes
4152    // arrow key events, not trackball events, from one child to the next
4153    private boolean mMapTrackballToArrowKeys = true;
4154
4155    public void setMapTrackballToArrowKeys(boolean setMap) {
4156        mMapTrackballToArrowKeys = setMap;
4157    }
4158
4159    void resetTrackballTime() {
4160        mTrackballLastTime = 0;
4161    }
4162
4163    @Override
4164    public boolean onTrackballEvent(MotionEvent ev) {
4165        long time = ev.getEventTime();
4166        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
4167            if (ev.getY() > 0) pageDown(true);
4168            if (ev.getY() < 0) pageUp(true);
4169            return true;
4170        }
4171        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
4172            if (mShiftIsPressed) {
4173                return true; // discard press if copy in progress
4174            }
4175            mTrackballDown = true;
4176            if (mNativeClass == 0) {
4177                return false;
4178            }
4179            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4180            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
4181                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
4182                nativeSelectBestAt(mLastCursorBounds);
4183            }
4184            if (DebugFlags.WEB_VIEW) {
4185                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
4186                        + " time=" + time
4187                        + " mLastCursorTime=" + mLastCursorTime);
4188            }
4189            if (isInTouchMode()) requestFocusFromTouch();
4190            return false; // let common code in onKeyDown at it
4191        }
4192        if (ev.getAction() == MotionEvent.ACTION_UP) {
4193            // LONG_PRESS_CENTER is set in common onKeyDown
4194            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4195            mTrackballDown = false;
4196            mTrackballUpTime = time;
4197            if (mShiftIsPressed) {
4198                if (mExtendSelection) {
4199                    commitCopy();
4200                } else {
4201                    mExtendSelection = true;
4202                    invalidate(); // draw the i-beam instead of the arrow
4203                }
4204                return true; // discard press if copy in progress
4205            }
4206            if (DebugFlags.WEB_VIEW) {
4207                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
4208                        + " time=" + time
4209                );
4210            }
4211            return false; // let common code in onKeyUp at it
4212        }
4213        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
4214            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
4215            return false;
4216        }
4217        if (mTrackballDown) {
4218            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
4219            return true; // discard move if trackball is down
4220        }
4221        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
4222            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
4223            return true;
4224        }
4225        // TODO: alternatively we can do panning as touch does
4226        switchOutDrawHistory();
4227        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
4228            if (DebugFlags.WEB_VIEW) {
4229                Log.v(LOGTAG, "onTrackballEvent time="
4230                        + time + " last=" + mTrackballLastTime);
4231            }
4232            mTrackballFirstTime = time;
4233            mTrackballXMove = mTrackballYMove = 0;
4234        }
4235        mTrackballLastTime = time;
4236        if (DebugFlags.WEB_VIEW) {
4237            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
4238        }
4239        mTrackballRemainsX += ev.getX();
4240        mTrackballRemainsY += ev.getY();
4241        doTrackball(time);
4242        return true;
4243    }
4244
4245    void moveSelection(float xRate, float yRate) {
4246        if (mNativeClass == 0)
4247            return;
4248        int width = getViewWidth();
4249        int height = getViewHeight();
4250        mSelectX += xRate;
4251        mSelectY += yRate;
4252        int maxX = width + mScrollX;
4253        int maxY = height + mScrollY;
4254        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
4255                , mSelectX));
4256        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
4257                , mSelectY));
4258        if (DebugFlags.WEB_VIEW) {
4259            Log.v(LOGTAG, "moveSelection"
4260                    + " mSelectX=" + mSelectX
4261                    + " mSelectY=" + mSelectY
4262                    + " mScrollX=" + mScrollX
4263                    + " mScrollY=" + mScrollY
4264                    + " xRate=" + xRate
4265                    + " yRate=" + yRate
4266                    );
4267        }
4268        nativeMoveSelection(viewToContentX(mSelectX),
4269                viewToContentY(mSelectY), mExtendSelection);
4270        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
4271                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
4272                : 0;
4273        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
4274                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
4275                : 0;
4276        pinScrollBy(scrollX, scrollY, true, 0);
4277        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
4278        requestRectangleOnScreen(select);
4279        invalidate();
4280   }
4281
4282    private int scaleTrackballX(float xRate, int width) {
4283        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
4284        int nextXMove = xMove;
4285        if (xMove > 0) {
4286            if (xMove > mTrackballXMove) {
4287                xMove -= mTrackballXMove;
4288            }
4289        } else if (xMove < mTrackballXMove) {
4290            xMove -= mTrackballXMove;
4291        }
4292        mTrackballXMove = nextXMove;
4293        return xMove;
4294    }
4295
4296    private int scaleTrackballY(float yRate, int height) {
4297        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
4298        int nextYMove = yMove;
4299        if (yMove > 0) {
4300            if (yMove > mTrackballYMove) {
4301                yMove -= mTrackballYMove;
4302            }
4303        } else if (yMove < mTrackballYMove) {
4304            yMove -= mTrackballYMove;
4305        }
4306        mTrackballYMove = nextYMove;
4307        return yMove;
4308    }
4309
4310    private int keyCodeToSoundsEffect(int keyCode) {
4311        switch(keyCode) {
4312            case KeyEvent.KEYCODE_DPAD_UP:
4313                return SoundEffectConstants.NAVIGATION_UP;
4314            case KeyEvent.KEYCODE_DPAD_RIGHT:
4315                return SoundEffectConstants.NAVIGATION_RIGHT;
4316            case KeyEvent.KEYCODE_DPAD_DOWN:
4317                return SoundEffectConstants.NAVIGATION_DOWN;
4318            case KeyEvent.KEYCODE_DPAD_LEFT:
4319                return SoundEffectConstants.NAVIGATION_LEFT;
4320        }
4321        throw new IllegalArgumentException("keyCode must be one of " +
4322                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
4323                "KEYCODE_DPAD_LEFT}.");
4324    }
4325
4326    private void doTrackball(long time) {
4327        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
4328        if (elapsed == 0) {
4329            elapsed = TRACKBALL_TIMEOUT;
4330        }
4331        float xRate = mTrackballRemainsX * 1000 / elapsed;
4332        float yRate = mTrackballRemainsY * 1000 / elapsed;
4333        int viewWidth = getViewWidth();
4334        int viewHeight = getViewHeight();
4335        if (mShiftIsPressed) {
4336            moveSelection(scaleTrackballX(xRate, viewWidth),
4337                    scaleTrackballY(yRate, viewHeight));
4338            mTrackballRemainsX = mTrackballRemainsY = 0;
4339            return;
4340        }
4341        float ax = Math.abs(xRate);
4342        float ay = Math.abs(yRate);
4343        float maxA = Math.max(ax, ay);
4344        if (DebugFlags.WEB_VIEW) {
4345            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
4346                    + " xRate=" + xRate
4347                    + " yRate=" + yRate
4348                    + " mTrackballRemainsX=" + mTrackballRemainsX
4349                    + " mTrackballRemainsY=" + mTrackballRemainsY);
4350        }
4351        int width = mContentWidth - viewWidth;
4352        int height = mContentHeight - viewHeight;
4353        if (width < 0) width = 0;
4354        if (height < 0) height = 0;
4355        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
4356        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
4357        maxA = Math.max(ax, ay);
4358        int count = Math.max(0, (int) maxA);
4359        int oldScrollX = mScrollX;
4360        int oldScrollY = mScrollY;
4361        if (count > 0) {
4362            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
4363                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
4364                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
4365                    KeyEvent.KEYCODE_DPAD_RIGHT;
4366            count = Math.min(count, TRACKBALL_MOVE_COUNT);
4367            if (DebugFlags.WEB_VIEW) {
4368                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
4369                        + " count=" + count
4370                        + " mTrackballRemainsX=" + mTrackballRemainsX
4371                        + " mTrackballRemainsY=" + mTrackballRemainsY);
4372            }
4373            if (navHandledKey(selectKeyCode, count, false, time, false)) {
4374                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
4375            }
4376            mTrackballRemainsX = mTrackballRemainsY = 0;
4377        }
4378        if (count >= TRACKBALL_SCROLL_COUNT) {
4379            int xMove = scaleTrackballX(xRate, width);
4380            int yMove = scaleTrackballY(yRate, height);
4381            if (DebugFlags.WEB_VIEW) {
4382                Log.v(LOGTAG, "doTrackball pinScrollBy"
4383                        + " count=" + count
4384                        + " xMove=" + xMove + " yMove=" + yMove
4385                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
4386                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
4387                        );
4388            }
4389            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
4390                xMove = 0;
4391            }
4392            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
4393                yMove = 0;
4394            }
4395            if (xMove != 0 || yMove != 0) {
4396                pinScrollBy(xMove, yMove, true, 0);
4397            }
4398            mUserScroll = true;
4399        }
4400    }
4401
4402    private int computeMaxScrollY() {
4403        int maxContentH = computeVerticalScrollRange() + getTitleHeight();
4404        return Math.max(maxContentH - getHeight(), getTitleHeight());
4405    }
4406
4407    public void flingScroll(int vx, int vy) {
4408        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
4409        int maxY = computeMaxScrollY();
4410
4411        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY);
4412        invalidate();
4413    }
4414
4415    private void doFling() {
4416        if (mVelocityTracker == null) {
4417            return;
4418        }
4419        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
4420        int maxY = computeMaxScrollY();
4421
4422        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
4423        int vx = (int) mVelocityTracker.getXVelocity();
4424        int vy = (int) mVelocityTracker.getYVelocity();
4425
4426        if (mSnapScrollMode != SNAP_NONE) {
4427            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
4428                vy = 0;
4429            } else {
4430                vx = 0;
4431            }
4432        }
4433
4434        if (true /* EMG release: make our fling more like Maps' */) {
4435            // maps cuts their velocity in half
4436            vx = vx * 3 / 4;
4437            vy = vy * 3 / 4;
4438        }
4439        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
4440            WebViewCore.resumeUpdate(mWebViewCore);
4441            return;
4442        }
4443        float currentVelocity = mScroller.getCurrVelocity();
4444        if (mLastVelocity > 0 && currentVelocity > 0) {
4445            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
4446                    - Math.atan2(vy, vx)));
4447            final float circle = (float) (Math.PI) * 2.0f;
4448            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
4449                vx += currentVelocity * mLastVelX / mLastVelocity;
4450                vy += currentVelocity * mLastVelY / mLastVelocity;
4451                if (DebugFlags.WEB_VIEW) {
4452                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
4453                }
4454            } else if (DebugFlags.WEB_VIEW) {
4455                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
4456            }
4457        } else if (DebugFlags.WEB_VIEW) {
4458            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
4459                    + " current=" + currentVelocity
4460                    + " vx=" + vx + " vy=" + vy
4461                    + " maxX=" + maxX + " maxY=" + maxY
4462                    + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
4463        }
4464        mLastVelX = vx;
4465        mLastVelY = vy;
4466        mLastVelocity = (float) Math.hypot(vx, vy);
4467
4468        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
4469        // TODO: duration is calculated based on velocity, if the range is
4470        // small, the animation will stop before duration is up. We may
4471        // want to calculate how long the animation is going to run to precisely
4472        // resume the webcore update.
4473        final int time = mScroller.getDuration();
4474        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_UPDATE, time);
4475        awakenScrollBars(time);
4476        invalidate();
4477    }
4478
4479    private boolean zoomWithPreview(float scale) {
4480        float oldScale = mActualScale;
4481        mInitialScrollX = mScrollX;
4482        mInitialScrollY = mScrollY;
4483
4484        // snap to DEFAULT_SCALE if it is close
4485        if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) {
4486            scale = mDefaultScale;
4487        }
4488
4489        setNewZoomScale(scale, false);
4490
4491        if (oldScale != mActualScale) {
4492            // use mZoomPickerScale to see zoom preview first
4493            mZoomStart = SystemClock.uptimeMillis();
4494            mInvInitialZoomScale = 1.0f / oldScale;
4495            mInvFinalZoomScale = 1.0f / mActualScale;
4496            mZoomScale = mActualScale;
4497            if (!mInZoomOverview) {
4498                mLastScale = scale;
4499            }
4500            invalidate();
4501            return true;
4502        } else {
4503            return false;
4504        }
4505    }
4506
4507    /**
4508     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
4509     * in charge of installing this view to the view hierarchy. This view will
4510     * become visible when the user starts scrolling via touch and fade away if
4511     * the user does not interact with it.
4512     * <p/>
4513     * API version 3 introduces a built-in zoom mechanism that is shown
4514     * automatically by the MapView. This is the preferred approach for
4515     * showing the zoom UI.
4516     *
4517     * @deprecated The built-in zoom mechanism is preferred, see
4518     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
4519     */
4520    @Deprecated
4521    public View getZoomControls() {
4522        if (!getSettings().supportZoom()) {
4523            Log.w(LOGTAG, "This WebView doesn't support zoom.");
4524            return null;
4525        }
4526        if (mZoomControls == null) {
4527            mZoomControls = createZoomControls();
4528
4529            /*
4530             * need to be set to VISIBLE first so that getMeasuredHeight() in
4531             * {@link #onSizeChanged()} can return the measured value for proper
4532             * layout.
4533             */
4534            mZoomControls.setVisibility(View.VISIBLE);
4535            mZoomControlRunnable = new Runnable() {
4536                public void run() {
4537
4538                    /* Don't dismiss the controls if the user has
4539                     * focus on them. Wait and check again later.
4540                     */
4541                    if (!mZoomControls.hasFocus()) {
4542                        mZoomControls.hide();
4543                    } else {
4544                        mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4545                        mPrivateHandler.postDelayed(mZoomControlRunnable,
4546                                ZOOM_CONTROLS_TIMEOUT);
4547                    }
4548                }
4549            };
4550        }
4551        return mZoomControls;
4552    }
4553
4554    private ExtendedZoomControls createZoomControls() {
4555        ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext
4556            , null);
4557        zoomControls.setOnZoomInClickListener(new OnClickListener() {
4558            public void onClick(View v) {
4559                // reset time out
4560                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4561                mPrivateHandler.postDelayed(mZoomControlRunnable,
4562                        ZOOM_CONTROLS_TIMEOUT);
4563                zoomIn();
4564            }
4565        });
4566        zoomControls.setOnZoomOutClickListener(new OnClickListener() {
4567            public void onClick(View v) {
4568                // reset time out
4569                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4570                mPrivateHandler.postDelayed(mZoomControlRunnable,
4571                        ZOOM_CONTROLS_TIMEOUT);
4572                zoomOut();
4573            }
4574        });
4575        return zoomControls;
4576    }
4577
4578    /**
4579     * Gets the {@link ZoomButtonsController} which can be used to add
4580     * additional buttons to the zoom controls window.
4581     *
4582     * @return The instance of {@link ZoomButtonsController} used by this class,
4583     *         or null if it is unavailable.
4584     * @hide
4585     */
4586    public ZoomButtonsController getZoomButtonsController() {
4587        return mZoomButtonsController;
4588    }
4589
4590    /**
4591     * Perform zoom in in the webview
4592     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
4593     */
4594    public boolean zoomIn() {
4595        // TODO: alternatively we can disallow this during draw history mode
4596        switchOutDrawHistory();
4597        // Center zooming to the center of the screen.
4598        if (mInZoomOverview) {
4599            // if in overview mode, bring it back to normal mode
4600            mLastTouchX = getViewWidth() * .5f;
4601            mLastTouchY = getViewHeight() * .5f;
4602            doDoubleTap();
4603            return true;
4604        } else {
4605            mZoomCenterX = getViewWidth() * .5f;
4606            mZoomCenterY = getViewHeight() * .5f;
4607            return zoomWithPreview(mActualScale * 1.25f);
4608        }
4609    }
4610
4611    /**
4612     * Perform zoom out in the webview
4613     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
4614     */
4615    public boolean zoomOut() {
4616        // TODO: alternatively we can disallow this during draw history mode
4617        switchOutDrawHistory();
4618        float scale = mActualScale * 0.8f;
4619        if (scale < (mMinZoomScale + 0.1f)
4620                && mWebViewCore.getSettings().getUseWideViewPort()) {
4621            // when zoom out to min scale, switch to overview mode
4622            doDoubleTap();
4623            return true;
4624        } else {
4625            // Center zooming to the center of the screen.
4626            mZoomCenterX = getViewWidth() * .5f;
4627            mZoomCenterY = getViewHeight() * .5f;
4628            return zoomWithPreview(scale);
4629        }
4630    }
4631
4632    private void updateSelection() {
4633        if (mNativeClass == 0) {
4634            return;
4635        }
4636        // mLastTouchX and mLastTouchY are the point in the current viewport
4637        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4638        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
4639        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
4640                contentX + mNavSlop, contentY + mNavSlop);
4641        nativeSelectBestAt(rect);
4642    }
4643
4644    /**
4645     * Scroll the focused text field/area to match the WebTextView
4646     * @param xPercent New x position of the WebTextView from 0 to 1.
4647     * @param y New y position of the WebTextView in view coordinates
4648     */
4649    /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
4650        if (!inEditingMode() || mWebViewCore == null) {
4651            return;
4652        }
4653        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
4654                // Since this position is relative to the top of the text input
4655                // field, we do not need to take the title bar's height into
4656                // consideration.
4657                viewToContentDimension(y),
4658                new Float(xPercent));
4659    }
4660
4661    /**
4662     * Set our starting point and time for a drag from the WebTextView.
4663     */
4664    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
4665        if (!inEditingMode()) {
4666            return;
4667        }
4668        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
4669        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
4670        mLastTouchTime = eventTime;
4671        if (!mScroller.isFinished()) {
4672            abortAnimation();
4673            mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
4674        }
4675        mSnapScrollMode = SNAP_NONE;
4676        mVelocityTracker = VelocityTracker.obtain();
4677        mTouchMode = TOUCH_DRAG_START_MODE;
4678    }
4679
4680    /**
4681     * Given a motion event from the WebTextView, set its location to our
4682     * coordinates, and handle the event.
4683     */
4684    /*package*/ boolean textFieldDrag(MotionEvent event) {
4685        if (!inEditingMode()) {
4686            return false;
4687        }
4688        mDragFromTextInput = true;
4689        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
4690                (float) (mWebTextView.getTop() - mScrollY));
4691        boolean result = onTouchEvent(event);
4692        mDragFromTextInput = false;
4693        return result;
4694    }
4695
4696    /**
4697     * Do a touch up from a WebTextView.  This will be handled by webkit to
4698     * change the selection.
4699     * @param event MotionEvent in the WebTextView's coordinates.
4700     */
4701    /*package*/ void touchUpOnTextField(MotionEvent event) {
4702        if (!inEditingMode()) {
4703            return;
4704        }
4705        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
4706        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
4707        if (nativeFocusNodePointer() != nativeCursorNodePointer()) {
4708            nativeMotionUp(x, y, mNavSlop);
4709        }
4710        nativeTextInputMotionUp(x, y);
4711    }
4712
4713    /**
4714     * Called when pressing the center key or trackball on a textfield.
4715     */
4716    /*package*/ void centerKeyPressOnTextField() {
4717        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
4718                    nativeCursorNodePointer());
4719        // Need to show the soft keyboard if it's not readonly.
4720        if (!nativeCursorIsReadOnly()) {
4721            displaySoftKeyboard(true);
4722        }
4723    }
4724
4725    private void doShortPress() {
4726        if (mNativeClass == 0) {
4727            return;
4728        }
4729        switchOutDrawHistory();
4730        // mLastTouchX and mLastTouchY are the point in the current viewport
4731        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4732        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
4733        if (nativeMotionUp(contentX, contentY, mNavSlop)) {
4734            if (mLogEvent) {
4735                Checkin.updateStats(mContext.getContentResolver(),
4736                        Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0);
4737            }
4738        }
4739        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
4740            playSoundEffect(SoundEffectConstants.CLICK);
4741        }
4742    }
4743
4744    private void doDoubleTap() {
4745        if (mWebViewCore.getSettings().getUseWideViewPort() == false) {
4746            return;
4747        }
4748        mZoomCenterX = mLastTouchX;
4749        mZoomCenterY = mLastTouchY;
4750        mInZoomOverview = !mInZoomOverview;
4751        // remove the zoom control after double tap
4752        WebSettings settings = getSettings();
4753        if (settings.getBuiltInZoomControls()) {
4754            if (mZoomButtonsController.isVisible()) {
4755                mZoomButtonsController.setVisible(false);
4756            }
4757        } else {
4758            if (mZoomControlRunnable != null) {
4759                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4760            }
4761            if (mZoomControls != null) {
4762                mZoomControls.hide();
4763            }
4764        }
4765        settings.setDoubleTapToastCount(0);
4766        if (mInZoomOverview) {
4767            // Force the titlebar fully reveal in overview mode
4768            if (mScrollY < getTitleHeight()) mScrollY = 0;
4769            zoomWithPreview((float) getViewWidth() / mZoomOverviewWidth);
4770        } else {
4771            // mLastTouchX and mLastTouchY are the point in the current viewport
4772            int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4773            int contentY = viewToContentY((int) mLastTouchY + mScrollY);
4774            int left = nativeGetBlockLeftEdge(contentX, contentY, mActualScale);
4775            if (left != NO_LEFTEDGE) {
4776                // add a 5pt padding to the left edge. Re-calculate the zoom
4777                // center so that the new scroll x will be on the left edge.
4778                mZoomCenterX = left < 5 ? 0 : (left - 5) * mLastScale
4779                        * mActualScale / (mLastScale - mActualScale);
4780            }
4781            zoomWithPreview(mLastScale);
4782        }
4783    }
4784
4785    // Called by JNI to handle a touch on a node representing an email address,
4786    // address, or phone number
4787    private void overrideLoading(String url) {
4788        mCallbackProxy.uiOverrideUrlLoading(url);
4789    }
4790
4791    @Override
4792    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4793        boolean result = false;
4794        if (inEditingMode()) {
4795            result = mWebTextView.requestFocus(direction,
4796                    previouslyFocusedRect);
4797        } else {
4798            result = super.requestFocus(direction, previouslyFocusedRect);
4799            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
4800                // For cases such as GMail, where we gain focus from a direction,
4801                // we want to move to the first available link.
4802                // FIXME: If there are no visible links, we may not want to
4803                int fakeKeyDirection = 0;
4804                switch(direction) {
4805                    case View.FOCUS_UP:
4806                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
4807                        break;
4808                    case View.FOCUS_DOWN:
4809                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
4810                        break;
4811                    case View.FOCUS_LEFT:
4812                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
4813                        break;
4814                    case View.FOCUS_RIGHT:
4815                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
4816                        break;
4817                    default:
4818                        return result;
4819                }
4820                if (mNativeClass != 0 && !nativeHasCursorNode()) {
4821                    navHandledKey(fakeKeyDirection, 1, true, 0, true);
4822                }
4823            }
4824        }
4825        return result;
4826    }
4827
4828    @Override
4829    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
4830        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
4831
4832        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
4833        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
4834        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
4835        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
4836
4837        int measuredHeight = heightSize;
4838        int measuredWidth = widthSize;
4839
4840        // Grab the content size from WebViewCore.
4841        int contentHeight = contentToViewDimension(mContentHeight);
4842        int contentWidth = contentToViewDimension(mContentWidth);
4843
4844//        Log.d(LOGTAG, "------- measure " + heightMode);
4845
4846        if (heightMode != MeasureSpec.EXACTLY) {
4847            mHeightCanMeasure = true;
4848            measuredHeight = contentHeight;
4849            if (heightMode == MeasureSpec.AT_MOST) {
4850                // If we are larger than the AT_MOST height, then our height can
4851                // no longer be measured and we should scroll internally.
4852                if (measuredHeight > heightSize) {
4853                    measuredHeight = heightSize;
4854                    mHeightCanMeasure = false;
4855                }
4856            }
4857        } else {
4858            mHeightCanMeasure = false;
4859        }
4860        if (mNativeClass != 0) {
4861            nativeSetHeightCanMeasure(mHeightCanMeasure);
4862        }
4863        // For the width, always use the given size unless unspecified.
4864        if (widthMode == MeasureSpec.UNSPECIFIED) {
4865            mWidthCanMeasure = true;
4866            measuredWidth = contentWidth;
4867        } else {
4868            mWidthCanMeasure = false;
4869        }
4870
4871        synchronized (this) {
4872            setMeasuredDimension(measuredWidth, measuredHeight);
4873        }
4874    }
4875
4876    @Override
4877    public boolean requestChildRectangleOnScreen(View child,
4878                                                 Rect rect,
4879                                                 boolean immediate) {
4880        rect.offset(child.getLeft() - child.getScrollX(),
4881                child.getTop() - child.getScrollY());
4882
4883        int height = getViewHeightWithTitle();
4884        int screenTop = mScrollY;
4885        int screenBottom = screenTop + height;
4886
4887        int scrollYDelta = 0;
4888
4889        if (rect.bottom > screenBottom) {
4890            int oneThirdOfScreenHeight = height / 3;
4891            if (rect.height() > 2 * oneThirdOfScreenHeight) {
4892                // If the rectangle is too tall to fit in the bottom two thirds
4893                // of the screen, place it at the top.
4894                scrollYDelta = rect.top - screenTop;
4895            } else {
4896                // If the rectangle will still fit on screen, we want its
4897                // top to be in the top third of the screen.
4898                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
4899            }
4900        } else if (rect.top < screenTop) {
4901            scrollYDelta = rect.top - screenTop;
4902        }
4903
4904        int width = getWidth() - getVerticalScrollbarWidth();
4905        int screenLeft = mScrollX;
4906        int screenRight = screenLeft + width;
4907
4908        int scrollXDelta = 0;
4909
4910        if (rect.right > screenRight && rect.left > screenLeft) {
4911            if (rect.width() > width) {
4912                scrollXDelta += (rect.left - screenLeft);
4913            } else {
4914                scrollXDelta += (rect.right - screenRight);
4915            }
4916        } else if (rect.left < screenLeft) {
4917            scrollXDelta -= (screenLeft - rect.left);
4918        }
4919
4920        if ((scrollYDelta | scrollXDelta) != 0) {
4921            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
4922        }
4923
4924        return false;
4925    }
4926
4927    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
4928            String replace, int newStart, int newEnd) {
4929        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
4930        arg.mReplace = replace;
4931        arg.mNewStart = newStart;
4932        arg.mNewEnd = newEnd;
4933        mTextGeneration++;
4934        arg.mTextGeneration = mTextGeneration;
4935        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
4936    }
4937
4938    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
4939        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
4940        arg.mEvent = event;
4941        arg.mCurrentText = currentText;
4942        // Increase our text generation number, and pass it to webcore thread
4943        mTextGeneration++;
4944        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
4945        // WebKit's document state is not saved until about to leave the page.
4946        // To make sure the host application, like Browser, has the up to date
4947        // document state when it goes to background, we force to save the
4948        // document state.
4949        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
4950        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
4951                cursorData(), 1000);
4952    }
4953
4954    /* package */ WebViewCore getWebViewCore() {
4955        return mWebViewCore;
4956    }
4957
4958    //-------------------------------------------------------------------------
4959    // Methods can be called from a separate thread, like WebViewCore
4960    // If it needs to call the View system, it has to send message.
4961    //-------------------------------------------------------------------------
4962
4963    /**
4964     * General handler to receive message coming from webkit thread
4965     */
4966    class PrivateHandler extends Handler {
4967        @Override
4968        public void handleMessage(Message msg) {
4969            // exclude INVAL_RECT_MSG_ID since it is frequently output
4970            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
4971                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
4972                        > REQUEST_KEYBOARD ? Integer.toString(msg.what)
4973                        : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
4974            }
4975            if (mWebViewCore == null) {
4976                // after WebView's destroy() is called, skip handling messages.
4977                return;
4978            }
4979            switch (msg.what) {
4980                case REMEMBER_PASSWORD: {
4981                    mDatabase.setUsernamePassword(
4982                            msg.getData().getString("host"),
4983                            msg.getData().getString("username"),
4984                            msg.getData().getString("password"));
4985                    ((Message) msg.obj).sendToTarget();
4986                    break;
4987                }
4988                case NEVER_REMEMBER_PASSWORD: {
4989                    mDatabase.setUsernamePassword(
4990                            msg.getData().getString("host"), null, null);
4991                    ((Message) msg.obj).sendToTarget();
4992                    break;
4993                }
4994                case SWITCH_TO_SHORTPRESS: {
4995                    // if mPreventDrag is not confirmed, treat it as no so that
4996                    // it won't block panning the page.
4997                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
4998                        mPreventDrag = PREVENT_DRAG_NO;
4999                    }
5000                    if (mTouchMode == TOUCH_INIT_MODE) {
5001                        mTouchMode = TOUCH_SHORTPRESS_START_MODE;
5002                        updateSelection();
5003                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5004                        mTouchMode = TOUCH_DONE_MODE;
5005                    }
5006                    break;
5007                }
5008                case SWITCH_TO_LONGPRESS: {
5009                    if (mPreventDrag == PREVENT_DRAG_NO) {
5010                        mTouchMode = TOUCH_DONE_MODE;
5011                        performLongClick();
5012                        rebuildWebTextView();
5013                    }
5014                    break;
5015                }
5016                case RELEASE_SINGLE_TAP: {
5017                    if (mPreventDrag == PREVENT_DRAG_NO) {
5018                        mTouchMode = TOUCH_DONE_MODE;
5019                        doShortPress();
5020                    }
5021                    break;
5022                }
5023                case SCROLL_BY_MSG_ID:
5024                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
5025                    break;
5026                case SYNC_SCROLL_TO_MSG_ID:
5027                    if (mUserScroll) {
5028                        // if user has scrolled explicitly, don't sync the
5029                        // scroll position any more
5030                        mUserScroll = false;
5031                        break;
5032                    }
5033                    // fall through
5034                case SCROLL_TO_MSG_ID:
5035                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
5036                        // if we can't scroll to the exact position due to pin,
5037                        // send a message to WebCore to re-scroll when we get a
5038                        // new picture
5039                        mUserScroll = false;
5040                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
5041                                msg.arg1, msg.arg2);
5042                    }
5043                    break;
5044                case SPAWN_SCROLL_TO_MSG_ID:
5045                    spawnContentScrollTo(msg.arg1, msg.arg2);
5046                    break;
5047                case NEW_PICTURE_MSG_ID: {
5048                    WebSettings settings = mWebViewCore.getSettings();
5049                    // called for new content
5050                    final int viewWidth = getViewWidth();
5051                    final WebViewCore.DrawData draw =
5052                            (WebViewCore.DrawData) msg.obj;
5053                    final Point viewSize = draw.mViewPoint;
5054                    boolean useWideViewport = settings.getUseWideViewPort();
5055                    WebViewCore.RestoreState restoreState = draw.mRestoreState;
5056                    if (restoreState != null) {
5057                        mInZoomOverview = false;
5058                        mLastScale = restoreState.mTextWrapScale;
5059                        if (restoreState.mMinScale == 0) {
5060                            if (restoreState.mMobileSite) {
5061                                if (draw.mMinPrefWidth >
5062                                        Math.max(0, draw.mViewPoint.x)) {
5063                                    mMinZoomScale = (float) viewWidth
5064                                            / draw.mMinPrefWidth;
5065                                    mMinZoomScaleFixed = false;
5066                                } else {
5067                                    mMinZoomScale = restoreState.mDefaultScale;
5068                                    mMinZoomScaleFixed = true;
5069                                }
5070                            } else {
5071                                mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
5072                                mMinZoomScaleFixed = false;
5073                            }
5074                        } else {
5075                            mMinZoomScale = restoreState.mMinScale;
5076                            mMinZoomScaleFixed = true;
5077                        }
5078                        if (restoreState.mMaxScale == 0) {
5079                            mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
5080                        } else {
5081                            mMaxZoomScale = restoreState.mMaxScale;
5082                        }
5083                        setNewZoomScale(mLastScale, false);
5084                        setContentScrollTo(restoreState.mScrollX,
5085                                restoreState.mScrollY);
5086                        if (useWideViewport
5087                                && settings.getLoadWithOverviewMode()) {
5088                            if (restoreState.mViewScale == 0
5089                                    || (restoreState.mMobileSite
5090                                    && mMinZoomScale < restoreState.mDefaultScale)) {
5091                                mInZoomOverview = true;
5092                            }
5093                        }
5094                        // As we are on a new page, remove the WebTextView. This
5095                        // is necessary for page loads driven by webkit, and in
5096                        // particular when the user was on a password field, so
5097                        // the WebTextView was visible.
5098                        clearTextEntry();
5099                    }
5100                    // We update the layout (i.e. request a layout from the
5101                    // view system) if the last view size that we sent to
5102                    // WebCore matches the view size of the picture we just
5103                    // received in the fixed dimension.
5104                    final boolean updateLayout = viewSize.x == mLastWidthSent
5105                            && viewSize.y == mLastHeightSent;
5106                    recordNewContentSize(draw.mWidthHeight.x,
5107                            draw.mWidthHeight.y
5108                            + (mFindIsUp ? mFindHeight : 0), updateLayout);
5109                    if (DebugFlags.WEB_VIEW) {
5110                        Rect b = draw.mInvalRegion.getBounds();
5111                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
5112                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
5113                    }
5114                    invalidateContentRect(draw.mInvalRegion.getBounds());
5115                    if (mPictureListener != null) {
5116                        mPictureListener.onNewPicture(WebView.this, capturePicture());
5117                    }
5118                    if (useWideViewport) {
5119                        mZoomOverviewWidth = Math.max(draw.mMinPrefWidth,
5120                                draw.mViewPoint.x);
5121                    }
5122                    if (!mMinZoomScaleFixed) {
5123                        mMinZoomScale = (float) viewWidth / mZoomOverviewWidth;
5124                    }
5125                    if (!mDrawHistory && mInZoomOverview) {
5126                        // fit the content width to the current view. Ignore
5127                        // the rounding error case.
5128                        if (Math.abs((viewWidth * mInvActualScale)
5129                                - mZoomOverviewWidth) > 1) {
5130                            setNewZoomScale((float) viewWidth
5131                                    / mZoomOverviewWidth, false);
5132                        }
5133                    }
5134                    if (draw.mFocusSizeChanged && inEditingMode()) {
5135                        mFocusSizeChanged = true;
5136                    }
5137                    break;
5138                }
5139                case WEBCORE_INITIALIZED_MSG_ID:
5140                    // nativeCreate sets mNativeClass to a non-zero value
5141                    nativeCreate(msg.arg1);
5142                    break;
5143                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
5144                    // Make sure that the textfield is currently focused
5145                    // and representing the same node as the pointer.
5146                    if (inEditingMode() &&
5147                            mWebTextView.isSameTextField(msg.arg1)) {
5148                        if (msg.getData().getBoolean("password")) {
5149                            Spannable text = (Spannable) mWebTextView.getText();
5150                            int start = Selection.getSelectionStart(text);
5151                            int end = Selection.getSelectionEnd(text);
5152                            mWebTextView.setInPassword(true);
5153                            // Restore the selection, which may have been
5154                            // ruined by setInPassword.
5155                            Spannable pword =
5156                                    (Spannable) mWebTextView.getText();
5157                            Selection.setSelection(pword, start, end);
5158                        // If the text entry has created more events, ignore
5159                        // this one.
5160                        } else if (msg.arg2 == mTextGeneration) {
5161                            mWebTextView.setTextAndKeepSelection(
5162                                    (String) msg.obj);
5163                        }
5164                    }
5165                    break;
5166                case UPDATE_TEXT_SELECTION_MSG_ID:
5167                    if (inEditingMode()
5168                            && mWebTextView.isSameTextField(msg.arg1)
5169                            && msg.arg2 == mTextGeneration) {
5170                        WebViewCore.TextSelectionData tData
5171                                = (WebViewCore.TextSelectionData) msg.obj;
5172                        mWebTextView.setSelectionFromWebKit(tData.mStart,
5173                                tData.mEnd);
5174                    }
5175                    break;
5176                case MOVE_OUT_OF_PLUGIN:
5177                    navHandledKey(msg.arg1, 1, false, 0, true);
5178                    break;
5179                case UPDATE_TEXT_ENTRY_MSG_ID:
5180                    // this is sent after finishing resize in WebViewCore. Make
5181                    // sure the text edit box is still on the  screen.
5182                    if (inEditingMode() && nativeCursorIsTextInput()) {
5183                        mWebTextView.bringIntoView();
5184                        rebuildWebTextView();
5185                    }
5186                    break;
5187                case CLEAR_TEXT_ENTRY:
5188                    clearTextEntry();
5189                    break;
5190                case INVAL_RECT_MSG_ID: {
5191                    Rect r = (Rect)msg.obj;
5192                    if (r == null) {
5193                        invalidate();
5194                    } else {
5195                        // we need to scale r from content into view coords,
5196                        // which viewInvalidate() does for us
5197                        viewInvalidate(r.left, r.top, r.right, r.bottom);
5198                    }
5199                    break;
5200                }
5201                case REQUEST_FORM_DATA:
5202                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
5203                    if (mWebTextView.isSameTextField(msg.arg1)) {
5204                        mWebTextView.setAdapterCustom(adapter);
5205                    }
5206                    break;
5207                case UPDATE_CLIPBOARD:
5208                    String str = (String) msg.obj;
5209                    if (DebugFlags.WEB_VIEW) {
5210                        Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str);
5211                    }
5212                    try {
5213                        IClipboard clip = IClipboard.Stub.asInterface(
5214                                ServiceManager.getService("clipboard"));
5215                                clip.setClipboardText(str);
5216                    } catch (android.os.RemoteException e) {
5217                        Log.e(LOGTAG, "Clipboard failed", e);
5218                    }
5219                    break;
5220                case RESUME_WEBCORE_UPDATE:
5221                    WebViewCore.resumeUpdate(mWebViewCore);
5222                    break;
5223
5224                case LONG_PRESS_CENTER:
5225                    // as this is shared by keydown and trackballdown, reset all
5226                    // the states
5227                    mGotCenterDown = false;
5228                    mTrackballDown = false;
5229                    // LONG_PRESS_CENTER is sent as a delayed message. If we
5230                    // switch to windows overview, the WebView will be
5231                    // temporarily removed from the view system. In that case,
5232                    // do nothing.
5233                    if (getParent() != null) {
5234                        performLongClick();
5235                    }
5236                    break;
5237
5238                case WEBCORE_NEED_TOUCH_EVENTS:
5239                    mForwardTouchEvents = (msg.arg1 != 0);
5240                    break;
5241
5242                case PREVENT_TOUCH_ID:
5243                    if (msg.arg1 == MotionEvent.ACTION_DOWN) {
5244                        // dont override if mPreventDrag has been set to no due
5245                        // to time out
5246                        if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
5247                            mPreventDrag = msg.arg2 == 1 ? PREVENT_DRAG_YES
5248                                    : PREVENT_DRAG_NO;
5249                            if (mPreventDrag == PREVENT_DRAG_YES) {
5250                                mTouchMode = TOUCH_DONE_MODE;
5251                            }
5252                        }
5253                    }
5254                    break;
5255
5256                case REQUEST_KEYBOARD:
5257                    if (msg.arg1 == 0) {
5258                        hideSoftKeyboard();
5259                    } else {
5260                        displaySoftKeyboard(false);
5261                        if (DebugFlags.WEB_VIEW) {
5262                            Log.v(LOGTAG, "REQUEST_KEYBOARD"
5263                                    + " focusCandidateIsPlugin="
5264                                    + nativeFocusCandidateIsPlugin());
5265                        }
5266                    }
5267                    break;
5268
5269                case FIND_AGAIN:
5270                    // Ignore if find has been dismissed.
5271                    if (mFindIsUp) {
5272                        findAll(mLastFind);
5273                    }
5274                    break;
5275
5276                case DRAG_HELD_MOTIONLESS:
5277                    mHeldMotionless = MOTIONLESS_TRUE;
5278                    invalidate();
5279                    // fall through to keep scrollbars awake
5280
5281                case AWAKEN_SCROLL_BARS:
5282                    if (mTouchMode == TOUCH_DRAG_MODE
5283                            && mHeldMotionless == MOTIONLESS_TRUE) {
5284                        awakenScrollBars(ViewConfiguration
5285                                .getScrollDefaultDelay(), false);
5286                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
5287                                .obtainMessage(AWAKEN_SCROLL_BARS),
5288                                ViewConfiguration.getScrollDefaultDelay());
5289                    }
5290                    break;
5291                default:
5292                    super.handleMessage(msg);
5293                    break;
5294            }
5295        }
5296    }
5297
5298    // Class used to use a dropdown for a <select> element
5299    private class InvokeListBox implements Runnable {
5300        // Whether the listbox allows multiple selection.
5301        private boolean     mMultiple;
5302        // Passed in to a list with multiple selection to tell
5303        // which items are selected.
5304        private int[]       mSelectedArray;
5305        // Passed in to a list with single selection to tell
5306        // where the initial selection is.
5307        private int         mSelection;
5308
5309        private Container[] mContainers;
5310
5311        // Need these to provide stable ids to my ArrayAdapter,
5312        // which normally does not have stable ids. (Bug 1250098)
5313        private class Container extends Object {
5314            /**
5315             * Possible values for mEnabled.  Keep in sync with OptionStatus in
5316             * WebViewCore.cpp
5317             */
5318            final static int OPTGROUP = -1;
5319            final static int OPTION_DISABLED = 0;
5320            final static int OPTION_ENABLED = 1;
5321
5322            String  mString;
5323            int     mEnabled;
5324            int     mId;
5325
5326            public String toString() {
5327                return mString;
5328            }
5329        }
5330
5331        /**
5332         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
5333         *  and allow filtering.
5334         */
5335        private class MyArrayListAdapter extends ArrayAdapter<Container> {
5336            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
5337                super(context,
5338                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
5339                            com.android.internal.R.layout.select_dialog_singlechoice,
5340                            objects);
5341            }
5342
5343            @Override
5344            public View getView(int position, View convertView,
5345                    ViewGroup parent) {
5346                // Always pass in null so that we will get a new CheckedTextView
5347                // Otherwise, an item which was previously used as an <optgroup>
5348                // element (i.e. has no check), could get used as an <option>
5349                // element, which needs a checkbox/radio, but it would not have
5350                // one.
5351                convertView = super.getView(position, null, parent);
5352                Container c = item(position);
5353                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
5354                    // ListView does not draw dividers between disabled and
5355                    // enabled elements.  Use a LinearLayout to provide dividers
5356                    LinearLayout layout = new LinearLayout(mContext);
5357                    layout.setOrientation(LinearLayout.VERTICAL);
5358                    if (position > 0) {
5359                        View dividerTop = new View(mContext);
5360                        dividerTop.setBackgroundResource(
5361                                android.R.drawable.divider_horizontal_bright);
5362                        layout.addView(dividerTop);
5363                    }
5364
5365                    if (Container.OPTGROUP == c.mEnabled) {
5366                        // Currently select_dialog_multichoice and
5367                        // select_dialog_singlechoice are CheckedTextViews.  If
5368                        // that changes, the class cast will no longer be valid.
5369                        Assert.assertTrue(
5370                                convertView instanceof CheckedTextView);
5371                        ((CheckedTextView) convertView).setCheckMarkDrawable(
5372                                null);
5373                    } else {
5374                        // c.mEnabled == Container.OPTION_DISABLED
5375                        // Draw the disabled element in a disabled state.
5376                        convertView.setEnabled(false);
5377                    }
5378
5379                    layout.addView(convertView);
5380                    if (position < getCount() - 1) {
5381                        View dividerBottom = new View(mContext);
5382                        dividerBottom.setBackgroundResource(
5383                                android.R.drawable.divider_horizontal_bright);
5384                        layout.addView(dividerBottom);
5385                    }
5386                    return layout;
5387                }
5388                return convertView;
5389            }
5390
5391            @Override
5392            public boolean hasStableIds() {
5393                // AdapterView's onChanged method uses this to determine whether
5394                // to restore the old state.  Return false so that the old (out
5395                // of date) state does not replace the new, valid state.
5396                return false;
5397            }
5398
5399            private Container item(int position) {
5400                if (position < 0 || position >= getCount()) {
5401                    return null;
5402                }
5403                return (Container) getItem(position);
5404            }
5405
5406            @Override
5407            public long getItemId(int position) {
5408                Container item = item(position);
5409                if (item == null) {
5410                    return -1;
5411                }
5412                return item.mId;
5413            }
5414
5415            @Override
5416            public boolean areAllItemsEnabled() {
5417                return false;
5418            }
5419
5420            @Override
5421            public boolean isEnabled(int position) {
5422                Container item = item(position);
5423                if (item == null) {
5424                    return false;
5425                }
5426                return Container.OPTION_ENABLED == item.mEnabled;
5427            }
5428        }
5429
5430        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
5431            mMultiple = true;
5432            mSelectedArray = selected;
5433
5434            int length = array.length;
5435            mContainers = new Container[length];
5436            for (int i = 0; i < length; i++) {
5437                mContainers[i] = new Container();
5438                mContainers[i].mString = array[i];
5439                mContainers[i].mEnabled = enabled[i];
5440                mContainers[i].mId = i;
5441            }
5442        }
5443
5444        private InvokeListBox(String[] array, int[] enabled, int selection) {
5445            mSelection = selection;
5446            mMultiple = false;
5447
5448            int length = array.length;
5449            mContainers = new Container[length];
5450            for (int i = 0; i < length; i++) {
5451                mContainers[i] = new Container();
5452                mContainers[i].mString = array[i];
5453                mContainers[i].mEnabled = enabled[i];
5454                mContainers[i].mId = i;
5455            }
5456        }
5457
5458        /*
5459         * Whenever the data set changes due to filtering, this class ensures
5460         * that the checked item remains checked.
5461         */
5462        private class SingleDataSetObserver extends DataSetObserver {
5463            private long        mCheckedId;
5464            private ListView    mListView;
5465            private Adapter     mAdapter;
5466
5467            /*
5468             * Create a new observer.
5469             * @param id The ID of the item to keep checked.
5470             * @param l ListView for getting and clearing the checked states
5471             * @param a Adapter for getting the IDs
5472             */
5473            public SingleDataSetObserver(long id, ListView l, Adapter a) {
5474                mCheckedId = id;
5475                mListView = l;
5476                mAdapter = a;
5477            }
5478
5479            public void onChanged() {
5480                // The filter may have changed which item is checked.  Find the
5481                // item that the ListView thinks is checked.
5482                int position = mListView.getCheckedItemPosition();
5483                long id = mAdapter.getItemId(position);
5484                if (mCheckedId != id) {
5485                    // Clear the ListView's idea of the checked item, since
5486                    // it is incorrect
5487                    mListView.clearChoices();
5488                    // Search for mCheckedId.  If it is in the filtered list,
5489                    // mark it as checked
5490                    int count = mAdapter.getCount();
5491                    for (int i = 0; i < count; i++) {
5492                        if (mAdapter.getItemId(i) == mCheckedId) {
5493                            mListView.setItemChecked(i, true);
5494                            break;
5495                        }
5496                    }
5497                }
5498            }
5499
5500            public void onInvalidate() {}
5501        }
5502
5503        public void run() {
5504            final ListView listView = (ListView) LayoutInflater.from(mContext)
5505                    .inflate(com.android.internal.R.layout.select_dialog, null);
5506            final MyArrayListAdapter adapter = new
5507                    MyArrayListAdapter(mContext, mContainers, mMultiple);
5508            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
5509                    .setView(listView).setCancelable(true)
5510                    .setInverseBackgroundForced(true);
5511
5512            if (mMultiple) {
5513                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
5514                    public void onClick(DialogInterface dialog, int which) {
5515                        mWebViewCore.sendMessage(
5516                                EventHub.LISTBOX_CHOICES,
5517                                adapter.getCount(), 0,
5518                                listView.getCheckedItemPositions());
5519                    }});
5520                b.setNegativeButton(android.R.string.cancel,
5521                        new DialogInterface.OnClickListener() {
5522                    public void onClick(DialogInterface dialog, int which) {
5523                        mWebViewCore.sendMessage(
5524                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5525                }});
5526            }
5527            final AlertDialog dialog = b.create();
5528            listView.setAdapter(adapter);
5529            listView.setFocusableInTouchMode(true);
5530            // There is a bug (1250103) where the checks in a ListView with
5531            // multiple items selected are associated with the positions, not
5532            // the ids, so the items do not properly retain their checks when
5533            // filtered.  Do not allow filtering on multiple lists until
5534            // that bug is fixed.
5535
5536            listView.setTextFilterEnabled(!mMultiple);
5537            if (mMultiple) {
5538                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
5539                int length = mSelectedArray.length;
5540                for (int i = 0; i < length; i++) {
5541                    listView.setItemChecked(mSelectedArray[i], true);
5542                }
5543            } else {
5544                listView.setOnItemClickListener(new OnItemClickListener() {
5545                    public void onItemClick(AdapterView parent, View v,
5546                            int position, long id) {
5547                        mWebViewCore.sendMessage(
5548                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
5549                        dialog.dismiss();
5550                    }
5551                });
5552                if (mSelection != -1) {
5553                    listView.setSelection(mSelection);
5554                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
5555                    listView.setItemChecked(mSelection, true);
5556                    DataSetObserver observer = new SingleDataSetObserver(
5557                            adapter.getItemId(mSelection), listView, adapter);
5558                    adapter.registerDataSetObserver(observer);
5559                }
5560            }
5561            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
5562                public void onCancel(DialogInterface dialog) {
5563                    mWebViewCore.sendMessage(
5564                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5565                }
5566            });
5567            dialog.show();
5568        }
5569    }
5570
5571    /*
5572     * Request a dropdown menu for a listbox with multiple selection.
5573     *
5574     * @param array Labels for the listbox.
5575     * @param enabledArray  State for each element in the list.  See static
5576     *      integers in Container class.
5577     * @param selectedArray Which positions are initally selected.
5578     */
5579    void requestListBox(String[] array, int[] enabledArray, int[]
5580            selectedArray) {
5581        mPrivateHandler.post(
5582                new InvokeListBox(array, enabledArray, selectedArray));
5583    }
5584
5585    /*
5586     * Request a dropdown menu for a listbox with single selection or a single
5587     * <select> element.
5588     *
5589     * @param array Labels for the listbox.
5590     * @param enabledArray  State for each element in the list.  See static
5591     *      integers in Container class.
5592     * @param selection Which position is initally selected.
5593     */
5594    void requestListBox(String[] array, int[] enabledArray, int selection) {
5595        mPrivateHandler.post(
5596                new InvokeListBox(array, enabledArray, selection));
5597    }
5598
5599    // called by JNI
5600    private void sendMoveMouse(int frame, int node, int x, int y) {
5601        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
5602                new WebViewCore.CursorData(frame, node, x, y));
5603    }
5604
5605    /*
5606     * Send a mouse move event to the webcore thread.
5607     *
5608     * @param removeFocus Pass true if the "mouse" cursor is now over a node
5609     *                    which wants key events, but it is not the focus. This
5610     *                    will make the visual appear as though nothing is in
5611     *                    focus.  Remove the WebTextView, if present, and stop
5612     *                    drawing the blinking caret.
5613     * called by JNI
5614     */
5615    private void sendMoveMouseIfLatest(boolean removeFocus) {
5616        if (removeFocus) {
5617            clearTextEntry();
5618            setFocusControllerInactive();
5619        }
5620        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
5621                cursorData());
5622    }
5623
5624    // called by JNI
5625    private void sendMotionUp(int touchGeneration,
5626            int frame, int node, int x, int y) {
5627        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
5628        touchUpData.mMoveGeneration = touchGeneration;
5629        touchUpData.mFrame = frame;
5630        touchUpData.mNode = node;
5631        touchUpData.mX = x;
5632        touchUpData.mY = y;
5633        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
5634    }
5635
5636
5637    private int getScaledMaxXScroll() {
5638        int width;
5639        if (mHeightCanMeasure == false) {
5640            width = getViewWidth() / 4;
5641        } else {
5642            Rect visRect = new Rect();
5643            calcOurVisibleRect(visRect);
5644            width = visRect.width() / 2;
5645        }
5646        // FIXME the divisor should be retrieved from somewhere
5647        return viewToContentX(width);
5648    }
5649
5650    private int getScaledMaxYScroll() {
5651        int height;
5652        if (mHeightCanMeasure == false) {
5653            height = getViewHeight() / 4;
5654        } else {
5655            Rect visRect = new Rect();
5656            calcOurVisibleRect(visRect);
5657            height = visRect.height() / 2;
5658        }
5659        // FIXME the divisor should be retrieved from somewhere
5660        // the closest thing today is hard-coded into ScrollView.java
5661        // (from ScrollView.java, line 363)   int maxJump = height/2;
5662        return Math.round(height * mInvActualScale);
5663    }
5664
5665    /**
5666     * Called by JNI to invalidate view
5667     */
5668    private void viewInvalidate() {
5669        invalidate();
5670    }
5671
5672    // return true if the key was handled
5673    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
5674            long time, boolean ignorePlugin) {
5675        if (mNativeClass == 0) {
5676            return false;
5677        }
5678        if (ignorePlugin == false && nativeFocusIsPlugin()) {
5679            KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN
5680                , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
5681                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
5682                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
5683                , 0, 0, 0);
5684            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5685            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5686            return true;
5687        }
5688        mLastCursorTime = time;
5689        mLastCursorBounds = nativeGetCursorRingBounds();
5690        boolean keyHandled
5691                = nativeMoveCursor(keyCode, count, noScroll) == false;
5692        if (DebugFlags.WEB_VIEW) {
5693            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
5694                    + " mLastCursorTime=" + mLastCursorTime
5695                    + " handled=" + keyHandled);
5696        }
5697        if (keyHandled == false || mHeightCanMeasure == false) {
5698            return keyHandled;
5699        }
5700        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
5701        if (contentCursorRingBounds.isEmpty()) return keyHandled;
5702        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
5703        Rect visRect = new Rect();
5704        calcOurVisibleRect(visRect);
5705        Rect outset = new Rect(visRect);
5706        int maxXScroll = visRect.width() / 2;
5707        int maxYScroll = visRect.height() / 2;
5708        outset.inset(-maxXScroll, -maxYScroll);
5709        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
5710            return keyHandled;
5711        }
5712        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
5713        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
5714                maxXScroll);
5715        if (maxH > 0) {
5716            pinScrollBy(maxH, 0, true, 0);
5717        } else {
5718            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
5719                    -maxXScroll);
5720            if (maxH < 0) {
5721                pinScrollBy(maxH, 0, true, 0);
5722            }
5723        }
5724        if (mLastCursorBounds.isEmpty()) return keyHandled;
5725        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
5726            return keyHandled;
5727        }
5728        if (DebugFlags.WEB_VIEW) {
5729            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
5730                    + contentCursorRingBounds);
5731        }
5732        requestRectangleOnScreen(viewCursorRingBounds);
5733        mUserScroll = true;
5734        return keyHandled;
5735    }
5736
5737    /**
5738     * Set the background color. It's white by default. Pass
5739     * zero to make the view transparent.
5740     * @param color   the ARGB color described by Color.java
5741     */
5742    public void setBackgroundColor(int color) {
5743        mBackgroundColor = color;
5744        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
5745    }
5746
5747    public void debugDump() {
5748        nativeDebugDump();
5749        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
5750    }
5751
5752    /**
5753     * Draw the HTML page into the specified canvas. This call ignores any
5754     * view-specific zoom, scroll offset, or other changes. It does not draw
5755     * any view-specific chrome, such as progress or URL bars.
5756     *
5757     * @hide only needs to be accessible to Browser and testing
5758     */
5759    public void drawPage(Canvas canvas) {
5760        mWebViewCore.drawContentPicture(canvas, 0, false, false);
5761    }
5762
5763    /**
5764     *  Update our cache with updatedText.
5765     *  @param updatedText  The new text to put in our cache.
5766     */
5767    /* package */ void updateCachedTextfield(String updatedText) {
5768        // Also place our generation number so that when we look at the cache
5769        // we recognize that it is up to date.
5770        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
5771    }
5772
5773    /* package */ native void nativeClearCursor();
5774    private native void     nativeCreate(int ptr);
5775    private native int      nativeCursorFramePointer();
5776    private native Rect     nativeCursorNodeBounds();
5777    /* package */ native int nativeCursorNodePointer();
5778    /* package */ native boolean nativeCursorMatchesFocus();
5779    private native boolean  nativeCursorIntersects(Rect visibleRect);
5780    private native boolean  nativeCursorIsAnchor();
5781    private native boolean  nativeCursorIsReadOnly();
5782    private native boolean  nativeCursorIsTextInput();
5783    private native Point    nativeCursorPosition();
5784    private native String   nativeCursorText();
5785    /**
5786     * Returns true if the native cursor node says it wants to handle key events
5787     * (ala plugins). This can only be called if mNativeClass is non-zero!
5788     */
5789    private native boolean  nativeCursorWantsKeyEvents();
5790    private native void     nativeDebugDump();
5791    private native void     nativeDestroy();
5792    private native void     nativeDrawCursorRing(Canvas content);
5793    private native void     nativeDrawMatches(Canvas canvas);
5794    private native void     nativeDrawSelectionPointer(Canvas content,
5795            float scale, int x, int y, boolean extendSelection);
5796    private native void     nativeDrawSelectionRegion(Canvas content);
5797    private native void     nativeDumpDisplayTree(String urlOrNull);
5798    private native int      nativeFindAll(String findLower, String findUpper);
5799    private native void     nativeFindNext(boolean forward);
5800    private native int      nativeFocusCandidateFramePointer();
5801    private native boolean  nativeFocusCandidateIsPassword();
5802    private native boolean  nativeFocusCandidateIsPlugin();
5803    private native boolean  nativeFocusCandidateIsRtlText();
5804    private native boolean  nativeFocusCandidateIsTextField();
5805    private native boolean  nativeFocusCandidateIsTextInput();
5806    private native int      nativeFocusCandidateMaxLength();
5807    /* package */ native String   nativeFocusCandidateName();
5808    private native Rect     nativeFocusCandidateNodeBounds();
5809    /* package */ native int nativeFocusCandidatePointer();
5810    private native String   nativeFocusCandidateText();
5811    private native int      nativeFocusCandidateTextSize();
5812    private native boolean  nativeFocusIsPlugin();
5813    /* package */ native int nativeFocusNodePointer();
5814    private native Rect     nativeGetCursorRingBounds();
5815    private native Region   nativeGetSelection();
5816    private native boolean  nativeHasCursorNode();
5817    private native boolean  nativeHasFocusNode();
5818    private native void     nativeHideCursor();
5819    private native String   nativeImageURI(int x, int y);
5820    private native void     nativeInstrumentReport();
5821    /* package */ native void nativeMoveCursorToNextTextInput();
5822    // return true if the page has been scrolled
5823    private native boolean  nativeMotionUp(int x, int y, int slop);
5824    // returns false if it handled the key
5825    private native boolean  nativeMoveCursor(int keyCode, int count,
5826            boolean noScroll);
5827    private native int      nativeMoveGeneration();
5828    private native void     nativeMoveSelection(int x, int y,
5829            boolean extendSelection);
5830    // Like many other of our native methods, you must make sure that
5831    // mNativeClass is not null before calling this method.
5832    private native void     nativeRecordButtons(boolean focused,
5833            boolean pressed, boolean invalidate);
5834    private native void     nativeSelectBestAt(Rect rect);
5835    private native void     nativeSetFindIsDown();
5836    private native void     nativeSetFollowedLink(boolean followed);
5837    private native void     nativeSetHeightCanMeasure(boolean measure);
5838    // Returns a value corresponding to CachedFrame::ImeAction
5839    /* package */ native int  nativeTextFieldAction();
5840    /**
5841     * Perform a click on a currently focused text input.  Since it is already
5842     * focused, there is no need to go through the nativeMotionUp code, which
5843     * may change the Cursor.
5844     */
5845    private native void     nativeTextInputMotionUp(int x, int y);
5846    private native int      nativeTextGeneration();
5847    // Never call this version except by updateCachedTextfield(String) -
5848    // we always want to pass in our generation number.
5849    private native void     nativeUpdateCachedTextfield(String updatedText,
5850            int generation);
5851    // return NO_LEFTEDGE means failure.
5852    private static final int NO_LEFTEDGE = -1;
5853    private native int      nativeGetBlockLeftEdge(int x, int y, float scale);
5854}
5855