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