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