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