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