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