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