WebView.java revision d84e7d53d379c9fdfe335f40e89e2dfd6144dfea
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                if (oldX != mScrollX || oldY != mScrollY) {
1921                    sendOurVisibleRect();
1922                }
1923                if (!mScroller.isFinished()) {
1924                    // We are in the middle of a scroll.  Repin the final scroll
1925                    // position.
1926                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
1927                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
1928                }
1929            }
1930        }
1931        contentSizeChanged(updateLayout);
1932    }
1933
1934    private void setNewZoomScale(float scale, boolean force) {
1935        if (scale < mMinZoomScale) {
1936            scale = mMinZoomScale;
1937        } else if (scale > mMaxZoomScale) {
1938            scale = mMaxZoomScale;
1939        }
1940        if (scale != mActualScale || force) {
1941            if (mDrawHistory) {
1942                // If history Picture is drawn, don't update scroll. They will
1943                // be updated when we get out of that mode.
1944                if (scale != mActualScale && !mPreviewZoomOnly) {
1945                    mCallbackProxy.onScaleChanged(mActualScale, scale);
1946                }
1947                mActualScale = scale;
1948                mInvActualScale = 1 / scale;
1949                if (!mPreviewZoomOnly) {
1950                    sendViewSizeZoom();
1951                }
1952            } else {
1953                // update our scroll so we don't appear to jump
1954                // i.e. keep the center of the doc in the center of the view
1955
1956                int oldX = mScrollX;
1957                int oldY = mScrollY;
1958                float ratio = scale * mInvActualScale;   // old inverse
1959                float sx = ratio * oldX + (ratio - 1) * mZoomCenterX;
1960                float sy = ratio * oldY + (ratio - 1)
1961                        * (mZoomCenterY - getTitleHeight());
1962
1963                // now update our new scale and inverse
1964                if (scale != mActualScale && !mPreviewZoomOnly) {
1965                    mCallbackProxy.onScaleChanged(mActualScale, scale);
1966                }
1967                mActualScale = scale;
1968                mInvActualScale = 1 / scale;
1969
1970                // Scale all the child views
1971                mViewManager.scaleAll();
1972
1973                // as we don't have animation for scaling, don't do animation
1974                // for scrolling, as it causes weird intermediate state
1975                //        pinScrollTo(Math.round(sx), Math.round(sy));
1976                mScrollX = pinLocX(Math.round(sx));
1977                mScrollY = pinLocY(Math.round(sy));
1978
1979                if (!mPreviewZoomOnly) {
1980                    sendViewSizeZoom();
1981                    sendOurVisibleRect();
1982                }
1983            }
1984        }
1985    }
1986
1987    // Used to avoid sending many visible rect messages.
1988    private Rect mLastVisibleRectSent;
1989    private Rect mLastGlobalRect;
1990
1991    private Rect sendOurVisibleRect() {
1992        Rect rect = new Rect();
1993        calcOurContentVisibleRect(rect);
1994        // Rect.equals() checks for null input.
1995        if (!rect.equals(mLastVisibleRectSent)) {
1996            Point pos = new Point(rect.left, rect.top);
1997            mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
1998                    nativeMoveGeneration(), 0, pos);
1999            mLastVisibleRectSent = rect;
2000        }
2001        Rect globalRect = new Rect();
2002        if (getGlobalVisibleRect(globalRect)
2003                && !globalRect.equals(mLastGlobalRect)) {
2004            if (DebugFlags.WEB_VIEW) {
2005                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2006                        + globalRect.top + ",r=" + globalRect.right + ",b="
2007                        + globalRect.bottom);
2008            }
2009            // TODO: the global offset is only used by windowRect()
2010            // in ChromeClientAndroid ; other clients such as touch
2011            // and mouse events could return view + screen relative points.
2012            mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2013            mLastGlobalRect = globalRect;
2014        }
2015        return rect;
2016    }
2017
2018    // Sets r to be the visible rectangle of our webview in view coordinates
2019    private void calcOurVisibleRect(Rect r) {
2020        Point p = new Point();
2021        getGlobalVisibleRect(r, p);
2022        r.offset(-p.x, -p.y);
2023        if (mFindIsUp) {
2024            r.bottom -= mFindHeight;
2025        }
2026    }
2027
2028    // Sets r to be our visible rectangle in content coordinates
2029    private void calcOurContentVisibleRect(Rect r) {
2030        calcOurVisibleRect(r);
2031        r.left = viewToContentX(r.left);
2032        // viewToContentY will remove the total height of the title bar.  Add
2033        // the visible height back in to account for the fact that if the title
2034        // bar is partially visible, the part of the visible rect which is
2035        // displaying our content is displaced by that amount.
2036        r.top = viewToContentY(r.top + getVisibleTitleHeight());
2037        r.right = viewToContentX(r.right);
2038        r.bottom = viewToContentY(r.bottom);
2039    }
2040
2041    static class ViewSizeData {
2042        int mWidth;
2043        int mHeight;
2044        int mTextWrapWidth;
2045        float mScale;
2046        boolean mIgnoreHeight;
2047    }
2048
2049    /**
2050     * Compute unzoomed width and height, and if they differ from the last
2051     * values we sent, send them to webkit (to be used has new viewport)
2052     *
2053     * @return true if new values were sent
2054     */
2055    private boolean sendViewSizeZoom() {
2056        int viewWidth = getViewWidth();
2057        int newWidth = Math.round(viewWidth * mInvActualScale);
2058        int newHeight = Math.round(getViewHeight() * mInvActualScale);
2059        /*
2060         * Because the native side may have already done a layout before the
2061         * View system was able to measure us, we have to send a height of 0 to
2062         * remove excess whitespace when we grow our width. This will trigger a
2063         * layout and a change in content size. This content size change will
2064         * mean that contentSizeChanged will either call this method directly or
2065         * indirectly from onSizeChanged.
2066         */
2067        if (newWidth > mLastWidthSent && mWrapContent) {
2068            newHeight = 0;
2069        }
2070        // Avoid sending another message if the dimensions have not changed.
2071        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) {
2072            ViewSizeData data = new ViewSizeData();
2073            data.mWidth = newWidth;
2074            data.mHeight = newHeight;
2075            // while in zoom overview mode, the text are wrapped to the screen
2076            // width matching mLastScale. So that we don't trigger re-flow while
2077            // toggling between overview mode and normal mode.
2078            data.mTextWrapWidth = mInZoomOverview ? Math.round(viewWidth
2079                    / mLastScale) : newWidth;
2080            data.mScale = mActualScale;
2081            data.mIgnoreHeight = mZoomScale != 0 && !mHeightCanMeasure;
2082            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
2083            mLastWidthSent = newWidth;
2084            mLastHeightSent = newHeight;
2085            return true;
2086        }
2087        return false;
2088    }
2089
2090    @Override
2091    protected int computeHorizontalScrollRange() {
2092        if (mDrawHistory) {
2093            return mHistoryWidth;
2094        } else {
2095            // to avoid rounding error caused unnecessary scrollbar, use floor
2096            return (int) Math.floor(mContentWidth * mActualScale);
2097        }
2098    }
2099
2100    @Override
2101    protected int computeVerticalScrollRange() {
2102        if (mDrawHistory) {
2103            return mHistoryHeight;
2104        } else {
2105            // to avoid rounding error caused unnecessary scrollbar, use floor
2106            return (int) Math.floor(mContentHeight * mActualScale);
2107        }
2108    }
2109
2110    @Override
2111    protected int computeVerticalScrollOffset() {
2112        return Math.max(mScrollY - getTitleHeight(), 0);
2113    }
2114
2115    @Override
2116    protected int computeVerticalScrollExtent() {
2117        return getViewHeight();
2118    }
2119
2120    /** @hide */
2121    @Override
2122    protected void onDrawVerticalScrollBar(Canvas canvas,
2123                                           Drawable scrollBar,
2124                                           int l, int t, int r, int b) {
2125        scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b);
2126        scrollBar.draw(canvas);
2127    }
2128
2129    /**
2130     * Get the url for the current page. This is not always the same as the url
2131     * passed to WebViewClient.onPageStarted because although the load for
2132     * that url has begun, the current page may not have changed.
2133     * @return The url for the current page.
2134     */
2135    public String getUrl() {
2136        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2137        return h != null ? h.getUrl() : null;
2138    }
2139
2140    /**
2141     * Get the original url for the current page. This is not always the same
2142     * as the url passed to WebViewClient.onPageStarted because although the
2143     * load for that url has begun, the current page may not have changed.
2144     * Also, there may have been redirects resulting in a different url to that
2145     * originally requested.
2146     * @return The url that was originally requested for the current page.
2147     */
2148    public String getOriginalUrl() {
2149        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2150        return h != null ? h.getOriginalUrl() : null;
2151    }
2152
2153    /**
2154     * Get the title for the current page. This is the title of the current page
2155     * until WebViewClient.onReceivedTitle is called.
2156     * @return The title for the current page.
2157     */
2158    public String getTitle() {
2159        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2160        return h != null ? h.getTitle() : null;
2161    }
2162
2163    /**
2164     * Get the favicon for the current page. This is the favicon of the current
2165     * page until WebViewClient.onReceivedIcon is called.
2166     * @return The favicon for the current page.
2167     */
2168    public Bitmap getFavicon() {
2169        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2170        return h != null ? h.getFavicon() : null;
2171    }
2172
2173    /**
2174     * Get the touch icon url for the apple-touch-icon <link> element.
2175     * @hide
2176     */
2177    public String getTouchIconUrl() {
2178        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2179        return h != null ? h.getTouchIconUrl() : null;
2180    }
2181
2182    /**
2183     * Get the progress for the current page.
2184     * @return The progress for the current page between 0 and 100.
2185     */
2186    public int getProgress() {
2187        return mCallbackProxy.getProgress();
2188    }
2189
2190    /**
2191     * @return the height of the HTML content.
2192     */
2193    public int getContentHeight() {
2194        return mContentHeight;
2195    }
2196
2197    /**
2198     * @return the width of the HTML content.
2199     * @hide
2200     */
2201    public int getContentWidth() {
2202        return mContentWidth;
2203    }
2204
2205    /**
2206     * Pause all layout, parsing, and javascript timers for all webviews. This
2207     * is a global requests, not restricted to just this webview. This can be
2208     * useful if the application has been paused.
2209     */
2210    public void pauseTimers() {
2211        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
2212    }
2213
2214    /**
2215     * Resume all layout, parsing, and javascript timers for all webviews.
2216     * This will resume dispatching all timers.
2217     */
2218    public void resumeTimers() {
2219        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
2220    }
2221
2222    /**
2223     * Call this to pause any extra processing associated with this view and
2224     * its associated DOM/plugins/javascript/etc. For example, if the view is
2225     * taken offscreen, this could be called to reduce unnecessary CPU and/or
2226     * network traffic. When the view is again "active", call onResume().
2227     *
2228     * Note that this differs from pauseTimers(), which affects all views/DOMs
2229     * @hide
2230     */
2231    public void onPause() {
2232        if (!mIsPaused) {
2233            mIsPaused = true;
2234            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
2235        }
2236    }
2237
2238    /**
2239     * Call this to balanace a previous call to onPause()
2240     * @hide
2241     */
2242    public void onResume() {
2243        if (mIsPaused) {
2244            mIsPaused = false;
2245            mWebViewCore.sendMessage(EventHub.ON_RESUME);
2246        }
2247    }
2248
2249    /**
2250     * Returns true if the view is paused, meaning onPause() was called. Calling
2251     * onResume() sets the paused state back to false.
2252     * @hide
2253     */
2254    public boolean isPaused() {
2255        return mIsPaused;
2256    }
2257
2258    /**
2259     * Call this to inform the view that memory is low so that it can
2260     * free any available memory.
2261     * @hide
2262     */
2263    public void freeMemory() {
2264        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
2265    }
2266
2267    /**
2268     * Clear the resource cache. Note that the cache is per-application, so
2269     * this will clear the cache for all WebViews used.
2270     *
2271     * @param includeDiskFiles If false, only the RAM cache is cleared.
2272     */
2273    public void clearCache(boolean includeDiskFiles) {
2274        // Note: this really needs to be a static method as it clears cache for all
2275        // WebView. But we need mWebViewCore to send message to WebCore thread, so
2276        // we can't make this static.
2277        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
2278                includeDiskFiles ? 1 : 0, 0);
2279    }
2280
2281    /**
2282     * Make sure that clearing the form data removes the adapter from the
2283     * currently focused textfield if there is one.
2284     */
2285    public void clearFormData() {
2286        if (inEditingMode()) {
2287            AutoCompleteAdapter adapter = null;
2288            mWebTextView.setAdapterCustom(adapter);
2289        }
2290    }
2291
2292    /**
2293     * Tell the WebView to clear its internal back/forward list.
2294     */
2295    public void clearHistory() {
2296        mCallbackProxy.getBackForwardList().setClearPending();
2297        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
2298    }
2299
2300    /**
2301     * Clear the SSL preferences table stored in response to proceeding with SSL
2302     * certificate errors.
2303     */
2304    public void clearSslPreferences() {
2305        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
2306    }
2307
2308    /**
2309     * Return the WebBackForwardList for this WebView. This contains the
2310     * back/forward list for use in querying each item in the history stack.
2311     * This is a copy of the private WebBackForwardList so it contains only a
2312     * snapshot of the current state. Multiple calls to this method may return
2313     * different objects. The object returned from this method will not be
2314     * updated to reflect any new state.
2315     */
2316    public WebBackForwardList copyBackForwardList() {
2317        return mCallbackProxy.getBackForwardList().clone();
2318    }
2319
2320    /*
2321     * Highlight and scroll to the next occurance of String in findAll.
2322     * Wraps the page infinitely, and scrolls.  Must be called after
2323     * calling findAll.
2324     *
2325     * @param forward Direction to search.
2326     */
2327    public void findNext(boolean forward) {
2328        nativeFindNext(forward);
2329    }
2330
2331    /*
2332     * Find all instances of find on the page and highlight them.
2333     * @param find  String to find.
2334     * @return int  The number of occurances of the String "find"
2335     *              that were found.
2336     */
2337    public int findAll(String find) {
2338        if (mFindIsUp == false) {
2339            recordNewContentSize(mContentWidth, mContentHeight + mFindHeight,
2340                    false);
2341            mFindIsUp = true;
2342        }
2343        int result = nativeFindAll(find.toLowerCase(), find.toUpperCase());
2344        invalidate();
2345        return result;
2346    }
2347
2348    // Used to know whether the find dialog is open.  Affects whether
2349    // or not we draw the highlights for matches.
2350    private boolean mFindIsUp;
2351    private int mFindHeight;
2352
2353    /**
2354     * Return the first substring consisting of the address of a physical
2355     * location. Currently, only addresses in the United States are detected,
2356     * and consist of:
2357     * - a house number
2358     * - a street name
2359     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2360     * - a city name
2361     * - a state or territory, either spelled out or two-letter abbr.
2362     * - an optional 5 digit or 9 digit zip code.
2363     *
2364     * All names must be correctly capitalized, and the zip code, if present,
2365     * must be valid for the state. The street type must be a standard USPS
2366     * spelling or abbreviation. The state or territory must also be spelled
2367     * or abbreviated using USPS standards. The house number may not exceed
2368     * five digits.
2369     * @param addr The string to search for addresses.
2370     *
2371     * @return the address, or if no address is found, return null.
2372     */
2373    public static String findAddress(String addr) {
2374        return findAddress(addr, false);
2375    }
2376
2377    /**
2378     * @hide
2379     * Return the first substring consisting of the address of a physical
2380     * location. Currently, only addresses in the United States are detected,
2381     * and consist of:
2382     * - a house number
2383     * - a street name
2384     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2385     * - a city name
2386     * - a state or territory, either spelled out or two-letter abbr.
2387     * - an optional 5 digit or 9 digit zip code.
2388     *
2389     * Names are optionally capitalized, and the zip code, if present,
2390     * must be valid for the state. The street type must be a standard USPS
2391     * spelling or abbreviation. The state or territory must also be spelled
2392     * or abbreviated using USPS standards. The house number may not exceed
2393     * five digits.
2394     * @param addr The string to search for addresses.
2395     * @param caseInsensitive addr Set to true to make search ignore case.
2396     *
2397     * @return the address, or if no address is found, return null.
2398     */
2399    public static String findAddress(String addr, boolean caseInsensitive) {
2400        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
2401    }
2402
2403    /*
2404     * Clear the highlighting surrounding text matches created by findAll.
2405     */
2406    public void clearMatches() {
2407        if (mFindIsUp) {
2408            recordNewContentSize(mContentWidth, mContentHeight - mFindHeight,
2409                    false);
2410            mFindIsUp = false;
2411        }
2412        nativeSetFindIsDown();
2413        // Now that the dialog has been removed, ensure that we scroll to a
2414        // location that is not beyond the end of the page.
2415        pinScrollTo(mScrollX, mScrollY, false, 0);
2416        invalidate();
2417    }
2418
2419    /**
2420     * @hide
2421     */
2422    public void setFindDialogHeight(int height) {
2423        if (DebugFlags.WEB_VIEW) {
2424            Log.v(LOGTAG, "setFindDialogHeight height=" + height);
2425        }
2426        mFindHeight = height;
2427    }
2428
2429    /**
2430     * Query the document to see if it contains any image references. The
2431     * message object will be dispatched with arg1 being set to 1 if images
2432     * were found and 0 if the document does not reference any images.
2433     * @param response The message that will be dispatched with the result.
2434     */
2435    public void documentHasImages(Message response) {
2436        if (response == null) {
2437            return;
2438        }
2439        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
2440    }
2441
2442    @Override
2443    public void computeScroll() {
2444        if (mScroller.computeScrollOffset()) {
2445            int oldX = mScrollX;
2446            int oldY = mScrollY;
2447            mScrollX = mScroller.getCurrX();
2448            mScrollY = mScroller.getCurrY();
2449            postInvalidate();  // So we draw again
2450            if (oldX != mScrollX || oldY != mScrollY) {
2451                // as onScrollChanged() is not called, sendOurVisibleRect()
2452                // needs to be call explicitly
2453                sendOurVisibleRect();
2454            }
2455        } else {
2456            super.computeScroll();
2457        }
2458    }
2459
2460    private static int computeDuration(int dx, int dy) {
2461        int distance = Math.max(Math.abs(dx), Math.abs(dy));
2462        int duration = distance * 1000 / STD_SPEED;
2463        return Math.min(duration, MAX_DURATION);
2464    }
2465
2466    // helper to pin the scrollBy parameters (already in view coordinates)
2467    // returns true if the scroll was changed
2468    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
2469        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
2470    }
2471    // helper to pin the scrollTo parameters (already in view coordinates)
2472    // returns true if the scroll was changed
2473    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
2474        x = pinLocX(x);
2475        y = pinLocY(y);
2476        int dx = x - mScrollX;
2477        int dy = y - mScrollY;
2478
2479        if ((dx | dy) == 0) {
2480            return false;
2481        }
2482        if (animate) {
2483            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
2484            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
2485                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
2486            awakenScrollBars(mScroller.getDuration());
2487            invalidate();
2488        } else {
2489            abortAnimation(); // just in case
2490            scrollTo(x, y);
2491        }
2492        return true;
2493    }
2494
2495    // Scale from content to view coordinates, and pin.
2496    // Also called by jni webview.cpp
2497    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
2498        if (mDrawHistory) {
2499            // disallow WebView to change the scroll position as History Picture
2500            // is used in the view system.
2501            // TODO: as we switchOutDrawHistory when trackball or navigation
2502            // keys are hit, this should be safe. Right?
2503            return false;
2504        }
2505        cx = contentToViewDimension(cx);
2506        cy = contentToViewDimension(cy);
2507        if (mHeightCanMeasure) {
2508            // move our visible rect according to scroll request
2509            if (cy != 0) {
2510                Rect tempRect = new Rect();
2511                calcOurVisibleRect(tempRect);
2512                tempRect.offset(cx, cy);
2513                requestRectangleOnScreen(tempRect);
2514            }
2515            // FIXME: We scroll horizontally no matter what because currently
2516            // ScrollView and ListView will not scroll horizontally.
2517            // FIXME: Why do we only scroll horizontally if there is no
2518            // vertical scroll?
2519//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
2520            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
2521        } else {
2522            return pinScrollBy(cx, cy, animate, 0);
2523        }
2524    }
2525
2526    // scale from content to view coordinates, and pin
2527    // return true if pin caused the final x/y different than the request cx/cy,
2528    // and a future scroll may reach the request cx/cy after our size has
2529    // changed
2530    // return false if the view scroll to the exact position as it is requested,
2531    // where negative numbers are taken to mean 0
2532    private boolean setContentScrollTo(int cx, int cy) {
2533        if (mDrawHistory) {
2534            // disallow WebView to change the scroll position as History Picture
2535            // is used in the view system.
2536            // One known case where this is called is that WebCore tries to
2537            // restore the scroll position. As history Picture already uses the
2538            // saved scroll position, it is ok to skip this.
2539            return false;
2540        }
2541        int vx;
2542        int vy;
2543        if ((cx | cy) == 0) {
2544            // If the page is being scrolled to (0,0), do not add in the title
2545            // bar's height, and simply scroll to (0,0). (The only other work
2546            // in contentToView_ is to multiply, so this would not change 0.)
2547            vx = 0;
2548            vy = 0;
2549        } else {
2550            vx = contentToViewX(cx);
2551            vy = contentToViewY(cy);
2552        }
2553//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
2554//                      vx + " " + vy + "]");
2555        // Some mobile sites attempt to scroll the title bar off the page by
2556        // scrolling to (0,1).  If we are at the top left corner of the
2557        // page, assume this is an attempt to scroll off the title bar, and
2558        // animate the title bar off screen slowly enough that the user can see
2559        // it.
2560        if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0) {
2561            pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
2562            // Since we are animating, we have not yet reached the desired
2563            // scroll position.  Do not return true to request another attempt
2564            return false;
2565        }
2566        pinScrollTo(vx, vy, false, 0);
2567        // If the request was to scroll to a negative coordinate, treat it as if
2568        // it was a request to scroll to 0
2569        if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
2570            return true;
2571        } else {
2572            return false;
2573        }
2574    }
2575
2576    // scale from content to view coordinates, and pin
2577    private void spawnContentScrollTo(int cx, int cy) {
2578        if (mDrawHistory) {
2579            // disallow WebView to change the scroll position as History Picture
2580            // is used in the view system.
2581            return;
2582        }
2583        int vx = contentToViewX(cx);
2584        int vy = contentToViewY(cy);
2585        pinScrollTo(vx, vy, true, 0);
2586    }
2587
2588    /**
2589     * These are from webkit, and are in content coordinate system (unzoomed)
2590     */
2591    private void contentSizeChanged(boolean updateLayout) {
2592        // suppress 0,0 since we usually see real dimensions soon after
2593        // this avoids drawing the prev content in a funny place. If we find a
2594        // way to consolidate these notifications, this check may become
2595        // obsolete
2596        if ((mContentWidth | mContentHeight) == 0) {
2597            return;
2598        }
2599
2600        if (mHeightCanMeasure) {
2601            if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
2602                    && updateLayout) {
2603                requestLayout();
2604            }
2605        } else if (mWidthCanMeasure) {
2606            if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
2607                    && updateLayout) {
2608                requestLayout();
2609            }
2610        } else {
2611            // If we don't request a layout, try to send our view size to the
2612            // native side to ensure that WebCore has the correct dimensions.
2613            sendViewSizeZoom();
2614        }
2615    }
2616
2617    /**
2618     * Set the WebViewClient that will receive various notifications and
2619     * requests. This will replace the current handler.
2620     * @param client An implementation of WebViewClient.
2621     */
2622    public void setWebViewClient(WebViewClient client) {
2623        mCallbackProxy.setWebViewClient(client);
2624    }
2625
2626    /**
2627     * Register the interface to be used when content can not be handled by
2628     * the rendering engine, and should be downloaded instead. This will replace
2629     * the current handler.
2630     * @param listener An implementation of DownloadListener.
2631     */
2632    public void setDownloadListener(DownloadListener listener) {
2633        mCallbackProxy.setDownloadListener(listener);
2634    }
2635
2636    /**
2637     * Set the chrome handler. This is an implementation of WebChromeClient for
2638     * use in handling Javascript dialogs, favicons, titles, and the progress.
2639     * This will replace the current handler.
2640     * @param client An implementation of WebChromeClient.
2641     */
2642    public void setWebChromeClient(WebChromeClient client) {
2643        mCallbackProxy.setWebChromeClient(client);
2644    }
2645
2646    /**
2647     * Gets the chrome handler.
2648     * @return the current WebChromeClient instance.
2649     *
2650     * @hide API council approval.
2651     */
2652    public WebChromeClient getWebChromeClient() {
2653        return mCallbackProxy.getWebChromeClient();
2654    }
2655
2656    /**
2657     * Set the Picture listener. This is an interface used to receive
2658     * notifications of a new Picture.
2659     * @param listener An implementation of WebView.PictureListener.
2660     */
2661    public void setPictureListener(PictureListener listener) {
2662        mPictureListener = listener;
2663    }
2664
2665    /**
2666     * {@hide}
2667     */
2668    /* FIXME: Debug only! Remove for SDK! */
2669    public void externalRepresentation(Message callback) {
2670        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
2671    }
2672
2673    /**
2674     * {@hide}
2675     */
2676    /* FIXME: Debug only! Remove for SDK! */
2677    public void documentAsText(Message callback) {
2678        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
2679    }
2680
2681    /**
2682     * Use this function to bind an object to Javascript so that the
2683     * methods can be accessed from Javascript.
2684     * <p><strong>IMPORTANT:</strong>
2685     * <ul>
2686     * <li> Using addJavascriptInterface() allows JavaScript to control your
2687     * application. This can be a very useful feature or a dangerous security
2688     * issue. When the HTML in the WebView is untrustworthy (for example, part
2689     * or all of the HTML is provided by some person or process), then an
2690     * attacker could inject HTML that will execute your code and possibly any
2691     * code of the attacker's choosing.<br>
2692     * Do not use addJavascriptInterface() unless all of the HTML in this
2693     * WebView was written by you.</li>
2694     * <li> The Java object that is bound runs in another thread and not in
2695     * the thread that it was constructed in.</li>
2696     * </ul></p>
2697     * @param obj The class instance to bind to Javascript
2698     * @param interfaceName The name to used to expose the class in Javascript
2699     */
2700    public void addJavascriptInterface(Object obj, String interfaceName) {
2701        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
2702        arg.mObject = obj;
2703        arg.mInterfaceName = interfaceName;
2704        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
2705    }
2706
2707    /**
2708     * Return the WebSettings object used to control the settings for this
2709     * WebView.
2710     * @return A WebSettings object that can be used to control this WebView's
2711     *         settings.
2712     */
2713    public WebSettings getSettings() {
2714        return mWebViewCore.getSettings();
2715    }
2716
2717   /**
2718    * Return the list of currently loaded plugins.
2719    * @return The list of currently loaded plugins.
2720    *
2721    * @deprecated This was used for Gears, which has been deprecated.
2722    */
2723    @Deprecated
2724    public static synchronized PluginList getPluginList() {
2725        return null;
2726    }
2727
2728   /**
2729    * @deprecated This was used for Gears, which has been deprecated.
2730    */
2731    @Deprecated
2732    public void refreshPlugins(boolean reloadOpenPages) { }
2733
2734    //-------------------------------------------------------------------------
2735    // Override View methods
2736    //-------------------------------------------------------------------------
2737
2738    @Override
2739    protected void finalize() throws Throwable {
2740        try {
2741            destroy();
2742        } finally {
2743            super.finalize();
2744        }
2745    }
2746
2747    @Override
2748    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
2749        if (child == mTitleBar) {
2750            // When drawing the title bar, move it horizontally to always show
2751            // at the top of the WebView.
2752            mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
2753        }
2754        return super.drawChild(canvas, child, drawingTime);
2755    }
2756
2757    @Override
2758    protected void onDraw(Canvas canvas) {
2759        // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
2760        if (mNativeClass == 0) {
2761            return;
2762        }
2763        int saveCount = canvas.save();
2764        if (mTitleBar != null) {
2765            canvas.translate(0, (int) mTitleBar.getHeight());
2766        }
2767        // Update the buttons in the picture, so when we draw the picture
2768        // to the screen, they are in the correct state.
2769        // Tell the native side if user is a) touching the screen,
2770        // b) pressing the trackball down, or c) pressing the enter key
2771        // If the cursor is on a button, we need to draw it in the pressed
2772        // state.
2773        // If mNativeClass is 0, we should not reach here, so we do not
2774        // need to check it again.
2775        nativeRecordButtons(hasFocus() && hasWindowFocus(),
2776                mTouchMode == TOUCH_SHORTPRESS_START_MODE
2777                || mTrackballDown || mGotCenterDown, false);
2778        drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
2779        canvas.restoreToCount(saveCount);
2780
2781        // Now draw the shadow.
2782        if (mTitleBar != null) {
2783            int y = mScrollY + getVisibleTitleHeight();
2784            int height = (int) (5f * getContext().getResources()
2785                    .getDisplayMetrics().density);
2786            mTitleShadow.setBounds(mScrollX, y, mScrollX + getWidth(),
2787                    y + height);
2788            mTitleShadow.draw(canvas);
2789        }
2790        if (AUTO_REDRAW_HACK && mAutoRedraw) {
2791            invalidate();
2792        }
2793    }
2794
2795    @Override
2796    public void setLayoutParams(ViewGroup.LayoutParams params) {
2797        if (params.height == LayoutParams.WRAP_CONTENT) {
2798            mWrapContent = true;
2799        }
2800        super.setLayoutParams(params);
2801    }
2802
2803    @Override
2804    public boolean performLongClick() {
2805        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
2806            // Send the click so that the textfield is in focus
2807            // FIXME: When we start respecting changes to the native textfield's
2808            // selection, need to make sure that this does not change it.
2809            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
2810                    nativeCursorNodePointer());
2811            rebuildWebTextView();
2812        }
2813        if (inEditingMode()) {
2814            return mWebTextView.performLongClick();
2815        } else {
2816            return super.performLongClick();
2817        }
2818    }
2819
2820    boolean inAnimateZoom() {
2821        return mZoomScale != 0;
2822    }
2823
2824    /**
2825     * Need to adjust the WebTextView after a change in zoom, since mActualScale
2826     * has changed.  This is especially important for password fields, which are
2827     * drawn by the WebTextView, since it conveys more information than what
2828     * webkit draws.  Thus we need to reposition it to show in the correct
2829     * place.
2830     */
2831    private boolean mNeedToAdjustWebTextView;
2832
2833    private void drawCoreAndCursorRing(Canvas canvas, int color,
2834        boolean drawCursorRing) {
2835        if (mDrawHistory) {
2836            canvas.scale(mActualScale, mActualScale);
2837            canvas.drawPicture(mHistoryPicture);
2838            return;
2839        }
2840
2841        boolean animateZoom = mZoomScale != 0;
2842        boolean animateScroll = !mScroller.isFinished()
2843                || mVelocityTracker != null;
2844        if (animateZoom) {
2845            float zoomScale;
2846            int interval = (int) (SystemClock.uptimeMillis() - mZoomStart);
2847            if (interval < ZOOM_ANIMATION_LENGTH) {
2848                float ratio = (float) interval / ZOOM_ANIMATION_LENGTH;
2849                zoomScale = 1.0f / (mInvInitialZoomScale
2850                        + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio);
2851                invalidate();
2852            } else {
2853                zoomScale = mZoomScale;
2854                // set mZoomScale to be 0 as we have done animation
2855                mZoomScale = 0;
2856                // call invalidate() again to draw with the final filters
2857                invalidate();
2858                if (mNeedToAdjustWebTextView) {
2859                    mNeedToAdjustWebTextView = false;
2860                    mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
2861                            contentToViewDimension(
2862                            nativeFocusCandidateTextSize()));
2863                    Rect bounds = nativeFocusCandidateNodeBounds();
2864                    Rect vBox = contentToViewRect(bounds);
2865                    mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
2866                            vBox.height());
2867                    // If it is a password field, start drawing the
2868                    // WebTextView once again.
2869                    if (nativeFocusCandidateIsPassword()) {
2870                        mWebTextView.setInPassword(true);
2871                    }
2872                }
2873            }
2874            // calculate the intermediate scroll position. As we need to use
2875            // zoomScale, we can't use pinLocX/Y directly. Copy the logic here.
2876            float scale = zoomScale * mInvInitialZoomScale;
2877            int tx = Math.round(scale * (mInitialScrollX + mZoomCenterX)
2878                    - mZoomCenterX);
2879            tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth
2880                    * zoomScale)) + mScrollX;
2881            int titleHeight = getTitleHeight();
2882            int ty = Math.round(scale
2883                    * (mInitialScrollY + mZoomCenterY - titleHeight)
2884                    - (mZoomCenterY - titleHeight));
2885            ty = -(ty <= titleHeight ? Math.max(ty, 0) : pinLoc(ty
2886                    - titleHeight, getViewHeight(), Math.round(mContentHeight
2887                    * zoomScale)) + titleHeight) + mScrollY;
2888            canvas.translate(tx, ty);
2889            canvas.scale(zoomScale, zoomScale);
2890            if (inEditingMode() && !mNeedToAdjustWebTextView
2891                    && mZoomScale != 0) {
2892                // The WebTextView is up.  Keep track of this so we can adjust
2893                // its size and placement when we finish zooming
2894                mNeedToAdjustWebTextView = true;
2895                // If it is in password mode, turn it off so it does not draw
2896                // misplaced.
2897                if (nativeFocusCandidateIsPassword()) {
2898                    mWebTextView.setInPassword(false);
2899                }
2900            }
2901        } else {
2902            canvas.scale(mActualScale, mActualScale);
2903        }
2904
2905        mWebViewCore.drawContentPicture(canvas, color, animateZoom,
2906                animateScroll);
2907
2908        if (mNativeClass == 0) return;
2909        if (mShiftIsPressed) {
2910            if (mTouchSelection) {
2911                nativeDrawSelectionRegion(canvas);
2912            } else {
2913                nativeDrawSelection(canvas, mSelectX, mSelectY,
2914                        mExtendSelection);
2915            }
2916        } else if (drawCursorRing) {
2917            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
2918                mTouchMode = TOUCH_SHORTPRESS_MODE;
2919                HitTestResult hitTest = getHitTestResult();
2920                if (hitTest != null &&
2921                        hitTest.mType != HitTestResult.UNKNOWN_TYPE) {
2922                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
2923                            .obtainMessage(SWITCH_TO_LONGPRESS),
2924                            LONG_PRESS_TIMEOUT);
2925                }
2926            }
2927            nativeDrawCursorRing(canvas);
2928        }
2929        // When the FindDialog is up, only draw the matches if we are not in
2930        // the process of scrolling them into view.
2931        if (mFindIsUp && !animateScroll) {
2932            nativeDrawMatches(canvas);
2933        }
2934    }
2935
2936    // draw history
2937    private boolean mDrawHistory = false;
2938    private Picture mHistoryPicture = null;
2939    private int mHistoryWidth = 0;
2940    private int mHistoryHeight = 0;
2941
2942    // Only check the flag, can be called from WebCore thread
2943    boolean drawHistory() {
2944        return mDrawHistory;
2945    }
2946
2947    // Should only be called in UI thread
2948    void switchOutDrawHistory() {
2949        if (null == mWebViewCore) return; // CallbackProxy may trigger this
2950        if (mDrawHistory && mWebViewCore.pictureReady()) {
2951            mDrawHistory = false;
2952            invalidate();
2953            int oldScrollX = mScrollX;
2954            int oldScrollY = mScrollY;
2955            mScrollX = pinLocX(mScrollX);
2956            mScrollY = pinLocY(mScrollY);
2957            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
2958                mUserScroll = false;
2959                mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
2960                        oldScrollY);
2961            }
2962            sendOurVisibleRect();
2963        }
2964    }
2965
2966    WebViewCore.CursorData cursorData() {
2967        WebViewCore.CursorData result = new WebViewCore.CursorData();
2968        result.mMoveGeneration = nativeMoveGeneration();
2969        result.mFrame = nativeCursorFramePointer();
2970        Point position = nativeCursorPosition();
2971        result.mX = position.x;
2972        result.mY = position.y;
2973        return result;
2974    }
2975
2976    /**
2977     *  Delete text from start to end in the focused textfield. If there is no
2978     *  focus, or if start == end, silently fail.  If start and end are out of
2979     *  order, swap them.
2980     *  @param  start   Beginning of selection to delete.
2981     *  @param  end     End of selection to delete.
2982     */
2983    /* package */ void deleteSelection(int start, int end) {
2984        mTextGeneration++;
2985        WebViewCore.TextSelectionData data
2986                = new WebViewCore.TextSelectionData(start, end);
2987        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
2988                data);
2989    }
2990
2991    /**
2992     *  Set the selection to (start, end) in the focused textfield. If start and
2993     *  end are out of order, swap them.
2994     *  @param  start   Beginning of selection.
2995     *  @param  end     End of selection.
2996     */
2997    /* package */ void setSelection(int start, int end) {
2998        mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
2999    }
3000
3001    // Called by JNI when a touch event puts a textfield into focus.
3002    private void displaySoftKeyboard(boolean isTextView) {
3003        InputMethodManager imm = (InputMethodManager)
3004                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3005
3006        if (isTextView) {
3007            if (mWebTextView == null) return;
3008
3009            imm.showSoftInput(mWebTextView, 0);
3010            // Now we need to fake a touch event to place the cursor where the
3011            // user touched.
3012            AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams)
3013                    mWebTextView.getLayoutParams();
3014            if (lp != null) {
3015                // Take the last touch and adjust for the location of the
3016                // WebTextView.
3017                float x = mLastTouchX + (float) (mScrollX - lp.x);
3018                float y = mLastTouchY + (float) (mScrollY - lp.y);
3019                mWebTextView.fakeTouchEvent(x, y);
3020            }
3021            if (mInZoomOverview) {
3022                // if in zoom overview mode, call doDoubleTap() to bring it back
3023                // to normal mode so that user can enter text.
3024                doDoubleTap();
3025            }
3026        }
3027        else { // used by plugins
3028            imm.showSoftInput(this, 0);
3029        }
3030    }
3031
3032    // Called by WebKit to instruct the UI to hide the keyboard
3033    private void hideSoftKeyboard() {
3034        InputMethodManager imm = (InputMethodManager)
3035                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3036
3037        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
3038    }
3039
3040    /*
3041     * This method checks the current focus and cursor and potentially rebuilds
3042     * mWebTextView to have the appropriate properties, such as password,
3043     * multiline, and what text it contains.  It also removes it if necessary.
3044     */
3045    /* package */ void rebuildWebTextView() {
3046        // If the WebView does not have focus, do nothing until it gains focus.
3047        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
3048            return;
3049        }
3050        boolean alreadyThere = inEditingMode();
3051        // inEditingMode can only return true if mWebTextView is non-null,
3052        // so we can safely call remove() if (alreadyThere)
3053        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
3054            if (alreadyThere) {
3055                mWebTextView.remove();
3056            }
3057            return;
3058        }
3059        // At this point, we know we have found an input field, so go ahead
3060        // and create the WebTextView if necessary.
3061        if (mWebTextView == null) {
3062            mWebTextView = new WebTextView(mContext, WebView.this);
3063            // Initialize our generation number.
3064            mTextGeneration = 0;
3065        }
3066        mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
3067                contentToViewDimension(nativeFocusCandidateTextSize()));
3068        Rect visibleRect = new Rect();
3069        calcOurContentVisibleRect(visibleRect);
3070        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
3071        // should be in content coordinates.
3072        Rect bounds = nativeFocusCandidateNodeBounds();
3073        if (!Rect.intersects(bounds, visibleRect)) {
3074            mWebTextView.bringIntoView();
3075        }
3076        String text = nativeFocusCandidateText();
3077        int nodePointer = nativeFocusCandidatePointer();
3078        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
3079            // It is possible that we have the same textfield, but it has moved,
3080            // i.e. In the case of opening/closing the screen.
3081            // In that case, we need to set the dimensions, but not the other
3082            // aspects.
3083            // We also need to restore the selection, which gets wrecked by
3084            // calling setTextEntryRect.
3085            Spannable spannable = (Spannable) mWebTextView.getText();
3086            int start = Selection.getSelectionStart(spannable);
3087            int end = Selection.getSelectionEnd(spannable);
3088            // If the text has been changed by webkit, update it.  However, if
3089            // there has been more UI text input, ignore it.  We will receive
3090            // another update when that text is recognized.
3091            if (text != null && !text.equals(spannable.toString())
3092                    && nativeTextGeneration() == mTextGeneration) {
3093                mWebTextView.setTextAndKeepSelection(text);
3094            } else {
3095                Selection.setSelection(spannable, start, end);
3096            }
3097        } else {
3098            Rect vBox = contentToViewRect(bounds);
3099            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3100                    vBox.height());
3101            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
3102                    Gravity.RIGHT : Gravity.NO_GRAVITY);
3103            // this needs to be called before update adapter thread starts to
3104            // ensure the mWebTextView has the same node pointer
3105            mWebTextView.setNodePointer(nodePointer);
3106            int maxLength = -1;
3107            boolean isTextField = nativeFocusCandidateIsTextField();
3108            if (isTextField) {
3109                maxLength = nativeFocusCandidateMaxLength();
3110                String name = nativeFocusCandidateName();
3111                if (mWebViewCore.getSettings().getSaveFormData()
3112                        && name != null) {
3113                    Message update = mPrivateHandler.obtainMessage(
3114                            REQUEST_FORM_DATA, nodePointer);
3115                    RequestFormData updater = new RequestFormData(name,
3116                            getUrl(), update);
3117                    Thread t = new Thread(updater);
3118                    t.start();
3119                }
3120            }
3121            mWebTextView.setMaxLength(maxLength);
3122            AutoCompleteAdapter adapter = null;
3123            mWebTextView.setAdapterCustom(adapter);
3124            mWebTextView.setSingleLine(isTextField);
3125            mWebTextView.setInPassword(nativeFocusCandidateIsPassword());
3126            if (null == text) {
3127                mWebTextView.setText("", 0, 0);
3128                if (DebugFlags.WEB_VIEW) {
3129                    Log.v(LOGTAG, "rebuildWebTextView null == text");
3130                }
3131            } else {
3132                // Change to true to enable the old style behavior, where
3133                // entering a textfield/textarea always set the selection to the
3134                // whole field.  This was desirable for the case where the user
3135                // intends to scroll past the field using the trackball.
3136                // However, it causes a problem when replying to emails - the
3137                // user expects the cursor to be at the beginning of the
3138                // textarea.  Testing out a new behavior, where textfields set
3139                // selection at the end, and textareas at the beginning.
3140                if (false) {
3141                    mWebTextView.setText(text, 0, text.length());
3142                } else if (isTextField) {
3143                    int length = text.length();
3144                    mWebTextView.setText(text, length, length);
3145                    if (DebugFlags.WEB_VIEW) {
3146                        Log.v(LOGTAG, "rebuildWebTextView length=" + length);
3147                    }
3148                } else {
3149                    mWebTextView.setText(text, 0, 0);
3150                    if (DebugFlags.WEB_VIEW) {
3151                        Log.v(LOGTAG, "rebuildWebTextView !isTextField");
3152                    }
3153                }
3154            }
3155            mWebTextView.requestFocus();
3156        }
3157    }
3158
3159    /*
3160     * This class requests an Adapter for the WebTextView which shows past
3161     * entries stored in the database.  It is a Runnable so that it can be done
3162     * in its own thread, without slowing down the UI.
3163     */
3164    private class RequestFormData implements Runnable {
3165        private String mName;
3166        private String mUrl;
3167        private Message mUpdateMessage;
3168
3169        public RequestFormData(String name, String url, Message msg) {
3170            mName = name;
3171            mUrl = url;
3172            mUpdateMessage = msg;
3173        }
3174
3175        public void run() {
3176            ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName);
3177            if (pastEntries.size() > 0) {
3178                AutoCompleteAdapter adapter = new
3179                        AutoCompleteAdapter(mContext, pastEntries);
3180                mUpdateMessage.obj = adapter;
3181                mUpdateMessage.sendToTarget();
3182            }
3183        }
3184    }
3185
3186    // This is used to determine long press with the center key.  Does not
3187    // affect long press with the trackball/touch.
3188    private boolean mGotCenterDown = false;
3189
3190    @Override
3191    public boolean onKeyDown(int keyCode, KeyEvent event) {
3192        if (DebugFlags.WEB_VIEW) {
3193            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
3194                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3195        }
3196
3197        if (mNativeClass == 0) {
3198            return false;
3199        }
3200
3201        // do this hack up front, so it always works, regardless of touch-mode
3202        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
3203            mAutoRedraw = !mAutoRedraw;
3204            if (mAutoRedraw) {
3205                invalidate();
3206            }
3207            return true;
3208        }
3209
3210        // Bubble up the key event if
3211        // 1. it is a system key; or
3212        // 2. the host application wants to handle it;
3213        if (event.isSystem()
3214                || mCallbackProxy.uiOverrideKeyEvent(event)) {
3215            return false;
3216        }
3217
3218        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
3219                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3220                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
3221            mExtendSelection = false;
3222            mShiftIsPressed = true;
3223            if (nativeHasCursorNode()) {
3224                Rect rect = nativeCursorNodeBounds();
3225                mSelectX = contentToViewX(rect.left);
3226                mSelectY = contentToViewY(rect.top);
3227            } else {
3228                mSelectX = mScrollX + (int) mLastTouchX;
3229                mSelectY = mScrollY + (int) mLastTouchY;
3230            }
3231            nativeHideCursor();
3232       }
3233
3234        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3235                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3236            // always handle the navigation keys in the UI thread
3237            switchOutDrawHistory();
3238            if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) {
3239                playSoundEffect(keyCodeToSoundsEffect(keyCode));
3240                return true;
3241            }
3242            // Bubble up the key event as WebView doesn't handle it
3243            return false;
3244        }
3245
3246        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3247            switchOutDrawHistory();
3248            if (event.getRepeatCount() == 0) {
3249                mGotCenterDown = true;
3250                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3251                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
3252                // Already checked mNativeClass, so we do not need to check it
3253                // again.
3254                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
3255                return true;
3256            }
3257            // Bubble up the key event as WebView doesn't handle it
3258            return false;
3259        }
3260
3261        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
3262                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
3263            // turn off copy select if a shift-key combo is pressed
3264            mExtendSelection = mShiftIsPressed = false;
3265            if (mTouchMode == TOUCH_SELECT_MODE) {
3266                mTouchMode = TOUCH_INIT_MODE;
3267            }
3268        }
3269
3270        if (getSettings().getNavDump()) {
3271            switch (keyCode) {
3272                case KeyEvent.KEYCODE_4:
3273                    // "/data/data/com.android.browser/displayTree.txt"
3274                    nativeDumpDisplayTree(getUrl());
3275                    break;
3276                case KeyEvent.KEYCODE_5:
3277                case KeyEvent.KEYCODE_6:
3278                    // 5: dump the dom tree to the file
3279                    // "/data/data/com.android.browser/domTree.txt"
3280                    // 6: dump the dom tree to the adb log
3281                    mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE,
3282                            (keyCode == KeyEvent.KEYCODE_5) ? 1 : 0, 0);
3283                    break;
3284                case KeyEvent.KEYCODE_7:
3285                case KeyEvent.KEYCODE_8:
3286                    // 7: dump the render tree to the file
3287                    // "/data/data/com.android.browser/renderTree.txt"
3288                    // 8: dump the render tree to the adb log
3289                    mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE,
3290                            (keyCode == KeyEvent.KEYCODE_7) ? 1 : 0, 0);
3291                    break;
3292                case KeyEvent.KEYCODE_9:
3293                    nativeInstrumentReport();
3294                    return true;
3295            }
3296        }
3297
3298        if (nativeCursorIsPlugin()) {
3299            nativeUpdatePluginReceivesEvents();
3300            invalidate();
3301        } else if (nativeCursorIsTextInput()) {
3302            // This message will put the node in focus, for the DOM's notion
3303            // of focus, and make the focuscontroller active
3304            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
3305                    nativeCursorNodePointer());
3306            // This will bring up the WebTextView and put it in focus, for
3307            // our view system's notion of focus
3308            rebuildWebTextView();
3309            // Now we need to pass the event to it
3310            return mWebTextView.onKeyDown(keyCode, event);
3311        } else if (nativeHasFocusNode()) {
3312            // In this case, the cursor is not on a text input, but the focus
3313            // might be.  Check it, and if so, hand over to the WebTextView.
3314            rebuildWebTextView();
3315            if (inEditingMode()) {
3316                return mWebTextView.onKeyDown(keyCode, event);
3317            }
3318        }
3319
3320        // TODO: should we pass all the keys to DOM or check the meta tag
3321        if (nativeCursorWantsKeyEvents() || true) {
3322            // pass the key to DOM
3323            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3324            // return true as DOM handles the key
3325            return true;
3326        }
3327
3328        // Bubble up the key event as WebView doesn't handle it
3329        return false;
3330    }
3331
3332    @Override
3333    public boolean onKeyUp(int keyCode, KeyEvent event) {
3334        if (DebugFlags.WEB_VIEW) {
3335            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
3336                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3337        }
3338
3339        if (mNativeClass == 0) {
3340            return false;
3341        }
3342
3343        // special CALL handling when cursor node's href is "tel:XXX"
3344        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
3345            String text = nativeCursorText();
3346            if (!nativeCursorIsTextInput() && text != null
3347                    && text.startsWith(SCHEME_TEL)) {
3348                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
3349                getContext().startActivity(intent);
3350                return true;
3351            }
3352        }
3353
3354        // Bubble up the key event if
3355        // 1. it is a system key; or
3356        // 2. the host application wants to handle it;
3357        if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) {
3358            return false;
3359        }
3360
3361        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3362                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3363            if (commitCopy()) {
3364                return true;
3365            }
3366        }
3367
3368        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3369                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3370            // always handle the navigation keys in the UI thread
3371            // Bubble up the key event as WebView doesn't handle it
3372            return false;
3373        }
3374
3375        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3376            // remove the long press message first
3377            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
3378            mGotCenterDown = false;
3379
3380            if (mShiftIsPressed) {
3381                return false;
3382            }
3383
3384            // perform the single click
3385            Rect visibleRect = sendOurVisibleRect();
3386            // Note that sendOurVisibleRect calls viewToContent, so the
3387            // coordinates should be in content coordinates.
3388            if (!nativeCursorIntersects(visibleRect)) {
3389                return false;
3390            }
3391            nativeSetFollowedLink(true);
3392            nativeUpdatePluginReceivesEvents();
3393            WebViewCore.CursorData data = cursorData();
3394            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
3395            playSoundEffect(SoundEffectConstants.CLICK);
3396            boolean isTextInput = nativeCursorIsTextInput();
3397            if (isTextInput || !mCallbackProxy.uiOverrideUrlLoading(
3398                        nativeCursorText())) {
3399                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
3400                        nativeCursorNodePointer());
3401            }
3402            if (isTextInput) {
3403                rebuildWebTextView();
3404            }
3405            return true;
3406        }
3407
3408        // TODO: should we pass all the keys to DOM or check the meta tag
3409        if (nativeCursorWantsKeyEvents() || true) {
3410            // pass the key to DOM
3411            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
3412            // return true as DOM handles the key
3413            return true;
3414        }
3415
3416        // Bubble up the key event as WebView doesn't handle it
3417        return false;
3418    }
3419
3420    /**
3421     * @hide
3422     */
3423    public void emulateShiftHeld() {
3424        mExtendSelection = false;
3425        mShiftIsPressed = true;
3426        nativeHideCursor();
3427    }
3428
3429    private boolean commitCopy() {
3430        boolean copiedSomething = false;
3431        if (mExtendSelection) {
3432            // copy region so core operates on copy without touching orig.
3433            Region selection = new Region(nativeGetSelection());
3434            if (selection.isEmpty() == false) {
3435                Toast.makeText(mContext
3436                        , com.android.internal.R.string.text_copied
3437                        , Toast.LENGTH_SHORT).show();
3438                mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection);
3439                copiedSomething = true;
3440            }
3441            mExtendSelection = false;
3442        }
3443        mShiftIsPressed = false;
3444        if (mTouchMode == TOUCH_SELECT_MODE) {
3445            mTouchMode = TOUCH_INIT_MODE;
3446        }
3447        return copiedSomething;
3448    }
3449
3450    // Set this as a hierarchy change listener so we can know when this view
3451    // is removed and still have access to our parent.
3452    @Override
3453    protected void onAttachedToWindow() {
3454        super.onAttachedToWindow();
3455        ViewParent parent = getParent();
3456        if (parent instanceof ViewGroup) {
3457            ViewGroup p = (ViewGroup) parent;
3458            p.setOnHierarchyChangeListener(this);
3459        }
3460    }
3461
3462    @Override
3463    protected void onDetachedFromWindow() {
3464        super.onDetachedFromWindow();
3465        ViewParent parent = getParent();
3466        if (parent instanceof ViewGroup) {
3467            ViewGroup p = (ViewGroup) parent;
3468            p.setOnHierarchyChangeListener(null);
3469        }
3470
3471        // Clean up the zoom controller
3472        mZoomButtonsController.setVisible(false);
3473    }
3474
3475    // Implementation for OnHierarchyChangeListener
3476    public void onChildViewAdded(View parent, View child) {}
3477
3478    public void onChildViewRemoved(View p, View child) {
3479        if (child == this) {
3480            clearTextEntry();
3481        }
3482    }
3483
3484    /**
3485     * @deprecated WebView should not have implemented
3486     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
3487     * does nothing now.
3488     */
3489    @Deprecated
3490    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
3491    }
3492
3493    // To avoid drawing the cursor ring, and remove the TextView when our window
3494    // loses focus.
3495    @Override
3496    public void onWindowFocusChanged(boolean hasWindowFocus) {
3497        if (hasWindowFocus) {
3498            if (hasFocus()) {
3499                // If our window regained focus, and we have focus, then begin
3500                // drawing the cursor ring
3501                mDrawCursorRing = true;
3502                if (mNativeClass != 0) {
3503                    nativeRecordButtons(true, false, true);
3504                    if (inEditingMode()) {
3505                        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0);
3506                    }
3507                }
3508            } else {
3509                // If our window gained focus, but we do not have it, do not
3510                // draw the cursor ring.
3511                mDrawCursorRing = false;
3512                // We do not call nativeRecordButtons here because we assume
3513                // that when we lost focus, or window focus, it got called with
3514                // false for the first parameter
3515            }
3516        } else {
3517            if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) {
3518                /*
3519                 * The zoom controls come in their own window, so our window
3520                 * loses focus. Our policy is to not draw the cursor ring if
3521                 * our window is not focused, but this is an exception since
3522                 * the user can still navigate the web page with the zoom
3523                 * controls showing.
3524                 */
3525                // If our window has lost focus, stop drawing the cursor ring
3526                mDrawCursorRing = false;
3527            }
3528            mGotKeyDown = false;
3529            mShiftIsPressed = false;
3530            if (mNativeClass != 0) {
3531                nativeRecordButtons(false, false, true);
3532            }
3533            setFocusControllerInactive();
3534        }
3535        invalidate();
3536        super.onWindowFocusChanged(hasWindowFocus);
3537    }
3538
3539    /*
3540     * Pass a message to WebCore Thread, telling the WebCore::Page's
3541     * FocusController to be  "inactive" so that it will
3542     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
3543     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
3544     */
3545    /* package */ void setFocusControllerInactive() {
3546        // Do not need to also check whether mWebViewCore is null, because
3547        // mNativeClass is only set if mWebViewCore is non null
3548        if (mNativeClass == 0) return;
3549        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
3550    }
3551
3552    @Override
3553    protected void onFocusChanged(boolean focused, int direction,
3554            Rect previouslyFocusedRect) {
3555        if (DebugFlags.WEB_VIEW) {
3556            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
3557        }
3558        if (focused) {
3559            // When we regain focus, if we have window focus, resume drawing
3560            // the cursor ring
3561            if (hasWindowFocus()) {
3562                mDrawCursorRing = true;
3563                if (mNativeClass != 0) {
3564                    nativeRecordButtons(true, false, true);
3565                }
3566            //} else {
3567                // The WebView has gained focus while we do not have
3568                // windowfocus.  When our window lost focus, we should have
3569                // called nativeRecordButtons(false...)
3570            }
3571        } else {
3572            // When we lost focus, unless focus went to the TextView (which is
3573            // true if we are in editing mode), stop drawing the cursor ring.
3574            if (!inEditingMode()) {
3575                mDrawCursorRing = false;
3576                if (mNativeClass != 0) {
3577                    nativeRecordButtons(false, false, true);
3578                }
3579                setFocusControllerInactive();
3580            }
3581            mGotKeyDown = false;
3582        }
3583
3584        super.onFocusChanged(focused, direction, previouslyFocusedRect);
3585    }
3586
3587    @Override
3588    protected void onSizeChanged(int w, int h, int ow, int oh) {
3589        super.onSizeChanged(w, h, ow, oh);
3590        // Center zooming to the center of the screen.
3591        if (mZoomScale == 0) { // unless we're already zooming
3592            mZoomCenterX = getViewWidth() * .5f;
3593            mZoomCenterY = getViewHeight() * .5f;
3594        }
3595
3596        // update mMinZoomScale if the minimum zoom scale is not fixed
3597        if (!mMinZoomScaleFixed) {
3598            // when change from narrow screen to wide screen, the new viewWidth
3599            // can be wider than the old content width. We limit the minimum
3600            // scale to 1.0f. The proper minimum scale will be calculated when
3601            // the new picture shows up.
3602            mMinZoomScale = Math.min(1.0f, (float) getViewWidth()
3603                    / (mDrawHistory ? mHistoryPicture.getWidth()
3604                            : mZoomOverviewWidth));
3605        }
3606
3607        // we always force, in case our height changed, in which case we still
3608        // want to send the notification over to webkit
3609        setNewZoomScale(mActualScale, true);
3610    }
3611
3612    @Override
3613    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
3614        super.onScrollChanged(l, t, oldl, oldt);
3615
3616        sendOurVisibleRect();
3617    }
3618
3619
3620    @Override
3621    public boolean dispatchKeyEvent(KeyEvent event) {
3622        boolean dispatch = true;
3623
3624        if (!inEditingMode()) {
3625            if (event.getAction() == KeyEvent.ACTION_DOWN) {
3626                mGotKeyDown = true;
3627            } else {
3628                if (!mGotKeyDown) {
3629                    /*
3630                     * We got a key up for which we were not the recipient of
3631                     * the original key down. Don't give it to the view.
3632                     */
3633                    dispatch = false;
3634                }
3635                mGotKeyDown = false;
3636            }
3637        }
3638
3639        if (dispatch) {
3640            return super.dispatchKeyEvent(event);
3641        } else {
3642            // We didn't dispatch, so let something else handle the key
3643            return false;
3644        }
3645    }
3646
3647    // Here are the snap align logic:
3648    // 1. If it starts nearly horizontally or vertically, snap align;
3649    // 2. If there is a dramitic direction change, let it go;
3650    // 3. If there is a same direction back and forth, lock it.
3651
3652    // adjustable parameters
3653    private int mMinLockSnapReverseDistance;
3654    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
3655    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
3656
3657    @Override
3658    public boolean onTouchEvent(MotionEvent ev) {
3659        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
3660            return false;
3661        }
3662
3663        if (DebugFlags.WEB_VIEW) {
3664            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
3665                    + mTouchMode);
3666        }
3667
3668        int action = ev.getAction();
3669        float x = ev.getX();
3670        float y = ev.getY();
3671        long eventTime = ev.getEventTime();
3672
3673        // Due to the touch screen edge effect, a touch closer to the edge
3674        // always snapped to the edge. As getViewWidth() can be different from
3675        // getWidth() due to the scrollbar, adjusting the point to match
3676        // getViewWidth(). Same applied to the height.
3677        if (x > getViewWidth() - 1) {
3678            x = getViewWidth() - 1;
3679        }
3680        if (y > getViewHeightWithTitle() - 1) {
3681            y = getViewHeightWithTitle() - 1;
3682        }
3683
3684        // pass the touch events from UI thread to WebCore thread
3685        if (mForwardTouchEvents && (action != MotionEvent.ACTION_MOVE
3686                || eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) {
3687            WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
3688            ted.mAction = action;
3689            ted.mX = viewToContentX((int) x + mScrollX);
3690            ted.mY = viewToContentY((int) y + mScrollY);
3691            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
3692            mLastSentTouchTime = eventTime;
3693        }
3694
3695        int deltaX = (int) (mLastTouchX - x);
3696        int deltaY = (int) (mLastTouchY - y);
3697
3698        switch (action) {
3699            case MotionEvent.ACTION_DOWN: {
3700                mPreventDrag = PREVENT_DRAG_NO;
3701                if (!mScroller.isFinished()) {
3702                    // stop the current scroll animation, but if this is
3703                    // the start of a fling, allow it to add to the current
3704                    // fling's velocity
3705                    mScroller.abortAnimation();
3706                    mTouchMode = TOUCH_DRAG_START_MODE;
3707                    mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
3708                } else if (mShiftIsPressed) {
3709                    mSelectX = mScrollX + (int) x;
3710                    mSelectY = mScrollY + (int) y;
3711                    mTouchMode = TOUCH_SELECT_MODE;
3712                    if (DebugFlags.WEB_VIEW) {
3713                        Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
3714                    }
3715                    nativeMoveSelection(viewToContentX(mSelectX),
3716                            viewToContentY(mSelectY), false);
3717                    mTouchSelection = mExtendSelection = true;
3718                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
3719                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
3720                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
3721                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
3722                    } else {
3723                        // commit the short press action for the previous tap
3724                        doShortPress();
3725                        // continue, mTouchMode should be still TOUCH_INIT_MODE
3726                    }
3727                } else {
3728                    mTouchMode = TOUCH_INIT_MODE;
3729                    mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES
3730                            : PREVENT_DRAG_NO;
3731                    mWebViewCore.sendMessage(
3732                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
3733                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
3734                        EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION,
3735                                (eventTime - mLastTouchUpTime), eventTime);
3736                    }
3737                }
3738                // Trigger the link
3739                if (mTouchMode == TOUCH_INIT_MODE
3740                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
3741                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
3742                            .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT);
3743                }
3744                // Remember where the motion event started
3745                mLastTouchX = x;
3746                mLastTouchY = y;
3747                mLastTouchTime = eventTime;
3748                mVelocityTracker = VelocityTracker.obtain();
3749                mSnapScrollMode = SNAP_NONE;
3750                break;
3751            }
3752            case MotionEvent.ACTION_MOVE: {
3753                if (mTouchMode == TOUCH_DONE_MODE) {
3754                    // no dragging during scroll zoom animation
3755                    break;
3756                }
3757                mVelocityTracker.addMovement(ev);
3758
3759                if (mTouchMode != TOUCH_DRAG_MODE) {
3760                    if (mTouchMode == TOUCH_SELECT_MODE) {
3761                        mSelectX = mScrollX + (int) x;
3762                        mSelectY = mScrollY + (int) y;
3763                        if (DebugFlags.WEB_VIEW) {
3764                            Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
3765                        }
3766                        nativeMoveSelection(viewToContentX(mSelectX),
3767                               viewToContentY(mSelectY), true);
3768                        invalidate();
3769                        break;
3770                    }
3771                    if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) {
3772                        break;
3773                    }
3774                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
3775                        // track mLastTouchTime as we may need to do fling at
3776                        // ACTION_UP
3777                        mLastTouchTime = eventTime;
3778                        break;
3779                    }
3780                    if (mTouchMode == TOUCH_SHORTPRESS_MODE
3781                            || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
3782                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3783                    } else if (mTouchMode == TOUCH_INIT_MODE
3784                            || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
3785                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3786                    }
3787
3788                    // if it starts nearly horizontal or vertical, enforce it
3789                    int ax = Math.abs(deltaX);
3790                    int ay = Math.abs(deltaY);
3791                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
3792                        mSnapScrollMode = SNAP_X;
3793                        mSnapPositive = deltaX > 0;
3794                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
3795                        mSnapScrollMode = SNAP_Y;
3796                        mSnapPositive = deltaY > 0;
3797                    }
3798
3799                    mTouchMode = TOUCH_DRAG_MODE;
3800                    WebViewCore.pauseUpdate(mWebViewCore);
3801                    if (!mDragFromTextInput) {
3802                        nativeHideCursor();
3803                    }
3804                    WebSettings settings = getSettings();
3805                    if (settings.supportZoom()
3806                            && settings.getBuiltInZoomControls()
3807                            && !mZoomButtonsController.isVisible()
3808                            && mMinZoomScale < mMaxZoomScale) {
3809                        mZoomButtonsController.setVisible(true);
3810                        int count = settings.getDoubleTapToastCount();
3811                        if (mInZoomOverview && count > 0) {
3812                            settings.setDoubleTapToastCount(--count);
3813                            Toast.makeText(mContext,
3814                                    com.android.internal.R.string.double_tap_toast,
3815                                    Toast.LENGTH_LONG).show();
3816                        }
3817                    }
3818                }
3819
3820                // do pan
3821                int newScrollX = pinLocX(mScrollX + deltaX);
3822                deltaX = newScrollX - mScrollX;
3823                int newScrollY = pinLocY(mScrollY + deltaY);
3824                deltaY = newScrollY - mScrollY;
3825                boolean done = false;
3826                if (deltaX == 0 && deltaY == 0) {
3827                    done = true;
3828                } else {
3829                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
3830                        int ax = Math.abs(deltaX);
3831                        int ay = Math.abs(deltaY);
3832                        if (mSnapScrollMode == SNAP_X) {
3833                            // radical change means getting out of snap mode
3834                            if (ay > MAX_SLOPE_FOR_DIAG * ax
3835                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3836                                mSnapScrollMode = SNAP_NONE;
3837                            }
3838                            // reverse direction means lock in the snap mode
3839                            if ((ax > MAX_SLOPE_FOR_DIAG * ay) &&
3840                                    ((mSnapPositive &&
3841                                    deltaX < -mMinLockSnapReverseDistance)
3842                                    || (!mSnapPositive &&
3843                                    deltaX > mMinLockSnapReverseDistance))) {
3844                                mSnapScrollMode = SNAP_X_LOCK;
3845                            }
3846                        } else {
3847                            // radical change means getting out of snap mode
3848                            if ((ax > MAX_SLOPE_FOR_DIAG * ay)
3849                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3850                                mSnapScrollMode = SNAP_NONE;
3851                            }
3852                            // reverse direction means lock in the snap mode
3853                            if ((ay > MAX_SLOPE_FOR_DIAG * ax) &&
3854                                    ((mSnapPositive &&
3855                                    deltaY < -mMinLockSnapReverseDistance)
3856                                    || (!mSnapPositive &&
3857                                    deltaY > mMinLockSnapReverseDistance))) {
3858                                mSnapScrollMode = SNAP_Y_LOCK;
3859                            }
3860                        }
3861                    }
3862
3863                    if (mSnapScrollMode == SNAP_X
3864                            || mSnapScrollMode == SNAP_X_LOCK) {
3865                        scrollBy(deltaX, 0);
3866                        mLastTouchX = x;
3867                    } else if (mSnapScrollMode == SNAP_Y
3868                            || mSnapScrollMode == SNAP_Y_LOCK) {
3869                        scrollBy(0, deltaY);
3870                        mLastTouchY = y;
3871                    } else {
3872                        scrollBy(deltaX, deltaY);
3873                        mLastTouchX = x;
3874                        mLastTouchY = y;
3875                    }
3876                    mLastTouchTime = eventTime;
3877                    mUserScroll = true;
3878                }
3879
3880                if (!getSettings().getBuiltInZoomControls()) {
3881                    boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
3882                    if (mZoomControls != null && showPlusMinus) {
3883                        if (mZoomControls.getVisibility() == View.VISIBLE) {
3884                            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
3885                        } else {
3886                            mZoomControls.show(showPlusMinus, false);
3887                        }
3888                        mPrivateHandler.postDelayed(mZoomControlRunnable,
3889                                ZOOM_CONTROLS_TIMEOUT);
3890                    }
3891                }
3892
3893                if (done) {
3894                    // return false to indicate that we can't pan out of the
3895                    // view space
3896                    return false;
3897                }
3898                break;
3899            }
3900            case MotionEvent.ACTION_UP: {
3901                mLastTouchUpTime = eventTime;
3902                switch (mTouchMode) {
3903                    case TOUCH_DOUBLE_TAP_MODE: // double tap
3904                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3905                        mTouchMode = TOUCH_DONE_MODE;
3906                        doDoubleTap();
3907                        break;
3908                    case TOUCH_SELECT_MODE:
3909                        commitCopy();
3910                        mTouchSelection = false;
3911                        break;
3912                    case TOUCH_INIT_MODE: // tap
3913                    case TOUCH_SHORTPRESS_START_MODE:
3914                    case TOUCH_SHORTPRESS_MODE:
3915                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3916                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3917                        if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) {
3918                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
3919                                    " WebCore's response for touch down.");
3920                            if (computeHorizontalScrollExtent() < computeHorizontalScrollRange()
3921                                    || computeVerticalScrollExtent() < computeVerticalScrollRange()) {
3922                                // we will not rewrite drag code here, but we
3923                                // will try fling if it applies.
3924                                WebViewCore.pauseUpdate(mWebViewCore);
3925                                // fall through to TOUCH_DRAG_MODE
3926                            } else {
3927                                break;
3928                            }
3929                        } else {
3930                            if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
3931                                // if mPreventDrag is not confirmed, treat it as
3932                                // no so that it won't block tap or double tap.
3933                                mPreventDrag = PREVENT_DRAG_NO;
3934                            }
3935                            if (mPreventDrag == PREVENT_DRAG_NO) {
3936                                if (mTouchMode == TOUCH_INIT_MODE) {
3937                                    mPrivateHandler.sendMessageDelayed(
3938                                            mPrivateHandler.obtainMessage(
3939                                            RELEASE_SINGLE_TAP),
3940                                            ViewConfiguration.getDoubleTapTimeout());
3941                                } else {
3942                                    mTouchMode = TOUCH_DONE_MODE;
3943                                    doShortPress();
3944                                }
3945                            }
3946                            break;
3947                        }
3948                    case TOUCH_DRAG_MODE:
3949                        // redraw in high-quality, as we're done dragging
3950                        invalidate();
3951                        // if the user waits a while w/o moving before the
3952                        // up, we don't want to do a fling
3953                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
3954                            mVelocityTracker.addMovement(ev);
3955                            doFling();
3956                            break;
3957                        }
3958                        mLastVelocity = 0;
3959                        WebViewCore.resumeUpdate(mWebViewCore);
3960                        break;
3961                    case TOUCH_DRAG_START_MODE:
3962                    case TOUCH_DONE_MODE:
3963                        // do nothing
3964                        break;
3965                }
3966                // we also use mVelocityTracker == null to tell us that we are
3967                // not "moving around", so we can take the slower/prettier
3968                // mode in the drawing code
3969                if (mVelocityTracker != null) {
3970                    mVelocityTracker.recycle();
3971                    mVelocityTracker = null;
3972                }
3973                break;
3974            }
3975            case MotionEvent.ACTION_CANCEL: {
3976                // we also use mVelocityTracker == null to tell us that we are
3977                // not "moving around", so we can take the slower/prettier
3978                // mode in the drawing code
3979                if (mVelocityTracker != null) {
3980                    mVelocityTracker.recycle();
3981                    mVelocityTracker = null;
3982                }
3983                if (mTouchMode == TOUCH_DRAG_MODE) {
3984                    WebViewCore.resumeUpdate(mWebViewCore);
3985                }
3986                mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3987                mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3988                mTouchMode = TOUCH_DONE_MODE;
3989                nativeHideCursor();
3990                break;
3991            }
3992        }
3993        return true;
3994    }
3995
3996    private long mTrackballFirstTime = 0;
3997    private long mTrackballLastTime = 0;
3998    private float mTrackballRemainsX = 0.0f;
3999    private float mTrackballRemainsY = 0.0f;
4000    private int mTrackballXMove = 0;
4001    private int mTrackballYMove = 0;
4002    private boolean mExtendSelection = false;
4003    private boolean mTouchSelection = false;
4004    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
4005    private static final int TRACKBALL_TIMEOUT = 200;
4006    private static final int TRACKBALL_WAIT = 100;
4007    private static final int TRACKBALL_SCALE = 400;
4008    private static final int TRACKBALL_SCROLL_COUNT = 5;
4009    private static final int TRACKBALL_MOVE_COUNT = 10;
4010    private static final int TRACKBALL_MULTIPLIER = 3;
4011    private static final int SELECT_CURSOR_OFFSET = 16;
4012    private int mSelectX = 0;
4013    private int mSelectY = 0;
4014    private boolean mShiftIsPressed = false;
4015    private boolean mTrackballDown = false;
4016    private long mTrackballUpTime = 0;
4017    private long mLastCursorTime = 0;
4018    private Rect mLastCursorBounds;
4019
4020    // Set by default; BrowserActivity clears to interpret trackball data
4021    // directly for movement. Currently, the framework only passes
4022    // arrow key events, not trackball events, from one child to the next
4023    private boolean mMapTrackballToArrowKeys = true;
4024
4025    public void setMapTrackballToArrowKeys(boolean setMap) {
4026        mMapTrackballToArrowKeys = setMap;
4027    }
4028
4029    void resetTrackballTime() {
4030        mTrackballLastTime = 0;
4031    }
4032
4033    @Override
4034    public boolean onTrackballEvent(MotionEvent ev) {
4035        long time = ev.getEventTime();
4036        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
4037            if (ev.getY() > 0) pageDown(true);
4038            if (ev.getY() < 0) pageUp(true);
4039            return true;
4040        }
4041        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
4042            mTrackballDown = true;
4043            if (mNativeClass == 0) {
4044                return false;
4045            }
4046            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4047            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
4048                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
4049                nativeSelectBestAt(mLastCursorBounds);
4050            }
4051            if (DebugFlags.WEB_VIEW) {
4052                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
4053                        + " time=" + time
4054                        + " mLastCursorTime=" + mLastCursorTime);
4055            }
4056            if (isInTouchMode()) requestFocusFromTouch();
4057            return false; // let common code in onKeyDown at it
4058        }
4059        if (ev.getAction() == MotionEvent.ACTION_UP) {
4060            // LONG_PRESS_CENTER is set in common onKeyDown
4061            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4062            mTrackballDown = false;
4063            mTrackballUpTime = time;
4064            if (mShiftIsPressed) {
4065                if (mExtendSelection) {
4066                    commitCopy();
4067                } else {
4068                    mExtendSelection = true;
4069                }
4070            }
4071            if (DebugFlags.WEB_VIEW) {
4072                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
4073                        + " time=" + time
4074                );
4075            }
4076            return false; // let common code in onKeyUp at it
4077        }
4078        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
4079            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
4080            return false;
4081        }
4082        if (mTrackballDown) {
4083            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
4084            return true; // discard move if trackball is down
4085        }
4086        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
4087            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
4088            return true;
4089        }
4090        // TODO: alternatively we can do panning as touch does
4091        switchOutDrawHistory();
4092        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
4093            if (DebugFlags.WEB_VIEW) {
4094                Log.v(LOGTAG, "onTrackballEvent time="
4095                        + time + " last=" + mTrackballLastTime);
4096            }
4097            mTrackballFirstTime = time;
4098            mTrackballXMove = mTrackballYMove = 0;
4099        }
4100        mTrackballLastTime = time;
4101        if (DebugFlags.WEB_VIEW) {
4102            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
4103        }
4104        mTrackballRemainsX += ev.getX();
4105        mTrackballRemainsY += ev.getY();
4106        doTrackball(time);
4107        return true;
4108    }
4109
4110    void moveSelection(float xRate, float yRate) {
4111        if (mNativeClass == 0)
4112            return;
4113        int width = getViewWidth();
4114        int height = getViewHeight();
4115        mSelectX += scaleTrackballX(xRate, width);
4116        mSelectY += scaleTrackballY(yRate, height);
4117        int maxX = width + mScrollX;
4118        int maxY = height + mScrollY;
4119        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
4120                , mSelectX));
4121        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
4122                , mSelectY));
4123        if (DebugFlags.WEB_VIEW) {
4124            Log.v(LOGTAG, "moveSelection"
4125                    + " mSelectX=" + mSelectX
4126                    + " mSelectY=" + mSelectY
4127                    + " mScrollX=" + mScrollX
4128                    + " mScrollY=" + mScrollY
4129                    + " xRate=" + xRate
4130                    + " yRate=" + yRate
4131                    );
4132        }
4133        nativeMoveSelection(viewToContentX(mSelectX),
4134                viewToContentY(mSelectY), mExtendSelection);
4135        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
4136                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
4137                : 0;
4138        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
4139                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
4140                : 0;
4141        pinScrollBy(scrollX, scrollY, true, 0);
4142        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
4143        requestRectangleOnScreen(select);
4144        invalidate();
4145   }
4146
4147    private int scaleTrackballX(float xRate, int width) {
4148        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
4149        int nextXMove = xMove;
4150        if (xMove > 0) {
4151            if (xMove > mTrackballXMove) {
4152                xMove -= mTrackballXMove;
4153            }
4154        } else if (xMove < mTrackballXMove) {
4155            xMove -= mTrackballXMove;
4156        }
4157        mTrackballXMove = nextXMove;
4158        return xMove;
4159    }
4160
4161    private int scaleTrackballY(float yRate, int height) {
4162        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
4163        int nextYMove = yMove;
4164        if (yMove > 0) {
4165            if (yMove > mTrackballYMove) {
4166                yMove -= mTrackballYMove;
4167            }
4168        } else if (yMove < mTrackballYMove) {
4169            yMove -= mTrackballYMove;
4170        }
4171        mTrackballYMove = nextYMove;
4172        return yMove;
4173    }
4174
4175    private int keyCodeToSoundsEffect(int keyCode) {
4176        switch(keyCode) {
4177            case KeyEvent.KEYCODE_DPAD_UP:
4178                return SoundEffectConstants.NAVIGATION_UP;
4179            case KeyEvent.KEYCODE_DPAD_RIGHT:
4180                return SoundEffectConstants.NAVIGATION_RIGHT;
4181            case KeyEvent.KEYCODE_DPAD_DOWN:
4182                return SoundEffectConstants.NAVIGATION_DOWN;
4183            case KeyEvent.KEYCODE_DPAD_LEFT:
4184                return SoundEffectConstants.NAVIGATION_LEFT;
4185        }
4186        throw new IllegalArgumentException("keyCode must be one of " +
4187                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
4188                "KEYCODE_DPAD_LEFT}.");
4189    }
4190
4191    private void doTrackball(long time) {
4192        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
4193        if (elapsed == 0) {
4194            elapsed = TRACKBALL_TIMEOUT;
4195        }
4196        float xRate = mTrackballRemainsX * 1000 / elapsed;
4197        float yRate = mTrackballRemainsY * 1000 / elapsed;
4198        if (mShiftIsPressed) {
4199            moveSelection(xRate, yRate);
4200            mTrackballRemainsX = mTrackballRemainsY = 0;
4201            return;
4202        }
4203        float ax = Math.abs(xRate);
4204        float ay = Math.abs(yRate);
4205        float maxA = Math.max(ax, ay);
4206        if (DebugFlags.WEB_VIEW) {
4207            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
4208                    + " xRate=" + xRate
4209                    + " yRate=" + yRate
4210                    + " mTrackballRemainsX=" + mTrackballRemainsX
4211                    + " mTrackballRemainsY=" + mTrackballRemainsY);
4212        }
4213        int width = mContentWidth - getViewWidth();
4214        int height = mContentHeight - getViewHeight();
4215        if (width < 0) width = 0;
4216        if (height < 0) height = 0;
4217        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
4218        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
4219        maxA = Math.max(ax, ay);
4220        int count = Math.max(0, (int) maxA);
4221        int oldScrollX = mScrollX;
4222        int oldScrollY = mScrollY;
4223        if (count > 0) {
4224            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
4225                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
4226                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
4227                    KeyEvent.KEYCODE_DPAD_RIGHT;
4228            count = Math.min(count, TRACKBALL_MOVE_COUNT);
4229            if (DebugFlags.WEB_VIEW) {
4230                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
4231                        + " count=" + count
4232                        + " mTrackballRemainsX=" + mTrackballRemainsX
4233                        + " mTrackballRemainsY=" + mTrackballRemainsY);
4234            }
4235            if (navHandledKey(selectKeyCode, count, false, time, false)) {
4236                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
4237            }
4238            mTrackballRemainsX = mTrackballRemainsY = 0;
4239        }
4240        if (count >= TRACKBALL_SCROLL_COUNT) {
4241            int xMove = scaleTrackballX(xRate, width);
4242            int yMove = scaleTrackballY(yRate, height);
4243            if (DebugFlags.WEB_VIEW) {
4244                Log.v(LOGTAG, "doTrackball pinScrollBy"
4245                        + " count=" + count
4246                        + " xMove=" + xMove + " yMove=" + yMove
4247                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
4248                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
4249                        );
4250            }
4251            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
4252                xMove = 0;
4253            }
4254            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
4255                yMove = 0;
4256            }
4257            if (xMove != 0 || yMove != 0) {
4258                pinScrollBy(xMove, yMove, true, 0);
4259            }
4260            mUserScroll = true;
4261        }
4262    }
4263
4264    private int computeMaxScrollY() {
4265        int maxContentH = computeVerticalScrollRange() + getTitleHeight();
4266        return Math.max(maxContentH - getHeight(), getTitleHeight());
4267    }
4268
4269    public void flingScroll(int vx, int vy) {
4270        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
4271        int maxY = computeMaxScrollY();
4272
4273        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY);
4274        invalidate();
4275    }
4276
4277    private void doFling() {
4278        if (mVelocityTracker == null) {
4279            return;
4280        }
4281        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
4282        int maxY = computeMaxScrollY();
4283
4284        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
4285        int vx = (int) mVelocityTracker.getXVelocity();
4286        int vy = (int) mVelocityTracker.getYVelocity();
4287
4288        if (mSnapScrollMode != SNAP_NONE) {
4289            if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_X_LOCK) {
4290                vy = 0;
4291            } else {
4292                vx = 0;
4293            }
4294        }
4295
4296        if (true /* EMG release: make our fling more like Maps' */) {
4297            // maps cuts their velocity in half
4298            vx = vx * 3 / 4;
4299            vy = vy * 3 / 4;
4300        }
4301        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
4302            WebViewCore.resumeUpdate(mWebViewCore);
4303            return;
4304        }
4305        float currentVelocity = mScroller.getCurrVelocity();
4306        if (mLastVelocity > 0 && currentVelocity > 0) {
4307            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
4308                    - Math.atan2(vy, vx)));
4309            final float circle = (float) (Math.PI) * 2.0f;
4310            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
4311                vx += currentVelocity * mLastVelX / mLastVelocity;
4312                vy += currentVelocity * mLastVelY / mLastVelocity;
4313                if (DebugFlags.WEB_VIEW) {
4314                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
4315                }
4316            } else if (DebugFlags.WEB_VIEW) {
4317                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
4318            }
4319        } else if (DebugFlags.WEB_VIEW) {
4320            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
4321                    + " current=" + currentVelocity
4322                    + " vx=" + vx + " vy=" + vy
4323                    + " maxX=" + maxX + " maxY=" + maxY
4324                    + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
4325        }
4326        mLastVelX = vx;
4327        mLastVelY = vy;
4328        mLastVelocity = (float) Math.hypot(vx, vy);
4329
4330        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
4331        // TODO: duration is calculated based on velocity, if the range is
4332        // small, the animation will stop before duration is up. We may
4333        // want to calculate how long the animation is going to run to precisely
4334        // resume the webcore update.
4335        final int time = mScroller.getDuration();
4336        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_UPDATE, time);
4337        awakenScrollBars(time);
4338        invalidate();
4339    }
4340
4341    private boolean zoomWithPreview(float scale) {
4342        float oldScale = mActualScale;
4343        mInitialScrollX = mScrollX;
4344        mInitialScrollY = mScrollY;
4345
4346        // snap to DEFAULT_SCALE if it is close
4347        if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) {
4348            scale = mDefaultScale;
4349        }
4350
4351        setNewZoomScale(scale, false);
4352
4353        if (oldScale != mActualScale) {
4354            // use mZoomPickerScale to see zoom preview first
4355            mZoomStart = SystemClock.uptimeMillis();
4356            mInvInitialZoomScale = 1.0f / oldScale;
4357            mInvFinalZoomScale = 1.0f / mActualScale;
4358            mZoomScale = mActualScale;
4359            if (!mInZoomOverview) {
4360                mLastScale = scale;
4361            }
4362            invalidate();
4363            return true;
4364        } else {
4365            return false;
4366        }
4367    }
4368
4369    /**
4370     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
4371     * in charge of installing this view to the view hierarchy. This view will
4372     * become visible when the user starts scrolling via touch and fade away if
4373     * the user does not interact with it.
4374     * <p/>
4375     * API version 3 introduces a built-in zoom mechanism that is shown
4376     * automatically by the MapView. This is the preferred approach for
4377     * showing the zoom UI.
4378     *
4379     * @deprecated The built-in zoom mechanism is preferred, see
4380     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
4381     */
4382    @Deprecated
4383    public View getZoomControls() {
4384        if (!getSettings().supportZoom()) {
4385            Log.w(LOGTAG, "This WebView doesn't support zoom.");
4386            return null;
4387        }
4388        if (mZoomControls == null) {
4389            mZoomControls = createZoomControls();
4390
4391            /*
4392             * need to be set to VISIBLE first so that getMeasuredHeight() in
4393             * {@link #onSizeChanged()} can return the measured value for proper
4394             * layout.
4395             */
4396            mZoomControls.setVisibility(View.VISIBLE);
4397            mZoomControlRunnable = new Runnable() {
4398                public void run() {
4399
4400                    /* Don't dismiss the controls if the user has
4401                     * focus on them. Wait and check again later.
4402                     */
4403                    if (!mZoomControls.hasFocus()) {
4404                        mZoomControls.hide();
4405                    } else {
4406                        mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4407                        mPrivateHandler.postDelayed(mZoomControlRunnable,
4408                                ZOOM_CONTROLS_TIMEOUT);
4409                    }
4410                }
4411            };
4412        }
4413        return mZoomControls;
4414    }
4415
4416    private ExtendedZoomControls createZoomControls() {
4417        ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext
4418            , null);
4419        zoomControls.setOnZoomInClickListener(new OnClickListener() {
4420            public void onClick(View v) {
4421                // reset time out
4422                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4423                mPrivateHandler.postDelayed(mZoomControlRunnable,
4424                        ZOOM_CONTROLS_TIMEOUT);
4425                zoomIn();
4426            }
4427        });
4428        zoomControls.setOnZoomOutClickListener(new OnClickListener() {
4429            public void onClick(View v) {
4430                // reset time out
4431                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4432                mPrivateHandler.postDelayed(mZoomControlRunnable,
4433                        ZOOM_CONTROLS_TIMEOUT);
4434                zoomOut();
4435            }
4436        });
4437        return zoomControls;
4438    }
4439
4440    /**
4441     * Gets the {@link ZoomButtonsController} which can be used to add
4442     * additional buttons to the zoom controls window.
4443     *
4444     * @return The instance of {@link ZoomButtonsController} used by this class,
4445     *         or null if it is unavailable.
4446     * @hide
4447     */
4448    public ZoomButtonsController getZoomButtonsController() {
4449        return mZoomButtonsController;
4450    }
4451
4452    /**
4453     * Perform zoom in in the webview
4454     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
4455     */
4456    public boolean zoomIn() {
4457        // TODO: alternatively we can disallow this during draw history mode
4458        switchOutDrawHistory();
4459        // Center zooming to the center of the screen.
4460        if (mInZoomOverview) {
4461            // if in overview mode, bring it back to normal mode
4462            mLastTouchX = getViewWidth() * .5f;
4463            mLastTouchY = getViewHeight() * .5f;
4464            doDoubleTap();
4465            return true;
4466        } else {
4467            mZoomCenterX = getViewWidth() * .5f;
4468            mZoomCenterY = getViewHeight() * .5f;
4469            return zoomWithPreview(mActualScale * 1.25f);
4470        }
4471    }
4472
4473    /**
4474     * Perform zoom out in the webview
4475     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
4476     */
4477    public boolean zoomOut() {
4478        // TODO: alternatively we can disallow this during draw history mode
4479        switchOutDrawHistory();
4480        float scale = mActualScale * 0.8f;
4481        if (scale < (mMinZoomScale + 0.1f)
4482                && mWebViewCore.getSettings().getUseWideViewPort()) {
4483            // when zoom out to min scale, switch to overview mode
4484            doDoubleTap();
4485            return true;
4486        } else {
4487            // Center zooming to the center of the screen.
4488            mZoomCenterX = getViewWidth() * .5f;
4489            mZoomCenterY = getViewHeight() * .5f;
4490            return zoomWithPreview(scale);
4491        }
4492    }
4493
4494    private void updateSelection() {
4495        if (mNativeClass == 0) {
4496            return;
4497        }
4498        // mLastTouchX and mLastTouchY are the point in the current viewport
4499        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4500        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
4501        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
4502                contentX + mNavSlop, contentY + mNavSlop);
4503        nativeSelectBestAt(rect);
4504    }
4505
4506    /**
4507     * Scroll the focused text field/area to match the WebTextView
4508     * @param x New x position of the WebTextView in view coordinates
4509     * @param y New y position of the WebTextView in view coordinates
4510     */
4511    /*package*/ void scrollFocusedTextInput(int x, int y) {
4512        if (!inEditingMode() || mWebViewCore == null) {
4513            return;
4514        }
4515        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, viewToContentX(x),
4516                // Since this position is relative to the top of the text input
4517                // field, we do not need to take the title bar's height into
4518                // consideration.
4519                viewToContentDimension(y));
4520    }
4521
4522    /**
4523     * Set our starting point and time for a drag from the WebTextView.
4524     */
4525    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
4526        if (!inEditingMode()) {
4527            return;
4528        }
4529        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
4530        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
4531        mLastTouchTime = eventTime;
4532        if (!mScroller.isFinished()) {
4533            abortAnimation();
4534            mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
4535        }
4536        mSnapScrollMode = SNAP_NONE;
4537        mVelocityTracker = VelocityTracker.obtain();
4538        mTouchMode = TOUCH_DRAG_START_MODE;
4539    }
4540
4541    /**
4542     * Given a motion event from the WebTextView, set its location to our
4543     * coordinates, and handle the event.
4544     */
4545    /*package*/ boolean textFieldDrag(MotionEvent event) {
4546        if (!inEditingMode()) {
4547            return false;
4548        }
4549        mDragFromTextInput = true;
4550        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
4551                (float) (mWebTextView.getTop() - mScrollY));
4552        boolean result = onTouchEvent(event);
4553        mDragFromTextInput = false;
4554        return result;
4555    }
4556
4557    /**
4558     * Do a touch up from a WebTextView.  This will be handled by webkit to
4559     * change the selection.
4560     * @param event MotionEvent in the WebTextView's coordinates.
4561     */
4562    /*package*/ void touchUpOnTextField(MotionEvent event) {
4563        if (!inEditingMode()) {
4564            return;
4565        }
4566        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
4567        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
4568        // In case the soft keyboard has been dismissed, bring it back up.
4569        InputMethodManager.getInstance(getContext()).showSoftInput(mWebTextView,
4570                0);
4571        if (nativeFocusNodePointer() != nativeCursorNodePointer()) {
4572            nativeMotionUp(x, y, mNavSlop);
4573        }
4574        nativeTextInputMotionUp(x, y);
4575    }
4576
4577    /*package*/ void shortPressOnTextField() {
4578        if (inEditingMode()) {
4579            View v = mWebTextView;
4580            int x = viewToContentX((v.getLeft() + v.getRight()) >> 1);
4581            int y = viewToContentY((v.getTop() + v.getBottom()) >> 1);
4582            nativeTextInputMotionUp(x, y);
4583        }
4584    }
4585
4586    private void doShortPress() {
4587        if (mNativeClass == 0) {
4588            return;
4589        }
4590        switchOutDrawHistory();
4591        // mLastTouchX and mLastTouchY are the point in the current viewport
4592        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4593        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
4594        if (nativeMotionUp(contentX, contentY, mNavSlop)) {
4595            if (mLogEvent) {
4596                Checkin.updateStats(mContext.getContentResolver(),
4597                        Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0);
4598            }
4599        }
4600        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
4601            playSoundEffect(SoundEffectConstants.CLICK);
4602        }
4603    }
4604
4605    private void doDoubleTap() {
4606        if (mWebViewCore.getSettings().getUseWideViewPort() == false) {
4607            return;
4608        }
4609        mZoomCenterX = mLastTouchX;
4610        mZoomCenterY = mLastTouchY;
4611        mInZoomOverview = !mInZoomOverview;
4612        // remove the zoom control after double tap
4613        WebSettings settings = getSettings();
4614        if (settings.getBuiltInZoomControls()) {
4615            if (mZoomButtonsController.isVisible()) {
4616                mZoomButtonsController.setVisible(false);
4617            }
4618        } else {
4619            if (mZoomControlRunnable != null) {
4620                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4621            }
4622            if (mZoomControls != null) {
4623                mZoomControls.hide();
4624            }
4625        }
4626        settings.setDoubleTapToastCount(0);
4627        if (mInZoomOverview) {
4628            // Force the titlebar fully reveal in overview mode
4629            if (mScrollY < getTitleHeight()) mScrollY = 0;
4630            zoomWithPreview((float) getViewWidth() / mZoomOverviewWidth);
4631        } else {
4632            // mLastTouchX and mLastTouchY are the point in the current viewport
4633            int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4634            int contentY = viewToContentY((int) mLastTouchY + mScrollY);
4635            int left = nativeGetBlockLeftEdge(contentX, contentY, mActualScale);
4636            if (left != NO_LEFTEDGE) {
4637                // add a 5pt padding to the left edge. Re-calculate the zoom
4638                // center so that the new scroll x will be on the left edge.
4639                mZoomCenterX = left < 5 ? 0 : (left - 5) * mLastScale
4640                        * mActualScale / (mLastScale - mActualScale);
4641            }
4642            zoomWithPreview(mLastScale);
4643        }
4644    }
4645
4646    // Called by JNI to handle a touch on a node representing an email address,
4647    // address, or phone number
4648    private void overrideLoading(String url) {
4649        mCallbackProxy.uiOverrideUrlLoading(url);
4650    }
4651
4652    // called by JNI
4653    private void sendPluginState(int state) {
4654        WebViewCore.PluginStateData psd = new WebViewCore.PluginStateData();
4655        psd.mFrame = nativeCursorFramePointer();
4656        psd.mNode = nativeCursorNodePointer();
4657        psd.mState = state;
4658        mWebViewCore.sendMessage(EventHub.PLUGIN_STATE, psd);
4659    }
4660
4661    @Override
4662    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4663        boolean result = false;
4664        if (inEditingMode()) {
4665            result = mWebTextView.requestFocus(direction,
4666                    previouslyFocusedRect);
4667        } else {
4668            result = super.requestFocus(direction, previouslyFocusedRect);
4669            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
4670                // For cases such as GMail, where we gain focus from a direction,
4671                // we want to move to the first available link.
4672                // FIXME: If there are no visible links, we may not want to
4673                int fakeKeyDirection = 0;
4674                switch(direction) {
4675                    case View.FOCUS_UP:
4676                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
4677                        break;
4678                    case View.FOCUS_DOWN:
4679                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
4680                        break;
4681                    case View.FOCUS_LEFT:
4682                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
4683                        break;
4684                    case View.FOCUS_RIGHT:
4685                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
4686                        break;
4687                    default:
4688                        return result;
4689                }
4690                if (mNativeClass != 0 && !nativeHasCursorNode()) {
4691                    navHandledKey(fakeKeyDirection, 1, true, 0, true);
4692                }
4693            }
4694        }
4695        return result;
4696    }
4697
4698    @Override
4699    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
4700        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
4701
4702        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
4703        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
4704        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
4705        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
4706
4707        int measuredHeight = heightSize;
4708        int measuredWidth = widthSize;
4709
4710        // Grab the content size from WebViewCore.
4711        int contentHeight = contentToViewDimension(mContentHeight);
4712        int contentWidth = contentToViewDimension(mContentWidth);
4713
4714//        Log.d(LOGTAG, "------- measure " + heightMode);
4715
4716        if (heightMode != MeasureSpec.EXACTLY) {
4717            mHeightCanMeasure = true;
4718            measuredHeight = contentHeight;
4719            if (heightMode == MeasureSpec.AT_MOST) {
4720                // If we are larger than the AT_MOST height, then our height can
4721                // no longer be measured and we should scroll internally.
4722                if (measuredHeight > heightSize) {
4723                    measuredHeight = heightSize;
4724                    mHeightCanMeasure = false;
4725                }
4726            }
4727        } else {
4728            mHeightCanMeasure = false;
4729        }
4730        if (mNativeClass != 0) {
4731            nativeSetHeightCanMeasure(mHeightCanMeasure);
4732        }
4733        // For the width, always use the given size unless unspecified.
4734        if (widthMode == MeasureSpec.UNSPECIFIED) {
4735            mWidthCanMeasure = true;
4736            measuredWidth = contentWidth;
4737        } else {
4738            mWidthCanMeasure = false;
4739        }
4740
4741        synchronized (this) {
4742            setMeasuredDimension(measuredWidth, measuredHeight);
4743        }
4744    }
4745
4746    @Override
4747    public boolean requestChildRectangleOnScreen(View child,
4748                                                 Rect rect,
4749                                                 boolean immediate) {
4750        rect.offset(child.getLeft() - child.getScrollX(),
4751                child.getTop() - child.getScrollY());
4752
4753        int height = getViewHeightWithTitle();
4754        int screenTop = mScrollY;
4755        int screenBottom = screenTop + height;
4756
4757        int scrollYDelta = 0;
4758
4759        if (rect.bottom > screenBottom) {
4760            int oneThirdOfScreenHeight = height / 3;
4761            if (rect.height() > 2 * oneThirdOfScreenHeight) {
4762                // If the rectangle is too tall to fit in the bottom two thirds
4763                // of the screen, place it at the top.
4764                scrollYDelta = rect.top - screenTop;
4765            } else {
4766                // If the rectangle will still fit on screen, we want its
4767                // top to be in the top third of the screen.
4768                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
4769            }
4770        } else if (rect.top < screenTop) {
4771            scrollYDelta = rect.top - screenTop;
4772        }
4773
4774        int width = getWidth() - getVerticalScrollbarWidth();
4775        int screenLeft = mScrollX;
4776        int screenRight = screenLeft + width;
4777
4778        int scrollXDelta = 0;
4779
4780        if (rect.right > screenRight && rect.left > screenLeft) {
4781            if (rect.width() > width) {
4782                scrollXDelta += (rect.left - screenLeft);
4783            } else {
4784                scrollXDelta += (rect.right - screenRight);
4785            }
4786        } else if (rect.left < screenLeft) {
4787            scrollXDelta -= (screenLeft - rect.left);
4788        }
4789
4790        if ((scrollYDelta | scrollXDelta) != 0) {
4791            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
4792        }
4793
4794        return false;
4795    }
4796
4797    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
4798            String replace, int newStart, int newEnd) {
4799        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
4800        arg.mReplace = replace;
4801        arg.mNewStart = newStart;
4802        arg.mNewEnd = newEnd;
4803        mTextGeneration++;
4804        arg.mTextGeneration = mTextGeneration;
4805        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
4806    }
4807
4808    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
4809        if (nativeCursorWantsKeyEvents() && !nativeCursorMatchesFocus()) {
4810            mWebViewCore.sendMessage(EventHub.CLICK);
4811            int select = nativeFocusCandidateIsTextField() ?
4812                    nativeFocusCandidateMaxLength() : 0;
4813            setSelection(select, select);
4814        }
4815        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
4816        arg.mEvent = event;
4817        arg.mCurrentText = currentText;
4818        // Increase our text generation number, and pass it to webcore thread
4819        mTextGeneration++;
4820        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
4821        // WebKit's document state is not saved until about to leave the page.
4822        // To make sure the host application, like Browser, has the up to date
4823        // document state when it goes to background, we force to save the
4824        // document state.
4825        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
4826        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
4827                cursorData(), 1000);
4828    }
4829
4830    /* package */ WebViewCore getWebViewCore() {
4831        return mWebViewCore;
4832    }
4833
4834    //-------------------------------------------------------------------------
4835    // Methods can be called from a separate thread, like WebViewCore
4836    // If it needs to call the View system, it has to send message.
4837    //-------------------------------------------------------------------------
4838
4839    /**
4840     * General handler to receive message coming from webkit thread
4841     */
4842    class PrivateHandler extends Handler {
4843        @Override
4844        public void handleMessage(Message msg) {
4845            if (DebugFlags.WEB_VIEW) {
4846                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
4847                        > INVAL_RECT_MSG_ID ? Integer.toString(msg.what)
4848                        : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
4849            }
4850            if (mWebViewCore == null) {
4851                // after WebView's destroy() is called, skip handling messages.
4852                return;
4853            }
4854            switch (msg.what) {
4855                case REMEMBER_PASSWORD: {
4856                    mDatabase.setUsernamePassword(
4857                            msg.getData().getString("host"),
4858                            msg.getData().getString("username"),
4859                            msg.getData().getString("password"));
4860                    ((Message) msg.obj).sendToTarget();
4861                    break;
4862                }
4863                case NEVER_REMEMBER_PASSWORD: {
4864                    mDatabase.setUsernamePassword(
4865                            msg.getData().getString("host"), null, null);
4866                    ((Message) msg.obj).sendToTarget();
4867                    break;
4868                }
4869                case SWITCH_TO_SHORTPRESS: {
4870                    // if mPreventDrag is not confirmed, treat it as no so that
4871                    // it won't block panning the page.
4872                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
4873                        mPreventDrag = PREVENT_DRAG_NO;
4874                    }
4875                    if (mTouchMode == TOUCH_INIT_MODE) {
4876                        mTouchMode = TOUCH_SHORTPRESS_START_MODE;
4877                        updateSelection();
4878                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4879                        mTouchMode = TOUCH_DONE_MODE;
4880                    }
4881                    break;
4882                }
4883                case SWITCH_TO_LONGPRESS: {
4884                    if (mPreventDrag == PREVENT_DRAG_NO) {
4885                        mTouchMode = TOUCH_DONE_MODE;
4886                        performLongClick();
4887                        rebuildWebTextView();
4888                    }
4889                    break;
4890                }
4891                case RELEASE_SINGLE_TAP: {
4892                    if (mPreventDrag == PREVENT_DRAG_NO) {
4893                        mTouchMode = TOUCH_DONE_MODE;
4894                        doShortPress();
4895                    }
4896                    break;
4897                }
4898                case SCROLL_BY_MSG_ID:
4899                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
4900                    break;
4901                case SYNC_SCROLL_TO_MSG_ID:
4902                    if (mUserScroll) {
4903                        // if user has scrolled explicitly, don't sync the
4904                        // scroll position any more
4905                        mUserScroll = false;
4906                        break;
4907                    }
4908                    // fall through
4909                case SCROLL_TO_MSG_ID:
4910                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
4911                        // if we can't scroll to the exact position due to pin,
4912                        // send a message to WebCore to re-scroll when we get a
4913                        // new picture
4914                        mUserScroll = false;
4915                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
4916                                msg.arg1, msg.arg2);
4917                    }
4918                    break;
4919                case SPAWN_SCROLL_TO_MSG_ID:
4920                    spawnContentScrollTo(msg.arg1, msg.arg2);
4921                    break;
4922                case NEW_PICTURE_MSG_ID: {
4923                    WebSettings settings = mWebViewCore.getSettings();
4924                    // called for new content
4925                    final int viewWidth = getViewWidth();
4926                    final WebViewCore.DrawData draw =
4927                            (WebViewCore.DrawData) msg.obj;
4928                    final Point viewSize = draw.mViewPoint;
4929                    boolean useWideViewport = settings.getUseWideViewPort();
4930                    WebViewCore.RestoreState restoreState = draw.mRestoreState;
4931                    if (restoreState != null) {
4932                        mInZoomOverview = false;
4933                        mLastScale = restoreState.mTextWrapScale;
4934                        if (restoreState.mMinScale == 0) {
4935                            if (restoreState.mMobileSite) {
4936                                if (draw.mMinPrefWidth >
4937                                        Math.max(0, draw.mViewPoint.x)) {
4938                                    mMinZoomScale = (float) viewWidth
4939                                            / draw.mMinPrefWidth;
4940                                    mMinZoomScaleFixed = false;
4941                                } else {
4942                                    mMinZoomScale = restoreState.mDefaultScale;
4943                                    mMinZoomScaleFixed = true;
4944                                }
4945                            } else {
4946                                mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
4947                                mMinZoomScaleFixed = false;
4948                            }
4949                        } else {
4950                            mMinZoomScale = restoreState.mMinScale;
4951                            mMinZoomScaleFixed = true;
4952                        }
4953                        if (restoreState.mMaxScale == 0) {
4954                            mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
4955                        } else {
4956                            mMaxZoomScale = restoreState.mMaxScale;
4957                        }
4958                        setNewZoomScale(mLastScale, false);
4959                        setContentScrollTo(restoreState.mScrollX,
4960                                restoreState.mScrollY);
4961                        if (useWideViewport
4962                                && settings.getLoadWithOverviewMode()) {
4963                            if (restoreState.mViewScale == 0
4964                                    || (restoreState.mMobileSite
4965                                    && mMinZoomScale < restoreState.mDefaultScale)) {
4966                                mInZoomOverview = true;
4967                            }
4968                        }
4969                        // As we are on a new page, remove the WebTextView. This
4970                        // is necessary for page loads driven by webkit, and in
4971                        // particular when the user was on a password field, so
4972                        // the WebTextView was visible.
4973                        clearTextEntry();
4974                    }
4975                    // We update the layout (i.e. request a layout from the
4976                    // view system) if the last view size that we sent to
4977                    // WebCore matches the view size of the picture we just
4978                    // received in the fixed dimension.
4979                    final boolean updateLayout = viewSize.x == mLastWidthSent
4980                            && viewSize.y == mLastHeightSent;
4981                    recordNewContentSize(draw.mWidthHeight.x,
4982                            draw.mWidthHeight.y
4983                            + (mFindIsUp ? mFindHeight : 0), updateLayout);
4984                    if (DebugFlags.WEB_VIEW) {
4985                        Rect b = draw.mInvalRegion.getBounds();
4986                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
4987                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
4988                    }
4989                    invalidateContentRect(draw.mInvalRegion.getBounds());
4990                    if (mPictureListener != null) {
4991                        mPictureListener.onNewPicture(WebView.this, capturePicture());
4992                    }
4993                    if (useWideViewport) {
4994                        mZoomOverviewWidth = Math.max(draw.mMinPrefWidth,
4995                                draw.mViewPoint.x);
4996                    }
4997                    if (!mMinZoomScaleFixed) {
4998                        mMinZoomScale = (float) viewWidth / mZoomOverviewWidth;
4999                    }
5000                    if (!mDrawHistory && mInZoomOverview) {
5001                        // fit the content width to the current view. Ignore
5002                        // the rounding error case.
5003                        if (Math.abs((viewWidth * mInvActualScale)
5004                                - mZoomOverviewWidth) > 1) {
5005                            setNewZoomScale((float) viewWidth
5006                                    / mZoomOverviewWidth, false);
5007                        }
5008                    }
5009                    break;
5010                }
5011                case WEBCORE_INITIALIZED_MSG_ID:
5012                    // nativeCreate sets mNativeClass to a non-zero value
5013                    nativeCreate(msg.arg1);
5014                    break;
5015                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
5016                    // Make sure that the textfield is currently focused
5017                    // and representing the same node as the pointer.
5018                    if (inEditingMode() &&
5019                            mWebTextView.isSameTextField(msg.arg1)) {
5020                        if (msg.getData().getBoolean("password")) {
5021                            Spannable text = (Spannable) mWebTextView.getText();
5022                            int start = Selection.getSelectionStart(text);
5023                            int end = Selection.getSelectionEnd(text);
5024                            mWebTextView.setInPassword(true);
5025                            // Restore the selection, which may have been
5026                            // ruined by setInPassword.
5027                            Spannable pword =
5028                                    (Spannable) mWebTextView.getText();
5029                            Selection.setSelection(pword, start, end);
5030                        // If the text entry has created more events, ignore
5031                        // this one.
5032                        } else if (msg.arg2 == mTextGeneration) {
5033                            mWebTextView.setTextAndKeepSelection(
5034                                    (String) msg.obj);
5035                        }
5036                    }
5037                    break;
5038                case UPDATE_TEXT_SELECTION_MSG_ID:
5039                    if (inEditingMode()
5040                            && mWebTextView.isSameTextField(msg.arg1)
5041                            && msg.arg2 == mTextGeneration) {
5042                        WebViewCore.TextSelectionData tData
5043                                = (WebViewCore.TextSelectionData) msg.obj;
5044                        mWebTextView.setSelectionFromWebKit(tData.mStart,
5045                                tData.mEnd);
5046                    }
5047                    break;
5048                case MOVE_OUT_OF_PLUGIN:
5049                    if (nativePluginEatsNavKey()) {
5050                        navHandledKey(msg.arg1, 1, false, 0, true);
5051                    }
5052                    break;
5053                case UPDATE_TEXT_ENTRY_MSG_ID:
5054                    // this is sent after finishing resize in WebViewCore. Make
5055                    // sure the text edit box is still on the  screen.
5056                    if (inEditingMode() && nativeCursorIsTextInput()) {
5057                        mWebTextView.bringIntoView();
5058                        rebuildWebTextView();
5059                    }
5060                    break;
5061                case CLEAR_TEXT_ENTRY:
5062                    clearTextEntry();
5063                    break;
5064                case INVAL_RECT_MSG_ID: {
5065                    Rect r = (Rect)msg.obj;
5066                    if (r == null) {
5067                        invalidate();
5068                    } else {
5069                        // we need to scale r from content into view coords,
5070                        // which viewInvalidate() does for us
5071                        viewInvalidate(r.left, r.top, r.right, r.bottom);
5072                    }
5073                    break;
5074                }
5075                case REQUEST_FORM_DATA:
5076                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
5077                    if (mWebTextView.isSameTextField(msg.arg1)) {
5078                        mWebTextView.setAdapterCustom(adapter);
5079                    }
5080                    break;
5081                case UPDATE_CLIPBOARD:
5082                    String str = (String) msg.obj;
5083                    if (DebugFlags.WEB_VIEW) {
5084                        Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str);
5085                    }
5086                    try {
5087                        IClipboard clip = IClipboard.Stub.asInterface(
5088                                ServiceManager.getService("clipboard"));
5089                                clip.setClipboardText(str);
5090                    } catch (android.os.RemoteException e) {
5091                        Log.e(LOGTAG, "Clipboard failed", e);
5092                    }
5093                    break;
5094                case RESUME_WEBCORE_UPDATE:
5095                    WebViewCore.resumeUpdate(mWebViewCore);
5096                    break;
5097
5098                case LONG_PRESS_CENTER:
5099                    // as this is shared by keydown and trackballdown, reset all
5100                    // the states
5101                    mGotCenterDown = false;
5102                    mTrackballDown = false;
5103                    // LONG_PRESS_CENTER is sent as a delayed message. If we
5104                    // switch to windows overview, the WebView will be
5105                    // temporarily removed from the view system. In that case,
5106                    // do nothing.
5107                    if (getParent() != null) {
5108                        performLongClick();
5109                    }
5110                    break;
5111
5112                case WEBCORE_NEED_TOUCH_EVENTS:
5113                    mForwardTouchEvents = (msg.arg1 != 0);
5114                    break;
5115
5116                case PREVENT_TOUCH_ID:
5117                    if (msg.arg1 == MotionEvent.ACTION_DOWN) {
5118                        // dont override if mPreventDrag has been set to no due
5119                        // to time out
5120                        if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
5121                            mPreventDrag = msg.arg2 == 1 ? PREVENT_DRAG_YES
5122                                    : PREVENT_DRAG_NO;
5123                            if (mPreventDrag == PREVENT_DRAG_YES) {
5124                                mTouchMode = TOUCH_DONE_MODE;
5125                            }
5126                        }
5127                    }
5128                    break;
5129
5130                case REQUEST_KEYBOARD:
5131                    if (msg.arg1 == 0) {
5132                        hideSoftKeyboard();
5133                    } else {
5134                        displaySoftKeyboard(false);
5135                    }
5136                    break;
5137
5138                default:
5139                    super.handleMessage(msg);
5140                    break;
5141            }
5142        }
5143    }
5144
5145    // Class used to use a dropdown for a <select> element
5146    private class InvokeListBox implements Runnable {
5147        // Whether the listbox allows multiple selection.
5148        private boolean     mMultiple;
5149        // Passed in to a list with multiple selection to tell
5150        // which items are selected.
5151        private int[]       mSelectedArray;
5152        // Passed in to a list with single selection to tell
5153        // where the initial selection is.
5154        private int         mSelection;
5155
5156        private Container[] mContainers;
5157
5158        // Need these to provide stable ids to my ArrayAdapter,
5159        // which normally does not have stable ids. (Bug 1250098)
5160        private class Container extends Object {
5161            String  mString;
5162            boolean mEnabled;
5163            int     mId;
5164
5165            public String toString() {
5166                return mString;
5167            }
5168        }
5169
5170        /**
5171         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
5172         *  and allow filtering.
5173         */
5174        private class MyArrayListAdapter extends ArrayAdapter<Container> {
5175            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
5176                super(context,
5177                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
5178                            com.android.internal.R.layout.select_dialog_singlechoice,
5179                            objects);
5180            }
5181
5182            @Override
5183            public boolean hasStableIds() {
5184                // AdapterView's onChanged method uses this to determine whether
5185                // to restore the old state.  Return false so that the old (out
5186                // of date) state does not replace the new, valid state.
5187                return false;
5188            }
5189
5190            private Container item(int position) {
5191                if (position < 0 || position >= getCount()) {
5192                    return null;
5193                }
5194                return (Container) getItem(position);
5195            }
5196
5197            @Override
5198            public long getItemId(int position) {
5199                Container item = item(position);
5200                if (item == null) {
5201                    return -1;
5202                }
5203                return item.mId;
5204            }
5205
5206            @Override
5207            public boolean areAllItemsEnabled() {
5208                return false;
5209            }
5210
5211            @Override
5212            public boolean isEnabled(int position) {
5213                Container item = item(position);
5214                if (item == null) {
5215                    return false;
5216                }
5217                return item.mEnabled;
5218            }
5219        }
5220
5221        private InvokeListBox(String[] array,
5222                boolean[] enabled, int[] selected) {
5223            mMultiple = true;
5224            mSelectedArray = selected;
5225
5226            int length = array.length;
5227            mContainers = new Container[length];
5228            for (int i = 0; i < length; i++) {
5229                mContainers[i] = new Container();
5230                mContainers[i].mString = array[i];
5231                mContainers[i].mEnabled = enabled[i];
5232                mContainers[i].mId = i;
5233            }
5234        }
5235
5236        private InvokeListBox(String[] array, boolean[] enabled, int
5237                selection) {
5238            mSelection = selection;
5239            mMultiple = false;
5240
5241            int length = array.length;
5242            mContainers = new Container[length];
5243            for (int i = 0; i < length; i++) {
5244                mContainers[i] = new Container();
5245                mContainers[i].mString = array[i];
5246                mContainers[i].mEnabled = enabled[i];
5247                mContainers[i].mId = i;
5248            }
5249        }
5250
5251        /*
5252         * Whenever the data set changes due to filtering, this class ensures
5253         * that the checked item remains checked.
5254         */
5255        private class SingleDataSetObserver extends DataSetObserver {
5256            private long        mCheckedId;
5257            private ListView    mListView;
5258            private Adapter     mAdapter;
5259
5260            /*
5261             * Create a new observer.
5262             * @param id The ID of the item to keep checked.
5263             * @param l ListView for getting and clearing the checked states
5264             * @param a Adapter for getting the IDs
5265             */
5266            public SingleDataSetObserver(long id, ListView l, Adapter a) {
5267                mCheckedId = id;
5268                mListView = l;
5269                mAdapter = a;
5270            }
5271
5272            public void onChanged() {
5273                // The filter may have changed which item is checked.  Find the
5274                // item that the ListView thinks is checked.
5275                int position = mListView.getCheckedItemPosition();
5276                long id = mAdapter.getItemId(position);
5277                if (mCheckedId != id) {
5278                    // Clear the ListView's idea of the checked item, since
5279                    // it is incorrect
5280                    mListView.clearChoices();
5281                    // Search for mCheckedId.  If it is in the filtered list,
5282                    // mark it as checked
5283                    int count = mAdapter.getCount();
5284                    for (int i = 0; i < count; i++) {
5285                        if (mAdapter.getItemId(i) == mCheckedId) {
5286                            mListView.setItemChecked(i, true);
5287                            break;
5288                        }
5289                    }
5290                }
5291            }
5292
5293            public void onInvalidate() {}
5294        }
5295
5296        public void run() {
5297            final ListView listView = (ListView) LayoutInflater.from(mContext)
5298                    .inflate(com.android.internal.R.layout.select_dialog, null);
5299            final MyArrayListAdapter adapter = new
5300                    MyArrayListAdapter(mContext, mContainers, mMultiple);
5301            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
5302                    .setView(listView).setCancelable(true)
5303                    .setInverseBackgroundForced(true);
5304
5305            if (mMultiple) {
5306                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
5307                    public void onClick(DialogInterface dialog, int which) {
5308                        mWebViewCore.sendMessage(
5309                                EventHub.LISTBOX_CHOICES,
5310                                adapter.getCount(), 0,
5311                                listView.getCheckedItemPositions());
5312                    }});
5313                b.setNegativeButton(android.R.string.cancel,
5314                        new DialogInterface.OnClickListener() {
5315                    public void onClick(DialogInterface dialog, int which) {
5316                        mWebViewCore.sendMessage(
5317                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5318                }});
5319            }
5320            final AlertDialog dialog = b.create();
5321            listView.setAdapter(adapter);
5322            listView.setFocusableInTouchMode(true);
5323            // There is a bug (1250103) where the checks in a ListView with
5324            // multiple items selected are associated with the positions, not
5325            // the ids, so the items do not properly retain their checks when
5326            // filtered.  Do not allow filtering on multiple lists until
5327            // that bug is fixed.
5328
5329            listView.setTextFilterEnabled(!mMultiple);
5330            if (mMultiple) {
5331                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
5332                int length = mSelectedArray.length;
5333                for (int i = 0; i < length; i++) {
5334                    listView.setItemChecked(mSelectedArray[i], true);
5335                }
5336            } else {
5337                listView.setOnItemClickListener(new OnItemClickListener() {
5338                    public void onItemClick(AdapterView parent, View v,
5339                            int position, long id) {
5340                        mWebViewCore.sendMessage(
5341                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
5342                        dialog.dismiss();
5343                    }
5344                });
5345                if (mSelection != -1) {
5346                    listView.setSelection(mSelection);
5347                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
5348                    listView.setItemChecked(mSelection, true);
5349                    DataSetObserver observer = new SingleDataSetObserver(
5350                            adapter.getItemId(mSelection), listView, adapter);
5351                    adapter.registerDataSetObserver(observer);
5352                }
5353            }
5354            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
5355                public void onCancel(DialogInterface dialog) {
5356                    mWebViewCore.sendMessage(
5357                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5358                }
5359            });
5360            dialog.show();
5361        }
5362    }
5363
5364    /*
5365     * Request a dropdown menu for a listbox with multiple selection.
5366     *
5367     * @param array Labels for the listbox.
5368     * @param enabledArray  Which positions are enabled.
5369     * @param selectedArray Which positions are initally selected.
5370     */
5371    void requestListBox(String[] array, boolean[]enabledArray, int[]
5372            selectedArray) {
5373        mPrivateHandler.post(
5374                new InvokeListBox(array, enabledArray, selectedArray));
5375    }
5376
5377    /*
5378     * Request a dropdown menu for a listbox with single selection or a single
5379     * <select> element.
5380     *
5381     * @param array Labels for the listbox.
5382     * @param enabledArray  Which positions are enabled.
5383     * @param selection Which position is initally selected.
5384     */
5385    void requestListBox(String[] array, boolean[]enabledArray, int selection) {
5386        mPrivateHandler.post(
5387                new InvokeListBox(array, enabledArray, selection));
5388    }
5389
5390    // called by JNI
5391    private void sendMoveMouse(int frame, int node, int x, int y) {
5392        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
5393                new WebViewCore.CursorData(frame, node, x, y));
5394    }
5395
5396    /*
5397     * Send a mouse move event to the webcore thread.
5398     *
5399     * @param removeFocus Pass true if the "mouse" cursor is now over a node
5400     *                    which wants key events, but it is not the focus. This
5401     *                    will make the visual appear as though nothing is in
5402     *                    focus.  Remove the WebTextView, if present, and stop
5403     *                    drawing the blinking caret.
5404     * called by JNI
5405     */
5406    private void sendMoveMouseIfLatest(boolean removeFocus) {
5407        if (removeFocus) {
5408            clearTextEntry();
5409            setFocusControllerInactive();
5410        }
5411        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
5412                cursorData());
5413    }
5414
5415    // called by JNI
5416    private void sendMotionUp(int touchGeneration,
5417            int frame, int node, int x, int y) {
5418        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
5419        touchUpData.mMoveGeneration = touchGeneration;
5420        touchUpData.mFrame = frame;
5421        touchUpData.mNode = node;
5422        touchUpData.mX = x;
5423        touchUpData.mY = y;
5424        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
5425    }
5426
5427
5428    private int getScaledMaxXScroll() {
5429        int width;
5430        if (mHeightCanMeasure == false) {
5431            width = getViewWidth() / 4;
5432        } else {
5433            Rect visRect = new Rect();
5434            calcOurVisibleRect(visRect);
5435            width = visRect.width() / 2;
5436        }
5437        // FIXME the divisor should be retrieved from somewhere
5438        return viewToContentX(width);
5439    }
5440
5441    private int getScaledMaxYScroll() {
5442        int height;
5443        if (mHeightCanMeasure == false) {
5444            height = getViewHeight() / 4;
5445        } else {
5446            Rect visRect = new Rect();
5447            calcOurVisibleRect(visRect);
5448            height = visRect.height() / 2;
5449        }
5450        // FIXME the divisor should be retrieved from somewhere
5451        // the closest thing today is hard-coded into ScrollView.java
5452        // (from ScrollView.java, line 363)   int maxJump = height/2;
5453        return Math.round(height * mInvActualScale);
5454    }
5455
5456    /**
5457     * Called by JNI to invalidate view
5458     */
5459    private void viewInvalidate() {
5460        invalidate();
5461    }
5462
5463    // return true if the key was handled
5464    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
5465            long time, boolean ignorePlugin) {
5466        if (mNativeClass == 0) {
5467            return false;
5468        }
5469        if (ignorePlugin == false && nativePluginEatsNavKey()) {
5470            KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN
5471                , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
5472                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
5473                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
5474                , 0, 0, 0);
5475            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5476            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5477            return true;
5478        }
5479        mLastCursorTime = time;
5480        mLastCursorBounds = nativeGetCursorRingBounds();
5481        boolean keyHandled
5482                = nativeMoveCursor(keyCode, count, noScroll) == false;
5483        if (DebugFlags.WEB_VIEW) {
5484            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
5485                    + " mLastCursorTime=" + mLastCursorTime
5486                    + " handled=" + keyHandled);
5487        }
5488        if (keyHandled == false || mHeightCanMeasure == false) {
5489            return keyHandled;
5490        }
5491        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
5492        if (contentCursorRingBounds.isEmpty()) return keyHandled;
5493        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
5494        Rect visRect = new Rect();
5495        calcOurVisibleRect(visRect);
5496        Rect outset = new Rect(visRect);
5497        int maxXScroll = visRect.width() / 2;
5498        int maxYScroll = visRect.height() / 2;
5499        outset.inset(-maxXScroll, -maxYScroll);
5500        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
5501            return keyHandled;
5502        }
5503        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
5504        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
5505                maxXScroll);
5506        if (maxH > 0) {
5507            pinScrollBy(maxH, 0, true, 0);
5508        } else {
5509            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
5510                    -maxXScroll);
5511            if (maxH < 0) {
5512                pinScrollBy(maxH, 0, true, 0);
5513            }
5514        }
5515        if (mLastCursorBounds.isEmpty()) return keyHandled;
5516        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
5517            return keyHandled;
5518        }
5519        if (DebugFlags.WEB_VIEW) {
5520            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
5521                    + contentCursorRingBounds);
5522        }
5523        requestRectangleOnScreen(viewCursorRingBounds);
5524        mUserScroll = true;
5525        return keyHandled;
5526    }
5527
5528    /**
5529     * Set the background color. It's white by default. Pass
5530     * zero to make the view transparent.
5531     * @param color   the ARGB color described by Color.java
5532     */
5533    public void setBackgroundColor(int color) {
5534        mBackgroundColor = color;
5535        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
5536    }
5537
5538    public void debugDump() {
5539        nativeDebugDump();
5540        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
5541    }
5542
5543    /**
5544     *  Update our cache with updatedText.
5545     *  @param updatedText  The new text to put in our cache.
5546     */
5547    /* package */ void updateCachedTextfield(String updatedText) {
5548        // Also place our generation number so that when we look at the cache
5549        // we recognize that it is up to date.
5550        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
5551    }
5552
5553    /* package */ native void nativeClearCursor();
5554    private native void     nativeCreate(int ptr);
5555    private native int      nativeCursorFramePointer();
5556    private native Rect     nativeCursorNodeBounds();
5557    /* package */ native int nativeCursorNodePointer();
5558    /* package */ native boolean nativeCursorMatchesFocus();
5559    private native boolean  nativeCursorIntersects(Rect visibleRect);
5560    private native boolean  nativeCursorIsAnchor();
5561    private native boolean  nativeCursorIsPlugin();
5562    private native boolean  nativeCursorIsTextInput();
5563    private native Point    nativeCursorPosition();
5564    private native String   nativeCursorText();
5565    /**
5566     * Returns true if the native cursor node says it wants to handle key events
5567     * (ala plugins). This can only be called if mNativeClass is non-zero!
5568     */
5569    private native boolean  nativeCursorWantsKeyEvents();
5570    private native void     nativeDebugDump();
5571    private native void     nativeDestroy();
5572    private native void     nativeDrawCursorRing(Canvas content);
5573    private native void     nativeDrawMatches(Canvas canvas);
5574    private native void     nativeDrawSelection(Canvas content
5575            , int x, int y, boolean extendSelection);
5576    private native void     nativeDrawSelectionRegion(Canvas content);
5577    private native void     nativeDumpDisplayTree(String urlOrNull);
5578    private native int      nativeFindAll(String findLower, String findUpper);
5579    private native void     nativeFindNext(boolean forward);
5580    private native boolean  nativeFocusCandidateIsPassword();
5581    private native boolean  nativeFocusCandidateIsRtlText();
5582    private native boolean  nativeFocusCandidateIsTextField();
5583    private native boolean  nativeFocusCandidateIsTextInput();
5584    private native int      nativeFocusCandidateMaxLength();
5585    /* package */ native String   nativeFocusCandidateName();
5586    private native Rect     nativeFocusCandidateNodeBounds();
5587    /* package */ native int nativeFocusCandidatePointer();
5588    private native String   nativeFocusCandidateText();
5589    private native int      nativeFocusCandidateTextSize();
5590    /* package */ native int nativeFocusNodePointer();
5591    private native Rect     nativeGetCursorRingBounds();
5592    private native Region   nativeGetSelection();
5593    private native boolean  nativeHasCursorNode();
5594    private native boolean  nativeHasFocusNode();
5595    private native void     nativeHideCursor();
5596    private native String   nativeImageURI(int x, int y);
5597    private native void     nativeInstrumentReport();
5598    /* package */ native void nativeMoveCursorToNextTextInput();
5599    // return true if the page has been scrolled
5600    private native boolean  nativeMotionUp(int x, int y, int slop);
5601    // returns false if it handled the key
5602    private native boolean  nativeMoveCursor(int keyCode, int count,
5603            boolean noScroll);
5604    private native int      nativeMoveGeneration();
5605    private native void     nativeMoveSelection(int x, int y,
5606            boolean extendSelection);
5607    private native boolean  nativePluginEatsNavKey();
5608    // Like many other of our native methods, you must make sure that
5609    // mNativeClass is not null before calling this method.
5610    private native void     nativeRecordButtons(boolean focused,
5611            boolean pressed, boolean invalidate);
5612    private native void     nativeSelectBestAt(Rect rect);
5613    private native void     nativeSetFindIsDown();
5614    private native void     nativeSetFollowedLink(boolean followed);
5615    private native void     nativeSetHeightCanMeasure(boolean measure);
5616    // Returns a value corresponding to CachedFrame::ImeAction
5617    /* package */ native int  nativeTextFieldAction();
5618    /**
5619     * Perform a click on a currently focused text input.  Since it is already
5620     * focused, there is no need to go through the nativeMotionUp code, which
5621     * may change the Cursor.
5622     */
5623    private native void     nativeTextInputMotionUp(int x, int y);
5624    private native int      nativeTextGeneration();
5625    // Never call this version except by updateCachedTextfield(String) -
5626    // we always want to pass in our generation number.
5627    private native void     nativeUpdateCachedTextfield(String updatedText,
5628            int generation);
5629    private native void     nativeUpdatePluginReceivesEvents();
5630    // return NO_LEFTEDGE means failure.
5631    private static final int NO_LEFTEDGE = -1;
5632    private native int      nativeGetBlockLeftEdge(int x, int y, float scale);
5633}
5634