WebView.java revision 7da0c067b87f92e4f3b849fabff201145dccf12b
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import android.annotation.Widget;
20import android.app.AlertDialog;
21import android.content.Context;
22import android.content.DialogInterface;
23import android.content.Intent;
24import android.content.DialogInterface.OnCancelListener;
25import android.content.pm.PackageManager;
26import android.database.DataSetObserver;
27import android.graphics.Bitmap;
28import android.graphics.BitmapFactory;
29import android.graphics.BitmapShader;
30import android.graphics.Canvas;
31import android.graphics.Color;
32import android.graphics.Interpolator;
33import android.graphics.Paint;
34import android.graphics.Picture;
35import android.graphics.Point;
36import android.graphics.Rect;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.Drawable;
40import android.net.Uri;
41import android.net.http.SslCertificate;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.Message;
45import android.os.ServiceManager;
46import android.os.SystemClock;
47import android.text.IClipboard;
48import android.text.Selection;
49import android.text.Spannable;
50import android.util.AttributeSet;
51import android.util.EventLog;
52import android.util.Log;
53import android.util.TypedValue;
54import android.view.Gravity;
55import android.view.KeyEvent;
56import android.view.LayoutInflater;
57import android.view.MotionEvent;
58import android.view.ScaleGestureDetector;
59import android.view.SoundEffectConstants;
60import android.view.VelocityTracker;
61import android.view.View;
62import android.view.ViewConfiguration;
63import android.view.ViewGroup;
64import android.view.ViewTreeObserver;
65import android.view.animation.AlphaAnimation;
66import android.view.inputmethod.EditorInfo;
67import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
69import android.webkit.WebTextView.AutoCompleteAdapter;
70import android.webkit.WebViewCore.EventHub;
71import android.webkit.WebViewCore.TouchEventData;
72import android.widget.AbsoluteLayout;
73import android.widget.Adapter;
74import android.widget.AdapterView;
75import android.widget.ArrayAdapter;
76import android.widget.CheckedTextView;
77import android.widget.FrameLayout;
78import android.widget.LinearLayout;
79import android.widget.ListView;
80import android.widget.Scroller;
81import android.widget.Toast;
82import android.widget.ZoomButtonsController;
83import android.widget.ZoomControls;
84import android.widget.AdapterView.OnItemClickListener;
85
86import java.io.File;
87import java.io.FileInputStream;
88import java.io.FileNotFoundException;
89import java.io.FileOutputStream;
90import java.io.IOException;
91import java.net.URLDecoder;
92import java.util.ArrayList;
93import java.util.HashMap;
94import java.util.List;
95import java.util.Map;
96import java.util.Set;
97
98import junit.framework.Assert;
99
100/**
101 * <p>A View that displays web pages. This class is the basis upon which you
102 * can roll your own web browser or simply display some online content within your Activity.
103 * It uses the WebKit rendering engine to display
104 * web pages and includes methods to navigate forward and backward
105 * through a history, zoom in and out, perform text searches and more.</p>
106 * <p>To enable the built-in zoom, set
107 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
108 * (introduced in API version 3).
109 * <p>Note that, in order for your Activity to access the Internet and load web pages
110 * in a WebView, you must add the <var>INTERNET</var> permissions to your
111 * Android Manifest file:</p>
112 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
113 *
114 * <p>This must be a child of the <code>&lt;manifest></code> element.</p>
115 *
116 * <h3>Basic usage</h3>
117 *
118 * <p>By default, a WebView provides no browser-like widgets, does not
119 * enable JavaScript and errors will be ignored. If your goal is only
120 * to display some HTML as a part of your UI, this is probably fine;
121 * the user won't need to interact with the web page beyond reading
122 * it, and the web page won't need to interact with the user. If you
123 * actually want a fully blown web browser, then you probably want to
124 * invoke the Browser application with your URL rather than show it
125 * with a WebView. See {@link android.content.Intent} for more information.</p>
126 *
127 * <pre class="prettyprint">
128 * WebView webview = new WebView(this);
129 * setContentView(webview);
130 *
131 * // Simplest usage: note that an exception will NOT be thrown
132 * // if there is an error loading this page (see below).
133 * webview.loadUrl("http://slashdot.org/");
134 *
135 * // Of course you can also load from any string:
136 * String summary = "&lt;html>&lt;body>You scored &lt;b>192</b> points.&lt;/body>&lt;/html>";
137 * webview.loadData(summary, "text/html", "utf-8");
138 * // ... although note that there are restrictions on what this HTML can do.
139 * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info.
140 * </pre>
141 *
142 * <p>A WebView has several customization points where you can add your
143 * own behavior. These are:</p>
144 *
145 * <ul>
146 *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
147 *       This class is called when something that might impact a
148 *       browser UI happens, for instance, progress updates and
149 *       JavaScript alerts are sent here.
150 *   </li>
151 *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
152 *       It will be called when things happen that impact the
153 *       rendering of the content, eg, errors or form submissions. You
154 *       can also intercept URL loading here.</li>
155 *   <li>Via the {@link android.webkit.WebSettings} class, which contains
156 *       miscellaneous configuration. </li>
157 *   <li>With the {@link android.webkit.WebView#addJavascriptInterface} method.
158 *       This lets you bind Java objects into the WebView so they can be
159 *       controlled from the web pages JavaScript.</li>
160 * </ul>
161 *
162 * <p>Here's a more complicated example, showing error handling,
163 *    settings, and progress notification:</p>
164 *
165 * <pre class="prettyprint">
166 * // Let's display the progress in the activity title bar, like the
167 * // browser app does.
168 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
169 *
170 * webview.getSettings().setJavaScriptEnabled(true);
171 *
172 * final Activity activity = this;
173 * webview.setWebChromeClient(new WebChromeClient() {
174 *   public void onProgressChanged(WebView view, int progress) {
175 *     // Activities and WebViews measure progress with different scales.
176 *     // The progress meter will automatically disappear when we reach 100%
177 *     activity.setProgress(progress * 1000);
178 *   }
179 * });
180 * webview.setWebViewClient(new WebViewClient() {
181 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
182 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
183 *   }
184 * });
185 *
186 * webview.loadUrl("http://slashdot.org/");
187 * </pre>
188 *
189 * <h3>Cookie and window management</h3>
190 *
191 * <p>For obvious security reasons, your application has its own
192 * cache, cookie store etc - it does not share the Browser
193 * applications data. Cookies are managed on a separate thread, so
194 * operations like index building don't block the UI
195 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
196 * if you want to use cookies in your application.
197 * </p>
198 *
199 * <p>By default, requests by the HTML to open new windows are
200 * ignored. This is true whether they be opened by JavaScript or by
201 * the target attribute on a link. You can customize your
202 * WebChromeClient to provide your own behaviour for opening multiple windows,
203 * and render them in whatever manner you want.</p>
204 *
205 * <p>Standard behavior for an Activity is to be destroyed and
206 * recreated when the devices orientation is changed. This will cause
207 * the WebView to reload the current page. If you don't want that, you
208 * can set your Activity to handle the orientation and keyboardHidden
209 * changes, and then just leave the WebView alone. It'll automatically
210 * re-orient itself as appropriate.</p>
211 */
212@Widget
213public class WebView extends AbsoluteLayout
214        implements ViewTreeObserver.OnGlobalFocusChangeListener,
215        ViewGroup.OnHierarchyChangeListener {
216
217    // enable debug output for drag trackers
218    private static final boolean DEBUG_DRAG_TRACKER = false;
219    // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
220    // the screen all-the-time. Good for profiling our drawing code
221    static private final boolean AUTO_REDRAW_HACK = false;
222    // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
223    private boolean mAutoRedraw;
224
225    static final String LOGTAG = "webview";
226
227    private static class ExtendedZoomControls extends FrameLayout {
228        public ExtendedZoomControls(Context context, AttributeSet attrs) {
229            super(context, attrs);
230            LayoutInflater inflater = (LayoutInflater)
231                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
232            inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true);
233            mPlusMinusZoomControls = (ZoomControls) findViewById(
234                    com.android.internal.R.id.zoomControls);
235            findViewById(com.android.internal.R.id.zoomMagnify).setVisibility(
236                    View.GONE);
237        }
238
239        public void show(boolean showZoom, boolean canZoomOut) {
240            mPlusMinusZoomControls.setVisibility(
241                    showZoom ? View.VISIBLE : View.GONE);
242            fade(View.VISIBLE, 0.0f, 1.0f);
243        }
244
245        public void hide() {
246            fade(View.GONE, 1.0f, 0.0f);
247        }
248
249        private void fade(int visibility, float startAlpha, float endAlpha) {
250            AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha);
251            anim.setDuration(500);
252            startAnimation(anim);
253            setVisibility(visibility);
254        }
255
256        public boolean hasFocus() {
257            return mPlusMinusZoomControls.hasFocus();
258        }
259
260        public void setOnZoomInClickListener(OnClickListener listener) {
261            mPlusMinusZoomControls.setOnZoomInClickListener(listener);
262        }
263
264        public void setOnZoomOutClickListener(OnClickListener listener) {
265            mPlusMinusZoomControls.setOnZoomOutClickListener(listener);
266        }
267
268        ZoomControls    mPlusMinusZoomControls;
269    }
270
271    /**
272     *  Transportation object for returning WebView across thread boundaries.
273     */
274    public class WebViewTransport {
275        private WebView mWebview;
276
277        /**
278         * Set the WebView to the transportation object.
279         * @param webview The WebView to transport.
280         */
281        public synchronized void setWebView(WebView webview) {
282            mWebview = webview;
283        }
284
285        /**
286         * Return the WebView object.
287         * @return WebView The transported WebView object.
288         */
289        public synchronized WebView getWebView() {
290            return mWebview;
291        }
292    }
293
294    // A final CallbackProxy shared by WebViewCore and BrowserFrame.
295    private final CallbackProxy mCallbackProxy;
296
297    private final WebViewDatabase mDatabase;
298
299    // SSL certificate for the main top-level page (if secure)
300    private SslCertificate mCertificate;
301
302    // Native WebView pointer that is 0 until the native object has been
303    // created.
304    private int mNativeClass;
305    // This would be final but it needs to be set to null when the WebView is
306    // destroyed.
307    private WebViewCore mWebViewCore;
308    // Handler for dispatching UI messages.
309    /* package */ final Handler mPrivateHandler = new PrivateHandler();
310    private WebTextView mWebTextView;
311    // Used to ignore changes to webkit text that arrives to the UI side after
312    // more key events.
313    private int mTextGeneration;
314
315    // Used by WebViewCore to create child views.
316    /* package */ final ViewManager mViewManager;
317
318    // Used to display in full screen mode
319    PluginFullScreenHolder mFullScreenHolder;
320
321    /**
322     * Position of the last touch event.
323     */
324    private float mLastTouchX;
325    private float mLastTouchY;
326
327    /**
328     * Time of the last touch event.
329     */
330    private long mLastTouchTime;
331
332    /**
333     * Time of the last time sending touch event to WebViewCore
334     */
335    private long mLastSentTouchTime;
336
337    /**
338     * The minimum elapsed time before sending another ACTION_MOVE event to
339     * WebViewCore. This really should be tuned for each type of the devices.
340     * For example in Google Map api test case, it takes Dream device at least
341     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
342     * triggering the layout and drawing the picture. While the same process
343     * takes 60+ms on the current high speed device. If we make
344     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
345     * to WebViewCore queue and the real layout and draw events will be pushed
346     * to further, which slows down the refresh rate. Choose 50 to favor the
347     * current high speed devices. For Dream like devices, 100 is a better
348     * choice. Maybe make this in the buildspec later.
349     */
350    private static final int TOUCH_SENT_INTERVAL = 50;
351    private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL;
352
353    /**
354     * Helper class to get velocity for fling
355     */
356    VelocityTracker mVelocityTracker;
357    private int mMaximumFling;
358    private float mLastVelocity;
359    private float mLastVelX;
360    private float mLastVelY;
361
362    /**
363     * Touch mode
364     */
365    private int mTouchMode = TOUCH_DONE_MODE;
366    private static final int TOUCH_INIT_MODE = 1;
367    private static final int TOUCH_DRAG_START_MODE = 2;
368    private static final int TOUCH_DRAG_MODE = 3;
369    private static final int TOUCH_SHORTPRESS_START_MODE = 4;
370    private static final int TOUCH_SHORTPRESS_MODE = 5;
371    private static final int TOUCH_DOUBLE_TAP_MODE = 6;
372    private static final int TOUCH_DONE_MODE = 7;
373    private static final int TOUCH_SELECT_MODE = 8;
374    private static final int TOUCH_PINCH_DRAG = 9;
375
376    // Whether to forward the touch events to WebCore
377    private boolean mForwardTouchEvents = false;
378
379    // Whether to prevent default during touch. The initial value depends on
380    // mForwardTouchEvents. If WebCore wants all the touch events, it says yes
381    // for touch down. Otherwise UI will wait for the answer of the first
382    // confirmed move before taking over the control.
383    private static final int PREVENT_DEFAULT_NO = 0;
384    private static final int PREVENT_DEFAULT_MAYBE_YES = 1;
385    private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2;
386    private static final int PREVENT_DEFAULT_YES = 3;
387    private static final int PREVENT_DEFAULT_IGNORE = 4;
388    private int mPreventDefault = PREVENT_DEFAULT_IGNORE;
389
390    // true when the touch movement exceeds the slop
391    private boolean mConfirmMove;
392
393    // if true, touch events will be first processed by WebCore, if prevent
394    // default is not set, the UI will continue handle them.
395    private boolean mDeferTouchProcess;
396
397    // to avoid interfering with the current touch events, track them
398    // separately. Currently no snapping or fling in the deferred process mode
399    private int mDeferTouchMode = TOUCH_DONE_MODE;
400    private float mLastDeferTouchX;
401    private float mLastDeferTouchY;
402
403    // To keep track of whether the current drag was initiated by a WebTextView,
404    // so that we know not to hide the cursor
405    boolean mDragFromTextInput;
406
407    // Whether or not to draw the cursor ring.
408    private boolean mDrawCursorRing = true;
409
410    // true if onPause has been called (and not onResume)
411    private boolean mIsPaused;
412
413    // true if, during a transition to a new page, we're delaying
414    // deleting a root layer until there's something to draw of the new page.
415    private boolean mDelayedDeleteRootLayer;
416
417    /**
418     * Customizable constant
419     */
420    // pre-computed square of ViewConfiguration.getScaledTouchSlop()
421    private int mTouchSlopSquare;
422    // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
423    private int mDoubleTapSlopSquare;
424    // pre-computed density adjusted navigation slop
425    private int mNavSlop;
426    // This should be ViewConfiguration.getTapTimeout()
427    // But system time out is 100ms, which is too short for the browser.
428    // In the browser, if it switches out of tap too soon, jump tap won't work.
429    private static final int TAP_TIMEOUT = 200;
430    // This should be ViewConfiguration.getLongPressTimeout()
431    // But system time out is 500ms, which is too short for the browser.
432    // With a short timeout, it's difficult to treat trigger a short press.
433    private static final int LONG_PRESS_TIMEOUT = 1000;
434    // needed to avoid flinging after a pause of no movement
435    private static final int MIN_FLING_TIME = 250;
436    // draw unfiltered after drag is held without movement
437    private static final int MOTIONLESS_TIME = 100;
438    // The time that the Zoom Controls are visible before fading away
439    private static final long ZOOM_CONTROLS_TIMEOUT =
440            ViewConfiguration.getZoomControlsTimeout();
441    // The amount of content to overlap between two screens when going through
442    // pages with the space bar, in pixels.
443    private static final int PAGE_SCROLL_OVERLAP = 24;
444
445    /**
446     * These prevent calling requestLayout if either dimension is fixed. This
447     * depends on the layout parameters and the measure specs.
448     */
449    boolean mWidthCanMeasure;
450    boolean mHeightCanMeasure;
451
452    // Remember the last dimensions we sent to the native side so we can avoid
453    // sending the same dimensions more than once.
454    int mLastWidthSent;
455    int mLastHeightSent;
456
457    private int mContentWidth;   // cache of value from WebViewCore
458    private int mContentHeight;  // cache of value from WebViewCore
459
460    // Need to have the separate control for horizontal and vertical scrollbar
461    // style than the View's single scrollbar style
462    private boolean mOverlayHorizontalScrollbar = true;
463    private boolean mOverlayVerticalScrollbar = false;
464
465    // our standard speed. this way small distances will be traversed in less
466    // time than large distances, but we cap the duration, so that very large
467    // distances won't take too long to get there.
468    private static final int STD_SPEED = 480;  // pixels per second
469    // time for the longest scroll animation
470    private static final int MAX_DURATION = 750;   // milliseconds
471    private static final int SLIDE_TITLE_DURATION = 500;   // milliseconds
472    private Scroller mScroller;
473
474    private boolean mWrapContent;
475    private static final int MOTIONLESS_FALSE           = 0;
476    private static final int MOTIONLESS_PENDING         = 1;
477    private static final int MOTIONLESS_TRUE            = 2;
478    private static final int MOTIONLESS_IGNORE          = 3;
479    private int mHeldMotionless;
480
481    // whether support multi-touch
482    private boolean mSupportMultiTouch;
483    // use the framework's ScaleGestureDetector to handle multi-touch
484    private ScaleGestureDetector mScaleDetector;
485
486    // the anchor point in the document space where VIEW_SIZE_CHANGED should
487    // apply to
488    private int mAnchorX;
489    private int mAnchorY;
490
491    /*
492     * Private message ids
493     */
494    private static final int REMEMBER_PASSWORD          = 1;
495    private static final int NEVER_REMEMBER_PASSWORD    = 2;
496    private static final int SWITCH_TO_SHORTPRESS       = 3;
497    private static final int SWITCH_TO_LONGPRESS        = 4;
498    private static final int RELEASE_SINGLE_TAP         = 5;
499    private static final int REQUEST_FORM_DATA          = 6;
500    private static final int RESUME_WEBCORE_PRIORITY    = 7;
501    private static final int DRAG_HELD_MOTIONLESS       = 8;
502    private static final int AWAKEN_SCROLL_BARS         = 9;
503    private static final int PREVENT_DEFAULT_TIMEOUT    = 10;
504
505    private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
506    private static final int LAST_PRIVATE_MSG_ID = PREVENT_DEFAULT_TIMEOUT;
507
508    /*
509     * Package message ids
510     */
511    //! arg1=x, arg2=y
512    static final int SCROLL_TO_MSG_ID                   = 101;
513    static final int SCROLL_BY_MSG_ID                   = 102;
514    //! arg1=x, arg2=y
515    static final int SPAWN_SCROLL_TO_MSG_ID             = 103;
516    //! arg1=x, arg2=y
517    static final int SYNC_SCROLL_TO_MSG_ID              = 104;
518    static final int NEW_PICTURE_MSG_ID                 = 105;
519    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 106;
520    static final int WEBCORE_INITIALIZED_MSG_ID         = 107;
521    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 108;
522    static final int UPDATE_ZOOM_RANGE                  = 109;
523    static final int MOVE_OUT_OF_PLUGIN                 = 110;
524    static final int CLEAR_TEXT_ENTRY                   = 111;
525    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 112;
526    static final int SHOW_RECT_MSG_ID                   = 113;
527    static final int LONG_PRESS_CENTER                  = 114;
528    static final int PREVENT_TOUCH_ID                   = 115;
529    static final int WEBCORE_NEED_TOUCH_EVENTS          = 116;
530    // obj=Rect in doc coordinates
531    static final int INVAL_RECT_MSG_ID                  = 117;
532    static final int REQUEST_KEYBOARD                   = 118;
533    static final int DO_MOTION_UP                       = 119;
534    static final int SHOW_FULLSCREEN                    = 120;
535    static final int HIDE_FULLSCREEN                    = 121;
536    static final int DOM_FOCUS_CHANGED                  = 122;
537    static final int IMMEDIATE_REPAINT_MSG_ID           = 123;
538    static final int SET_ROOT_LAYER_MSG_ID              = 124;
539    static final int RETURN_LABEL                       = 125;
540    static final int FIND_AGAIN                         = 126;
541    static final int CENTER_FIT_RECT                    = 127;
542    static final int REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID = 128;
543    static final int SET_SCROLLBAR_MODES                = 129;
544
545    private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
546    private static final int LAST_PACKAGE_MSG_ID = SET_SCROLLBAR_MODES;
547
548    static final String[] HandlerPrivateDebugString = {
549        "REMEMBER_PASSWORD", //              = 1;
550        "NEVER_REMEMBER_PASSWORD", //        = 2;
551        "SWITCH_TO_SHORTPRESS", //           = 3;
552        "SWITCH_TO_LONGPRESS", //            = 4;
553        "RELEASE_SINGLE_TAP", //             = 5;
554        "REQUEST_FORM_DATA", //              = 6;
555        "RESUME_WEBCORE_PRIORITY", //        = 7;
556        "DRAG_HELD_MOTIONLESS", //           = 8;
557        "AWAKEN_SCROLL_BARS", //             = 9;
558        "PREVENT_DEFAULT_TIMEOUT" //         = 10;
559    };
560
561    static final String[] HandlerPackageDebugString = {
562        "SCROLL_TO_MSG_ID", //               = 101;
563        "SCROLL_BY_MSG_ID", //               = 102;
564        "SPAWN_SCROLL_TO_MSG_ID", //         = 103;
565        "SYNC_SCROLL_TO_MSG_ID", //          = 104;
566        "NEW_PICTURE_MSG_ID", //             = 105;
567        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 106;
568        "WEBCORE_INITIALIZED_MSG_ID", //     = 107;
569        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 108;
570        "UPDATE_ZOOM_RANGE", //              = 109;
571        "MOVE_OUT_OF_PLUGIN", //             = 110;
572        "CLEAR_TEXT_ENTRY", //               = 111;
573        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 112;
574        "SHOW_RECT_MSG_ID", //               = 113;
575        "LONG_PRESS_CENTER", //              = 114;
576        "PREVENT_TOUCH_ID", //               = 115;
577        "WEBCORE_NEED_TOUCH_EVENTS", //      = 116;
578        "INVAL_RECT_MSG_ID", //              = 117;
579        "REQUEST_KEYBOARD", //               = 118;
580        "DO_MOTION_UP", //                   = 119;
581        "SHOW_FULLSCREEN", //                = 120;
582        "HIDE_FULLSCREEN", //                = 121;
583        "DOM_FOCUS_CHANGED", //              = 122;
584        "IMMEDIATE_REPAINT_MSG_ID", //       = 123;
585        "SET_ROOT_LAYER_MSG_ID", //          = 124;
586        "RETURN_LABEL", //                   = 125;
587        "FIND_AGAIN", //                     = 126;
588        "CENTER_FIT_RECT", //                = 127;
589        "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128;
590        "SET_SCROLLBAR_MODES" //             = 129;
591    };
592
593    // If the site doesn't use the viewport meta tag to specify the viewport,
594    // use DEFAULT_VIEWPORT_WIDTH as the default viewport width
595    static final int DEFAULT_VIEWPORT_WIDTH = 800;
596
597    // normally we try to fit the content to the minimum preferred width
598    // calculated by the Webkit. To avoid the bad behavior when some site's
599    // minimum preferred width keeps growing when changing the viewport width or
600    // the minimum preferred width is huge, an upper limit is needed.
601    static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH;
602
603    // default scale limit. Depending on the display density
604    private static float DEFAULT_MAX_ZOOM_SCALE;
605    private static float DEFAULT_MIN_ZOOM_SCALE;
606    // scale limit, which can be set through viewport meta tag in the web page
607    private float mMaxZoomScale;
608    private float mMinZoomScale;
609    private boolean mMinZoomScaleFixed = true;
610
611    // initial scale in percent. 0 means using default.
612    private int mInitialScaleInPercent = 0;
613
614    // while in the zoom overview mode, the page's width is fully fit to the
615    // current window. The page is alive, in another words, you can click to
616    // follow the links. Double tap will toggle between zoom overview mode and
617    // the last zoom scale.
618    boolean mInZoomOverview = false;
619
620    // ideally mZoomOverviewWidth should be mContentWidth. But sites like espn,
621    // engadget always have wider mContentWidth no matter what viewport size is.
622    int mZoomOverviewWidth = DEFAULT_VIEWPORT_WIDTH;
623    float mTextWrapScale;
624
625    // default scale. Depending on the display density.
626    static int DEFAULT_SCALE_PERCENT;
627    private float mDefaultScale;
628
629    private static float MINIMUM_SCALE_INCREMENT = 0.01f;
630
631    // set to true temporarily during ScaleGesture triggered zoom
632    private boolean mPreviewZoomOnly = false;
633
634    // computed scale and inverse, from mZoomWidth.
635    private float mActualScale;
636    private float mInvActualScale;
637    // if this is non-zero, it is used on drawing rather than mActualScale
638    private float mZoomScale;
639    private float mInvInitialZoomScale;
640    private float mInvFinalZoomScale;
641    private int mInitialScrollX;
642    private int mInitialScrollY;
643    private long mZoomStart;
644    private static final int ZOOM_ANIMATION_LENGTH = 500;
645
646    private boolean mUserScroll = false;
647
648    private int mSnapScrollMode = SNAP_NONE;
649    private static final int SNAP_NONE = 0;
650    private static final int SNAP_LOCK = 1; // not a separate state
651    private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
652    private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
653    private boolean mSnapPositive;
654
655    // keep these in sync with their counterparts in WebView.cpp
656    private static final int DRAW_EXTRAS_NONE = 0;
657    private static final int DRAW_EXTRAS_FIND = 1;
658    private static final int DRAW_EXTRAS_SELECTION = 2;
659    private static final int DRAW_EXTRAS_CURSOR_RING = 3;
660
661    // keep this in sync with WebCore:ScrollbarMode in WebKit
662    private static final int SCROLLBAR_AUTO = 0;
663    private static final int SCROLLBAR_ALWAYSOFF = 1;
664    // as we auto fade scrollbar, this is ignored.
665    private static final int SCROLLBAR_ALWAYSON = 2;
666    private int mHorizontalScrollBarMode = SCROLLBAR_AUTO;
667    private int mVerticalScrollBarMode = SCROLLBAR_AUTO;
668
669    // Used to match key downs and key ups
670    private boolean mGotKeyDown;
671
672    /* package */ static boolean mLogEvent = true;
673
674    // for event log
675    private long mLastTouchUpTime = 0;
676
677    /**
678     * URI scheme for telephone number
679     */
680    public static final String SCHEME_TEL = "tel:";
681    /**
682     * URI scheme for email address
683     */
684    public static final String SCHEME_MAILTO = "mailto:";
685    /**
686     * URI scheme for map address
687     */
688    public static final String SCHEME_GEO = "geo:0,0?q=";
689
690    private int mBackgroundColor = Color.WHITE;
691
692    // Used to notify listeners of a new picture.
693    private PictureListener mPictureListener;
694    /**
695     * Interface to listen for new pictures as they change.
696     */
697    public interface PictureListener {
698        /**
699         * Notify the listener that the picture has changed.
700         * @param view The WebView that owns the picture.
701         * @param picture The new picture.
702         */
703        public void onNewPicture(WebView view, Picture picture);
704    }
705
706    // FIXME: Want to make this public, but need to change the API file.
707    public /*static*/ class HitTestResult {
708        /**
709         * Default HitTestResult, where the target is unknown
710         */
711        public static final int UNKNOWN_TYPE = 0;
712        /**
713         * HitTestResult for hitting a HTML::a tag
714         */
715        public static final int ANCHOR_TYPE = 1;
716        /**
717         * HitTestResult for hitting a phone number
718         */
719        public static final int PHONE_TYPE = 2;
720        /**
721         * HitTestResult for hitting a map address
722         */
723        public static final int GEO_TYPE = 3;
724        /**
725         * HitTestResult for hitting an email address
726         */
727        public static final int EMAIL_TYPE = 4;
728        /**
729         * HitTestResult for hitting an HTML::img tag
730         */
731        public static final int IMAGE_TYPE = 5;
732        /**
733         * HitTestResult for hitting a HTML::a tag which contains HTML::img
734         */
735        public static final int IMAGE_ANCHOR_TYPE = 6;
736        /**
737         * HitTestResult for hitting a HTML::a tag with src=http
738         */
739        public static final int SRC_ANCHOR_TYPE = 7;
740        /**
741         * HitTestResult for hitting a HTML::a tag with src=http + HTML::img
742         */
743        public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
744        /**
745         * HitTestResult for hitting an edit text area
746         */
747        public static final int EDIT_TEXT_TYPE = 9;
748
749        private int mType;
750        private String mExtra;
751
752        HitTestResult() {
753            mType = UNKNOWN_TYPE;
754        }
755
756        private void setType(int type) {
757            mType = type;
758        }
759
760        private void setExtra(String extra) {
761            mExtra = extra;
762        }
763
764        public int getType() {
765            return mType;
766        }
767
768        public String getExtra() {
769            return mExtra;
770        }
771    }
772
773    // The View containing the zoom controls
774    private ExtendedZoomControls mZoomControls;
775    private Runnable mZoomControlRunnable;
776
777    // mZoomButtonsController will be lazy initialized in
778    // getZoomButtonsController() to get better performance.
779    private ZoomButtonsController mZoomButtonsController;
780
781    // These keep track of the center point of the zoom.  They are used to
782    // determine the point around which we should zoom.
783    private float mZoomCenterX;
784    private float mZoomCenterY;
785
786    private ZoomButtonsController.OnZoomListener mZoomListener =
787            new ZoomButtonsController.OnZoomListener() {
788
789        public void onVisibilityChanged(boolean visible) {
790            if (visible) {
791                switchOutDrawHistory();
792                // Bring back the hidden zoom controls.
793                mZoomButtonsController.getZoomControls().setVisibility(
794                        View.VISIBLE);
795                updateZoomButtonsEnabled();
796            }
797        }
798
799        public void onZoom(boolean zoomIn) {
800            if (zoomIn) {
801                zoomIn();
802            } else {
803                zoomOut();
804            }
805
806            updateZoomButtonsEnabled();
807        }
808    };
809
810    /**
811     * Construct a new WebView with a Context object.
812     * @param context A Context object used to access application assets.
813     */
814    public WebView(Context context) {
815        this(context, null);
816    }
817
818    /**
819     * Construct a new WebView with layout parameters.
820     * @param context A Context object used to access application assets.
821     * @param attrs An AttributeSet passed to our parent.
822     */
823    public WebView(Context context, AttributeSet attrs) {
824        this(context, attrs, com.android.internal.R.attr.webViewStyle);
825    }
826
827    /**
828     * Construct a new WebView with layout parameters and a default style.
829     * @param context A Context object used to access application assets.
830     * @param attrs An AttributeSet passed to our parent.
831     * @param defStyle The default style resource ID.
832     */
833    public WebView(Context context, AttributeSet attrs, int defStyle) {
834        this(context, attrs, defStyle, null);
835    }
836
837    /**
838     * Construct a new WebView with layout parameters, a default style and a set
839     * of custom Javscript interfaces to be added to the WebView at initialization
840     * time. This guarantees that these interfaces will be available when the JS
841     * context is initialized.
842     * @param context A Context object used to access application assets.
843     * @param attrs An AttributeSet passed to our parent.
844     * @param defStyle The default style resource ID.
845     * @param javascriptInterfaces is a Map of intareface names, as keys, and
846     * object implementing those interfaces, as values.
847     * @hide pending API council approval.
848     */
849    protected WebView(Context context, AttributeSet attrs, int defStyle,
850            Map<String, Object> javascriptInterfaces) {
851        super(context, attrs, defStyle);
852        init();
853
854        mCallbackProxy = new CallbackProxy(context, this);
855        mViewManager = new ViewManager(this);
856        mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces);
857        mDatabase = WebViewDatabase.getInstance(context);
858        mScroller = new Scroller(context);
859
860        updateMultiTouchSupport(context);
861    }
862
863    void updateMultiTouchSupport(Context context) {
864        WebSettings settings = getSettings();
865        mSupportMultiTouch = context.getPackageManager().hasSystemFeature(
866                PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)
867                && settings.supportZoom() && settings.getBuiltInZoomControls();
868        if (mSupportMultiTouch && (mScaleDetector == null)) {
869            mScaleDetector = new ScaleGestureDetector(context,
870                    new ScaleDetectorListener());
871        } else if (!mSupportMultiTouch && (mScaleDetector != null)) {
872            mScaleDetector = null;
873        }
874    }
875
876    private void updateZoomButtonsEnabled() {
877        if (mZoomButtonsController == null) return;
878        boolean canZoomIn = mActualScale < mMaxZoomScale;
879        boolean canZoomOut = mActualScale > mMinZoomScale && !mInZoomOverview;
880        if (!canZoomIn && !canZoomOut) {
881            // Hide the zoom in and out buttons, as well as the fit to page
882            // button, if the page cannot zoom
883            mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
884        } else {
885            // Set each one individually, as a page may be able to zoom in
886            // or out.
887            mZoomButtonsController.setZoomInEnabled(canZoomIn);
888            mZoomButtonsController.setZoomOutEnabled(canZoomOut);
889        }
890    }
891
892    private void init() {
893        setWillNotDraw(false);
894        setFocusable(true);
895        setFocusableInTouchMode(true);
896        setClickable(true);
897        setLongClickable(true);
898
899        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
900        int slop = configuration.getScaledTouchSlop();
901        mTouchSlopSquare = slop * slop;
902        mMinLockSnapReverseDistance = slop;
903        slop = configuration.getScaledDoubleTapSlop();
904        mDoubleTapSlopSquare = slop * slop;
905        final float density = getContext().getResources().getDisplayMetrics().density;
906        // use one line height, 16 based on our current default font, for how
907        // far we allow a touch be away from the edge of a link
908        mNavSlop = (int) (16 * density);
909        // density adjusted scale factors
910        DEFAULT_SCALE_PERCENT = (int) (100 * density);
911        mDefaultScale = density;
912        mActualScale = density;
913        mInvActualScale = 1 / density;
914        mTextWrapScale = density;
915        DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
916        DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
917        mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
918        mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
919        mMaximumFling = configuration.getScaledMaximumFlingVelocity();
920    }
921
922    /* package */void updateDefaultZoomDensity(int zoomDensity) {
923        final float density = getContext().getResources().getDisplayMetrics().density
924                * 100 / zoomDensity;
925        if (Math.abs(density - mDefaultScale) > 0.01) {
926            float scaleFactor = density / mDefaultScale;
927            // adjust the limits
928            mNavSlop = (int) (16 * density);
929            DEFAULT_SCALE_PERCENT = (int) (100 * density);
930            DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
931            DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
932            mDefaultScale = density;
933            mMaxZoomScale *= scaleFactor;
934            mMinZoomScale *= scaleFactor;
935            setNewZoomScale(mActualScale * scaleFactor, true, false);
936        }
937    }
938
939    /* package */ boolean onSavePassword(String schemePlusHost, String username,
940            String password, final Message resumeMsg) {
941       boolean rVal = false;
942       if (resumeMsg == null) {
943           // null resumeMsg implies saving password silently
944           mDatabase.setUsernamePassword(schemePlusHost, username, password);
945       } else {
946            final Message remember = mPrivateHandler.obtainMessage(
947                    REMEMBER_PASSWORD);
948            remember.getData().putString("host", schemePlusHost);
949            remember.getData().putString("username", username);
950            remember.getData().putString("password", password);
951            remember.obj = resumeMsg;
952
953            final Message neverRemember = mPrivateHandler.obtainMessage(
954                    NEVER_REMEMBER_PASSWORD);
955            neverRemember.getData().putString("host", schemePlusHost);
956            neverRemember.getData().putString("username", username);
957            neverRemember.getData().putString("password", password);
958            neverRemember.obj = resumeMsg;
959
960            new AlertDialog.Builder(getContext())
961                    .setTitle(com.android.internal.R.string.save_password_label)
962                    .setMessage(com.android.internal.R.string.save_password_message)
963                    .setPositiveButton(com.android.internal.R.string.save_password_notnow,
964                    new DialogInterface.OnClickListener() {
965                        public void onClick(DialogInterface dialog, int which) {
966                            resumeMsg.sendToTarget();
967                        }
968                    })
969                    .setNeutralButton(com.android.internal.R.string.save_password_remember,
970                    new DialogInterface.OnClickListener() {
971                        public void onClick(DialogInterface dialog, int which) {
972                            remember.sendToTarget();
973                        }
974                    })
975                    .setNegativeButton(com.android.internal.R.string.save_password_never,
976                    new DialogInterface.OnClickListener() {
977                        public void onClick(DialogInterface dialog, int which) {
978                            neverRemember.sendToTarget();
979                        }
980                    })
981                    .setOnCancelListener(new OnCancelListener() {
982                        public void onCancel(DialogInterface dialog) {
983                            resumeMsg.sendToTarget();
984                        }
985                    }).show();
986            // Return true so that WebViewCore will pause while the dialog is
987            // up.
988            rVal = true;
989        }
990       return rVal;
991    }
992
993    @Override
994    public void setScrollBarStyle(int style) {
995        if (style == View.SCROLLBARS_INSIDE_INSET
996                || style == View.SCROLLBARS_OUTSIDE_INSET) {
997            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
998        } else {
999            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
1000        }
1001        super.setScrollBarStyle(style);
1002    }
1003
1004    /**
1005     * Specify whether the horizontal scrollbar has overlay style.
1006     * @param overlay TRUE if horizontal scrollbar should have overlay style.
1007     */
1008    public void setHorizontalScrollbarOverlay(boolean overlay) {
1009        mOverlayHorizontalScrollbar = overlay;
1010    }
1011
1012    /**
1013     * Specify whether the vertical scrollbar has overlay style.
1014     * @param overlay TRUE if vertical scrollbar should have overlay style.
1015     */
1016    public void setVerticalScrollbarOverlay(boolean overlay) {
1017        mOverlayVerticalScrollbar = overlay;
1018    }
1019
1020    /**
1021     * Return whether horizontal scrollbar has overlay style
1022     * @return TRUE if horizontal scrollbar has overlay style.
1023     */
1024    public boolean overlayHorizontalScrollbar() {
1025        return mOverlayHorizontalScrollbar;
1026    }
1027
1028    /**
1029     * Return whether vertical scrollbar has overlay style
1030     * @return TRUE if vertical scrollbar has overlay style.
1031     */
1032    public boolean overlayVerticalScrollbar() {
1033        return mOverlayVerticalScrollbar;
1034    }
1035
1036    /*
1037     * Return the width of the view where the content of WebView should render
1038     * to.
1039     * Note: this can be called from WebCoreThread.
1040     */
1041    /* package */ int getViewWidth() {
1042        if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
1043            return getWidth();
1044        } else {
1045            return getWidth() - getVerticalScrollbarWidth();
1046        }
1047    }
1048
1049    /*
1050     * returns the height of the titlebarview (if any). Does not care about
1051     * scrolling
1052     */
1053    private int getTitleHeight() {
1054        return mTitleBar != null ? mTitleBar.getHeight() : 0;
1055    }
1056
1057    /*
1058     * Return the amount of the titlebarview (if any) that is visible
1059     */
1060    private int getVisibleTitleHeight() {
1061        return Math.max(getTitleHeight() - mScrollY, 0);
1062    }
1063
1064    /*
1065     * Return the height of the view where the content of WebView should render
1066     * to.  Note that this excludes mTitleBar, if there is one.
1067     * Note: this can be called from WebCoreThread.
1068     */
1069    /* package */ int getViewHeight() {
1070        return getViewHeightWithTitle() - getVisibleTitleHeight();
1071    }
1072
1073    private int getViewHeightWithTitle() {
1074        int height = getHeight();
1075        if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
1076            height -= getHorizontalScrollbarHeight();
1077        }
1078        return height;
1079    }
1080
1081    /**
1082     * @return The SSL certificate for the main top-level page or null if
1083     * there is no certificate (the site is not secure).
1084     */
1085    public SslCertificate getCertificate() {
1086        return mCertificate;
1087    }
1088
1089    /**
1090     * Sets the SSL certificate for the main top-level page.
1091     */
1092    public void setCertificate(SslCertificate certificate) {
1093        if (DebugFlags.WEB_VIEW) {
1094            Log.v(LOGTAG, "setCertificate=" + certificate);
1095        }
1096        // here, the certificate can be null (if the site is not secure)
1097        mCertificate = certificate;
1098    }
1099
1100    //-------------------------------------------------------------------------
1101    // Methods called by activity
1102    //-------------------------------------------------------------------------
1103
1104    /**
1105     * Save the username and password for a particular host in the WebView's
1106     * internal database.
1107     * @param host The host that required the credentials.
1108     * @param username The username for the given host.
1109     * @param password The password for the given host.
1110     */
1111    public void savePassword(String host, String username, String password) {
1112        mDatabase.setUsernamePassword(host, username, password);
1113    }
1114
1115    /**
1116     * Set the HTTP authentication credentials for a given host and realm.
1117     *
1118     * @param host The host for the credentials.
1119     * @param realm The realm for the credentials.
1120     * @param username The username for the password. If it is null, it means
1121     *                 password can't be saved.
1122     * @param password The password
1123     */
1124    public void setHttpAuthUsernamePassword(String host, String realm,
1125            String username, String password) {
1126        mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
1127    }
1128
1129    /**
1130     * Retrieve the HTTP authentication username and password for a given
1131     * host & realm pair
1132     *
1133     * @param host The host for which the credentials apply.
1134     * @param realm The realm for which the credentials apply.
1135     * @return String[] if found, String[0] is username, which can be null and
1136     *         String[1] is password. Return null if it can't find anything.
1137     */
1138    public String[] getHttpAuthUsernamePassword(String host, String realm) {
1139        return mDatabase.getHttpAuthUsernamePassword(host, realm);
1140    }
1141
1142    /**
1143     * Destroy the internal state of the WebView. This method should be called
1144     * after the WebView has been removed from the view system. No other
1145     * methods may be called on a WebView after destroy.
1146     */
1147    public void destroy() {
1148        clearTextEntry(false);
1149        if (mWebViewCore != null) {
1150            // Set the handlers to null before destroying WebViewCore so no
1151            // more messages will be posted.
1152            mCallbackProxy.setWebViewClient(null);
1153            mCallbackProxy.setWebChromeClient(null);
1154            // Tell WebViewCore to destroy itself
1155            synchronized (this) {
1156                WebViewCore webViewCore = mWebViewCore;
1157                mWebViewCore = null; // prevent using partial webViewCore
1158                webViewCore.destroy();
1159            }
1160            // Remove any pending messages that might not be serviced yet.
1161            mPrivateHandler.removeCallbacksAndMessages(null);
1162            mCallbackProxy.removeCallbacksAndMessages(null);
1163            // Wake up the WebCore thread just in case it is waiting for a
1164            // javascript dialog.
1165            synchronized (mCallbackProxy) {
1166                mCallbackProxy.notify();
1167            }
1168        }
1169        if (mNativeClass != 0) {
1170            nativeDestroy();
1171            mNativeClass = 0;
1172        }
1173    }
1174
1175    /**
1176     * Enables platform notifications of data state and proxy changes.
1177     */
1178    public static void enablePlatformNotifications() {
1179        Network.enablePlatformNotifications();
1180    }
1181
1182    /**
1183     * If platform notifications are enabled, this should be called
1184     * from the Activity's onPause() or onStop().
1185     */
1186    public static void disablePlatformNotifications() {
1187        Network.disablePlatformNotifications();
1188    }
1189
1190    /**
1191     * Sets JavaScript engine flags.
1192     *
1193     * @param flags JS engine flags in a String
1194     *
1195     * @hide pending API solidification
1196     */
1197    public void setJsFlags(String flags) {
1198        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
1199    }
1200
1201    /**
1202     * Inform WebView of the network state. This is used to set
1203     * the javascript property window.navigator.isOnline and
1204     * generates the online/offline event as specified in HTML5, sec. 5.7.7
1205     * @param networkUp boolean indicating if network is available
1206     */
1207    public void setNetworkAvailable(boolean networkUp) {
1208        mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
1209                networkUp ? 1 : 0, 0);
1210    }
1211
1212    /**
1213     * Inform WebView about the current network type.
1214     * {@hide}
1215     */
1216    public void setNetworkType(String type, String subtype) {
1217        Map<String, String> map = new HashMap<String, String>();
1218        map.put("type", type);
1219        map.put("subtype", subtype);
1220        mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map);
1221    }
1222    /**
1223     * Save the state of this WebView used in
1224     * {@link android.app.Activity#onSaveInstanceState}. Please note that this
1225     * method no longer stores the display data for this WebView. The previous
1226     * behavior could potentially leak files if {@link #restoreState} was never
1227     * called. See {@link #savePicture} and {@link #restorePicture} for saving
1228     * and restoring the display data.
1229     * @param outState The Bundle to store the WebView state.
1230     * @return The same copy of the back/forward list used to save the state. If
1231     *         saveState fails, the returned list will be null.
1232     * @see #savePicture
1233     * @see #restorePicture
1234     */
1235    public WebBackForwardList saveState(Bundle outState) {
1236        if (outState == null) {
1237            return null;
1238        }
1239        // We grab a copy of the back/forward list because a client of WebView
1240        // may have invalidated the history list by calling clearHistory.
1241        WebBackForwardList list = copyBackForwardList();
1242        final int currentIndex = list.getCurrentIndex();
1243        final int size = list.getSize();
1244        // We should fail saving the state if the list is empty or the index is
1245        // not in a valid range.
1246        if (currentIndex < 0 || currentIndex >= size || size == 0) {
1247            return null;
1248        }
1249        outState.putInt("index", currentIndex);
1250        // FIXME: This should just be a byte[][] instead of ArrayList but
1251        // Parcel.java does not have the code to handle multi-dimensional
1252        // arrays.
1253        ArrayList<byte[]> history = new ArrayList<byte[]>(size);
1254        for (int i = 0; i < size; i++) {
1255            WebHistoryItem item = list.getItemAtIndex(i);
1256            if (null == item) {
1257                // FIXME: this shouldn't happen
1258                // need to determine how item got set to null
1259                Log.w(LOGTAG, "saveState: Unexpected null history item.");
1260                return null;
1261            }
1262            byte[] data = item.getFlattenedData();
1263            if (data == null) {
1264                // It would be very odd to not have any data for a given history
1265                // item. And we will fail to rebuild the history list without
1266                // flattened data.
1267                return null;
1268            }
1269            history.add(data);
1270        }
1271        outState.putSerializable("history", history);
1272        if (mCertificate != null) {
1273            outState.putBundle("certificate",
1274                               SslCertificate.saveState(mCertificate));
1275        }
1276        return list;
1277    }
1278
1279    /**
1280     * Save the current display data to the Bundle given. Used in conjunction
1281     * with {@link #saveState}.
1282     * @param b A Bundle to store the display data.
1283     * @param dest The file to store the serialized picture data. Will be
1284     *             overwritten with this WebView's picture data.
1285     * @return True if the picture was successfully saved.
1286     */
1287    public boolean savePicture(Bundle b, final File dest) {
1288        if (dest == null || b == null) {
1289            return false;
1290        }
1291        final Picture p = capturePicture();
1292        // Use a temporary file while writing to ensure the destination file
1293        // contains valid data.
1294        final File temp = new File(dest.getPath() + ".writing");
1295        new Thread(new Runnable() {
1296            public void run() {
1297                try {
1298                    FileOutputStream out = new FileOutputStream(temp);
1299                    p.writeToStream(out);
1300                    out.close();
1301                    // Writing the picture succeeded, rename the temporary file
1302                    // to the destination.
1303                    temp.renameTo(dest);
1304                } catch (Exception e) {
1305                    // too late to do anything about it.
1306                } finally {
1307                    temp.delete();
1308                }
1309            }
1310        }).start();
1311        // now update the bundle
1312        b.putInt("scrollX", mScrollX);
1313        b.putInt("scrollY", mScrollY);
1314        b.putFloat("scale", mActualScale);
1315        b.putFloat("textwrapScale", mTextWrapScale);
1316        b.putBoolean("overview", mInZoomOverview);
1317        return true;
1318    }
1319
1320    private void restoreHistoryPictureFields(Picture p, Bundle b) {
1321        int sx = b.getInt("scrollX", 0);
1322        int sy = b.getInt("scrollY", 0);
1323        float scale = b.getFloat("scale", 1.0f);
1324        mDrawHistory = true;
1325        mHistoryPicture = p;
1326        mScrollX = sx;
1327        mScrollY = sy;
1328        mHistoryWidth = Math.round(p.getWidth() * scale);
1329        mHistoryHeight = Math.round(p.getHeight() * scale);
1330        // as getWidth() / getHeight() of the view are not available yet, set up
1331        // mActualScale, so that when onSizeChanged() is called, the rest will
1332        // be set correctly
1333        mActualScale = scale;
1334        mInvActualScale = 1 / scale;
1335        mTextWrapScale = b.getFloat("textwrapScale", scale);
1336        mInZoomOverview = b.getBoolean("overview");
1337        invalidate();
1338    }
1339
1340    /**
1341     * Restore the display data that was save in {@link #savePicture}. Used in
1342     * conjunction with {@link #restoreState}.
1343     * @param b A Bundle containing the saved display data.
1344     * @param src The file where the picture data was stored.
1345     * @return True if the picture was successfully restored.
1346     */
1347    public boolean restorePicture(Bundle b, File src) {
1348        if (src == null || b == null) {
1349            return false;
1350        }
1351        if (!src.exists()) {
1352            return false;
1353        }
1354        try {
1355            final FileInputStream in = new FileInputStream(src);
1356            final Bundle copy = new Bundle(b);
1357            new Thread(new Runnable() {
1358                public void run() {
1359                    final Picture p = Picture.createFromStream(in);
1360                    if (p != null) {
1361                        // Post a runnable on the main thread to update the
1362                        // history picture fields.
1363                        mPrivateHandler.post(new Runnable() {
1364                            public void run() {
1365                                restoreHistoryPictureFields(p, copy);
1366                            }
1367                        });
1368                    }
1369                    try {
1370                        in.close();
1371                    } catch (Exception e) {
1372                        // Nothing we can do now.
1373                    }
1374                }
1375            }).start();
1376        } catch (FileNotFoundException e){
1377            e.printStackTrace();
1378        }
1379        return true;
1380    }
1381
1382    /**
1383     * Restore the state of this WebView from the given map used in
1384     * {@link android.app.Activity#onRestoreInstanceState}. This method should
1385     * be called to restore the state of the WebView before using the object. If
1386     * it is called after the WebView has had a chance to build state (load
1387     * pages, create a back/forward list, etc.) there may be undesirable
1388     * side-effects. Please note that this method no longer restores the
1389     * display data for this WebView. See {@link #savePicture} and {@link
1390     * #restorePicture} for saving and restoring the display data.
1391     * @param inState The incoming Bundle of state.
1392     * @return The restored back/forward list or null if restoreState failed.
1393     * @see #savePicture
1394     * @see #restorePicture
1395     */
1396    public WebBackForwardList restoreState(Bundle inState) {
1397        WebBackForwardList returnList = null;
1398        if (inState == null) {
1399            return returnList;
1400        }
1401        if (inState.containsKey("index") && inState.containsKey("history")) {
1402            mCertificate = SslCertificate.restoreState(
1403                inState.getBundle("certificate"));
1404
1405            final WebBackForwardList list = mCallbackProxy.getBackForwardList();
1406            final int index = inState.getInt("index");
1407            // We can't use a clone of the list because we need to modify the
1408            // shared copy, so synchronize instead to prevent concurrent
1409            // modifications.
1410            synchronized (list) {
1411                final List<byte[]> history =
1412                        (List<byte[]>) inState.getSerializable("history");
1413                final int size = history.size();
1414                // Check the index bounds so we don't crash in native code while
1415                // restoring the history index.
1416                if (index < 0 || index >= size) {
1417                    return null;
1418                }
1419                for (int i = 0; i < size; i++) {
1420                    byte[] data = history.remove(0);
1421                    if (data == null) {
1422                        // If we somehow have null data, we cannot reconstruct
1423                        // the item and thus our history list cannot be rebuilt.
1424                        return null;
1425                    }
1426                    WebHistoryItem item = new WebHistoryItem(data);
1427                    list.addHistoryItem(item);
1428                }
1429                // Grab the most recent copy to return to the caller.
1430                returnList = copyBackForwardList();
1431                // Update the copy to have the correct index.
1432                returnList.setCurrentIndex(index);
1433            }
1434            // Remove all pending messages because we are restoring previous
1435            // state.
1436            mWebViewCore.removeMessages();
1437            // Send a restore state message.
1438            mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
1439        }
1440        return returnList;
1441    }
1442
1443    /**
1444     * Load the given url with the extra headers.
1445     * @param url The url of the resource to load.
1446     * @param extraHeaders The extra headers sent with this url. This should not
1447     *            include the common headers like "user-agent". If it does, it
1448     *            will be replaced by the intrinsic value of the WebView.
1449     */
1450    public void loadUrl(String url, Map<String, String> extraHeaders) {
1451        switchOutDrawHistory();
1452        WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData();
1453        arg.mUrl = url;
1454        arg.mExtraHeaders = extraHeaders;
1455        mWebViewCore.sendMessage(EventHub.LOAD_URL, arg);
1456        clearTextEntry(false);
1457    }
1458
1459    /**
1460     * Load the given url.
1461     * @param url The url of the resource to load.
1462     */
1463    public void loadUrl(String url) {
1464        if (url == null) {
1465            return;
1466        }
1467        loadUrl(url, null);
1468    }
1469
1470    /**
1471     * Load the url with postData using "POST" method into the WebView. If url
1472     * is not a network url, it will be loaded with {link
1473     * {@link #loadUrl(String)} instead.
1474     *
1475     * @param url The url of the resource to load.
1476     * @param postData The data will be passed to "POST" request.
1477     */
1478    public void postUrl(String url, byte[] postData) {
1479        if (URLUtil.isNetworkUrl(url)) {
1480            switchOutDrawHistory();
1481            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
1482            arg.mUrl = url;
1483            arg.mPostData = postData;
1484            mWebViewCore.sendMessage(EventHub.POST_URL, arg);
1485            clearTextEntry(false);
1486        } else {
1487            loadUrl(url);
1488        }
1489    }
1490
1491    /**
1492     * Load the given data into the WebView. This will load the data into
1493     * WebView using the data: scheme. Content loaded through this mechanism
1494     * does not have the ability to load content from the network.
1495     * @param data A String of data in the given encoding. The date must
1496     * be URI-escaped -- '#', '%', '\', '?' should be replaced by %23, %25,
1497     * %27, %3f respectively.
1498     * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg
1499     * @param encoding The encoding of the data. i.e. utf-8, base64
1500     */
1501    public void loadData(String data, String mimeType, String encoding) {
1502        loadUrl("data:" + mimeType + ";" + encoding + "," + data);
1503    }
1504
1505    /**
1506     * Load the given data into the WebView, use the provided URL as the base
1507     * URL for the content. The base URL is the URL that represents the page
1508     * that is loaded through this interface. As such, it is used to resolve any
1509     * relative URLs. The historyUrl is used for the history entry.
1510     * <p>
1511     * Note for post 1.0. Due to the change in the WebKit, the access to asset
1512     * files through "file:///android_asset/" for the sub resources is more
1513     * restricted. If you provide null or empty string as baseUrl, you won't be
1514     * able to access asset files. If the baseUrl is anything other than
1515     * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for
1516     * sub resources.
1517     *
1518     * @param baseUrl Url to resolve relative paths with, if null defaults to
1519     *            "about:blank"
1520     * @param data A String of data in the given encoding.
1521     * @param mimeType The MIMEType of the data. i.e. text/html. If null,
1522     *            defaults to "text/html"
1523     * @param encoding The encoding of the data. i.e. utf-8, us-ascii
1524     * @param historyUrl URL to use as the history entry.  Can be null.
1525     */
1526    public void loadDataWithBaseURL(String baseUrl, String data,
1527            String mimeType, String encoding, String historyUrl) {
1528
1529        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
1530            loadData(data, mimeType, encoding);
1531            return;
1532        }
1533        switchOutDrawHistory();
1534        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
1535        arg.mBaseUrl = baseUrl;
1536        arg.mData = data;
1537        arg.mMimeType = mimeType;
1538        arg.mEncoding = encoding;
1539        arg.mHistoryUrl = historyUrl;
1540        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
1541        clearTextEntry(false);
1542    }
1543
1544    /**
1545     * Stop the current load.
1546     */
1547    public void stopLoading() {
1548        // TODO: should we clear all the messages in the queue before sending
1549        // STOP_LOADING?
1550        switchOutDrawHistory();
1551        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
1552    }
1553
1554    /**
1555     * Reload the current url.
1556     */
1557    public void reload() {
1558        clearTextEntry(false);
1559        switchOutDrawHistory();
1560        mWebViewCore.sendMessage(EventHub.RELOAD);
1561    }
1562
1563    /**
1564     * Return true if this WebView has a back history item.
1565     * @return True iff this WebView has a back history item.
1566     */
1567    public boolean canGoBack() {
1568        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1569        synchronized (l) {
1570            if (l.getClearPending()) {
1571                return false;
1572            } else {
1573                return l.getCurrentIndex() > 0;
1574            }
1575        }
1576    }
1577
1578    /**
1579     * Go back in the history of this WebView.
1580     */
1581    public void goBack() {
1582        goBackOrForward(-1);
1583    }
1584
1585    /**
1586     * Return true if this WebView has a forward history item.
1587     * @return True iff this Webview has a forward history item.
1588     */
1589    public boolean canGoForward() {
1590        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1591        synchronized (l) {
1592            if (l.getClearPending()) {
1593                return false;
1594            } else {
1595                return l.getCurrentIndex() < l.getSize() - 1;
1596            }
1597        }
1598    }
1599
1600    /**
1601     * Go forward in the history of this WebView.
1602     */
1603    public void goForward() {
1604        goBackOrForward(1);
1605    }
1606
1607    /**
1608     * Return true if the page can go back or forward the given
1609     * number of steps.
1610     * @param steps The negative or positive number of steps to move the
1611     *              history.
1612     */
1613    public boolean canGoBackOrForward(int steps) {
1614        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1615        synchronized (l) {
1616            if (l.getClearPending()) {
1617                return false;
1618            } else {
1619                int newIndex = l.getCurrentIndex() + steps;
1620                return newIndex >= 0 && newIndex < l.getSize();
1621            }
1622        }
1623    }
1624
1625    /**
1626     * Go to the history item that is the number of steps away from
1627     * the current item. Steps is negative if backward and positive
1628     * if forward.
1629     * @param steps The number of steps to take back or forward in the back
1630     *              forward list.
1631     */
1632    public void goBackOrForward(int steps) {
1633        goBackOrForward(steps, false);
1634    }
1635
1636    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
1637        if (steps != 0) {
1638            clearTextEntry(false);
1639            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
1640                    ignoreSnapshot ? 1 : 0);
1641        }
1642    }
1643
1644    private boolean extendScroll(int y) {
1645        int finalY = mScroller.getFinalY();
1646        int newY = pinLocY(finalY + y);
1647        if (newY == finalY) return false;
1648        mScroller.setFinalY(newY);
1649        mScroller.extendDuration(computeDuration(0, y));
1650        return true;
1651    }
1652
1653    /**
1654     * Scroll the contents of the view up by half the view size
1655     * @param top true to jump to the top of the page
1656     * @return true if the page was scrolled
1657     */
1658    public boolean pageUp(boolean top) {
1659        if (mNativeClass == 0) {
1660            return false;
1661        }
1662        nativeClearCursor(); // start next trackball movement from page edge
1663        if (top) {
1664            // go to the top of the document
1665            return pinScrollTo(mScrollX, 0, true, 0);
1666        }
1667        // Page up
1668        int h = getHeight();
1669        int y;
1670        if (h > 2 * PAGE_SCROLL_OVERLAP) {
1671            y = -h + PAGE_SCROLL_OVERLAP;
1672        } else {
1673            y = -h / 2;
1674        }
1675        mUserScroll = true;
1676        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
1677                : extendScroll(y);
1678    }
1679
1680    /**
1681     * Scroll the contents of the view down by half the page size
1682     * @param bottom true to jump to bottom of page
1683     * @return true if the page was scrolled
1684     */
1685    public boolean pageDown(boolean bottom) {
1686        if (mNativeClass == 0) {
1687            return false;
1688        }
1689        nativeClearCursor(); // start next trackball movement from page edge
1690        if (bottom) {
1691            return pinScrollTo(mScrollX, computeVerticalScrollRange(), true, 0);
1692        }
1693        // Page down.
1694        int h = getHeight();
1695        int y;
1696        if (h > 2 * PAGE_SCROLL_OVERLAP) {
1697            y = h - PAGE_SCROLL_OVERLAP;
1698        } else {
1699            y = h / 2;
1700        }
1701        mUserScroll = true;
1702        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
1703                : extendScroll(y);
1704    }
1705
1706    /**
1707     * Clear the view so that onDraw() will draw nothing but white background,
1708     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
1709     */
1710    public void clearView() {
1711        mContentWidth = 0;
1712        mContentHeight = 0;
1713        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
1714    }
1715
1716    /**
1717     * Return a new picture that captures the current display of the webview.
1718     * This is a copy of the display, and will be unaffected if the webview
1719     * later loads a different URL.
1720     *
1721     * @return a picture containing the current contents of the view. Note this
1722     *         picture is of the entire document, and is not restricted to the
1723     *         bounds of the view.
1724     */
1725    public Picture capturePicture() {
1726        if (null == mWebViewCore) return null; // check for out of memory tab
1727        return mWebViewCore.copyContentPicture();
1728    }
1729
1730    /**
1731     *  Return true if the browser is displaying a TextView for text input.
1732     */
1733    private boolean inEditingMode() {
1734        return mWebTextView != null && mWebTextView.getParent() != null;
1735    }
1736
1737    /**
1738     * Remove the WebTextView.
1739     * @param disableFocusController If true, send a message to webkit
1740     *     disabling the focus controller, so the caret stops blinking.
1741     */
1742    private void clearTextEntry(boolean disableFocusController) {
1743        if (inEditingMode()) {
1744            mWebTextView.remove();
1745            if (disableFocusController) {
1746                setFocusControllerInactive();
1747            }
1748        }
1749    }
1750
1751    /**
1752     * Return the current scale of the WebView
1753     * @return The current scale.
1754     */
1755    public float getScale() {
1756        return mActualScale;
1757    }
1758
1759    /**
1760     * Set the initial scale for the WebView. 0 means default. If
1761     * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
1762     * way. Otherwise it starts with 100%. If initial scale is greater than 0,
1763     * WebView starts will this value as initial scale.
1764     *
1765     * @param scaleInPercent The initial scale in percent.
1766     */
1767    public void setInitialScale(int scaleInPercent) {
1768        mInitialScaleInPercent = scaleInPercent;
1769    }
1770
1771    /**
1772     * Invoke the graphical zoom picker widget for this WebView. This will
1773     * result in the zoom widget appearing on the screen to control the zoom
1774     * level of this WebView.
1775     */
1776    public void invokeZoomPicker() {
1777        if (!getSettings().supportZoom()) {
1778            Log.w(LOGTAG, "This WebView doesn't support zoom.");
1779            return;
1780        }
1781        clearTextEntry(false);
1782        if (getSettings().getBuiltInZoomControls()) {
1783            getZoomButtonsController().setVisible(true);
1784        } else {
1785            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
1786            mPrivateHandler.postDelayed(mZoomControlRunnable,
1787                    ZOOM_CONTROLS_TIMEOUT);
1788        }
1789    }
1790
1791    /**
1792     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
1793     * is found and the anchor has a non-javascript url, the HitTestResult type
1794     * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
1795     * anchor does not have a url or if it is a javascript url, the type will
1796     * be UNKNOWN_TYPE and the url has to be retrieved through
1797     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1798     * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
1799     * the "extra" field. A type of
1800     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
1801     * a child node. If a phone number is found, the HitTestResult type is set
1802     * to PHONE_TYPE and the phone number is set in the "extra" field of
1803     * HitTestResult. If a map address is found, the HitTestResult type is set
1804     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1805     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1806     * and the email is set in the "extra" field of HitTestResult. Otherwise,
1807     * HitTestResult type is set to UNKNOWN_TYPE.
1808     */
1809    public HitTestResult getHitTestResult() {
1810        if (mNativeClass == 0) {
1811            return null;
1812        }
1813
1814        HitTestResult result = new HitTestResult();
1815        if (nativeHasCursorNode()) {
1816            if (nativeCursorIsTextInput()) {
1817                result.setType(HitTestResult.EDIT_TEXT_TYPE);
1818            } else {
1819                String text = nativeCursorText();
1820                if (text != null) {
1821                    if (text.startsWith(SCHEME_TEL)) {
1822                        result.setType(HitTestResult.PHONE_TYPE);
1823                        result.setExtra(text.substring(SCHEME_TEL.length()));
1824                    } else if (text.startsWith(SCHEME_MAILTO)) {
1825                        result.setType(HitTestResult.EMAIL_TYPE);
1826                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
1827                    } else if (text.startsWith(SCHEME_GEO)) {
1828                        result.setType(HitTestResult.GEO_TYPE);
1829                        result.setExtra(URLDecoder.decode(text
1830                                .substring(SCHEME_GEO.length())));
1831                    } else if (nativeCursorIsAnchor()) {
1832                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
1833                        result.setExtra(text);
1834                    }
1835                }
1836            }
1837        }
1838        int type = result.getType();
1839        if (type == HitTestResult.UNKNOWN_TYPE
1840                || type == HitTestResult.SRC_ANCHOR_TYPE) {
1841            // Now check to see if it is an image.
1842            int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1843            int contentY = viewToContentY((int) mLastTouchY + mScrollY);
1844            String text = nativeImageURI(contentX, contentY);
1845            if (text != null) {
1846                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
1847                        HitTestResult.IMAGE_TYPE :
1848                        HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1849                result.setExtra(text);
1850            }
1851        }
1852        return result;
1853    }
1854
1855    // Called by JNI when the DOM has changed the focus.  Clear the focus so
1856    // that new keys will go to the newly focused field
1857    private void domChangedFocus() {
1858        if (inEditingMode()) {
1859            mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget();
1860        }
1861    }
1862    /**
1863     * Request the href of an anchor element due to getFocusNodePath returning
1864     * "href." If hrefMsg is null, this method returns immediately and does not
1865     * dispatch hrefMsg to its target.
1866     *
1867     * @param hrefMsg This message will be dispatched with the result of the
1868     *            request as the data member with "url" as key. The result can
1869     *            be null.
1870     */
1871    // FIXME: API change required to change the name of this function.  We now
1872    // look at the cursor node, and not the focus node.  Also, what is
1873    // getFocusNodePath?
1874    public void requestFocusNodeHref(Message hrefMsg) {
1875        if (hrefMsg == null || mNativeClass == 0) {
1876            return;
1877        }
1878        if (nativeCursorIsAnchor()) {
1879            mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
1880                    nativeCursorFramePointer(), nativeCursorNodePointer(),
1881                    hrefMsg);
1882        }
1883    }
1884
1885    /**
1886     * Request the url of the image last touched by the user. msg will be sent
1887     * to its target with a String representing the url as its object.
1888     *
1889     * @param msg This message will be dispatched with the result of the request
1890     *            as the data member with "url" as key. The result can be null.
1891     */
1892    public void requestImageRef(Message msg) {
1893        if (0 == mNativeClass) return; // client isn't initialized
1894        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1895        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
1896        String ref = nativeImageURI(contentX, contentY);
1897        Bundle data = msg.getData();
1898        data.putString("url", ref);
1899        msg.setData(data);
1900        msg.sendToTarget();
1901    }
1902
1903    private static int pinLoc(int x, int viewMax, int docMax) {
1904//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
1905        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
1906            // pin the short document to the top/left of the screen
1907            x = 0;
1908//            Log.d(LOGTAG, "--- center " + x);
1909        } else if (x < 0) {
1910            x = 0;
1911//            Log.d(LOGTAG, "--- zero");
1912        } else if (x + viewMax > docMax) {
1913            x = docMax - viewMax;
1914//            Log.d(LOGTAG, "--- pin " + x);
1915        }
1916        return x;
1917    }
1918
1919    // Expects x in view coordinates
1920    private int pinLocX(int x) {
1921        return pinLoc(x, getViewWidth(), computeHorizontalScrollRange());
1922    }
1923
1924    // Expects y in view coordinates
1925    private int pinLocY(int y) {
1926        return pinLoc(y, getViewHeightWithTitle(),
1927                      computeVerticalScrollRange() + getTitleHeight());
1928    }
1929
1930    /**
1931     * A title bar which is embedded in this WebView, and scrolls along with it
1932     * vertically, but not horizontally.
1933     */
1934    private View mTitleBar;
1935
1936    /**
1937     * Since we draw the title bar ourselves, we removed the shadow from the
1938     * browser's activity.  We do want a shadow at the bottom of the title bar,
1939     * or at the top of the screen if the title bar is not visible.  This
1940     * drawable serves that purpose.
1941     */
1942    private Drawable mTitleShadow;
1943
1944    /**
1945     * Add or remove a title bar to be embedded into the WebView, and scroll
1946     * along with it vertically, while remaining in view horizontally. Pass
1947     * null to remove the title bar from the WebView, and return to drawing
1948     * the WebView normally without translating to account for the title bar.
1949     * @hide
1950     */
1951    public void setEmbeddedTitleBar(View v) {
1952        if (mTitleBar == v) return;
1953        if (mTitleBar != null) {
1954            removeView(mTitleBar);
1955        }
1956        if (null != v) {
1957            addView(v, new AbsoluteLayout.LayoutParams(
1958                    ViewGroup.LayoutParams.MATCH_PARENT,
1959                    ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
1960            if (mTitleShadow == null) {
1961                mTitleShadow = (Drawable) mContext.getResources().getDrawable(
1962                        com.android.internal.R.drawable.title_bar_shadow);
1963            }
1964        }
1965        mTitleBar = v;
1966    }
1967
1968    /**
1969     * Given a distance in view space, convert it to content space. Note: this
1970     * does not reflect translation, just scaling, so this should not be called
1971     * with coordinates, but should be called for dimensions like width or
1972     * height.
1973     */
1974    private int viewToContentDimension(int d) {
1975        return Math.round(d * mInvActualScale);
1976    }
1977
1978    /**
1979     * Given an x coordinate in view space, convert it to content space.  Also
1980     * may be used for absolute heights (such as for the WebTextView's
1981     * textSize, which is unaffected by the height of the title bar).
1982     */
1983    /*package*/ int viewToContentX(int x) {
1984        return viewToContentDimension(x);
1985    }
1986
1987    /**
1988     * Given a y coordinate in view space, convert it to content space.
1989     * Takes into account the height of the title bar if there is one
1990     * embedded into the WebView.
1991     */
1992    /*package*/ int viewToContentY(int y) {
1993        return viewToContentDimension(y - getTitleHeight());
1994    }
1995
1996    /**
1997     * Given a distance in content space, convert it to view space. Note: this
1998     * does not reflect translation, just scaling, so this should not be called
1999     * with coordinates, but should be called for dimensions like width or
2000     * height.
2001     */
2002    /*package*/ int contentToViewDimension(int d) {
2003        return Math.round(d * mActualScale);
2004    }
2005
2006    /**
2007     * Given an x coordinate in content space, convert it to view
2008     * space.
2009     */
2010    /*package*/ int contentToViewX(int x) {
2011        return contentToViewDimension(x);
2012    }
2013
2014    /**
2015     * Given a y coordinate in content space, convert it to view
2016     * space.  Takes into account the height of the title bar.
2017     */
2018    /*package*/ int contentToViewY(int y) {
2019        return contentToViewDimension(y) + getTitleHeight();
2020    }
2021
2022    private Rect contentToViewRect(Rect x) {
2023        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
2024                        contentToViewX(x.right), contentToViewY(x.bottom));
2025    }
2026
2027    /*  To invalidate a rectangle in content coordinates, we need to transform
2028        the rect into view coordinates, so we can then call invalidate(...).
2029
2030        Normally, we would just call contentToView[XY](...), which eventually
2031        calls Math.round(coordinate * mActualScale). However, for invalidates,
2032        we need to account for the slop that occurs with antialiasing. To
2033        address that, we are a little more liberal in the size of the rect that
2034        we invalidate.
2035
2036        This liberal calculation calls floor() for the top/left, and ceil() for
2037        the bottom/right coordinates. This catches the possible extra pixels of
2038        antialiasing that we might have missed with just round().
2039     */
2040
2041    // Called by JNI to invalidate the View, given rectangle coordinates in
2042    // content space
2043    private void viewInvalidate(int l, int t, int r, int b) {
2044        final float scale = mActualScale;
2045        final int dy = getTitleHeight();
2046        invalidate((int)Math.floor(l * scale),
2047                   (int)Math.floor(t * scale) + dy,
2048                   (int)Math.ceil(r * scale),
2049                   (int)Math.ceil(b * scale) + dy);
2050    }
2051
2052    // Called by JNI to invalidate the View after a delay, given rectangle
2053    // coordinates in content space
2054    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
2055        final float scale = mActualScale;
2056        final int dy = getTitleHeight();
2057        postInvalidateDelayed(delay,
2058                              (int)Math.floor(l * scale),
2059                              (int)Math.floor(t * scale) + dy,
2060                              (int)Math.ceil(r * scale),
2061                              (int)Math.ceil(b * scale) + dy);
2062    }
2063
2064    private void invalidateContentRect(Rect r) {
2065        viewInvalidate(r.left, r.top, r.right, r.bottom);
2066    }
2067
2068    // stop the scroll animation, and don't let a subsequent fling add
2069    // to the existing velocity
2070    private void abortAnimation() {
2071        mScroller.abortAnimation();
2072        mLastVelocity = 0;
2073    }
2074
2075    /* call from webcoreview.draw(), so we're still executing in the UI thread
2076    */
2077    private void recordNewContentSize(int w, int h, boolean updateLayout) {
2078
2079        // premature data from webkit, ignore
2080        if ((w | h) == 0) {
2081            return;
2082        }
2083
2084        // don't abort a scroll animation if we didn't change anything
2085        if (mContentWidth != w || mContentHeight != h) {
2086            // record new dimensions
2087            mContentWidth = w;
2088            mContentHeight = h;
2089            // If history Picture is drawn, don't update scroll. They will be
2090            // updated when we get out of that mode.
2091            if (!mDrawHistory) {
2092                // repin our scroll, taking into account the new content size
2093                int oldX = mScrollX;
2094                int oldY = mScrollY;
2095                mScrollX = pinLocX(mScrollX);
2096                mScrollY = pinLocY(mScrollY);
2097                if (oldX != mScrollX || oldY != mScrollY) {
2098                    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
2099                }
2100                if (!mScroller.isFinished()) {
2101                    // We are in the middle of a scroll.  Repin the final scroll
2102                    // position.
2103                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
2104                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
2105                }
2106            }
2107        }
2108        contentSizeChanged(updateLayout);
2109    }
2110
2111    private void setNewZoomScale(float scale, boolean updateTextWrapScale,
2112            boolean force) {
2113        if (scale < mMinZoomScale) {
2114            scale = mMinZoomScale;
2115            // set mInZoomOverview for non mobile sites
2116            if (scale < mDefaultScale) mInZoomOverview = true;
2117        } else if (scale > mMaxZoomScale) {
2118            scale = mMaxZoomScale;
2119        }
2120        if (updateTextWrapScale) {
2121            mTextWrapScale = scale;
2122            // reset mLastHeightSent to force VIEW_SIZE_CHANGED sent to WebKit
2123            mLastHeightSent = 0;
2124        }
2125        if (scale != mActualScale || force) {
2126            if (mDrawHistory) {
2127                // If history Picture is drawn, don't update scroll. They will
2128                // be updated when we get out of that mode.
2129                if (scale != mActualScale && !mPreviewZoomOnly) {
2130                    mCallbackProxy.onScaleChanged(mActualScale, scale);
2131                }
2132                mActualScale = scale;
2133                mInvActualScale = 1 / scale;
2134                sendViewSizeZoom();
2135            } else {
2136                // update our scroll so we don't appear to jump
2137                // i.e. keep the center of the doc in the center of the view
2138
2139                int oldX = mScrollX;
2140                int oldY = mScrollY;
2141                float ratio = scale * mInvActualScale;   // old inverse
2142                float sx = ratio * oldX + (ratio - 1) * mZoomCenterX;
2143                float sy = ratio * oldY + (ratio - 1)
2144                        * (mZoomCenterY - getTitleHeight());
2145
2146                // now update our new scale and inverse
2147                if (scale != mActualScale && !mPreviewZoomOnly) {
2148                    mCallbackProxy.onScaleChanged(mActualScale, scale);
2149                }
2150                mActualScale = scale;
2151                mInvActualScale = 1 / scale;
2152
2153                // Scale all the child views
2154                mViewManager.scaleAll();
2155
2156                // as we don't have animation for scaling, don't do animation
2157                // for scrolling, as it causes weird intermediate state
2158                //        pinScrollTo(Math.round(sx), Math.round(sy));
2159                mScrollX = pinLocX(Math.round(sx));
2160                mScrollY = pinLocY(Math.round(sy));
2161
2162                // update webkit
2163                if (oldX != mScrollX || oldY != mScrollY) {
2164                    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
2165                } else {
2166                    // the scroll position is adjusted at the beginning of the
2167                    // zoom animation. But we want to update the WebKit at the
2168                    // end of the zoom animation. See comments in onScaleEnd().
2169                    sendOurVisibleRect();
2170                }
2171                sendViewSizeZoom();
2172            }
2173        }
2174    }
2175
2176    // Used to avoid sending many visible rect messages.
2177    private Rect mLastVisibleRectSent;
2178    private Rect mLastGlobalRect;
2179
2180    private Rect sendOurVisibleRect() {
2181        if (mPreviewZoomOnly) return mLastVisibleRectSent;
2182
2183        Rect rect = new Rect();
2184        calcOurContentVisibleRect(rect);
2185        // Rect.equals() checks for null input.
2186        if (!rect.equals(mLastVisibleRectSent)) {
2187            Point pos = new Point(rect.left, rect.top);
2188            mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
2189                    nativeMoveGeneration(), 0, pos);
2190            mLastVisibleRectSent = rect;
2191        }
2192        Rect globalRect = new Rect();
2193        if (getGlobalVisibleRect(globalRect)
2194                && !globalRect.equals(mLastGlobalRect)) {
2195            if (DebugFlags.WEB_VIEW) {
2196                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2197                        + globalRect.top + ",r=" + globalRect.right + ",b="
2198                        + globalRect.bottom);
2199            }
2200            // TODO: the global offset is only used by windowRect()
2201            // in ChromeClientAndroid ; other clients such as touch
2202            // and mouse events could return view + screen relative points.
2203            mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2204            mLastGlobalRect = globalRect;
2205        }
2206        return rect;
2207    }
2208
2209    // Sets r to be the visible rectangle of our webview in view coordinates
2210    private void calcOurVisibleRect(Rect r) {
2211        Point p = new Point();
2212        getGlobalVisibleRect(r, p);
2213        r.offset(-p.x, -p.y);
2214        if (mFindIsUp) {
2215            r.bottom -= mFindHeight;
2216        }
2217    }
2218
2219    // Sets r to be our visible rectangle in content coordinates
2220    private void calcOurContentVisibleRect(Rect r) {
2221        calcOurVisibleRect(r);
2222        // pin the rect to the bounds of the content
2223        r.left = Math.max(viewToContentX(r.left), 0);
2224        // viewToContentY will remove the total height of the title bar.  Add
2225        // the visible height back in to account for the fact that if the title
2226        // bar is partially visible, the part of the visible rect which is
2227        // displaying our content is displaced by that amount.
2228        r.top = Math.max(viewToContentY(r.top + getVisibleTitleHeight()), 0);
2229        r.right = Math.min(viewToContentX(r.right), mContentWidth);
2230        r.bottom = Math.min(viewToContentY(r.bottom), mContentHeight);
2231    }
2232
2233    static class ViewSizeData {
2234        int mWidth;
2235        int mHeight;
2236        int mTextWrapWidth;
2237        int mAnchorX;
2238        int mAnchorY;
2239        float mScale;
2240        boolean mIgnoreHeight;
2241    }
2242
2243    /**
2244     * Compute unzoomed width and height, and if they differ from the last
2245     * values we sent, send them to webkit (to be used has new viewport)
2246     *
2247     * @return true if new values were sent
2248     */
2249    private boolean sendViewSizeZoom() {
2250        if (mPreviewZoomOnly) return false;
2251
2252        int viewWidth = getViewWidth();
2253        int newWidth = Math.round(viewWidth * mInvActualScale);
2254        int newHeight = Math.round(getViewHeight() * mInvActualScale);
2255        /*
2256         * Because the native side may have already done a layout before the
2257         * View system was able to measure us, we have to send a height of 0 to
2258         * remove excess whitespace when we grow our width. This will trigger a
2259         * layout and a change in content size. This content size change will
2260         * mean that contentSizeChanged will either call this method directly or
2261         * indirectly from onSizeChanged.
2262         */
2263        if (newWidth > mLastWidthSent && mWrapContent) {
2264            newHeight = 0;
2265        }
2266        // Avoid sending another message if the dimensions have not changed.
2267        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) {
2268            ViewSizeData data = new ViewSizeData();
2269            data.mWidth = newWidth;
2270            data.mHeight = newHeight;
2271            data.mTextWrapWidth = Math.round(viewWidth / mTextWrapScale);;
2272            data.mScale = mActualScale;
2273            data.mIgnoreHeight = mZoomScale != 0 && !mHeightCanMeasure;
2274            data.mAnchorX = mAnchorX;
2275            data.mAnchorY = mAnchorY;
2276            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
2277            mLastWidthSent = newWidth;
2278            mLastHeightSent = newHeight;
2279            mAnchorX = mAnchorY = 0;
2280            return true;
2281        }
2282        return false;
2283    }
2284
2285    @Override
2286    protected int computeHorizontalScrollRange() {
2287        if (mDrawHistory) {
2288            return mHistoryWidth;
2289        } else if (mHorizontalScrollBarMode == SCROLLBAR_ALWAYSOFF) {
2290            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                    && (mZoomButtonsController == null ||
4032                            !mZoomButtonsController.isVisible())) {
4033                /*
4034                 * The zoom controls come in their own window, so our window
4035                 * loses focus. Our policy is to not draw the cursor ring if
4036                 * our window is not focused, but this is an exception since
4037                 * the user can still navigate the web page with the zoom
4038                 * controls showing.
4039                 */
4040                // If our window has lost focus, stop drawing the cursor ring
4041                mDrawCursorRing = false;
4042            }
4043            mGotKeyDown = false;
4044            mShiftIsPressed = false;
4045            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4046            mTouchMode = TOUCH_DONE_MODE;
4047            if (mNativeClass != 0) {
4048                nativeRecordButtons(false, false, true);
4049            }
4050            setFocusControllerInactive();
4051        }
4052        invalidate();
4053    }
4054
4055    // To avoid drawing the cursor ring, and remove the TextView when our window
4056    // loses focus.
4057    @Override
4058    public void onWindowFocusChanged(boolean hasWindowFocus) {
4059        setActive(hasWindowFocus);
4060        if (hasWindowFocus) {
4061            BrowserFrame.sJavaBridge.setActiveWebView(this);
4062        } else {
4063            BrowserFrame.sJavaBridge.removeActiveWebView(this);
4064        }
4065        super.onWindowFocusChanged(hasWindowFocus);
4066    }
4067
4068    /*
4069     * Pass a message to WebCore Thread, telling the WebCore::Page's
4070     * FocusController to be  "inactive" so that it will
4071     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
4072     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
4073     */
4074    /* package */ void setFocusControllerInactive() {
4075        // Do not need to also check whether mWebViewCore is null, because
4076        // mNativeClass is only set if mWebViewCore is non null
4077        if (mNativeClass == 0) return;
4078        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
4079    }
4080
4081    @Override
4082    protected void onFocusChanged(boolean focused, int direction,
4083            Rect previouslyFocusedRect) {
4084        if (DebugFlags.WEB_VIEW) {
4085            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
4086        }
4087        if (focused) {
4088            // When we regain focus, if we have window focus, resume drawing
4089            // the cursor ring
4090            if (hasWindowFocus()) {
4091                mDrawCursorRing = true;
4092                if (mNativeClass != 0) {
4093                    nativeRecordButtons(true, false, true);
4094                }
4095            //} else {
4096                // The WebView has gained focus while we do not have
4097                // windowfocus.  When our window lost focus, we should have
4098                // called nativeRecordButtons(false...)
4099            }
4100        } else {
4101            // When we lost focus, unless focus went to the TextView (which is
4102            // true if we are in editing mode), stop drawing the cursor ring.
4103            if (!inEditingMode()) {
4104                mDrawCursorRing = false;
4105                if (mNativeClass != 0) {
4106                    nativeRecordButtons(false, false, true);
4107                }
4108                setFocusControllerInactive();
4109            }
4110            mGotKeyDown = false;
4111        }
4112
4113        super.onFocusChanged(focused, direction, previouslyFocusedRect);
4114    }
4115
4116    /**
4117     * @hide
4118     */
4119    @Override
4120    protected boolean setFrame(int left, int top, int right, int bottom) {
4121        boolean changed = super.setFrame(left, top, right, bottom);
4122        if (!changed && mHeightCanMeasure) {
4123            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
4124            // in WebViewCore after we get the first layout. We do call
4125            // requestLayout() when we get contentSizeChanged(). But the View
4126            // system won't call onSizeChanged if the dimension is not changed.
4127            // In this case, we need to call sendViewSizeZoom() explicitly to
4128            // notify the WebKit about the new dimensions.
4129            sendViewSizeZoom();
4130        }
4131        return changed;
4132    }
4133
4134    private static class PostScale implements Runnable {
4135        final WebView mWebView;
4136        final boolean mUpdateTextWrap;
4137
4138        public PostScale(WebView webView, boolean updateTextWrap) {
4139            mWebView = webView;
4140            mUpdateTextWrap = updateTextWrap;
4141        }
4142
4143        public void run() {
4144            if (mWebView.mWebViewCore != null) {
4145                // we always force, in case our height changed, in which case we
4146                // still want to send the notification over to webkit.
4147                mWebView.setNewZoomScale(mWebView.mActualScale,
4148                        mUpdateTextWrap, true);
4149                // update the zoom buttons as the scale can be changed
4150                if (mWebView.getSettings().getBuiltInZoomControls()) {
4151                    mWebView.updateZoomButtonsEnabled();
4152                }
4153            }
4154        }
4155    }
4156
4157    @Override
4158    protected void onSizeChanged(int w, int h, int ow, int oh) {
4159        super.onSizeChanged(w, h, ow, oh);
4160        // Center zooming to the center of the screen.
4161        if (mZoomScale == 0) { // unless we're already zooming
4162            // To anchor at top left corner.
4163            mZoomCenterX = 0;
4164            mZoomCenterY = getVisibleTitleHeight();
4165            mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
4166            mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
4167        }
4168
4169        // adjust the max viewport width depending on the view dimensions. This
4170        // is to ensure the scaling is not going insane. So do not shrink it if
4171        // the view size is temporarily smaller, e.g. when soft keyboard is up.
4172        int newMaxViewportWidth = (int) (Math.max(w, h) / DEFAULT_MIN_ZOOM_SCALE);
4173        if (newMaxViewportWidth > sMaxViewportWidth) {
4174            sMaxViewportWidth = newMaxViewportWidth;
4175        }
4176
4177        // update mMinZoomScale if the minimum zoom scale is not fixed
4178        if (!mMinZoomScaleFixed) {
4179            // when change from narrow screen to wide screen, the new viewWidth
4180            // can be wider than the old content width. We limit the minimum
4181            // scale to 1.0f. The proper minimum scale will be calculated when
4182            // the new picture shows up.
4183            mMinZoomScale = Math.min(1.0f, (float) getViewWidth()
4184                    / (mDrawHistory ? mHistoryPicture.getWidth()
4185                            : mZoomOverviewWidth));
4186            if (mInitialScaleInPercent > 0) {
4187                // limit the minZoomScale to the initialScale if it is set
4188                float initialScale = mInitialScaleInPercent / 100.0f;
4189                if (mMinZoomScale > initialScale) {
4190                    mMinZoomScale = initialScale;
4191                }
4192            }
4193        }
4194
4195        dismissZoomControl();
4196
4197        // onSizeChanged() is called during WebView layout. And any
4198        // requestLayout() is blocked during layout. As setNewZoomScale() will
4199        // call its child View to reposition itself through ViewManager's
4200        // scaleAll(), we need to post a Runnable to ensure requestLayout().
4201        // <b/>
4202        // only update the text wrap scale if width changed.
4203        post(new PostScale(this, w != ow));
4204    }
4205
4206    @Override
4207    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4208        super.onScrollChanged(l, t, oldl, oldt);
4209        sendOurVisibleRect();
4210        // update WebKit if visible title bar height changed. The logic is same
4211        // as getVisibleTitleHeight.
4212        int titleHeight = getTitleHeight();
4213        if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
4214            sendViewSizeZoom();
4215        }
4216    }
4217
4218    @Override
4219    public boolean dispatchKeyEvent(KeyEvent event) {
4220        boolean dispatch = true;
4221
4222        // Textfields and plugins need to receive the shift up key even if
4223        // another key was released while the shift key was held down.
4224        if (!inEditingMode() && (mNativeClass == 0 || !nativeFocusIsPlugin())) {
4225            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4226                mGotKeyDown = true;
4227            } else {
4228                if (!mGotKeyDown) {
4229                    /*
4230                     * We got a key up for which we were not the recipient of
4231                     * the original key down. Don't give it to the view.
4232                     */
4233                    dispatch = false;
4234                }
4235                mGotKeyDown = false;
4236            }
4237        }
4238
4239        if (dispatch) {
4240            return super.dispatchKeyEvent(event);
4241        } else {
4242            // We didn't dispatch, so let something else handle the key
4243            return false;
4244        }
4245    }
4246
4247    // Here are the snap align logic:
4248    // 1. If it starts nearly horizontally or vertically, snap align;
4249    // 2. If there is a dramitic direction change, let it go;
4250    // 3. If there is a same direction back and forth, lock it.
4251
4252    // adjustable parameters
4253    private int mMinLockSnapReverseDistance;
4254    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
4255    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
4256
4257    private static int sign(float x) {
4258        return x > 0 ? 1 : (x < 0 ? -1 : 0);
4259    }
4260
4261    // if the page can scroll <= this value, we won't allow the drag tracker
4262    // to have any effect.
4263    private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4;
4264
4265    private class DragTrackerHandler {
4266        private final DragTracker mProxy;
4267        private final float mStartY, mStartX;
4268        private final float mMinDY, mMinDX;
4269        private final float mMaxDY, mMaxDX;
4270        private float mCurrStretchY, mCurrStretchX;
4271        private int mSX, mSY;
4272        private Interpolator mInterp;
4273        private float[] mXY = new float[2];
4274
4275        // inner (non-state) classes can't have enums :(
4276        private static final int DRAGGING_STATE = 0;
4277        private static final int ANIMATING_STATE = 1;
4278        private static final int FINISHED_STATE = 2;
4279        private int mState;
4280
4281        public DragTrackerHandler(float x, float y, DragTracker proxy) {
4282            mProxy = proxy;
4283
4284            int docBottom = computeVerticalScrollRange() + getTitleHeight();
4285            int viewTop = getScrollY();
4286            int viewBottom = viewTop + getHeight();
4287
4288            mStartY = y;
4289            mMinDY = -viewTop;
4290            mMaxDY = docBottom - viewBottom;
4291
4292            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4293                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y +
4294                      " up/down= " + mMinDY + " " + mMaxDY);
4295            }
4296
4297            int docRight = computeHorizontalScrollRange();
4298            int viewLeft = getScrollX();
4299            int viewRight = viewLeft + getWidth();
4300            mStartX = x;
4301            mMinDX = -viewLeft;
4302            mMaxDX = docRight - viewRight;
4303
4304            mState = DRAGGING_STATE;
4305            mProxy.onStartDrag(x, y);
4306
4307            // ensure we buildBitmap at least once
4308            mSX = -99999;
4309        }
4310
4311        private float computeStretch(float delta, float min, float max) {
4312            float stretch = 0;
4313            if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) {
4314                if (delta < min) {
4315                    stretch = delta - min;
4316                } else if (delta > max) {
4317                    stretch = delta - max;
4318                }
4319            }
4320            return stretch;
4321        }
4322
4323        public void dragTo(float x, float y) {
4324            float sy = computeStretch(mStartY - y, mMinDY, mMaxDY);
4325            float sx = computeStretch(mStartX - x, mMinDX, mMaxDX);
4326
4327            if ((mSnapScrollMode & SNAP_X) != 0) {
4328                sy = 0;
4329            } else if ((mSnapScrollMode & SNAP_Y) != 0) {
4330                sx = 0;
4331            }
4332
4333            if (mCurrStretchX != sx || mCurrStretchY != sy) {
4334                mCurrStretchX = sx;
4335                mCurrStretchY = sy;
4336                if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4337                    Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx +
4338                          " " + sy);
4339                }
4340                if (mProxy.onStretchChange(sx, sy)) {
4341                    invalidate();
4342                }
4343            }
4344        }
4345
4346        public void stopDrag() {
4347            final int DURATION = 200;
4348            int now = (int)SystemClock.uptimeMillis();
4349            mInterp = new Interpolator(2);
4350            mXY[0] = mCurrStretchX;
4351            mXY[1] = mCurrStretchY;
4352         //   float[] blend = new float[] { 0.5f, 0, 0.75f, 1 };
4353            float[] blend = new float[] { 0, 0.5f, 0.75f, 1 };
4354            mInterp.setKeyFrame(0, now, mXY, blend);
4355            float[] zerozero = new float[] { 0, 0 };
4356            mInterp.setKeyFrame(1, now + DURATION, zerozero, null);
4357            mState = ANIMATING_STATE;
4358
4359            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4360                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation");
4361            }
4362        }
4363
4364        // Call this after each draw. If it ruturns null, the tracker is done
4365        public boolean isFinished() {
4366            return mState == FINISHED_STATE;
4367        }
4368
4369        private int hiddenHeightOfTitleBar() {
4370            return getTitleHeight() - getVisibleTitleHeight();
4371        }
4372
4373        // need a way to know if 565 or 8888 is the right config for
4374        // capturing the display and giving it to the drag proxy
4375        private Bitmap.Config offscreenBitmapConfig() {
4376            // hard code 565 for now
4377            return Bitmap.Config.RGB_565;
4378        }
4379
4380        /*  If the tracker draws, then this returns true, otherwise it will
4381            return false, and draw nothing.
4382         */
4383        public boolean draw(Canvas canvas) {
4384            if (mCurrStretchX != 0 || mCurrStretchY != 0) {
4385                int sx = getScrollX();
4386                int sy = getScrollY() - hiddenHeightOfTitleBar();
4387                if (mSX != sx || mSY != sy) {
4388                    buildBitmap(sx, sy);
4389                    mSX = sx;
4390                    mSY = sy;
4391                }
4392
4393                if (mState == ANIMATING_STATE) {
4394                    Interpolator.Result result = mInterp.timeToValues(mXY);
4395                    if (result == Interpolator.Result.FREEZE_END) {
4396                        mState = FINISHED_STATE;
4397                        return false;
4398                    } else {
4399                        mProxy.onStretchChange(mXY[0], mXY[1]);
4400                        invalidate();
4401                        // fall through to the draw
4402                    }
4403                }
4404                int count = canvas.save(Canvas.MATRIX_SAVE_FLAG);
4405                canvas.translate(sx, sy);
4406                mProxy.onDraw(canvas);
4407                canvas.restoreToCount(count);
4408                return true;
4409            }
4410            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4411                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " +
4412                      mCurrStretchX + " " + mCurrStretchY);
4413            }
4414            return false;
4415        }
4416
4417        private void buildBitmap(int sx, int sy) {
4418            int w = getWidth();
4419            int h = getViewHeight();
4420            Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig());
4421            Canvas canvas = new Canvas(bm);
4422            canvas.translate(-sx, -sy);
4423            drawContent(canvas);
4424
4425            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4426                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx +
4427                      " " + sy + " " + w + " " + h);
4428            }
4429            mProxy.onBitmapChange(bm);
4430        }
4431    }
4432
4433    /** @hide */
4434    public static class DragTracker {
4435        public void onStartDrag(float x, float y) {}
4436        public boolean onStretchChange(float sx, float sy) {
4437            // return true to have us inval the view
4438            return false;
4439        }
4440        public void onStopDrag() {}
4441        public void onBitmapChange(Bitmap bm) {}
4442        public void onDraw(Canvas canvas) {}
4443    }
4444
4445    /** @hide */
4446    public DragTracker getDragTracker() {
4447        return mDragTracker;
4448    }
4449
4450    /** @hide */
4451    public void setDragTracker(DragTracker tracker) {
4452        mDragTracker = tracker;
4453    }
4454
4455    private DragTracker mDragTracker;
4456    private DragTrackerHandler mDragTrackerHandler;
4457
4458    private class ScaleDetectorListener implements
4459            ScaleGestureDetector.OnScaleGestureListener {
4460
4461        public boolean onScaleBegin(ScaleGestureDetector detector) {
4462            // cancel the single touch handling
4463            cancelTouch();
4464            dismissZoomControl();
4465            // reset the zoom overview mode so that the page won't auto grow
4466            mInZoomOverview = false;
4467            // If it is in password mode, turn it off so it does not draw
4468            // misplaced.
4469            if (inEditingMode() && nativeFocusCandidateIsPassword()) {
4470                mWebTextView.setInPassword(false);
4471            }
4472
4473            mViewManager.startZoom();
4474
4475            return true;
4476        }
4477
4478        public void onScaleEnd(ScaleGestureDetector detector) {
4479            if (mPreviewZoomOnly) {
4480                mPreviewZoomOnly = false;
4481                mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
4482                mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
4483                // don't reflow when zoom in; when zoom out, do reflow if the
4484                // new scale is almost minimum scale;
4485                boolean reflowNow = (mActualScale - mMinZoomScale
4486                        <= MINIMUM_SCALE_INCREMENT)
4487                        || ((mActualScale <= 0.8 * mTextWrapScale));
4488                // force zoom after mPreviewZoomOnly is set to false so that the
4489                // new view size will be passed to the WebKit
4490                setNewZoomScale(mActualScale, reflowNow, true);
4491                // call invalidate() to draw without zoom filter
4492                invalidate();
4493            }
4494            // adjust the edit text view if needed
4495            if (inEditingMode() && didUpdateTextViewBounds(false)
4496                    && nativeFocusCandidateIsPassword()) {
4497                // If it is a password field, start drawing the
4498                // WebTextView once again.
4499                mWebTextView.setInPassword(true);
4500            }
4501            // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as it
4502            // may trigger the unwanted click, can't use TOUCH_DRAG_MODE as it
4503            // may trigger the unwanted fling.
4504            mTouchMode = TOUCH_PINCH_DRAG;
4505            mConfirmMove = true;
4506            startTouch(detector.getFocusX(), detector.getFocusY(),
4507                    mLastTouchTime);
4508
4509            mViewManager.endZoom();
4510        }
4511
4512        public boolean onScale(ScaleGestureDetector detector) {
4513            float scale = (float) (Math.round(detector.getScaleFactor()
4514                    * mActualScale * 100) / 100.0);
4515            if (Math.abs(scale - mActualScale) >= MINIMUM_SCALE_INCREMENT) {
4516                mPreviewZoomOnly = true;
4517                // limit the scale change per step
4518                if (scale > mActualScale) {
4519                    scale = Math.min(scale, mActualScale * 1.25f);
4520                } else {
4521                    scale = Math.max(scale, mActualScale * 0.8f);
4522                }
4523                mZoomCenterX = detector.getFocusX();
4524                mZoomCenterY = detector.getFocusY();
4525                setNewZoomScale(scale, false, false);
4526                invalidate();
4527                return true;
4528            }
4529            return false;
4530        }
4531    }
4532
4533    private boolean hitFocusedPlugin(int contentX, int contentY) {
4534        if (DebugFlags.WEB_VIEW) {
4535            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
4536            Rect r = nativeFocusNodeBounds();
4537            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
4538                    + ", " + r.right + ", " + r.bottom + ")");
4539        }
4540        return nativeFocusIsPlugin()
4541                && nativeFocusNodeBounds().contains(contentX, contentY);
4542    }
4543
4544    private boolean shouldForwardTouchEvent() {
4545        return mFullScreenHolder != null || (mForwardTouchEvents
4546                && mTouchMode != TOUCH_SELECT_MODE
4547                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
4548    }
4549
4550    private boolean inFullScreenMode() {
4551        return mFullScreenHolder != null;
4552    }
4553
4554    @Override
4555    public boolean onTouchEvent(MotionEvent ev) {
4556        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
4557            return false;
4558        }
4559
4560        if (DebugFlags.WEB_VIEW) {
4561            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
4562                    + mTouchMode);
4563        }
4564
4565        int action;
4566        float x, y;
4567        long eventTime = ev.getEventTime();
4568
4569        // FIXME: we may consider to give WebKit an option to handle multi-touch
4570        // events later.
4571        if (mSupportMultiTouch && ev.getPointerCount() > 1) {
4572            if (mMinZoomScale < mMaxZoomScale) {
4573                mScaleDetector.onTouchEvent(ev);
4574                if (mScaleDetector.isInProgress()) {
4575                    mLastTouchTime = eventTime;
4576                    return true;
4577                }
4578                x = mScaleDetector.getFocusX();
4579                y = mScaleDetector.getFocusY();
4580                action = ev.getAction() & MotionEvent.ACTION_MASK;
4581                if (action == MotionEvent.ACTION_POINTER_DOWN) {
4582                    cancelTouch();
4583                    action = MotionEvent.ACTION_DOWN;
4584                } else if (action == MotionEvent.ACTION_POINTER_UP) {
4585                    // set mLastTouchX/Y to the remaining point
4586                    mLastTouchX = x;
4587                    mLastTouchY = y;
4588                } else if (action == MotionEvent.ACTION_MOVE) {
4589                    // negative x or y indicate it is on the edge, skip it.
4590                    if (x < 0 || y < 0) {
4591                        return true;
4592                    }
4593                }
4594            } else {
4595                // if the page disallow zoom, skip multi-pointer action
4596                return true;
4597            }
4598        } else {
4599            action = ev.getAction();
4600            x = ev.getX();
4601            y = ev.getY();
4602        }
4603
4604        // Due to the touch screen edge effect, a touch closer to the edge
4605        // always snapped to the edge. As getViewWidth() can be different from
4606        // getWidth() due to the scrollbar, adjusting the point to match
4607        // getViewWidth(). Same applied to the height.
4608        if (x > getViewWidth() - 1) {
4609            x = getViewWidth() - 1;
4610        }
4611        if (y > getViewHeightWithTitle() - 1) {
4612            y = getViewHeightWithTitle() - 1;
4613        }
4614
4615        float fDeltaX = mLastTouchX - x;
4616        float fDeltaY = mLastTouchY - y;
4617        int deltaX = (int) fDeltaX;
4618        int deltaY = (int) fDeltaY;
4619        int contentX = viewToContentX((int) x + mScrollX);
4620        int contentY = viewToContentY((int) y + mScrollY);
4621
4622        switch (action) {
4623            case MotionEvent.ACTION_DOWN: {
4624                mPreventDefault = PREVENT_DEFAULT_NO;
4625                mConfirmMove = false;
4626                if (!mScroller.isFinished()) {
4627                    // stop the current scroll animation, but if this is
4628                    // the start of a fling, allow it to add to the current
4629                    // fling's velocity
4630                    mScroller.abortAnimation();
4631                    mTouchMode = TOUCH_DRAG_START_MODE;
4632                    mConfirmMove = true;
4633                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
4634                } else if (!inFullScreenMode() && mShiftIsPressed) {
4635                    mSelectX = mScrollX + (int) x;
4636                    mSelectY = mScrollY + (int) y;
4637                    mTouchMode = TOUCH_SELECT_MODE;
4638                    if (DebugFlags.WEB_VIEW) {
4639                        Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
4640                    }
4641                    nativeMoveSelection(contentX, contentY, false);
4642                    mTouchSelection = mExtendSelection = true;
4643                    invalidate(); // draw the i-beam instead of the arrow
4644                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
4645                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
4646                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
4647                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
4648                    } else {
4649                        // commit the short press action for the previous tap
4650                        doShortPress();
4651                        mTouchMode = TOUCH_INIT_MODE;
4652                        mDeferTouchProcess = (!inFullScreenMode()
4653                                && mForwardTouchEvents) ? hitFocusedPlugin(
4654                                contentX, contentY) : false;
4655                    }
4656                } else { // the normal case
4657                    mPreviewZoomOnly = false;
4658                    mTouchMode = TOUCH_INIT_MODE;
4659                    mDeferTouchProcess = (!inFullScreenMode()
4660                            && mForwardTouchEvents) ? hitFocusedPlugin(
4661                            contentX, contentY) : false;
4662                    mWebViewCore.sendMessage(
4663                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
4664                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
4665                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
4666                                (eventTime - mLastTouchUpTime), eventTime);
4667                    }
4668                }
4669                // Trigger the link
4670                if (mTouchMode == TOUCH_INIT_MODE
4671                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4672                    mPrivateHandler.sendEmptyMessageDelayed(
4673                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
4674                    mPrivateHandler.sendEmptyMessageDelayed(
4675                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
4676                    if (inFullScreenMode() || mDeferTouchProcess) {
4677                        mPreventDefault = PREVENT_DEFAULT_YES;
4678                    } else if (mForwardTouchEvents) {
4679                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
4680                    } else {
4681                        mPreventDefault = PREVENT_DEFAULT_NO;
4682                    }
4683                    // pass the touch events from UI thread to WebCore thread
4684                    if (shouldForwardTouchEvent()) {
4685                        TouchEventData ted = new TouchEventData();
4686                        ted.mAction = action;
4687                        ted.mX = contentX;
4688                        ted.mY = contentY;
4689                        ted.mMetaState = ev.getMetaState();
4690                        ted.mReprocess = mDeferTouchProcess;
4691                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4692                        if (mDeferTouchProcess) {
4693                            // still needs to set them for compute deltaX/Y
4694                            mLastTouchX = x;
4695                            mLastTouchY = y;
4696                            break;
4697                        }
4698                        if (!inFullScreenMode()) {
4699                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
4700                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
4701                                            action, 0), TAP_TIMEOUT);
4702                        }
4703                    }
4704                }
4705                startTouch(x, y, eventTime);
4706                break;
4707            }
4708            case MotionEvent.ACTION_MOVE: {
4709                boolean firstMove = false;
4710                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
4711                        >= mTouchSlopSquare) {
4712                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4713                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4714                    mConfirmMove = true;
4715                    firstMove = true;
4716                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4717                        mTouchMode = TOUCH_INIT_MODE;
4718                    }
4719                }
4720                // pass the touch events from UI thread to WebCore thread
4721                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
4722                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
4723                    TouchEventData ted = new TouchEventData();
4724                    ted.mAction = action;
4725                    ted.mX = contentX;
4726                    ted.mY = contentY;
4727                    ted.mMetaState = ev.getMetaState();
4728                    ted.mReprocess = mDeferTouchProcess;
4729                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4730                    mLastSentTouchTime = eventTime;
4731                    if (mDeferTouchProcess) {
4732                        break;
4733                    }
4734                    if (firstMove && !inFullScreenMode()) {
4735                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
4736                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
4737                                        action, 0), TAP_TIMEOUT);
4738                    }
4739                }
4740                if (mTouchMode == TOUCH_DONE_MODE
4741                        || mPreventDefault == PREVENT_DEFAULT_YES) {
4742                    // no dragging during scroll zoom animation, or when prevent
4743                    // default is yes
4744                    break;
4745                }
4746                if (mVelocityTracker == null) {
4747                    Log.e(LOGTAG, "Got null mVelocityTracker when "
4748                            + "mPreventDefault = " + mPreventDefault
4749                            + " mDeferTouchProcess = " + mDeferTouchProcess
4750                            + " mTouchMode = " + mTouchMode);
4751                }
4752                mVelocityTracker.addMovement(ev);
4753                if (mTouchMode != TOUCH_DRAG_MODE) {
4754                    if (mTouchMode == TOUCH_SELECT_MODE) {
4755                        mSelectX = mScrollX + (int) x;
4756                        mSelectY = mScrollY + (int) y;
4757                        if (DebugFlags.WEB_VIEW) {
4758                            Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
4759                        }
4760                        nativeMoveSelection(contentX, contentY, true);
4761                        invalidate();
4762                        break;
4763                    }
4764                    if (!mConfirmMove) {
4765                        break;
4766                    }
4767                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
4768                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
4769                        // track mLastTouchTime as we may need to do fling at
4770                        // ACTION_UP
4771                        mLastTouchTime = eventTime;
4772                        break;
4773                    }
4774                    // if it starts nearly horizontal or vertical, enforce it
4775                    int ax = Math.abs(deltaX);
4776                    int ay = Math.abs(deltaY);
4777                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
4778                        mSnapScrollMode = SNAP_X;
4779                        mSnapPositive = deltaX > 0;
4780                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
4781                        mSnapScrollMode = SNAP_Y;
4782                        mSnapPositive = deltaY > 0;
4783                    }
4784
4785                    mTouchMode = TOUCH_DRAG_MODE;
4786                    mLastTouchX = x;
4787                    mLastTouchY = y;
4788                    fDeltaX = 0.0f;
4789                    fDeltaY = 0.0f;
4790                    deltaX = 0;
4791                    deltaY = 0;
4792
4793                    startDrag();
4794                }
4795
4796                if (mDragTrackerHandler != null) {
4797                    mDragTrackerHandler.dragTo(x, y);
4798                }
4799
4800                // do pan
4801                int newScrollX = pinLocX(mScrollX + deltaX);
4802                int newDeltaX = newScrollX - mScrollX;
4803                if (deltaX != newDeltaX) {
4804                    deltaX = newDeltaX;
4805                    fDeltaX = (float) newDeltaX;
4806                }
4807                int newScrollY = pinLocY(mScrollY + deltaY);
4808                int newDeltaY = newScrollY - mScrollY;
4809                if (deltaY != newDeltaY) {
4810                    deltaY = newDeltaY;
4811                    fDeltaY = (float) newDeltaY;
4812                }
4813                boolean done = false;
4814                boolean keepScrollBarsVisible = false;
4815                if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
4816                    keepScrollBarsVisible = done = true;
4817                } else {
4818                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
4819                        int ax = Math.abs(deltaX);
4820                        int ay = Math.abs(deltaY);
4821                        if (mSnapScrollMode == SNAP_X) {
4822                            // radical change means getting out of snap mode
4823                            if (ay > MAX_SLOPE_FOR_DIAG * ax
4824                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
4825                                mSnapScrollMode = SNAP_NONE;
4826                            }
4827                            // reverse direction means lock in the snap mode
4828                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
4829                                    (mSnapPositive
4830                                    ? deltaX < -mMinLockSnapReverseDistance
4831                                    : deltaX > mMinLockSnapReverseDistance)) {
4832                                mSnapScrollMode |= SNAP_LOCK;
4833                            }
4834                        } else {
4835                            // radical change means getting out of snap mode
4836                            if (ax > MAX_SLOPE_FOR_DIAG * ay
4837                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
4838                                mSnapScrollMode = SNAP_NONE;
4839                            }
4840                            // reverse direction means lock in the snap mode
4841                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
4842                                    (mSnapPositive
4843                                    ? deltaY < -mMinLockSnapReverseDistance
4844                                    : deltaY > mMinLockSnapReverseDistance)) {
4845                                mSnapScrollMode |= SNAP_LOCK;
4846                            }
4847                        }
4848                    }
4849                    if (mSnapScrollMode != SNAP_NONE) {
4850                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
4851                            deltaY = 0;
4852                        } else {
4853                            deltaX = 0;
4854                        }
4855                    }
4856                    if ((deltaX | deltaY) != 0) {
4857                        if (deltaX != 0) {
4858                            mLastTouchX = x;
4859                        }
4860                        if (deltaY != 0) {
4861                            mLastTouchY = y;
4862                        }
4863                        mHeldMotionless = MOTIONLESS_FALSE;
4864                    } else {
4865                        // keep the scrollbar on the screen even there is no
4866                        // scroll
4867                        keepScrollBarsVisible = true;
4868                    }
4869                    mLastTouchTime = eventTime;
4870                    mUserScroll = true;
4871                }
4872
4873                doDrag(deltaX, deltaY);
4874
4875                if (keepScrollBarsVisible) {
4876                    if (mHeldMotionless != MOTIONLESS_TRUE) {
4877                        mHeldMotionless = MOTIONLESS_TRUE;
4878                        invalidate();
4879                    }
4880                    // keep the scrollbar on the screen even there is no scroll
4881                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
4882                            false);
4883                    // return false to indicate that we can't pan out of the
4884                    // view space
4885                    return !done;
4886                }
4887                break;
4888            }
4889            case MotionEvent.ACTION_UP: {
4890                if (!isFocused()) requestFocus();
4891                // pass the touch events from UI thread to WebCore thread
4892                if (shouldForwardTouchEvent()) {
4893                    TouchEventData ted = new TouchEventData();
4894                    ted.mAction = action;
4895                    ted.mX = contentX;
4896                    ted.mY = contentY;
4897                    ted.mMetaState = ev.getMetaState();
4898                    ted.mReprocess = mDeferTouchProcess;
4899                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4900                }
4901                mLastTouchUpTime = eventTime;
4902                switch (mTouchMode) {
4903                    case TOUCH_DOUBLE_TAP_MODE: // double tap
4904                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4905                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4906                        if (inFullScreenMode() || mDeferTouchProcess) {
4907                            TouchEventData ted = new TouchEventData();
4908                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
4909                            ted.mX = contentX;
4910                            ted.mY = contentY;
4911                            ted.mMetaState = ev.getMetaState();
4912                            ted.mReprocess = mDeferTouchProcess;
4913                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4914                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
4915                            doDoubleTap();
4916                            mTouchMode = TOUCH_DONE_MODE;
4917                        }
4918                        break;
4919                    case TOUCH_SELECT_MODE:
4920                        commitCopy();
4921                        mTouchSelection = false;
4922                        break;
4923                    case TOUCH_INIT_MODE: // tap
4924                    case TOUCH_SHORTPRESS_START_MODE:
4925                    case TOUCH_SHORTPRESS_MODE:
4926                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4927                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4928                        if (mConfirmMove) {
4929                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
4930                                    " WebCore's response for touch down.");
4931                            if (mPreventDefault != PREVENT_DEFAULT_YES
4932                                    && (computeMaxScrollX() > 0
4933                                            || computeMaxScrollY() > 0)) {
4934                                // UI takes control back, cancel WebCore touch
4935                                cancelWebCoreTouchEvent(contentX, contentY,
4936                                        true);
4937                                // we will not rewrite drag code here, but we
4938                                // will try fling if it applies.
4939                                WebViewCore.reducePriority();
4940                                // to get better performance, pause updating the
4941                                // picture
4942                                WebViewCore.pauseUpdatePicture(mWebViewCore);
4943                                // fall through to TOUCH_DRAG_MODE
4944                            } else {
4945                                // WebKit may consume the touch event and modify
4946                                // DOM. drawContentPicture() will be called with
4947                                // animateSroll as true for better performance.
4948                                // Force redraw in high-quality.
4949                                invalidate();
4950                                break;
4951                            }
4952                        } else {
4953                            if (mTouchMode == TOUCH_INIT_MODE) {
4954                                mPrivateHandler.sendEmptyMessageDelayed(
4955                                        RELEASE_SINGLE_TAP, ViewConfiguration
4956                                                .getDoubleTapTimeout());
4957                            } else {
4958                                doShortPress();
4959                            }
4960                            break;
4961                        }
4962                    case TOUCH_DRAG_MODE:
4963                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4964                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4965                        // if the user waits a while w/o moving before the
4966                        // up, we don't want to do a fling
4967                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
4968                            if (mVelocityTracker == null) {
4969                                Log.e(LOGTAG, "Got null mVelocityTracker when "
4970                                        + "mPreventDefault = "
4971                                        + mPreventDefault
4972                                        + " mDeferTouchProcess = "
4973                                        + mDeferTouchProcess);
4974                            }
4975                            mVelocityTracker.addMovement(ev);
4976                            // set to MOTIONLESS_IGNORE so that it won't keep
4977                            // removing and sending message in
4978                            // drawCoreAndCursorRing()
4979                            mHeldMotionless = MOTIONLESS_IGNORE;
4980                            doFling();
4981                            break;
4982                        }
4983                        // redraw in high-quality, as we're done dragging
4984                        mHeldMotionless = MOTIONLESS_TRUE;
4985                        invalidate();
4986                        // fall through
4987                    case TOUCH_DRAG_START_MODE:
4988                        // TOUCH_DRAG_START_MODE should not happen for the real
4989                        // device as we almost certain will get a MOVE. But this
4990                        // is possible on emulator.
4991                        mLastVelocity = 0;
4992                        WebViewCore.resumePriority();
4993                        WebViewCore.resumeUpdatePicture(mWebViewCore);
4994                        break;
4995                }
4996                stopTouch();
4997                break;
4998            }
4999            case MotionEvent.ACTION_CANCEL: {
5000                if (mTouchMode == TOUCH_DRAG_MODE) {
5001                    invalidate();
5002                }
5003                cancelWebCoreTouchEvent(contentX, contentY, false);
5004                cancelTouch();
5005                break;
5006            }
5007        }
5008        return true;
5009    }
5010
5011    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
5012        if (shouldForwardTouchEvent()) {
5013            if (removeEvents) {
5014                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5015            }
5016            TouchEventData ted = new TouchEventData();
5017            ted.mX = x;
5018            ted.mY = y;
5019            ted.mAction = MotionEvent.ACTION_CANCEL;
5020            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5021            mPreventDefault = PREVENT_DEFAULT_IGNORE;
5022        }
5023    }
5024
5025    private void startTouch(float x, float y, long eventTime) {
5026        // Remember where the motion event started
5027        mLastTouchX = x;
5028        mLastTouchY = y;
5029        mLastTouchTime = eventTime;
5030        mVelocityTracker = VelocityTracker.obtain();
5031        mSnapScrollMode = SNAP_NONE;
5032        if (mDragTracker != null) {
5033            mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker);
5034        }
5035    }
5036
5037    private void startDrag() {
5038        WebViewCore.reducePriority();
5039        // to get better performance, pause updating the picture
5040        WebViewCore.pauseUpdatePicture(mWebViewCore);
5041        if (!mDragFromTextInput) {
5042            nativeHideCursor();
5043        }
5044        WebSettings settings = getSettings();
5045        if (settings.supportZoom()
5046                && settings.getBuiltInZoomControls()
5047                && !getZoomButtonsController().isVisible()
5048                && mMinZoomScale < mMaxZoomScale
5049                && (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
5050                        || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF)) {
5051            mZoomButtonsController.setVisible(true);
5052            int count = settings.getDoubleTapToastCount();
5053            if (mInZoomOverview && count > 0) {
5054                settings.setDoubleTapToastCount(--count);
5055                Toast.makeText(mContext,
5056                        com.android.internal.R.string.double_tap_toast,
5057                        Toast.LENGTH_LONG).show();
5058            }
5059        }
5060    }
5061
5062    private void doDrag(int deltaX, int deltaY) {
5063        if ((deltaX | deltaY) != 0) {
5064            scrollBy(deltaX, deltaY);
5065        }
5066        if (!getSettings().getBuiltInZoomControls()) {
5067            boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
5068            if (mZoomControls != null && showPlusMinus) {
5069                if (mZoomControls.getVisibility() == View.VISIBLE) {
5070                    mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5071                } else {
5072                    mZoomControls.show(showPlusMinus, false);
5073                }
5074                mPrivateHandler.postDelayed(mZoomControlRunnable,
5075                        ZOOM_CONTROLS_TIMEOUT);
5076            }
5077        }
5078    }
5079
5080    private void stopTouch() {
5081        if (mDragTrackerHandler != null) {
5082            mDragTrackerHandler.stopDrag();
5083        }
5084        // we also use mVelocityTracker == null to tell us that we are
5085        // not "moving around", so we can take the slower/prettier
5086        // mode in the drawing code
5087        if (mVelocityTracker != null) {
5088            mVelocityTracker.recycle();
5089            mVelocityTracker = null;
5090        }
5091    }
5092
5093    private void cancelTouch() {
5094        if (mDragTrackerHandler != null) {
5095            mDragTrackerHandler.stopDrag();
5096        }
5097        // we also use mVelocityTracker == null to tell us that we are
5098        // not "moving around", so we can take the slower/prettier
5099        // mode in the drawing code
5100        if (mVelocityTracker != null) {
5101            mVelocityTracker.recycle();
5102            mVelocityTracker = null;
5103        }
5104        if (mTouchMode == TOUCH_DRAG_MODE) {
5105            WebViewCore.resumePriority();
5106            WebViewCore.resumeUpdatePicture(mWebViewCore);
5107        }
5108        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5109        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5110        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5111        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5112        mHeldMotionless = MOTIONLESS_TRUE;
5113        mTouchMode = TOUCH_DONE_MODE;
5114        nativeHideCursor();
5115    }
5116
5117    private long mTrackballFirstTime = 0;
5118    private long mTrackballLastTime = 0;
5119    private float mTrackballRemainsX = 0.0f;
5120    private float mTrackballRemainsY = 0.0f;
5121    private int mTrackballXMove = 0;
5122    private int mTrackballYMove = 0;
5123    private boolean mExtendSelection = false;
5124    private boolean mTouchSelection = false;
5125    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
5126    private static final int TRACKBALL_TIMEOUT = 200;
5127    private static final int TRACKBALL_WAIT = 100;
5128    private static final int TRACKBALL_SCALE = 400;
5129    private static final int TRACKBALL_SCROLL_COUNT = 5;
5130    private static final int TRACKBALL_MOVE_COUNT = 10;
5131    private static final int TRACKBALL_MULTIPLIER = 3;
5132    private static final int SELECT_CURSOR_OFFSET = 16;
5133    private int mSelectX = 0;
5134    private int mSelectY = 0;
5135    private boolean mFocusSizeChanged = false;
5136    private boolean mShiftIsPressed = false;
5137    private boolean mTrackballDown = false;
5138    private long mTrackballUpTime = 0;
5139    private long mLastCursorTime = 0;
5140    private Rect mLastCursorBounds;
5141
5142    // Set by default; BrowserActivity clears to interpret trackball data
5143    // directly for movement. Currently, the framework only passes
5144    // arrow key events, not trackball events, from one child to the next
5145    private boolean mMapTrackballToArrowKeys = true;
5146
5147    public void setMapTrackballToArrowKeys(boolean setMap) {
5148        mMapTrackballToArrowKeys = setMap;
5149    }
5150
5151    void resetTrackballTime() {
5152        mTrackballLastTime = 0;
5153    }
5154
5155    @Override
5156    public boolean onTrackballEvent(MotionEvent ev) {
5157        long time = ev.getEventTime();
5158        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
5159            if (ev.getY() > 0) pageDown(true);
5160            if (ev.getY() < 0) pageUp(true);
5161            return true;
5162        }
5163        boolean shiftPressed = mShiftIsPressed && (mNativeClass == 0
5164                || !nativeFocusIsPlugin());
5165        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
5166            if (shiftPressed) {
5167                return true; // discard press if copy in progress
5168            }
5169            mTrackballDown = true;
5170            if (mNativeClass == 0) {
5171                return false;
5172            }
5173            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
5174            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
5175                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
5176                nativeSelectBestAt(mLastCursorBounds);
5177            }
5178            if (DebugFlags.WEB_VIEW) {
5179                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
5180                        + " time=" + time
5181                        + " mLastCursorTime=" + mLastCursorTime);
5182            }
5183            if (isInTouchMode()) requestFocusFromTouch();
5184            return false; // let common code in onKeyDown at it
5185        }
5186        if (ev.getAction() == MotionEvent.ACTION_UP) {
5187            // LONG_PRESS_CENTER is set in common onKeyDown
5188            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5189            mTrackballDown = false;
5190            mTrackballUpTime = time;
5191            if (shiftPressed) {
5192                if (mExtendSelection) {
5193                    commitCopy();
5194                } else {
5195                    mExtendSelection = true;
5196                    invalidate(); // draw the i-beam instead of the arrow
5197                }
5198                return true; // discard press if copy in progress
5199            }
5200            if (DebugFlags.WEB_VIEW) {
5201                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
5202                        + " time=" + time
5203                );
5204            }
5205            return false; // let common code in onKeyUp at it
5206        }
5207        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
5208            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
5209            return false;
5210        }
5211        if (mTrackballDown) {
5212            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
5213            return true; // discard move if trackball is down
5214        }
5215        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
5216            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
5217            return true;
5218        }
5219        // TODO: alternatively we can do panning as touch does
5220        switchOutDrawHistory();
5221        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
5222            if (DebugFlags.WEB_VIEW) {
5223                Log.v(LOGTAG, "onTrackballEvent time="
5224                        + time + " last=" + mTrackballLastTime);
5225            }
5226            mTrackballFirstTime = time;
5227            mTrackballXMove = mTrackballYMove = 0;
5228        }
5229        mTrackballLastTime = time;
5230        if (DebugFlags.WEB_VIEW) {
5231            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
5232        }
5233        mTrackballRemainsX += ev.getX();
5234        mTrackballRemainsY += ev.getY();
5235        doTrackball(time);
5236        return true;
5237    }
5238
5239    void moveSelection(float xRate, float yRate) {
5240        if (mNativeClass == 0)
5241            return;
5242        int width = getViewWidth();
5243        int height = getViewHeight();
5244        mSelectX += xRate;
5245        mSelectY += yRate;
5246        int maxX = width + mScrollX;
5247        int maxY = height + mScrollY;
5248        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
5249                , mSelectX));
5250        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
5251                , mSelectY));
5252        if (DebugFlags.WEB_VIEW) {
5253            Log.v(LOGTAG, "moveSelection"
5254                    + " mSelectX=" + mSelectX
5255                    + " mSelectY=" + mSelectY
5256                    + " mScrollX=" + mScrollX
5257                    + " mScrollY=" + mScrollY
5258                    + " xRate=" + xRate
5259                    + " yRate=" + yRate
5260                    );
5261        }
5262        nativeMoveSelection(viewToContentX(mSelectX),
5263                viewToContentY(mSelectY), mExtendSelection);
5264        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
5265                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5266                : 0;
5267        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
5268                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5269                : 0;
5270        pinScrollBy(scrollX, scrollY, true, 0);
5271        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
5272        requestRectangleOnScreen(select);
5273        invalidate();
5274   }
5275
5276    private int scaleTrackballX(float xRate, int width) {
5277        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
5278        int nextXMove = xMove;
5279        if (xMove > 0) {
5280            if (xMove > mTrackballXMove) {
5281                xMove -= mTrackballXMove;
5282            }
5283        } else if (xMove < mTrackballXMove) {
5284            xMove -= mTrackballXMove;
5285        }
5286        mTrackballXMove = nextXMove;
5287        return xMove;
5288    }
5289
5290    private int scaleTrackballY(float yRate, int height) {
5291        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
5292        int nextYMove = yMove;
5293        if (yMove > 0) {
5294            if (yMove > mTrackballYMove) {
5295                yMove -= mTrackballYMove;
5296            }
5297        } else if (yMove < mTrackballYMove) {
5298            yMove -= mTrackballYMove;
5299        }
5300        mTrackballYMove = nextYMove;
5301        return yMove;
5302    }
5303
5304    private int keyCodeToSoundsEffect(int keyCode) {
5305        switch(keyCode) {
5306            case KeyEvent.KEYCODE_DPAD_UP:
5307                return SoundEffectConstants.NAVIGATION_UP;
5308            case KeyEvent.KEYCODE_DPAD_RIGHT:
5309                return SoundEffectConstants.NAVIGATION_RIGHT;
5310            case KeyEvent.KEYCODE_DPAD_DOWN:
5311                return SoundEffectConstants.NAVIGATION_DOWN;
5312            case KeyEvent.KEYCODE_DPAD_LEFT:
5313                return SoundEffectConstants.NAVIGATION_LEFT;
5314        }
5315        throw new IllegalArgumentException("keyCode must be one of " +
5316                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
5317                "KEYCODE_DPAD_LEFT}.");
5318    }
5319
5320    private void doTrackball(long time) {
5321        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
5322        if (elapsed == 0) {
5323            elapsed = TRACKBALL_TIMEOUT;
5324        }
5325        float xRate = mTrackballRemainsX * 1000 / elapsed;
5326        float yRate = mTrackballRemainsY * 1000 / elapsed;
5327        int viewWidth = getViewWidth();
5328        int viewHeight = getViewHeight();
5329        if (mShiftIsPressed && (mNativeClass == 0 || !nativeFocusIsPlugin())) {
5330            moveSelection(scaleTrackballX(xRate, viewWidth),
5331                    scaleTrackballY(yRate, viewHeight));
5332            mTrackballRemainsX = mTrackballRemainsY = 0;
5333            return;
5334        }
5335        float ax = Math.abs(xRate);
5336        float ay = Math.abs(yRate);
5337        float maxA = Math.max(ax, ay);
5338        if (DebugFlags.WEB_VIEW) {
5339            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
5340                    + " xRate=" + xRate
5341                    + " yRate=" + yRate
5342                    + " mTrackballRemainsX=" + mTrackballRemainsX
5343                    + " mTrackballRemainsY=" + mTrackballRemainsY);
5344        }
5345        int width = mContentWidth - viewWidth;
5346        int height = mContentHeight - viewHeight;
5347        if (width < 0) width = 0;
5348        if (height < 0) height = 0;
5349        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
5350        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
5351        maxA = Math.max(ax, ay);
5352        int count = Math.max(0, (int) maxA);
5353        int oldScrollX = mScrollX;
5354        int oldScrollY = mScrollY;
5355        if (count > 0) {
5356            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
5357                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
5358                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
5359                    KeyEvent.KEYCODE_DPAD_RIGHT;
5360            count = Math.min(count, TRACKBALL_MOVE_COUNT);
5361            if (DebugFlags.WEB_VIEW) {
5362                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
5363                        + " count=" + count
5364                        + " mTrackballRemainsX=" + mTrackballRemainsX
5365                        + " mTrackballRemainsY=" + mTrackballRemainsY);
5366            }
5367            if (mNativeClass != 0 && nativeFocusIsPlugin()) {
5368                for (int i = 0; i < count; i++) {
5369                    letPluginHandleNavKey(selectKeyCode, time, true);
5370                }
5371                letPluginHandleNavKey(selectKeyCode, time, false);
5372            } else if (navHandledKey(selectKeyCode, count, false, time)) {
5373                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
5374            }
5375            mTrackballRemainsX = mTrackballRemainsY = 0;
5376        }
5377        if (count >= TRACKBALL_SCROLL_COUNT) {
5378            int xMove = scaleTrackballX(xRate, width);
5379            int yMove = scaleTrackballY(yRate, height);
5380            if (DebugFlags.WEB_VIEW) {
5381                Log.v(LOGTAG, "doTrackball pinScrollBy"
5382                        + " count=" + count
5383                        + " xMove=" + xMove + " yMove=" + yMove
5384                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
5385                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
5386                        );
5387            }
5388            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
5389                xMove = 0;
5390            }
5391            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
5392                yMove = 0;
5393            }
5394            if (xMove != 0 || yMove != 0) {
5395                pinScrollBy(xMove, yMove, true, 0);
5396            }
5397            mUserScroll = true;
5398        }
5399    }
5400
5401    private int computeMaxScrollX() {
5402        return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
5403    }
5404
5405    private int computeMaxScrollY() {
5406        return Math.max(computeVerticalScrollRange() + getTitleHeight()
5407                - getViewHeightWithTitle(), 0);
5408    }
5409
5410    public void flingScroll(int vx, int vy) {
5411        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
5412                computeMaxScrollY());
5413        invalidate();
5414    }
5415
5416    private void doFling() {
5417        if (mVelocityTracker == null) {
5418            return;
5419        }
5420        int maxX = computeMaxScrollX();
5421        int maxY = computeMaxScrollY();
5422
5423        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
5424        int vx = (int) mVelocityTracker.getXVelocity();
5425        int vy = (int) mVelocityTracker.getYVelocity();
5426
5427        if (mSnapScrollMode != SNAP_NONE) {
5428            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5429                vy = 0;
5430            } else {
5431                vx = 0;
5432            }
5433        }
5434        if (true /* EMG release: make our fling more like Maps' */) {
5435            // maps cuts their velocity in half
5436            vx = vx * 3 / 4;
5437            vy = vy * 3 / 4;
5438        }
5439        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
5440            WebViewCore.resumePriority();
5441            WebViewCore.resumeUpdatePicture(mWebViewCore);
5442            return;
5443        }
5444        float currentVelocity = mScroller.getCurrVelocity();
5445        if (mLastVelocity > 0 && currentVelocity > 0) {
5446            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
5447                    - Math.atan2(vy, vx)));
5448            final float circle = (float) (Math.PI) * 2.0f;
5449            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
5450                vx += currentVelocity * mLastVelX / mLastVelocity;
5451                vy += currentVelocity * mLastVelY / mLastVelocity;
5452                if (DebugFlags.WEB_VIEW) {
5453                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
5454                }
5455            } else if (DebugFlags.WEB_VIEW) {
5456                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
5457            }
5458        } else if (DebugFlags.WEB_VIEW) {
5459            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
5460                    + " current=" + currentVelocity
5461                    + " vx=" + vx + " vy=" + vy
5462                    + " maxX=" + maxX + " maxY=" + maxY
5463                    + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
5464        }
5465        mLastVelX = vx;
5466        mLastVelY = vy;
5467        mLastVelocity = (float) Math.hypot(vx, vy);
5468
5469        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
5470        // TODO: duration is calculated based on velocity, if the range is
5471        // small, the animation will stop before duration is up. We may
5472        // want to calculate how long the animation is going to run to precisely
5473        // resume the webcore update.
5474        final int time = mScroller.getDuration();
5475        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time);
5476        awakenScrollBars(time);
5477        invalidate();
5478    }
5479
5480    private boolean zoomWithPreview(float scale, boolean updateTextWrapScale) {
5481        float oldScale = mActualScale;
5482        mInitialScrollX = mScrollX;
5483        mInitialScrollY = mScrollY;
5484
5485        // snap to DEFAULT_SCALE if it is close
5486        if (Math.abs(scale - mDefaultScale) < MINIMUM_SCALE_INCREMENT) {
5487            scale = mDefaultScale;
5488        }
5489
5490        setNewZoomScale(scale, updateTextWrapScale, false);
5491
5492        if (oldScale != mActualScale) {
5493            // use mZoomPickerScale to see zoom preview first
5494            mZoomStart = SystemClock.uptimeMillis();
5495            mInvInitialZoomScale = 1.0f / oldScale;
5496            mInvFinalZoomScale = 1.0f / mActualScale;
5497            mZoomScale = mActualScale;
5498            WebViewCore.pauseUpdatePicture(mWebViewCore);
5499            invalidate();
5500            return true;
5501        } else {
5502            return false;
5503        }
5504    }
5505
5506    /**
5507     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
5508     * in charge of installing this view to the view hierarchy. This view will
5509     * become visible when the user starts scrolling via touch and fade away if
5510     * the user does not interact with it.
5511     * <p/>
5512     * API version 3 introduces a built-in zoom mechanism that is shown
5513     * automatically by the MapView. This is the preferred approach for
5514     * showing the zoom UI.
5515     *
5516     * @deprecated The built-in zoom mechanism is preferred, see
5517     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
5518     */
5519    @Deprecated
5520    public View getZoomControls() {
5521        if (!getSettings().supportZoom()) {
5522            Log.w(LOGTAG, "This WebView doesn't support zoom.");
5523            return null;
5524        }
5525        if (mZoomControls == null) {
5526            mZoomControls = createZoomControls();
5527
5528            /*
5529             * need to be set to VISIBLE first so that getMeasuredHeight() in
5530             * {@link #onSizeChanged()} can return the measured value for proper
5531             * layout.
5532             */
5533            mZoomControls.setVisibility(View.VISIBLE);
5534            mZoomControlRunnable = new Runnable() {
5535                public void run() {
5536
5537                    /* Don't dismiss the controls if the user has
5538                     * focus on them. Wait and check again later.
5539                     */
5540                    if (!mZoomControls.hasFocus()) {
5541                        mZoomControls.hide();
5542                    } else {
5543                        mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5544                        mPrivateHandler.postDelayed(mZoomControlRunnable,
5545                                ZOOM_CONTROLS_TIMEOUT);
5546                    }
5547                }
5548            };
5549        }
5550        return mZoomControls;
5551    }
5552
5553    private ExtendedZoomControls createZoomControls() {
5554        ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext
5555            , null);
5556        zoomControls.setOnZoomInClickListener(new OnClickListener() {
5557            public void onClick(View v) {
5558                // reset time out
5559                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5560                mPrivateHandler.postDelayed(mZoomControlRunnable,
5561                        ZOOM_CONTROLS_TIMEOUT);
5562                zoomIn();
5563            }
5564        });
5565        zoomControls.setOnZoomOutClickListener(new OnClickListener() {
5566            public void onClick(View v) {
5567                // reset time out
5568                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5569                mPrivateHandler.postDelayed(mZoomControlRunnable,
5570                        ZOOM_CONTROLS_TIMEOUT);
5571                zoomOut();
5572            }
5573        });
5574        return zoomControls;
5575    }
5576
5577    /**
5578     * Gets the {@link ZoomButtonsController} which can be used to add
5579     * additional buttons to the zoom controls window.
5580     *
5581     * @return The instance of {@link ZoomButtonsController} used by this class,
5582     *         or null if it is unavailable.
5583     * @hide
5584     */
5585    public ZoomButtonsController getZoomButtonsController() {
5586        if (mZoomButtonsController == null) {
5587            mZoomButtonsController = new ZoomButtonsController(this);
5588            mZoomButtonsController.setOnZoomListener(mZoomListener);
5589            // ZoomButtonsController positions the buttons at the bottom, but in
5590            // the middle. Change their layout parameters so they appear on the
5591            // right.
5592            View controls = mZoomButtonsController.getZoomControls();
5593            ViewGroup.LayoutParams params = controls.getLayoutParams();
5594            if (params instanceof FrameLayout.LayoutParams) {
5595                FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) params;
5596                frameParams.gravity = Gravity.RIGHT;
5597            }
5598        }
5599        return mZoomButtonsController;
5600    }
5601
5602    /**
5603     * Perform zoom in in the webview
5604     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
5605     */
5606    public boolean zoomIn() {
5607        // TODO: alternatively we can disallow this during draw history mode
5608        switchOutDrawHistory();
5609        mInZoomOverview = false;
5610        // Center zooming to the center of the screen.
5611        mZoomCenterX = getViewWidth() * .5f;
5612        mZoomCenterY = getViewHeight() * .5f;
5613        mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
5614        mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
5615        return zoomWithPreview(mActualScale * 1.25f, true);
5616    }
5617
5618    /**
5619     * Perform zoom out in the webview
5620     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
5621     */
5622    public boolean zoomOut() {
5623        // TODO: alternatively we can disallow this during draw history mode
5624        switchOutDrawHistory();
5625        // Center zooming to the center of the screen.
5626        mZoomCenterX = getViewWidth() * .5f;
5627        mZoomCenterY = getViewHeight() * .5f;
5628        mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
5629        mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
5630        return zoomWithPreview(mActualScale * 0.8f, true);
5631    }
5632
5633    private void updateSelection() {
5634        if (mNativeClass == 0) {
5635            return;
5636        }
5637        // mLastTouchX and mLastTouchY are the point in the current viewport
5638        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5639        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5640        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
5641                contentX + mNavSlop, contentY + mNavSlop);
5642        nativeSelectBestAt(rect);
5643    }
5644
5645    /**
5646     * Scroll the focused text field/area to match the WebTextView
5647     * @param xPercent New x position of the WebTextView from 0 to 1.
5648     * @param y New y position of the WebTextView in view coordinates
5649     */
5650    /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
5651        if (!inEditingMode() || mWebViewCore == null) {
5652            return;
5653        }
5654        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
5655                // Since this position is relative to the top of the text input
5656                // field, we do not need to take the title bar's height into
5657                // consideration.
5658                viewToContentDimension(y),
5659                new Float(xPercent));
5660    }
5661
5662    /**
5663     * Set our starting point and time for a drag from the WebTextView.
5664     */
5665    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
5666        if (!inEditingMode()) {
5667            return;
5668        }
5669        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
5670        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
5671        mLastTouchTime = eventTime;
5672        if (!mScroller.isFinished()) {
5673            abortAnimation();
5674            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5675        }
5676        mSnapScrollMode = SNAP_NONE;
5677        mVelocityTracker = VelocityTracker.obtain();
5678        mTouchMode = TOUCH_DRAG_START_MODE;
5679    }
5680
5681    /**
5682     * Given a motion event from the WebTextView, set its location to our
5683     * coordinates, and handle the event.
5684     */
5685    /*package*/ boolean textFieldDrag(MotionEvent event) {
5686        if (!inEditingMode()) {
5687            return false;
5688        }
5689        mDragFromTextInput = true;
5690        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
5691                (float) (mWebTextView.getTop() - mScrollY));
5692        boolean result = onTouchEvent(event);
5693        mDragFromTextInput = false;
5694        return result;
5695    }
5696
5697    /**
5698     * Due a touch up from a WebTextView.  This will be handled by webkit to
5699     * change the selection.
5700     * @param event MotionEvent in the WebTextView's coordinates.
5701     */
5702    /*package*/ void touchUpOnTextField(MotionEvent event) {
5703        if (!inEditingMode()) {
5704            return;
5705        }
5706        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
5707        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
5708        nativeMotionUp(x, y, mNavSlop);
5709    }
5710
5711    /**
5712     * Called when pressing the center key or trackball on a textfield.
5713     */
5714    /*package*/ void centerKeyPressOnTextField() {
5715        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
5716                    nativeCursorNodePointer());
5717    }
5718
5719    private void doShortPress() {
5720        if (mNativeClass == 0) {
5721            return;
5722        }
5723        if (mPreventDefault == PREVENT_DEFAULT_YES) {
5724            return;
5725        }
5726        mTouchMode = TOUCH_DONE_MODE;
5727        switchOutDrawHistory();
5728        // mLastTouchX and mLastTouchY are the point in the current viewport
5729        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5730        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5731        if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
5732            WebViewCore.MotionUpData motionUpData = new WebViewCore
5733                    .MotionUpData();
5734            motionUpData.mFrame = nativeCacheHitFramePointer();
5735            motionUpData.mNode = nativeCacheHitNodePointer();
5736            motionUpData.mBounds = nativeCacheHitNodeBounds();
5737            motionUpData.mX = contentX;
5738            motionUpData.mY = contentY;
5739            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
5740                    motionUpData);
5741        } else {
5742            doMotionUp(contentX, contentY);
5743        }
5744    }
5745
5746    private void doMotionUp(int contentX, int contentY) {
5747        if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) {
5748            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
5749        }
5750        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
5751            playSoundEffect(SoundEffectConstants.CLICK);
5752        }
5753    }
5754
5755    /*
5756     * Return true if the view (Plugin) is fully visible and maximized inside
5757     * the WebView.
5758     */
5759    private boolean isPluginFitOnScreen(ViewManager.ChildView view) {
5760        int viewWidth = getViewWidth();
5761        int viewHeight = getViewHeightWithTitle();
5762        float scale = Math.min((float) viewWidth / view.width,
5763                (float) viewHeight / view.height);
5764        if (scale < mMinZoomScale) {
5765            scale = mMinZoomScale;
5766        } else if (scale > mMaxZoomScale) {
5767            scale = mMaxZoomScale;
5768        }
5769        if (Math.abs(scale - mActualScale) < MINIMUM_SCALE_INCREMENT) {
5770            if (contentToViewX(view.x) >= mScrollX
5771                    && contentToViewX(view.x + view.width) <= mScrollX
5772                            + viewWidth
5773                    && contentToViewY(view.y) >= mScrollY
5774                    && contentToViewY(view.y + view.height) <= mScrollY
5775                            + viewHeight) {
5776                return true;
5777            }
5778        }
5779        return false;
5780    }
5781
5782    /*
5783     * Maximize and center the rectangle, specified in the document coordinate
5784     * space, inside the WebView. If the zoom doesn't need to be changed, do an
5785     * animated scroll to center it. If the zoom needs to be changed, find the
5786     * zoom center and do a smooth zoom transition.
5787     */
5788    private void centerFitRect(int docX, int docY, int docWidth, int docHeight) {
5789        int viewWidth = getViewWidth();
5790        int viewHeight = getViewHeightWithTitle();
5791        float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight
5792                / docHeight);
5793        if (scale < mMinZoomScale) {
5794            scale = mMinZoomScale;
5795        } else if (scale > mMaxZoomScale) {
5796            scale = mMaxZoomScale;
5797        }
5798        if (Math.abs(scale - mActualScale) < MINIMUM_SCALE_INCREMENT) {
5799            pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2,
5800                    contentToViewY(docY + docHeight / 2) - viewHeight / 2,
5801                    true, 0);
5802        } else {
5803            float oldScreenX = docX * mActualScale - mScrollX;
5804            float rectViewX = docX * scale;
5805            float rectViewWidth = docWidth * scale;
5806            float newMaxWidth = mContentWidth * scale;
5807            float newScreenX = (viewWidth - rectViewWidth) / 2;
5808            // pin the newX to the WebView
5809            if (newScreenX > rectViewX) {
5810                newScreenX = rectViewX;
5811            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
5812                newScreenX = viewWidth - (newMaxWidth - rectViewX);
5813            }
5814            mZoomCenterX = (oldScreenX * scale - newScreenX * mActualScale)
5815                    / (scale - mActualScale);
5816            float oldScreenY = docY * mActualScale + getTitleHeight()
5817                    - mScrollY;
5818            float rectViewY = docY * scale + getTitleHeight();
5819            float rectViewHeight = docHeight * scale;
5820            float newMaxHeight = mContentHeight * scale + getTitleHeight();
5821            float newScreenY = (viewHeight - rectViewHeight) / 2;
5822            // pin the newY to the WebView
5823            if (newScreenY > rectViewY) {
5824                newScreenY = rectViewY;
5825            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
5826                newScreenY = viewHeight - (newMaxHeight - rectViewY);
5827            }
5828            mZoomCenterY = (oldScreenY * scale - newScreenY * mActualScale)
5829                    / (scale - mActualScale);
5830            zoomWithPreview(scale, false);
5831        }
5832    }
5833
5834    void dismissZoomControl() {
5835        if (mWebViewCore == null) {
5836            // maybe called after WebView's destroy(). As we can't get settings,
5837            // just hide zoom control for both styles.
5838            if (mZoomButtonsController != null) {
5839                mZoomButtonsController.setVisible(false);
5840            }
5841            if (mZoomControls != null) {
5842                mZoomControls.hide();
5843            }
5844            return;
5845        }
5846        WebSettings settings = getSettings();
5847        if (settings.getBuiltInZoomControls()) {
5848            if (mZoomButtonsController != null) {
5849                mZoomButtonsController.setVisible(false);
5850            }
5851        } else {
5852            if (mZoomControlRunnable != null) {
5853                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5854            }
5855            if (mZoomControls != null) {
5856                mZoomControls.hide();
5857            }
5858        }
5859    }
5860
5861    // Rule for double tap:
5862    // 1. if the current scale is not same as the text wrap scale and layout
5863    //    algorithm is NARROW_COLUMNS, fit to column;
5864    // 2. if the current state is not overview mode, change to overview mode;
5865    // 3. if the current state is overview mode, change to default scale.
5866    private void doDoubleTap() {
5867        if (mWebViewCore.getSettings().getUseWideViewPort() == false) {
5868            return;
5869        }
5870        mZoomCenterX = mLastTouchX;
5871        mZoomCenterY = mLastTouchY;
5872        mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
5873        mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
5874        WebSettings settings = getSettings();
5875        settings.setDoubleTapToastCount(0);
5876        // remove the zoom control after double tap
5877        dismissZoomControl();
5878        ViewManager.ChildView plugin = mViewManager.hitTest(mAnchorX, mAnchorY);
5879        if (plugin != null) {
5880            if (isPluginFitOnScreen(plugin)) {
5881                mInZoomOverview = true;
5882                // Force the titlebar fully reveal in overview mode
5883                if (mScrollY < getTitleHeight()) mScrollY = 0;
5884                zoomWithPreview((float) getViewWidth() / mZoomOverviewWidth,
5885                        true);
5886            } else {
5887                mInZoomOverview = false;
5888                centerFitRect(plugin.x, plugin.y, plugin.width, plugin.height);
5889            }
5890            return;
5891        }
5892        boolean zoomToDefault = false;
5893        if ((settings.getLayoutAlgorithm() == WebSettings.LayoutAlgorithm.NARROW_COLUMNS)
5894                && (Math.abs(mActualScale - mTextWrapScale) >= MINIMUM_SCALE_INCREMENT)) {
5895            setNewZoomScale(mActualScale, true, true);
5896            float overviewScale = (float) getViewWidth() / mZoomOverviewWidth;
5897            if (Math.abs(mActualScale - overviewScale) < MINIMUM_SCALE_INCREMENT) {
5898                mInZoomOverview = true;
5899            }
5900        } else if (!mInZoomOverview) {
5901            float newScale = (float) getViewWidth() / mZoomOverviewWidth;
5902            if (Math.abs(mActualScale - newScale) >= MINIMUM_SCALE_INCREMENT) {
5903                mInZoomOverview = true;
5904                // Force the titlebar fully reveal in overview mode
5905                if (mScrollY < getTitleHeight()) mScrollY = 0;
5906                zoomWithPreview(newScale, true);
5907            } else if (Math.abs(mActualScale - mDefaultScale) >= MINIMUM_SCALE_INCREMENT) {
5908                zoomToDefault = true;
5909            }
5910        } else {
5911            zoomToDefault = true;
5912        }
5913        if (zoomToDefault) {
5914            mInZoomOverview = false;
5915            int left = nativeGetBlockLeftEdge(mAnchorX, mAnchorY, mActualScale);
5916            if (left != NO_LEFTEDGE) {
5917                // add a 5pt padding to the left edge.
5918                int viewLeft = contentToViewX(left < 5 ? 0 : (left - 5))
5919                        - mScrollX;
5920                // Re-calculate the zoom center so that the new scroll x will be
5921                // on the left edge.
5922                if (viewLeft > 0) {
5923                    mZoomCenterX = viewLeft * mDefaultScale
5924                            / (mDefaultScale - mActualScale);
5925                } else {
5926                    scrollBy(viewLeft, 0);
5927                    mZoomCenterX = 0;
5928                }
5929            }
5930            zoomWithPreview(mDefaultScale, true);
5931        }
5932    }
5933
5934    // Called by JNI to handle a touch on a node representing an email address,
5935    // address, or phone number
5936    private void overrideLoading(String url) {
5937        mCallbackProxy.uiOverrideUrlLoading(url);
5938    }
5939
5940    @Override
5941    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5942        boolean result = false;
5943        if (inEditingMode()) {
5944            result = mWebTextView.requestFocus(direction,
5945                    previouslyFocusedRect);
5946        } else {
5947            result = super.requestFocus(direction, previouslyFocusedRect);
5948            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
5949                // For cases such as GMail, where we gain focus from a direction,
5950                // we want to move to the first available link.
5951                // FIXME: If there are no visible links, we may not want to
5952                int fakeKeyDirection = 0;
5953                switch(direction) {
5954                    case View.FOCUS_UP:
5955                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
5956                        break;
5957                    case View.FOCUS_DOWN:
5958                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
5959                        break;
5960                    case View.FOCUS_LEFT:
5961                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
5962                        break;
5963                    case View.FOCUS_RIGHT:
5964                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
5965                        break;
5966                    default:
5967                        return result;
5968                }
5969                if (mNativeClass != 0 && !nativeHasCursorNode()) {
5970                    navHandledKey(fakeKeyDirection, 1, true, 0);
5971                }
5972            }
5973        }
5974        return result;
5975    }
5976
5977    @Override
5978    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5979        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
5980
5981        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5982        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5983        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5984        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5985
5986        int measuredHeight = heightSize;
5987        int measuredWidth = widthSize;
5988
5989        // Grab the content size from WebViewCore.
5990        int contentHeight = contentToViewDimension(mContentHeight);
5991        int contentWidth = contentToViewDimension(mContentWidth);
5992
5993//        Log.d(LOGTAG, "------- measure " + heightMode);
5994
5995        if (heightMode != MeasureSpec.EXACTLY) {
5996            mHeightCanMeasure = true;
5997            measuredHeight = contentHeight;
5998            if (heightMode == MeasureSpec.AT_MOST) {
5999                // If we are larger than the AT_MOST height, then our height can
6000                // no longer be measured and we should scroll internally.
6001                if (measuredHeight > heightSize) {
6002                    measuredHeight = heightSize;
6003                    mHeightCanMeasure = false;
6004                }
6005            }
6006        } else {
6007            mHeightCanMeasure = false;
6008        }
6009        if (mNativeClass != 0) {
6010            nativeSetHeightCanMeasure(mHeightCanMeasure);
6011        }
6012        // For the width, always use the given size unless unspecified.
6013        if (widthMode == MeasureSpec.UNSPECIFIED) {
6014            mWidthCanMeasure = true;
6015            measuredWidth = contentWidth;
6016        } else {
6017            mWidthCanMeasure = false;
6018        }
6019
6020        synchronized (this) {
6021            setMeasuredDimension(measuredWidth, measuredHeight);
6022        }
6023    }
6024
6025    @Override
6026    public boolean requestChildRectangleOnScreen(View child,
6027                                                 Rect rect,
6028                                                 boolean immediate) {
6029        rect.offset(child.getLeft() - child.getScrollX(),
6030                child.getTop() - child.getScrollY());
6031
6032        Rect content = new Rect(viewToContentX(mScrollX),
6033                viewToContentY(mScrollY),
6034                viewToContentX(mScrollX + getWidth()
6035                - getVerticalScrollbarWidth()),
6036                viewToContentY(mScrollY + getViewHeightWithTitle()));
6037        content = nativeSubtractLayers(content);
6038        int screenTop = contentToViewY(content.top);
6039        int screenBottom = contentToViewY(content.bottom);
6040        int height = screenBottom - screenTop;
6041        int scrollYDelta = 0;
6042
6043        if (rect.bottom > screenBottom) {
6044            int oneThirdOfScreenHeight = height / 3;
6045            if (rect.height() > 2 * oneThirdOfScreenHeight) {
6046                // If the rectangle is too tall to fit in the bottom two thirds
6047                // of the screen, place it at the top.
6048                scrollYDelta = rect.top - screenTop;
6049            } else {
6050                // If the rectangle will still fit on screen, we want its
6051                // top to be in the top third of the screen.
6052                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
6053            }
6054        } else if (rect.top < screenTop) {
6055            scrollYDelta = rect.top - screenTop;
6056        }
6057
6058        int screenLeft = contentToViewX(content.left);
6059        int screenRight = contentToViewX(content.right);
6060        int width = screenRight - screenLeft;
6061        int scrollXDelta = 0;
6062
6063        if (rect.right > screenRight && rect.left > screenLeft) {
6064            if (rect.width() > width) {
6065                scrollXDelta += (rect.left - screenLeft);
6066            } else {
6067                scrollXDelta += (rect.right - screenRight);
6068            }
6069        } else if (rect.left < screenLeft) {
6070            scrollXDelta -= (screenLeft - rect.left);
6071        }
6072
6073        if ((scrollYDelta | scrollXDelta) != 0) {
6074            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
6075        }
6076
6077        return false;
6078    }
6079
6080    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
6081            String replace, int newStart, int newEnd) {
6082        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
6083        arg.mReplace = replace;
6084        arg.mNewStart = newStart;
6085        arg.mNewEnd = newEnd;
6086        mTextGeneration++;
6087        arg.mTextGeneration = mTextGeneration;
6088        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
6089    }
6090
6091    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
6092        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
6093        arg.mEvent = event;
6094        arg.mCurrentText = currentText;
6095        // Increase our text generation number, and pass it to webcore thread
6096        mTextGeneration++;
6097        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
6098        // WebKit's document state is not saved until about to leave the page.
6099        // To make sure the host application, like Browser, has the up to date
6100        // document state when it goes to background, we force to save the
6101        // document state.
6102        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
6103        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
6104                cursorData(), 1000);
6105    }
6106
6107    /* package */ synchronized WebViewCore getWebViewCore() {
6108        return mWebViewCore;
6109    }
6110
6111    //-------------------------------------------------------------------------
6112    // Methods can be called from a separate thread, like WebViewCore
6113    // If it needs to call the View system, it has to send message.
6114    //-------------------------------------------------------------------------
6115
6116    /**
6117     * General handler to receive message coming from webkit thread
6118     */
6119    class PrivateHandler extends Handler {
6120        @Override
6121        public void handleMessage(Message msg) {
6122            // exclude INVAL_RECT_MSG_ID since it is frequently output
6123            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
6124                if (msg.what >= FIRST_PRIVATE_MSG_ID
6125                        && msg.what <= LAST_PRIVATE_MSG_ID) {
6126                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
6127                            - FIRST_PRIVATE_MSG_ID]);
6128                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
6129                        && msg.what <= LAST_PACKAGE_MSG_ID) {
6130                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
6131                            - FIRST_PACKAGE_MSG_ID]);
6132                } else {
6133                    Log.v(LOGTAG, Integer.toString(msg.what));
6134                }
6135            }
6136            if (mWebViewCore == null) {
6137                // after WebView's destroy() is called, skip handling messages.
6138                return;
6139            }
6140            switch (msg.what) {
6141                case REMEMBER_PASSWORD: {
6142                    mDatabase.setUsernamePassword(
6143                            msg.getData().getString("host"),
6144                            msg.getData().getString("username"),
6145                            msg.getData().getString("password"));
6146                    ((Message) msg.obj).sendToTarget();
6147                    break;
6148                }
6149                case NEVER_REMEMBER_PASSWORD: {
6150                    mDatabase.setUsernamePassword(
6151                            msg.getData().getString("host"), null, null);
6152                    ((Message) msg.obj).sendToTarget();
6153                    break;
6154                }
6155                case PREVENT_DEFAULT_TIMEOUT: {
6156                    // if timeout happens, cancel it so that it won't block UI
6157                    // to continue handling touch events
6158                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
6159                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
6160                            || (msg.arg1 == MotionEvent.ACTION_MOVE
6161                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
6162                        cancelWebCoreTouchEvent(
6163                                viewToContentX((int) mLastTouchX + mScrollX),
6164                                viewToContentY((int) mLastTouchY + mScrollY),
6165                                true);
6166                    }
6167                    break;
6168                }
6169                case SWITCH_TO_SHORTPRESS: {
6170                    if (mTouchMode == TOUCH_INIT_MODE) {
6171                        if (mPreventDefault != PREVENT_DEFAULT_YES) {
6172                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
6173                            updateSelection();
6174                        } else {
6175                            // set to TOUCH_SHORTPRESS_MODE so that it won't
6176                            // trigger double tap any more
6177                            mTouchMode = TOUCH_SHORTPRESS_MODE;
6178                        }
6179                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
6180                        mTouchMode = TOUCH_DONE_MODE;
6181                    }
6182                    break;
6183                }
6184                case SWITCH_TO_LONGPRESS: {
6185                    if (inFullScreenMode() || mDeferTouchProcess) {
6186                        TouchEventData ted = new TouchEventData();
6187                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
6188                        ted.mX = viewToContentX((int) mLastTouchX + mScrollX);
6189                        ted.mY = viewToContentY((int) mLastTouchY + mScrollY);
6190                        // metaState for long press is tricky. Should it be the
6191                        // state when the press started or when the press was
6192                        // released? Or some intermediary key state? For
6193                        // simplicity for now, we don't set it.
6194                        ted.mMetaState = 0;
6195                        ted.mReprocess = mDeferTouchProcess;
6196                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6197                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
6198                        mTouchMode = TOUCH_DONE_MODE;
6199                        performLongClick();
6200                        rebuildWebTextView();
6201                    }
6202                    break;
6203                }
6204                case RELEASE_SINGLE_TAP: {
6205                    doShortPress();
6206                    break;
6207                }
6208                case SCROLL_BY_MSG_ID:
6209                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
6210                    break;
6211                case SYNC_SCROLL_TO_MSG_ID:
6212                    if (mUserScroll) {
6213                        // if user has scrolled explicitly, don't sync the
6214                        // scroll position any more
6215                        mUserScroll = false;
6216                        break;
6217                    }
6218                    // fall through
6219                case SCROLL_TO_MSG_ID:
6220                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
6221                        // if we can't scroll to the exact position due to pin,
6222                        // send a message to WebCore to re-scroll when we get a
6223                        // new picture
6224                        mUserScroll = false;
6225                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
6226                                msg.arg1, msg.arg2);
6227                    }
6228                    break;
6229                case SPAWN_SCROLL_TO_MSG_ID:
6230                    spawnContentScrollTo(msg.arg1, msg.arg2);
6231                    break;
6232                case UPDATE_ZOOM_RANGE: {
6233                    WebViewCore.RestoreState restoreState
6234                            = (WebViewCore.RestoreState) msg.obj;
6235                    // mScrollX contains the new minPrefWidth
6236                    updateZoomRange(restoreState, getViewWidth(),
6237                            restoreState.mScrollX, false);
6238                    break;
6239                }
6240                case NEW_PICTURE_MSG_ID: {
6241                    // If we've previously delayed deleting a root
6242                    // layer, do it now.
6243                    if (mDelayedDeleteRootLayer) {
6244                        mDelayedDeleteRootLayer = false;
6245                        nativeSetRootLayer(0);
6246                    }
6247                    WebSettings settings = mWebViewCore.getSettings();
6248                    // called for new content
6249                    final int viewWidth = getViewWidth();
6250                    final WebViewCore.DrawData draw =
6251                            (WebViewCore.DrawData) msg.obj;
6252                    final Point viewSize = draw.mViewPoint;
6253                    boolean useWideViewport = settings.getUseWideViewPort();
6254                    WebViewCore.RestoreState restoreState = draw.mRestoreState;
6255                    boolean hasRestoreState = restoreState != null;
6256                    if (hasRestoreState) {
6257                        updateZoomRange(restoreState, viewSize.x,
6258                                draw.mMinPrefWidth, true);
6259                        if (!mDrawHistory) {
6260                            mInZoomOverview = false;
6261
6262                            if (mInitialScaleInPercent > 0) {
6263                                setNewZoomScale(mInitialScaleInPercent / 100.0f,
6264                                    mInitialScaleInPercent != mTextWrapScale * 100,
6265                                    false);
6266                            } else if (restoreState.mViewScale > 0) {
6267                                mTextWrapScale = restoreState.mTextWrapScale;
6268                                setNewZoomScale(restoreState.mViewScale, false,
6269                                    false);
6270                            } else {
6271                                mInZoomOverview = useWideViewport
6272                                    && settings.getLoadWithOverviewMode();
6273                                float scale;
6274                                if (mInZoomOverview) {
6275                                    scale = (float) viewWidth
6276                                        / DEFAULT_VIEWPORT_WIDTH;
6277                                } else {
6278                                    scale = restoreState.mTextWrapScale;
6279                                }
6280                                setNewZoomScale(scale, Math.abs(scale
6281                                    - mTextWrapScale) >= MINIMUM_SCALE_INCREMENT,
6282                                    false);
6283                            }
6284                            setContentScrollTo(restoreState.mScrollX,
6285                                restoreState.mScrollY);
6286                            // As we are on a new page, remove the WebTextView. This
6287                            // is necessary for page loads driven by webkit, and in
6288                            // particular when the user was on a password field, so
6289                            // the WebTextView was visible.
6290                            clearTextEntry(false);
6291                            // update the zoom buttons as the scale can be changed
6292                            if (getSettings().getBuiltInZoomControls()) {
6293                                updateZoomButtonsEnabled();
6294                            }
6295                        }
6296                    }
6297                    // We update the layout (i.e. request a layout from the
6298                    // view system) if the last view size that we sent to
6299                    // WebCore matches the view size of the picture we just
6300                    // received in the fixed dimension.
6301                    final boolean updateLayout = viewSize.x == mLastWidthSent
6302                            && viewSize.y == mLastHeightSent;
6303                    recordNewContentSize(draw.mWidthHeight.x,
6304                            draw.mWidthHeight.y
6305                            + (mFindIsUp ? mFindHeight : 0), updateLayout);
6306                    if (DebugFlags.WEB_VIEW) {
6307                        Rect b = draw.mInvalRegion.getBounds();
6308                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
6309                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
6310                    }
6311                    invalidateContentRect(draw.mInvalRegion.getBounds());
6312                    if (mPictureListener != null) {
6313                        mPictureListener.onNewPicture(WebView.this, capturePicture());
6314                    }
6315                    if (useWideViewport) {
6316                        // limit mZoomOverviewWidth upper bound to
6317                        // sMaxViewportWidth so that if the page doesn't behave
6318                        // well, the WebView won't go insane. limit the lower
6319                        // bound to match the default scale for mobile sites.
6320                        mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math
6321                                .max((int) (viewWidth / mDefaultScale), Math
6322                                        .max(draw.mMinPrefWidth,
6323                                                draw.mViewPoint.x)));
6324                    }
6325                    if (!mMinZoomScaleFixed) {
6326                        mMinZoomScale = (float) viewWidth / mZoomOverviewWidth;
6327                    }
6328                    if (!mDrawHistory && mInZoomOverview) {
6329                        // fit the content width to the current view. Ignore
6330                        // the rounding error case.
6331                        if (Math.abs((viewWidth * mInvActualScale)
6332                                - mZoomOverviewWidth) > 1) {
6333                            setNewZoomScale((float) viewWidth
6334                                    / mZoomOverviewWidth, Math.abs(mActualScale
6335                                    - mTextWrapScale) < MINIMUM_SCALE_INCREMENT,
6336                                    false);
6337                        }
6338                    }
6339                    if (draw.mFocusSizeChanged && inEditingMode()) {
6340                        mFocusSizeChanged = true;
6341                    }
6342                    if (hasRestoreState) {
6343                        mViewManager.postReadyToDrawAll();
6344                    }
6345                    break;
6346                }
6347                case WEBCORE_INITIALIZED_MSG_ID:
6348                    // nativeCreate sets mNativeClass to a non-zero value
6349                    nativeCreate(msg.arg1);
6350                    break;
6351                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
6352                    // Make sure that the textfield is currently focused
6353                    // and representing the same node as the pointer.
6354                    if (inEditingMode() &&
6355                            mWebTextView.isSameTextField(msg.arg1)) {
6356                        if (msg.getData().getBoolean("password")) {
6357                            Spannable text = (Spannable) mWebTextView.getText();
6358                            int start = Selection.getSelectionStart(text);
6359                            int end = Selection.getSelectionEnd(text);
6360                            mWebTextView.setInPassword(true);
6361                            // Restore the selection, which may have been
6362                            // ruined by setInPassword.
6363                            Spannable pword =
6364                                    (Spannable) mWebTextView.getText();
6365                            Selection.setSelection(pword, start, end);
6366                        // If the text entry has created more events, ignore
6367                        // this one.
6368                        } else if (msg.arg2 == mTextGeneration) {
6369                            mWebTextView.setTextAndKeepSelection(
6370                                    (String) msg.obj);
6371                        }
6372                    }
6373                    break;
6374                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
6375                    displaySoftKeyboard(true);
6376                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
6377                            (WebViewCore.TextSelectionData) msg.obj);
6378                    break;
6379                case UPDATE_TEXT_SELECTION_MSG_ID:
6380                    // If no textfield was in focus, and the user touched one,
6381                    // causing it to send this message, then WebTextView has not
6382                    // been set up yet.  Rebuild it so it can set its selection.
6383                    rebuildWebTextView();
6384                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
6385                            (WebViewCore.TextSelectionData) msg.obj);
6386                    break;
6387                case RETURN_LABEL:
6388                    if (inEditingMode()
6389                            && mWebTextView.isSameTextField(msg.arg1)) {
6390                        mWebTextView.setHint((String) msg.obj);
6391                        InputMethodManager imm
6392                                = InputMethodManager.peekInstance();
6393                        // The hint is propagated to the IME in
6394                        // onCreateInputConnection.  If the IME is already
6395                        // active, restart it so that its hint text is updated.
6396                        if (imm != null && imm.isActive(mWebTextView)) {
6397                            imm.restartInput(mWebTextView);
6398                        }
6399                    }
6400                    break;
6401                case MOVE_OUT_OF_PLUGIN:
6402                    navHandledKey(msg.arg1, 1, false, 0);
6403                    break;
6404                case UPDATE_TEXT_ENTRY_MSG_ID:
6405                    // this is sent after finishing resize in WebViewCore. Make
6406                    // sure the text edit box is still on the  screen.
6407                    if (inEditingMode() && nativeCursorIsTextInput()) {
6408                        mWebTextView.bringIntoView();
6409                        rebuildWebTextView();
6410                    }
6411                    break;
6412                case CLEAR_TEXT_ENTRY:
6413                    clearTextEntry(false);
6414                    break;
6415                case INVAL_RECT_MSG_ID: {
6416                    Rect r = (Rect)msg.obj;
6417                    if (r == null) {
6418                        invalidate();
6419                    } else {
6420                        // we need to scale r from content into view coords,
6421                        // which viewInvalidate() does for us
6422                        viewInvalidate(r.left, r.top, r.right, r.bottom);
6423                    }
6424                    break;
6425                }
6426                case IMMEDIATE_REPAINT_MSG_ID: {
6427                    invalidate();
6428                    break;
6429                }
6430                case SET_ROOT_LAYER_MSG_ID: {
6431                    if (0 == msg.arg1) {
6432                        // Null indicates deleting the old layer, but
6433                        // don't actually do so until we've got the
6434                        // new page to display.
6435                        mDelayedDeleteRootLayer = true;
6436                    } else {
6437                        mDelayedDeleteRootLayer = false;
6438                        nativeSetRootLayer(msg.arg1);
6439                        invalidate();
6440                    }
6441                    break;
6442                }
6443                case REQUEST_FORM_DATA:
6444                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
6445                    if (mWebTextView.isSameTextField(msg.arg1)) {
6446                        mWebTextView.setAdapterCustom(adapter);
6447                    }
6448                    break;
6449                case RESUME_WEBCORE_PRIORITY:
6450                    WebViewCore.resumePriority();
6451                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6452                    break;
6453
6454                case LONG_PRESS_CENTER:
6455                    // as this is shared by keydown and trackballdown, reset all
6456                    // the states
6457                    mGotCenterDown = false;
6458                    mTrackballDown = false;
6459                    performLongClick();
6460                    break;
6461
6462                case WEBCORE_NEED_TOUCH_EVENTS:
6463                    mForwardTouchEvents = (msg.arg1 != 0);
6464                    break;
6465
6466                case PREVENT_TOUCH_ID:
6467                    if (inFullScreenMode()) {
6468                        break;
6469                    }
6470                    if (msg.obj == null) {
6471                        if (msg.arg1 == MotionEvent.ACTION_DOWN
6472                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
6473                            // if prevent default is called from WebCore, UI
6474                            // will not handle the rest of the touch events any
6475                            // more.
6476                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6477                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
6478                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
6479                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
6480                            // the return for the first ACTION_MOVE will decide
6481                            // whether UI will handle touch or not. Currently no
6482                            // support for alternating prevent default
6483                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6484                                    : PREVENT_DEFAULT_NO;
6485                        }
6486                    } else if (msg.arg2 == 0) {
6487                        // prevent default is not called in WebCore, so the
6488                        // message needs to be reprocessed in UI
6489                        TouchEventData ted = (TouchEventData) msg.obj;
6490                        switch (ted.mAction) {
6491                            case MotionEvent.ACTION_DOWN:
6492                                mLastDeferTouchX = contentToViewX(ted.mX)
6493                                        - mScrollX;
6494                                mLastDeferTouchY = contentToViewY(ted.mY)
6495                                        - mScrollY;
6496                                mDeferTouchMode = TOUCH_INIT_MODE;
6497                                break;
6498                            case MotionEvent.ACTION_MOVE: {
6499                                // no snapping in defer process
6500                                int x = contentToViewX(ted.mX) - mScrollX;
6501                                int y = contentToViewY(ted.mY) - mScrollY;
6502                                if (mDeferTouchMode != TOUCH_DRAG_MODE) {
6503                                    mDeferTouchMode = TOUCH_DRAG_MODE;
6504                                    mLastDeferTouchX = x;
6505                                    mLastDeferTouchY = y;
6506                                    startDrag();
6507                                }
6508                                int deltaX = pinLocX((int) (mScrollX
6509                                        + mLastDeferTouchX - x))
6510                                        - mScrollX;
6511                                int deltaY = pinLocY((int) (mScrollY
6512                                        + mLastDeferTouchY - y))
6513                                        - mScrollY;
6514                                doDrag(deltaX, deltaY);
6515                                if (deltaX != 0) mLastDeferTouchX = x;
6516                                if (deltaY != 0) mLastDeferTouchY = y;
6517                                break;
6518                            }
6519                            case MotionEvent.ACTION_UP:
6520                            case MotionEvent.ACTION_CANCEL:
6521                                if (mDeferTouchMode == TOUCH_DRAG_MODE) {
6522                                    // no fling in defer process
6523                                    WebViewCore.resumePriority();
6524                                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6525                                }
6526                                mDeferTouchMode = TOUCH_DONE_MODE;
6527                                break;
6528                            case WebViewCore.ACTION_DOUBLETAP:
6529                                // doDoubleTap() needs mLastTouchX/Y as anchor
6530                                mLastTouchX = contentToViewX(ted.mX) - mScrollX;
6531                                mLastTouchY = contentToViewY(ted.mY) - mScrollY;
6532                                doDoubleTap();
6533                                mDeferTouchMode = TOUCH_DONE_MODE;
6534                                break;
6535                            case WebViewCore.ACTION_LONGPRESS:
6536                                HitTestResult hitTest = getHitTestResult();
6537                                if (hitTest != null && hitTest.mType
6538                                        != HitTestResult.UNKNOWN_TYPE) {
6539                                    performLongClick();
6540                                    rebuildWebTextView();
6541                                }
6542                                mDeferTouchMode = TOUCH_DONE_MODE;
6543                                break;
6544                        }
6545                    }
6546                    break;
6547
6548                case REQUEST_KEYBOARD:
6549                    if (msg.arg1 == 0) {
6550                        hideSoftKeyboard();
6551                    } else {
6552                        displaySoftKeyboard(false);
6553                    }
6554                    break;
6555
6556                case FIND_AGAIN:
6557                    // Ignore if find has been dismissed.
6558                    if (mFindIsUp) {
6559                        findAll(mLastFind);
6560                    }
6561                    break;
6562
6563                case DRAG_HELD_MOTIONLESS:
6564                    mHeldMotionless = MOTIONLESS_TRUE;
6565                    invalidate();
6566                    // fall through to keep scrollbars awake
6567
6568                case AWAKEN_SCROLL_BARS:
6569                    if (mTouchMode == TOUCH_DRAG_MODE
6570                            && mHeldMotionless == MOTIONLESS_TRUE) {
6571                        awakenScrollBars(ViewConfiguration
6572                                .getScrollDefaultDelay(), false);
6573                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
6574                                .obtainMessage(AWAKEN_SCROLL_BARS),
6575                                ViewConfiguration.getScrollDefaultDelay());
6576                    }
6577                    break;
6578
6579                case DO_MOTION_UP:
6580                    doMotionUp(msg.arg1, msg.arg2);
6581                    break;
6582
6583                case SHOW_FULLSCREEN: {
6584                    View view = (View) msg.obj;
6585                    int npp = msg.arg1;
6586
6587                    if (mFullScreenHolder != null) {
6588                        Log.w(LOGTAG, "Should not have another full screen.");
6589                        mFullScreenHolder.dismiss();
6590                    }
6591                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp);
6592                    mFullScreenHolder.setContentView(view);
6593                    mFullScreenHolder.setCancelable(false);
6594                    mFullScreenHolder.setCanceledOnTouchOutside(false);
6595                    mFullScreenHolder.show();
6596
6597                    break;
6598                }
6599                case HIDE_FULLSCREEN:
6600                    if (inFullScreenMode()) {
6601                        mFullScreenHolder.dismiss();
6602                        mFullScreenHolder = null;
6603                    }
6604                    break;
6605
6606                case DOM_FOCUS_CHANGED:
6607                    if (inEditingMode()) {
6608                        nativeClearCursor();
6609                        rebuildWebTextView();
6610                    }
6611                    break;
6612
6613                case SHOW_RECT_MSG_ID: {
6614                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
6615                    int x = mScrollX;
6616                    int left = contentToViewX(data.mLeft);
6617                    int width = contentToViewDimension(data.mWidth);
6618                    int maxWidth = contentToViewDimension(data.mContentWidth);
6619                    int viewWidth = getViewWidth();
6620                    if (width < viewWidth) {
6621                        // center align
6622                        x += left + width / 2 - mScrollX - viewWidth / 2;
6623                    } else {
6624                        x += (int) (left + data.mXPercentInDoc * width
6625                                - mScrollX - data.mXPercentInView * viewWidth);
6626                    }
6627                    if (DebugFlags.WEB_VIEW) {
6628                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
6629                              width + ",maxWidth=" + maxWidth +
6630                              ",viewWidth=" + viewWidth + ",x="
6631                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
6632                              ",xPercentInView=" + data.mXPercentInView+ ")");
6633                    }
6634                    // use the passing content width to cap x as the current
6635                    // mContentWidth may not be updated yet
6636                    x = Math.max(0,
6637                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
6638                    int top = contentToViewY(data.mTop);
6639                    int height = contentToViewDimension(data.mHeight);
6640                    int maxHeight = contentToViewDimension(data.mContentHeight);
6641                    int viewHeight = getViewHeight();
6642                    int y = (int) (top + data.mYPercentInDoc * height -
6643                                   data.mYPercentInView * viewHeight);
6644                    if (DebugFlags.WEB_VIEW) {
6645                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
6646                              height + ",maxHeight=" + maxHeight +
6647                              ",viewHeight=" + viewHeight + ",y="
6648                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
6649                              ",yPercentInView=" + data.mYPercentInView+ ")");
6650                    }
6651                    // use the passing content height to cap y as the current
6652                    // mContentHeight may not be updated yet
6653                    y = Math.max(0,
6654                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
6655                    // We need to take into account the visible title height
6656                    // when scrolling since y is an absolute view position.
6657                    y = Math.max(0, y - getVisibleTitleHeight());
6658                    scrollTo(x, y);
6659                    }
6660                    break;
6661
6662                case CENTER_FIT_RECT:
6663                    Rect r = (Rect)msg.obj;
6664                    mInZoomOverview = false;
6665                    centerFitRect(r.left, r.top, r.width(), r.height());
6666                    break;
6667
6668                case SET_SCROLLBAR_MODES:
6669                    mHorizontalScrollBarMode = msg.arg1;
6670                    mVerticalScrollBarMode = msg.arg2;
6671                    break;
6672
6673                default:
6674                    super.handleMessage(msg);
6675                    break;
6676            }
6677        }
6678    }
6679
6680    /**
6681     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
6682     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
6683     */
6684    private void updateTextSelectionFromMessage(int nodePointer,
6685            int textGeneration, WebViewCore.TextSelectionData data) {
6686        if (inEditingMode()
6687                && mWebTextView.isSameTextField(nodePointer)
6688                && textGeneration == mTextGeneration) {
6689            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
6690        }
6691    }
6692
6693    // Class used to use a dropdown for a <select> element
6694    private class InvokeListBox implements Runnable {
6695        // Whether the listbox allows multiple selection.
6696        private boolean     mMultiple;
6697        // Passed in to a list with multiple selection to tell
6698        // which items are selected.
6699        private int[]       mSelectedArray;
6700        // Passed in to a list with single selection to tell
6701        // where the initial selection is.
6702        private int         mSelection;
6703
6704        private Container[] mContainers;
6705
6706        // Need these to provide stable ids to my ArrayAdapter,
6707        // which normally does not have stable ids. (Bug 1250098)
6708        private class Container extends Object {
6709            /**
6710             * Possible values for mEnabled.  Keep in sync with OptionStatus in
6711             * WebViewCore.cpp
6712             */
6713            final static int OPTGROUP = -1;
6714            final static int OPTION_DISABLED = 0;
6715            final static int OPTION_ENABLED = 1;
6716
6717            String  mString;
6718            int     mEnabled;
6719            int     mId;
6720
6721            public String toString() {
6722                return mString;
6723            }
6724        }
6725
6726        /**
6727         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
6728         *  and allow filtering.
6729         */
6730        private class MyArrayListAdapter extends ArrayAdapter<Container> {
6731            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
6732                super(context,
6733                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
6734                            com.android.internal.R.layout.select_dialog_singlechoice,
6735                            objects);
6736            }
6737
6738            @Override
6739            public View getView(int position, View convertView,
6740                    ViewGroup parent) {
6741                // Always pass in null so that we will get a new CheckedTextView
6742                // Otherwise, an item which was previously used as an <optgroup>
6743                // element (i.e. has no check), could get used as an <option>
6744                // element, which needs a checkbox/radio, but it would not have
6745                // one.
6746                convertView = super.getView(position, null, parent);
6747                Container c = item(position);
6748                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
6749                    // ListView does not draw dividers between disabled and
6750                    // enabled elements.  Use a LinearLayout to provide dividers
6751                    LinearLayout layout = new LinearLayout(mContext);
6752                    layout.setOrientation(LinearLayout.VERTICAL);
6753                    if (position > 0) {
6754                        View dividerTop = new View(mContext);
6755                        dividerTop.setBackgroundResource(
6756                                android.R.drawable.divider_horizontal_bright);
6757                        layout.addView(dividerTop);
6758                    }
6759
6760                    if (Container.OPTGROUP == c.mEnabled) {
6761                        // Currently select_dialog_multichoice and
6762                        // select_dialog_singlechoice are CheckedTextViews.  If
6763                        // that changes, the class cast will no longer be valid.
6764                        Assert.assertTrue(
6765                                convertView instanceof CheckedTextView);
6766                        ((CheckedTextView) convertView).setCheckMarkDrawable(
6767                                null);
6768                    } else {
6769                        // c.mEnabled == Container.OPTION_DISABLED
6770                        // Draw the disabled element in a disabled state.
6771                        convertView.setEnabled(false);
6772                    }
6773
6774                    layout.addView(convertView);
6775                    if (position < getCount() - 1) {
6776                        View dividerBottom = new View(mContext);
6777                        dividerBottom.setBackgroundResource(
6778                                android.R.drawable.divider_horizontal_bright);
6779                        layout.addView(dividerBottom);
6780                    }
6781                    return layout;
6782                }
6783                return convertView;
6784            }
6785
6786            @Override
6787            public boolean hasStableIds() {
6788                // AdapterView's onChanged method uses this to determine whether
6789                // to restore the old state.  Return false so that the old (out
6790                // of date) state does not replace the new, valid state.
6791                return false;
6792            }
6793
6794            private Container item(int position) {
6795                if (position < 0 || position >= getCount()) {
6796                    return null;
6797                }
6798                return (Container) getItem(position);
6799            }
6800
6801            @Override
6802            public long getItemId(int position) {
6803                Container item = item(position);
6804                if (item == null) {
6805                    return -1;
6806                }
6807                return item.mId;
6808            }
6809
6810            @Override
6811            public boolean areAllItemsEnabled() {
6812                return false;
6813            }
6814
6815            @Override
6816            public boolean isEnabled(int position) {
6817                Container item = item(position);
6818                if (item == null) {
6819                    return false;
6820                }
6821                return Container.OPTION_ENABLED == item.mEnabled;
6822            }
6823        }
6824
6825        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
6826            mMultiple = true;
6827            mSelectedArray = selected;
6828
6829            int length = array.length;
6830            mContainers = new Container[length];
6831            for (int i = 0; i < length; i++) {
6832                mContainers[i] = new Container();
6833                mContainers[i].mString = array[i];
6834                mContainers[i].mEnabled = enabled[i];
6835                mContainers[i].mId = i;
6836            }
6837        }
6838
6839        private InvokeListBox(String[] array, int[] enabled, int selection) {
6840            mSelection = selection;
6841            mMultiple = false;
6842
6843            int length = array.length;
6844            mContainers = new Container[length];
6845            for (int i = 0; i < length; i++) {
6846                mContainers[i] = new Container();
6847                mContainers[i].mString = array[i];
6848                mContainers[i].mEnabled = enabled[i];
6849                mContainers[i].mId = i;
6850            }
6851        }
6852
6853        /*
6854         * Whenever the data set changes due to filtering, this class ensures
6855         * that the checked item remains checked.
6856         */
6857        private class SingleDataSetObserver extends DataSetObserver {
6858            private long        mCheckedId;
6859            private ListView    mListView;
6860            private Adapter     mAdapter;
6861
6862            /*
6863             * Create a new observer.
6864             * @param id The ID of the item to keep checked.
6865             * @param l ListView for getting and clearing the checked states
6866             * @param a Adapter for getting the IDs
6867             */
6868            public SingleDataSetObserver(long id, ListView l, Adapter a) {
6869                mCheckedId = id;
6870                mListView = l;
6871                mAdapter = a;
6872            }
6873
6874            public void onChanged() {
6875                // The filter may have changed which item is checked.  Find the
6876                // item that the ListView thinks is checked.
6877                int position = mListView.getCheckedItemPosition();
6878                long id = mAdapter.getItemId(position);
6879                if (mCheckedId != id) {
6880                    // Clear the ListView's idea of the checked item, since
6881                    // it is incorrect
6882                    mListView.clearChoices();
6883                    // Search for mCheckedId.  If it is in the filtered list,
6884                    // mark it as checked
6885                    int count = mAdapter.getCount();
6886                    for (int i = 0; i < count; i++) {
6887                        if (mAdapter.getItemId(i) == mCheckedId) {
6888                            mListView.setItemChecked(i, true);
6889                            break;
6890                        }
6891                    }
6892                }
6893            }
6894
6895            public void onInvalidate() {}
6896        }
6897
6898        public void run() {
6899            final ListView listView = (ListView) LayoutInflater.from(mContext)
6900                    .inflate(com.android.internal.R.layout.select_dialog, null);
6901            final MyArrayListAdapter adapter = new
6902                    MyArrayListAdapter(mContext, mContainers, mMultiple);
6903            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
6904                    .setView(listView).setCancelable(true)
6905                    .setInverseBackgroundForced(true);
6906
6907            if (mMultiple) {
6908                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
6909                    public void onClick(DialogInterface dialog, int which) {
6910                        mWebViewCore.sendMessage(
6911                                EventHub.LISTBOX_CHOICES,
6912                                adapter.getCount(), 0,
6913                                listView.getCheckedItemPositions());
6914                    }});
6915                b.setNegativeButton(android.R.string.cancel,
6916                        new DialogInterface.OnClickListener() {
6917                    public void onClick(DialogInterface dialog, int which) {
6918                        mWebViewCore.sendMessage(
6919                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6920                }});
6921            }
6922            final AlertDialog dialog = b.create();
6923            listView.setAdapter(adapter);
6924            listView.setFocusableInTouchMode(true);
6925            // There is a bug (1250103) where the checks in a ListView with
6926            // multiple items selected are associated with the positions, not
6927            // the ids, so the items do not properly retain their checks when
6928            // filtered.  Do not allow filtering on multiple lists until
6929            // that bug is fixed.
6930
6931            listView.setTextFilterEnabled(!mMultiple);
6932            if (mMultiple) {
6933                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
6934                int length = mSelectedArray.length;
6935                for (int i = 0; i < length; i++) {
6936                    listView.setItemChecked(mSelectedArray[i], true);
6937                }
6938            } else {
6939                listView.setOnItemClickListener(new OnItemClickListener() {
6940                    public void onItemClick(AdapterView parent, View v,
6941                            int position, long id) {
6942                        mWebViewCore.sendMessage(
6943                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
6944                        dialog.dismiss();
6945                    }
6946                });
6947                if (mSelection != -1) {
6948                    listView.setSelection(mSelection);
6949                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
6950                    listView.setItemChecked(mSelection, true);
6951                    DataSetObserver observer = new SingleDataSetObserver(
6952                            adapter.getItemId(mSelection), listView, adapter);
6953                    adapter.registerDataSetObserver(observer);
6954                }
6955            }
6956            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
6957                public void onCancel(DialogInterface dialog) {
6958                    mWebViewCore.sendMessage(
6959                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6960                }
6961            });
6962            dialog.show();
6963        }
6964    }
6965
6966    /*
6967     * Request a dropdown menu for a listbox with multiple selection.
6968     *
6969     * @param array Labels for the listbox.
6970     * @param enabledArray  State for each element in the list.  See static
6971     *      integers in Container class.
6972     * @param selectedArray Which positions are initally selected.
6973     */
6974    void requestListBox(String[] array, int[] enabledArray, int[]
6975            selectedArray) {
6976        mPrivateHandler.post(
6977                new InvokeListBox(array, enabledArray, selectedArray));
6978    }
6979
6980    private void updateZoomRange(WebViewCore.RestoreState restoreState,
6981            int viewWidth, int minPrefWidth, boolean updateZoomOverview) {
6982        if (restoreState.mMinScale == 0) {
6983            if (restoreState.mMobileSite) {
6984                if (minPrefWidth > Math.max(0, viewWidth)) {
6985                    mMinZoomScale = (float) viewWidth / minPrefWidth;
6986                    mMinZoomScaleFixed = false;
6987                    if (updateZoomOverview) {
6988                        WebSettings settings = getSettings();
6989                        mInZoomOverview = settings.getUseWideViewPort() &&
6990                                settings.getLoadWithOverviewMode();
6991                    }
6992                } else {
6993                    mMinZoomScale = restoreState.mDefaultScale;
6994                    mMinZoomScaleFixed = true;
6995                }
6996            } else {
6997                mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
6998                mMinZoomScaleFixed = false;
6999            }
7000        } else {
7001            mMinZoomScale = restoreState.mMinScale;
7002            mMinZoomScaleFixed = true;
7003        }
7004        if (restoreState.mMaxScale == 0) {
7005            mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
7006        } else {
7007            mMaxZoomScale = restoreState.mMaxScale;
7008        }
7009    }
7010
7011    /*
7012     * Request a dropdown menu for a listbox with single selection or a single
7013     * <select> element.
7014     *
7015     * @param array Labels for the listbox.
7016     * @param enabledArray  State for each element in the list.  See static
7017     *      integers in Container class.
7018     * @param selection Which position is initally selected.
7019     */
7020    void requestListBox(String[] array, int[] enabledArray, int selection) {
7021        mPrivateHandler.post(
7022                new InvokeListBox(array, enabledArray, selection));
7023    }
7024
7025    // called by JNI
7026    private void sendMoveFocus(int frame, int node) {
7027        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
7028                new WebViewCore.CursorData(frame, node, 0, 0));
7029    }
7030
7031    // called by JNI
7032    private void sendMoveMouse(int frame, int node, int x, int y) {
7033        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
7034                new WebViewCore.CursorData(frame, node, x, y));
7035    }
7036
7037    /*
7038     * Send a mouse move event to the webcore thread.
7039     *
7040     * @param removeFocus Pass true if the "mouse" cursor is now over a node
7041     *                    which wants key events, but it is not the focus. This
7042     *                    will make the visual appear as though nothing is in
7043     *                    focus.  Remove the WebTextView, if present, and stop
7044     *                    drawing the blinking caret.
7045     * called by JNI
7046     */
7047    private void sendMoveMouseIfLatest(boolean removeFocus) {
7048        if (removeFocus) {
7049            clearTextEntry(true);
7050        }
7051        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
7052                cursorData());
7053    }
7054
7055    // called by JNI
7056    private void sendMotionUp(int touchGeneration,
7057            int frame, int node, int x, int y) {
7058        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7059        touchUpData.mMoveGeneration = touchGeneration;
7060        touchUpData.mFrame = frame;
7061        touchUpData.mNode = node;
7062        touchUpData.mX = x;
7063        touchUpData.mY = y;
7064        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7065    }
7066
7067
7068    private int getScaledMaxXScroll() {
7069        int width;
7070        if (mHeightCanMeasure == false) {
7071            width = getViewWidth() / 4;
7072        } else {
7073            Rect visRect = new Rect();
7074            calcOurVisibleRect(visRect);
7075            width = visRect.width() / 2;
7076        }
7077        // FIXME the divisor should be retrieved from somewhere
7078        return viewToContentX(width);
7079    }
7080
7081    private int getScaledMaxYScroll() {
7082        int height;
7083        if (mHeightCanMeasure == false) {
7084            height = getViewHeight() / 4;
7085        } else {
7086            Rect visRect = new Rect();
7087            calcOurVisibleRect(visRect);
7088            height = visRect.height() / 2;
7089        }
7090        // FIXME the divisor should be retrieved from somewhere
7091        // the closest thing today is hard-coded into ScrollView.java
7092        // (from ScrollView.java, line 363)   int maxJump = height/2;
7093        return Math.round(height * mInvActualScale);
7094    }
7095
7096    /**
7097     * Called by JNI to invalidate view
7098     */
7099    private void viewInvalidate() {
7100        invalidate();
7101    }
7102
7103    /**
7104     * Pass the key to the plugin.  This assumes that nativeFocusIsPlugin()
7105     * returned true.
7106     */
7107    private void letPluginHandleNavKey(int keyCode, long time, boolean down) {
7108        int keyEventAction;
7109        int eventHubAction;
7110        if (down) {
7111            keyEventAction = KeyEvent.ACTION_DOWN;
7112            eventHubAction = EventHub.KEY_DOWN;
7113            playSoundEffect(keyCodeToSoundsEffect(keyCode));
7114        } else {
7115            keyEventAction = KeyEvent.ACTION_UP;
7116            eventHubAction = EventHub.KEY_UP;
7117        }
7118        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
7119                1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
7120                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
7121                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
7122                , 0, 0, 0);
7123        mWebViewCore.sendMessage(eventHubAction, event);
7124    }
7125
7126    // return true if the key was handled
7127    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
7128            long time) {
7129        if (mNativeClass == 0) {
7130            return false;
7131        }
7132        mLastCursorTime = time;
7133        mLastCursorBounds = nativeGetCursorRingBounds();
7134        boolean keyHandled
7135                = nativeMoveCursor(keyCode, count, noScroll) == false;
7136        if (DebugFlags.WEB_VIEW) {
7137            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
7138                    + " mLastCursorTime=" + mLastCursorTime
7139                    + " handled=" + keyHandled);
7140        }
7141        if (keyHandled == false || mHeightCanMeasure == false) {
7142            return keyHandled;
7143        }
7144        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
7145        if (contentCursorRingBounds.isEmpty()) return keyHandled;
7146        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
7147        Rect visRect = new Rect();
7148        calcOurVisibleRect(visRect);
7149        Rect outset = new Rect(visRect);
7150        int maxXScroll = visRect.width() / 2;
7151        int maxYScroll = visRect.height() / 2;
7152        outset.inset(-maxXScroll, -maxYScroll);
7153        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
7154            return keyHandled;
7155        }
7156        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
7157        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
7158                maxXScroll);
7159        if (maxH > 0) {
7160            pinScrollBy(maxH, 0, true, 0);
7161        } else {
7162            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
7163                    -maxXScroll);
7164            if (maxH < 0) {
7165                pinScrollBy(maxH, 0, true, 0);
7166            }
7167        }
7168        if (mLastCursorBounds.isEmpty()) return keyHandled;
7169        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
7170            return keyHandled;
7171        }
7172        if (DebugFlags.WEB_VIEW) {
7173            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
7174                    + contentCursorRingBounds);
7175        }
7176        requestRectangleOnScreen(viewCursorRingBounds);
7177        mUserScroll = true;
7178        return keyHandled;
7179    }
7180
7181    /**
7182     * Set the background color. It's white by default. Pass
7183     * zero to make the view transparent.
7184     * @param color   the ARGB color described by Color.java
7185     */
7186    public void setBackgroundColor(int color) {
7187        mBackgroundColor = color;
7188        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
7189    }
7190
7191    public void debugDump() {
7192        nativeDebugDump();
7193        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
7194    }
7195
7196    /**
7197     * Draw the HTML page into the specified canvas. This call ignores any
7198     * view-specific zoom, scroll offset, or other changes. It does not draw
7199     * any view-specific chrome, such as progress or URL bars.
7200     *
7201     * @hide only needs to be accessible to Browser and testing
7202     */
7203    public void drawPage(Canvas canvas) {
7204        mWebViewCore.drawContentPicture(canvas, 0, false, false);
7205    }
7206
7207    /**
7208     * Set the time to wait between passing touches to WebCore. See also the
7209     * TOUCH_SENT_INTERVAL member for further discussion.
7210     *
7211     * @hide This is only used by the DRT test application.
7212     */
7213    public void setTouchInterval(int interval) {
7214        mCurrentTouchInterval = interval;
7215    }
7216
7217    /**
7218     *  Update our cache with updatedText.
7219     *  @param updatedText  The new text to put in our cache.
7220     */
7221    /* package */ void updateCachedTextfield(String updatedText) {
7222        // Also place our generation number so that when we look at the cache
7223        // we recognize that it is up to date.
7224        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
7225    }
7226
7227    private native int nativeCacheHitFramePointer();
7228    private native Rect nativeCacheHitNodeBounds();
7229    private native int nativeCacheHitNodePointer();
7230    /* package */ native void nativeClearCursor();
7231    private native void     nativeCreate(int ptr);
7232    private native int      nativeCursorFramePointer();
7233    private native Rect     nativeCursorNodeBounds();
7234    private native int nativeCursorNodePointer();
7235    /* package */ native boolean nativeCursorMatchesFocus();
7236    private native boolean  nativeCursorIntersects(Rect visibleRect);
7237    private native boolean  nativeCursorIsAnchor();
7238    private native boolean  nativeCursorIsTextInput();
7239    private native Point    nativeCursorPosition();
7240    private native String   nativeCursorText();
7241    /**
7242     * Returns true if the native cursor node says it wants to handle key events
7243     * (ala plugins). This can only be called if mNativeClass is non-zero!
7244     */
7245    private native boolean  nativeCursorWantsKeyEvents();
7246    private native void     nativeDebugDump();
7247    private native void     nativeDestroy();
7248    private native boolean  nativeEvaluateLayersAnimations();
7249    private native void     nativeDrawExtras(Canvas canvas, int extra);
7250    private native void     nativeDumpDisplayTree(String urlOrNull);
7251    private native int      nativeFindAll(String findLower, String findUpper);
7252    private native void     nativeFindNext(boolean forward);
7253    /* package */ native int      nativeFocusCandidateFramePointer();
7254    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
7255    private native boolean  nativeFocusCandidateIsPassword();
7256    private native boolean  nativeFocusCandidateIsRtlText();
7257    private native boolean  nativeFocusCandidateIsTextInput();
7258    /* package */ native int      nativeFocusCandidateMaxLength();
7259    /* package */ native String   nativeFocusCandidateName();
7260    private native Rect     nativeFocusCandidateNodeBounds();
7261    private native int      nativeFocusCandidatePointer();
7262    private native String   nativeFocusCandidateText();
7263    private native int      nativeFocusCandidateTextSize();
7264    /**
7265     * Returns an integer corresponding to WebView.cpp::type.
7266     * See WebTextView.setType()
7267     */
7268    private native int      nativeFocusCandidateType();
7269    private native boolean  nativeFocusIsPlugin();
7270    private native Rect     nativeFocusNodeBounds();
7271    /* package */ native int nativeFocusNodePointer();
7272    private native Rect     nativeGetCursorRingBounds();
7273    private native String   nativeGetSelection();
7274    private native boolean  nativeHasCursorNode();
7275    private native boolean  nativeHasFocusNode();
7276    private native void     nativeHideCursor();
7277    private native String   nativeImageURI(int x, int y);
7278    private native void     nativeInstrumentReport();
7279    /* package */ native boolean nativeMoveCursorToNextTextInput();
7280    // return true if the page has been scrolled
7281    private native boolean  nativeMotionUp(int x, int y, int slop);
7282    // returns false if it handled the key
7283    private native boolean  nativeMoveCursor(int keyCode, int count,
7284            boolean noScroll);
7285    private native int      nativeMoveGeneration();
7286    private native void     nativeMoveSelection(int x, int y,
7287            boolean extendSelection);
7288    private native boolean  nativePointInNavCache(int x, int y, int slop);
7289    // Like many other of our native methods, you must make sure that
7290    // mNativeClass is not null before calling this method.
7291    private native void     nativeRecordButtons(boolean focused,
7292            boolean pressed, boolean invalidate);
7293    private native void     nativeSelectBestAt(Rect rect);
7294    private native void     nativeSetFindIsEmpty();
7295    private native void     nativeSetFindIsUp(boolean isUp);
7296    private native void     nativeSetFollowedLink(boolean followed);
7297    private native void     nativeSetHeightCanMeasure(boolean measure);
7298    private native void     nativeSetRootLayer(int layer);
7299    private native void     nativeSetSelectionPointer(boolean set,
7300            float scale, int x, int y, boolean extendSelection);
7301    private native void     nativeSetSelectionRegion(boolean set);
7302    private native Rect     nativeSubtractLayers(Rect content);
7303    private native int      nativeTextGeneration();
7304    // Never call this version except by updateCachedTextfield(String) -
7305    // we always want to pass in our generation number.
7306    private native void     nativeUpdateCachedTextfield(String updatedText,
7307            int generation);
7308    // return NO_LEFTEDGE means failure.
7309    private static final int NO_LEFTEDGE = -1;
7310    private native int      nativeGetBlockLeftEdge(int x, int y, float scale);
7311}
7312