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