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