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