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