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