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