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