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