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