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