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