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