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