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