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