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