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