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