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