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