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