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