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