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