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