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