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