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