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