WebView.java revision e88ca718ed9af788f2dc46b5f2db494906bbf41d
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.ComponentCallbacks2;
24import android.content.Context;
25import android.content.DialogInterface;
26import android.content.DialogInterface.OnCancelListener;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.pm.PackageInfo;
30import android.content.pm.PackageManager;
31import android.content.res.Configuration;
32import android.database.DataSetObserver;
33import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
35import android.graphics.BitmapShader;
36import android.graphics.Canvas;
37import android.graphics.Color;
38import android.graphics.DrawFilter;
39import android.graphics.Paint;
40import android.graphics.PaintFlagsDrawFilter;
41import android.graphics.Picture;
42import android.graphics.Point;
43import android.graphics.Rect;
44import android.graphics.RectF;
45import android.graphics.Region;
46import android.graphics.RegionIterator;
47import android.graphics.Shader;
48import android.graphics.drawable.Drawable;
49import android.net.Proxy;
50import android.net.ProxyProperties;
51import android.net.Uri;
52import android.net.http.SslCertificate;
53import android.os.AsyncTask;
54import android.os.Bundle;
55import android.os.Handler;
56import android.os.Looper;
57import android.os.Message;
58import android.os.StrictMode;
59import android.provider.Settings;
60import android.speech.tts.TextToSpeech;
61import android.util.AttributeSet;
62import android.util.EventLog;
63import android.util.Log;
64import android.view.Gravity;
65import android.view.HapticFeedbackConstants;
66import android.view.HardwareCanvas;
67import android.view.InputDevice;
68import android.view.KeyCharacterMap;
69import android.view.KeyEvent;
70import android.view.LayoutInflater;
71import android.view.MotionEvent;
72import android.view.ScaleGestureDetector;
73import android.view.SoundEffectConstants;
74import android.view.VelocityTracker;
75import android.view.View;
76import android.view.ViewConfiguration;
77import android.view.ViewGroup;
78import android.view.ViewParent;
79import android.view.ViewTreeObserver;
80import android.view.accessibility.AccessibilityEvent;
81import android.view.accessibility.AccessibilityManager;
82import android.view.accessibility.AccessibilityNodeInfo;
83import android.view.inputmethod.EditorInfo;
84import android.view.inputmethod.InputConnection;
85import android.view.inputmethod.InputMethodManager;
86import android.webkit.WebTextView.AutoCompleteAdapter;
87import android.webkit.WebViewCore.DrawData;
88import android.webkit.WebViewCore.EventHub;
89import android.webkit.WebViewCore.TouchEventData;
90import android.webkit.WebViewCore.TouchHighlightData;
91import android.widget.AbsoluteLayout;
92import android.widget.Adapter;
93import android.widget.AdapterView;
94import android.widget.AdapterView.OnItemClickListener;
95import android.widget.ArrayAdapter;
96import android.widget.CheckedTextView;
97import android.widget.LinearLayout;
98import android.widget.ListView;
99import android.widget.OverScroller;
100import android.widget.Toast;
101
102import junit.framework.Assert;
103
104import java.io.File;
105import java.io.FileInputStream;
106import java.io.FileNotFoundException;
107import java.io.FileOutputStream;
108import java.io.IOException;
109import java.io.InputStream;
110import java.io.OutputStream;
111import java.net.URLDecoder;
112import java.util.ArrayList;
113import java.util.HashMap;
114import java.util.HashSet;
115import java.util.List;
116import java.util.Map;
117import java.util.Set;
118import java.util.Vector;
119import java.util.regex.Matcher;
120import java.util.regex.Pattern;
121
122import javax.microedition.khronos.egl.EGL10;
123import javax.microedition.khronos.egl.EGLContext;
124import javax.microedition.khronos.egl.EGLDisplay;
125import static javax.microedition.khronos.egl.EGL10.*;
126
127/**
128 * <p>A View that displays web pages. This class is the basis upon which you
129 * can roll your own web browser or simply display some online content within your Activity.
130 * It uses the WebKit rendering engine to display
131 * web pages and includes methods to navigate forward and backward
132 * through a history, zoom in and out, perform text searches and more.</p>
133 * <p>To enable the built-in zoom, set
134 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
135 * (introduced in API version 3).
136 * <p>Note that, in order for your Activity to access the Internet and load web pages
137 * in a WebView, you must add the {@code INTERNET} permissions to your
138 * Android Manifest file:</p>
139 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
140 *
141 * <p>This must be a child of the <a
142 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a>
143 * element.</p>
144 *
145 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-webview.html">Web View
146 * tutorial</a>.</p>
147 *
148 * <h3>Basic usage</h3>
149 *
150 * <p>By default, a WebView provides no browser-like widgets, does not
151 * enable JavaScript and web page errors are ignored. If your goal is only
152 * to display some HTML as a part of your UI, this is probably fine;
153 * the user won't need to interact with the web page beyond reading
154 * it, and the web page won't need to interact with the user. If you
155 * actually want a full-blown web browser, then you probably want to
156 * invoke the Browser application with a URL Intent rather than show it
157 * with a WebView. For example:
158 * <pre>
159 * Uri uri = Uri.parse("http://www.example.com");
160 * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
161 * startActivity(intent);
162 * </pre>
163 * <p>See {@link android.content.Intent} for more information.</p>
164 *
165 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout,
166 * or set the entire Activity window as a WebView during {@link
167 * android.app.Activity#onCreate(Bundle) onCreate()}:</p>
168 * <pre class="prettyprint">
169 * WebView webview = new WebView(this);
170 * setContentView(webview);
171 * </pre>
172 *
173 * <p>Then load the desired web page:</p>
174 * <pre>
175 * // Simplest usage: note that an exception will NOT be thrown
176 * // if there is an error loading this page (see below).
177 * webview.loadUrl("http://slashdot.org/");
178 *
179 * // OR, you can also load from an HTML string:
180 * String summary = "&lt;html>&lt;body>You scored &lt;b>192&lt;/b> points.&lt;/body>&lt;/html>";
181 * webview.loadData(summary, "text/html", null);
182 * // ... although note that there are restrictions on what this HTML can do.
183 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
184 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
185 * </pre>
186 *
187 * <p>A WebView has several customization points where you can add your
188 * own behavior. These are:</p>
189 *
190 * <ul>
191 *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
192 *       This class is called when something that might impact a
193 *       browser UI happens, for instance, progress updates and
194 *       JavaScript alerts are sent here (see <a
195 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>).
196 *   </li>
197 *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
198 *       It will be called when things happen that impact the
199 *       rendering of the content, eg, errors or form submissions. You
200 *       can also intercept URL loading here (via {@link
201 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String)
202 * shouldOverrideUrlLoading()}).</li>
203 *   <li>Modifying the {@link android.webkit.WebSettings}, such as
204 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean)
205 * setJavaScriptEnabled()}. </li>
206 *   <li>Adding JavaScript-to-Java interfaces with the {@link
207 * android.webkit.WebView#addJavascriptInterface} method.
208 *       This lets you bind Java objects into the WebView so they can be
209 *       controlled from the web pages JavaScript.</li>
210 * </ul>
211 *
212 * <p>Here's a more complicated example, showing error handling,
213 *    settings, and progress notification:</p>
214 *
215 * <pre class="prettyprint">
216 * // Let's display the progress in the activity title bar, like the
217 * // browser app does.
218 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
219 *
220 * webview.getSettings().setJavaScriptEnabled(true);
221 *
222 * final Activity activity = this;
223 * webview.setWebChromeClient(new WebChromeClient() {
224 *   public void onProgressChanged(WebView view, int progress) {
225 *     // Activities and WebViews measure progress with different scales.
226 *     // The progress meter will automatically disappear when we reach 100%
227 *     activity.setProgress(progress * 1000);
228 *   }
229 * });
230 * webview.setWebViewClient(new WebViewClient() {
231 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
232 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
233 *   }
234 * });
235 *
236 * webview.loadUrl("http://slashdot.org/");
237 * </pre>
238 *
239 * <h3>Cookie and window management</h3>
240 *
241 * <p>For obvious security reasons, your application has its own
242 * cache, cookie store etc.&mdash;it does not share the Browser
243 * application's data. Cookies are managed on a separate thread, so
244 * operations like index building don't block the UI
245 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
246 * if you want to use cookies in your application.
247 * </p>
248 *
249 * <p>By default, requests by the HTML to open new windows are
250 * ignored. This is true whether they be opened by JavaScript or by
251 * the target attribute on a link. You can customize your
252 * {@link WebChromeClient} to provide your own behaviour for opening multiple windows,
253 * and render them in whatever manner you want.</p>
254 *
255 * <p>The standard behavior for an Activity is to be destroyed and
256 * recreated when the device orientation or any other configuration changes. This will cause
257 * the WebView to reload the current page. If you don't want that, you
258 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden}
259 * changes, and then just leave the WebView alone. It'll automatically
260 * re-orient itself as appropriate. Read <a
261 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for
262 * more information about how to handle configuration changes during runtime.</p>
263 *
264 *
265 * <h3>Building web pages to support different screen densities</h3>
266 *
267 * <p>The screen density of a device is based on the screen resolution. A screen with low density
268 * has fewer available pixels per inch, where a screen with high density
269 * has more &mdash; sometimes significantly more &mdash; pixels per inch. The density of a
270 * screen is important because, other things being equal, a UI element (such as a button) whose
271 * height and width are defined in terms of screen pixels will appear larger on the lower density
272 * screen and smaller on the higher density screen.
273 * For simplicity, Android collapses all actual screen densities into three generalized densities:
274 * high, medium, and low.</p>
275 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default
276 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen
277 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels
278 * are bigger).
279 * Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help
280 * you (as a web developer) target screens with different screen densities.</p>
281 * <p>Here's a summary of the features you can use to handle different screen densities:</p>
282 * <ul>
283 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the
284 * default scaling factor used for the current device. For example, if the value of {@code
285 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device
286 * and default scaling is not applied to the web page; if the value is "1.5", then the device is
287 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the
288 * value is "0.75", then the device is considered a low density device (ldpi) and the content is
289 * scaled 0.75x. However, if you specify the {@code "target-densitydpi"} meta property
290 * (discussed below), then you can stop this default scaling behavior.</li>
291 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen
292 * densities for which this style sheet is to be used. The corresponding value should be either
293 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium
294 * density, or high density screens, respectively. For example:
295 * <pre>
296 * &lt;link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /&gt;</pre>
297 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5,
298 * which is the high density pixel ratio.</p>
299 * </li>
300 * <li>The {@code target-densitydpi} property for the {@code viewport} meta tag. You can use
301 * this to specify the target density for which the web page is designed, using the following
302 * values:
303 * <ul>
304 * <li>{@code device-dpi} - Use the device's native dpi as the target dpi. Default scaling never
305 * occurs.</li>
306 * <li>{@code high-dpi} - Use hdpi as the target dpi. Medium and low density screens scale down
307 * as appropriate.</li>
308 * <li>{@code medium-dpi} - Use mdpi as the target dpi. High density screens scale up and
309 * low density screens scale down. This is also the default behavior.</li>
310 * <li>{@code low-dpi} - Use ldpi as the target dpi. Medium and high density screens scale up
311 * as appropriate.</li>
312 * <li><em>{@code <value>}</em> - Specify a dpi value to use as the target dpi (accepted
313 * values are 70-400).</li>
314 * </ul>
315 * <p>Here's an example meta tag to specify the target density:</p>
316 * <pre>&lt;meta name="viewport" content="target-densitydpi=device-dpi" /&gt;</pre></li>
317 * </ul>
318 * <p>If you want to modify your web page for different densities, by using the {@code
319 * -webkit-device-pixel-ratio} CSS media query and/or the {@code
320 * window.devicePixelRatio} DOM property, then you should set the {@code target-densitydpi} meta
321 * property to {@code device-dpi}. This stops Android from performing scaling in your web page and
322 * allows you to make the necessary adjustments for each density via CSS and JavaScript.</p>
323 *
324 *
325 */
326@Widget
327public class WebView extends AbsoluteLayout
328        implements ViewTreeObserver.OnGlobalFocusChangeListener,
329        ViewGroup.OnHierarchyChangeListener {
330
331    private class InnerGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
332        public void onGlobalLayout() {
333            if (isShown()) {
334                setGLRectViewport();
335            }
336        }
337    }
338
339    private class InnerScrollChangedListener implements ViewTreeObserver.OnScrollChangedListener {
340        public void onScrollChanged() {
341            if (isShown()) {
342                setGLRectViewport();
343            }
344        }
345    }
346
347    // The listener to capture global layout change event.
348    private InnerGlobalLayoutListener mGlobalLayoutListener = null;
349
350    // The listener to capture scroll event.
351    private InnerScrollChangedListener mScrollChangedListener = null;
352
353    // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
354    // the screen all-the-time. Good for profiling our drawing code
355    static private final boolean AUTO_REDRAW_HACK = false;
356    // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
357    private boolean mAutoRedraw;
358
359    // Reference to the AlertDialog displayed by InvokeListBox.
360    // It's used to dismiss the dialog in destroy if not done before.
361    private AlertDialog mListBoxDialog = null;
362
363    static final String LOGTAG = "webview";
364
365    private ZoomManager mZoomManager;
366
367    private final Rect mGLRectViewport = new Rect();
368    private final Rect mViewRectViewport = new Rect();
369    private boolean mGLViewportEmpty = false;
370
371    /**
372     *  Transportation object for returning WebView across thread boundaries.
373     */
374    public class WebViewTransport {
375        private WebView mWebview;
376
377        /**
378         * Set the WebView to the transportation object.
379         * @param webview The WebView to transport.
380         */
381        public synchronized void setWebView(WebView webview) {
382            mWebview = webview;
383        }
384
385        /**
386         * Return the WebView object.
387         * @return WebView The transported WebView object.
388         */
389        public synchronized WebView getWebView() {
390            return mWebview;
391        }
392    }
393
394    private static class OnTrimMemoryListener implements ComponentCallbacks2 {
395        private static OnTrimMemoryListener sInstance = null;
396
397        static void init(Context c) {
398            if (sInstance == null) {
399                sInstance = new OnTrimMemoryListener(c.getApplicationContext());
400            }
401        }
402
403        private OnTrimMemoryListener(Context c) {
404            c.registerComponentCallbacks(this);
405        }
406
407        @Override
408        public void onConfigurationChanged(Configuration newConfig) {
409            // Ignore
410        }
411
412        @Override
413        public void onLowMemory() {
414            // Ignore
415        }
416
417        @Override
418        public void onTrimMemory(int level) {
419            if (DebugFlags.WEB_VIEW) {
420                Log.d("WebView", "onTrimMemory: " + level);
421            }
422            WebView.nativeOnTrimMemory(level);
423        }
424
425    }
426
427    // A final CallbackProxy shared by WebViewCore and BrowserFrame.
428    private final CallbackProxy mCallbackProxy;
429
430    private final WebViewDatabase mDatabase;
431
432    // SSL certificate for the main top-level page (if secure)
433    private SslCertificate mCertificate;
434
435    // Native WebView pointer that is 0 until the native object has been
436    // created.
437    private int mNativeClass;
438    // This would be final but it needs to be set to null when the WebView is
439    // destroyed.
440    private WebViewCore mWebViewCore;
441    // Handler for dispatching UI messages.
442    /* package */ final Handler mPrivateHandler = new PrivateHandler();
443    private WebTextView mWebTextView;
444    // Used to ignore changes to webkit text that arrives to the UI side after
445    // more key events.
446    private int mTextGeneration;
447
448    /* package */ void incrementTextGeneration() { mTextGeneration++; }
449
450    // Used by WebViewCore to create child views.
451    /* package */ final ViewManager mViewManager;
452
453    // Used to display in full screen mode
454    PluginFullScreenHolder mFullScreenHolder;
455
456    /**
457     * Position of the last touch event in pixels.
458     * Use integer to prevent loss of dragging delta calculation accuracy;
459     * which was done in float and converted to integer, and resulted in gradual
460     * and compounding touch position and view dragging mismatch.
461     */
462    private int mLastTouchX;
463    private int mLastTouchY;
464    private int mStartTouchX;
465    private int mStartTouchY;
466    private float mAverageAngle;
467
468    /**
469     * Time of the last touch event.
470     */
471    private long mLastTouchTime;
472
473    /**
474     * Time of the last time sending touch event to WebViewCore
475     */
476    private long mLastSentTouchTime;
477
478    /**
479     * The minimum elapsed time before sending another ACTION_MOVE event to
480     * WebViewCore. This really should be tuned for each type of the devices.
481     * For example in Google Map api test case, it takes Dream device at least
482     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
483     * triggering the layout and drawing the picture. While the same process
484     * takes 60+ms on the current high speed device. If we make
485     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
486     * to WebViewCore queue and the real layout and draw events will be pushed
487     * to further, which slows down the refresh rate. Choose 50 to favor the
488     * current high speed devices. For Dream like devices, 100 is a better
489     * choice. Maybe make this in the buildspec later.
490     * (Update 12/14/2010: changed to 0 since current device should be able to
491     * handle the raw events and Map team voted to have the raw events too.
492     */
493    private static final int TOUCH_SENT_INTERVAL = 0;
494    private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL;
495
496    /**
497     * Helper class to get velocity for fling
498     */
499    VelocityTracker mVelocityTracker;
500    private int mMaximumFling;
501    private float mLastVelocity;
502    private float mLastVelX;
503    private float mLastVelY;
504
505    // The id of the native layer being scrolled.
506    private int mScrollingLayer;
507    private Rect mScrollingLayerRect = new Rect();
508
509    // only trigger accelerated fling if the new velocity is at least
510    // MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION times of the previous velocity
511    private static final float MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION = 0.2f;
512
513    /**
514     * Touch mode
515     */
516    private int mTouchMode = TOUCH_DONE_MODE;
517    private static final int TOUCH_INIT_MODE = 1;
518    private static final int TOUCH_DRAG_START_MODE = 2;
519    private static final int TOUCH_DRAG_MODE = 3;
520    private static final int TOUCH_SHORTPRESS_START_MODE = 4;
521    private static final int TOUCH_SHORTPRESS_MODE = 5;
522    private static final int TOUCH_DOUBLE_TAP_MODE = 6;
523    private static final int TOUCH_DONE_MODE = 7;
524    private static final int TOUCH_PINCH_DRAG = 8;
525    private static final int TOUCH_DRAG_LAYER_MODE = 9;
526
527    // Whether to forward the touch events to WebCore
528    // Can only be set by WebKit via JNI.
529    private boolean mForwardTouchEvents = false;
530
531    // Whether to prevent default during touch. The initial value depends on
532    // mForwardTouchEvents. If WebCore wants all the touch events, it says yes
533    // for touch down. Otherwise UI will wait for the answer of the first
534    // confirmed move before taking over the control.
535    private static final int PREVENT_DEFAULT_NO = 0;
536    private static final int PREVENT_DEFAULT_MAYBE_YES = 1;
537    private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2;
538    private static final int PREVENT_DEFAULT_YES = 3;
539    private static final int PREVENT_DEFAULT_IGNORE = 4;
540    private int mPreventDefault = PREVENT_DEFAULT_IGNORE;
541
542    // true when the touch movement exceeds the slop
543    private boolean mConfirmMove;
544
545    // if true, touch events will be first processed by WebCore, if prevent
546    // default is not set, the UI will continue handle them.
547    private boolean mDeferTouchProcess;
548
549    // to avoid interfering with the current touch events, track them
550    // separately. Currently no snapping or fling in the deferred process mode
551    private int mDeferTouchMode = TOUCH_DONE_MODE;
552    private float mLastDeferTouchX;
553    private float mLastDeferTouchY;
554
555    // To keep track of whether the current drag was initiated by a WebTextView,
556    // so that we know not to hide the cursor
557    boolean mDragFromTextInput;
558
559    // Whether or not to draw the cursor ring.
560    private boolean mDrawCursorRing = true;
561
562    // true if onPause has been called (and not onResume)
563    private boolean mIsPaused;
564
565    private HitTestResult mInitialHitTestResult;
566
567    /**
568     * Customizable constant
569     */
570    // pre-computed square of ViewConfiguration.getScaledTouchSlop()
571    private int mTouchSlopSquare;
572    // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
573    private int mDoubleTapSlopSquare;
574    // pre-computed density adjusted navigation slop
575    private int mNavSlop;
576    // This should be ViewConfiguration.getTapTimeout()
577    // But system time out is 100ms, which is too short for the browser.
578    // In the browser, if it switches out of tap too soon, jump tap won't work.
579    // In addition, a double tap on a trackpad will always have a duration of
580    // 300ms, so this value must be at least that (otherwise we will timeout the
581    // first tap and convert it to a long press).
582    private static final int TAP_TIMEOUT = 300;
583    // This should be ViewConfiguration.getLongPressTimeout()
584    // But system time out is 500ms, which is too short for the browser.
585    // With a short timeout, it's difficult to treat trigger a short press.
586    private static final int LONG_PRESS_TIMEOUT = 1000;
587    // needed to avoid flinging after a pause of no movement
588    private static final int MIN_FLING_TIME = 250;
589    // draw unfiltered after drag is held without movement
590    private static final int MOTIONLESS_TIME = 100;
591    // The amount of content to overlap between two screens when going through
592    // pages with the space bar, in pixels.
593    private static final int PAGE_SCROLL_OVERLAP = 24;
594
595    /**
596     * These prevent calling requestLayout if either dimension is fixed. This
597     * depends on the layout parameters and the measure specs.
598     */
599    boolean mWidthCanMeasure;
600    boolean mHeightCanMeasure;
601
602    // Remember the last dimensions we sent to the native side so we can avoid
603    // sending the same dimensions more than once.
604    int mLastWidthSent;
605    int mLastHeightSent;
606    // Since view height sent to webkit could be fixed to avoid relayout, this
607    // value records the last sent actual view height.
608    int mLastActualHeightSent;
609
610    private int mContentWidth;   // cache of value from WebViewCore
611    private int mContentHeight;  // cache of value from WebViewCore
612
613    // Need to have the separate control for horizontal and vertical scrollbar
614    // style than the View's single scrollbar style
615    private boolean mOverlayHorizontalScrollbar = true;
616    private boolean mOverlayVerticalScrollbar = false;
617
618    // our standard speed. this way small distances will be traversed in less
619    // time than large distances, but we cap the duration, so that very large
620    // distances won't take too long to get there.
621    private static final int STD_SPEED = 480;  // pixels per second
622    // time for the longest scroll animation
623    private static final int MAX_DURATION = 750;   // milliseconds
624    private static final int SLIDE_TITLE_DURATION = 500;   // milliseconds
625
626    // Used by OverScrollGlow
627    OverScroller mScroller;
628
629    private boolean mInOverScrollMode = false;
630    private static Paint mOverScrollBackground;
631    private static Paint mOverScrollBorder;
632
633    private boolean mWrapContent;
634    private static final int MOTIONLESS_FALSE           = 0;
635    private static final int MOTIONLESS_PENDING         = 1;
636    private static final int MOTIONLESS_TRUE            = 2;
637    private static final int MOTIONLESS_IGNORE          = 3;
638    private int mHeldMotionless;
639
640    // An instance for injecting accessibility in WebViews with disabled
641    // JavaScript or ones for which no accessibility script exists
642    private AccessibilityInjector mAccessibilityInjector;
643
644    // flag indicating if accessibility script is injected so we
645    // know to handle Shift and arrows natively first
646    private boolean mAccessibilityScriptInjected;
647
648    static final boolean USE_JAVA_TEXT_SELECTION = true;
649    static final boolean DEBUG_TEXT_HANDLES = false;
650    private Region mTextSelectionRegion = new Region();
651    private Paint mTextSelectionPaint;
652    private Drawable mSelectHandleLeft;
653    private Drawable mSelectHandleRight;
654
655    static final boolean USE_WEBKIT_RINGS = false;
656    // the color used to highlight the touch rectangles
657    private static final int HIGHLIGHT_COLOR = 0x6633b5e5;
658    // the round corner for the highlight path
659    private static final float TOUCH_HIGHLIGHT_ARC = 5.0f;
660    // the region indicating where the user touched on the screen
661    private Region mTouchHighlightRegion = new Region();
662    // the paint for the touch highlight
663    private Paint mTouchHightlightPaint;
664    // debug only
665    private static final boolean DEBUG_TOUCH_HIGHLIGHT = true;
666    private static final int TOUCH_HIGHLIGHT_ELAPSE_TIME = 2000;
667    private Paint mTouchCrossHairColor;
668    private int mTouchHighlightX;
669    private int mTouchHighlightY;
670    private long mTouchHighlightRequested;
671
672    // Basically this proxy is used to tell the Video to update layer tree at
673    // SetBaseLayer time and to pause when WebView paused.
674    private HTML5VideoViewProxy mHTML5VideoViewProxy;
675
676    // If we are using a set picture, don't send view updates to webkit
677    private boolean mBlockWebkitViewMessages = false;
678
679    // cached value used to determine if we need to switch drawing models
680    private boolean mHardwareAccelSkia = false;
681
682    /*
683     * Private message ids
684     */
685    private static final int REMEMBER_PASSWORD          = 1;
686    private static final int NEVER_REMEMBER_PASSWORD    = 2;
687    private static final int SWITCH_TO_SHORTPRESS       = 3;
688    private static final int SWITCH_TO_LONGPRESS        = 4;
689    private static final int RELEASE_SINGLE_TAP         = 5;
690    private static final int REQUEST_FORM_DATA          = 6;
691    private static final int DRAG_HELD_MOTIONLESS       = 8;
692    private static final int AWAKEN_SCROLL_BARS         = 9;
693    private static final int PREVENT_DEFAULT_TIMEOUT    = 10;
694    private static final int SCROLL_SELECT_TEXT         = 11;
695
696
697    private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
698    private static final int LAST_PRIVATE_MSG_ID = SCROLL_SELECT_TEXT;
699
700    /*
701     * Package message ids
702     */
703    static final int SCROLL_TO_MSG_ID                   = 101;
704    static final int NEW_PICTURE_MSG_ID                 = 105;
705    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 106;
706    static final int WEBCORE_INITIALIZED_MSG_ID         = 107;
707    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 108;
708    static final int UPDATE_ZOOM_RANGE                  = 109;
709    static final int UNHANDLED_NAV_KEY                  = 110;
710    static final int CLEAR_TEXT_ENTRY                   = 111;
711    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 112;
712    static final int SHOW_RECT_MSG_ID                   = 113;
713    static final int LONG_PRESS_CENTER                  = 114;
714    static final int PREVENT_TOUCH_ID                   = 115;
715    static final int WEBCORE_NEED_TOUCH_EVENTS          = 116;
716    // obj=Rect in doc coordinates
717    static final int INVAL_RECT_MSG_ID                  = 117;
718    static final int REQUEST_KEYBOARD                   = 118;
719    static final int DO_MOTION_UP                       = 119;
720    static final int SHOW_FULLSCREEN                    = 120;
721    static final int HIDE_FULLSCREEN                    = 121;
722    static final int DOM_FOCUS_CHANGED                  = 122;
723    static final int REPLACE_BASE_CONTENT               = 123;
724    static final int FORM_DID_BLUR                      = 124;
725    static final int RETURN_LABEL                       = 125;
726    static final int FIND_AGAIN                         = 126;
727    static final int CENTER_FIT_RECT                    = 127;
728    static final int REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID = 128;
729    static final int SET_SCROLLBAR_MODES                = 129;
730    static final int SELECTION_STRING_CHANGED           = 130;
731    static final int SET_TOUCH_HIGHLIGHT_RECTS          = 131;
732    static final int SAVE_WEBARCHIVE_FINISHED           = 132;
733
734    static final int SET_AUTOFILLABLE                   = 133;
735    static final int AUTOFILL_COMPLETE                  = 134;
736
737    static final int SELECT_AT                          = 135;
738    static final int SCREEN_ON                          = 136;
739    static final int ENTER_FULLSCREEN_VIDEO             = 137;
740    static final int UPDATE_SELECTION                   = 138;
741
742    private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
743    private static final int LAST_PACKAGE_MSG_ID = SET_TOUCH_HIGHLIGHT_RECTS;
744
745    static final String[] HandlerPrivateDebugString = {
746        "REMEMBER_PASSWORD", //              = 1;
747        "NEVER_REMEMBER_PASSWORD", //        = 2;
748        "SWITCH_TO_SHORTPRESS", //           = 3;
749        "SWITCH_TO_LONGPRESS", //            = 4;
750        "RELEASE_SINGLE_TAP", //             = 5;
751        "REQUEST_FORM_DATA", //              = 6;
752        "RESUME_WEBCORE_PRIORITY", //        = 7;
753        "DRAG_HELD_MOTIONLESS", //           = 8;
754        "AWAKEN_SCROLL_BARS", //             = 9;
755        "PREVENT_DEFAULT_TIMEOUT", //        = 10;
756        "SCROLL_SELECT_TEXT" //              = 11;
757    };
758
759    static final String[] HandlerPackageDebugString = {
760        "SCROLL_TO_MSG_ID", //               = 101;
761        "102", //                            = 102;
762        "103", //                            = 103;
763        "104", //                            = 104;
764        "NEW_PICTURE_MSG_ID", //             = 105;
765        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 106;
766        "WEBCORE_INITIALIZED_MSG_ID", //     = 107;
767        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 108;
768        "UPDATE_ZOOM_RANGE", //              = 109;
769        "UNHANDLED_NAV_KEY", //              = 110;
770        "CLEAR_TEXT_ENTRY", //               = 111;
771        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 112;
772        "SHOW_RECT_MSG_ID", //               = 113;
773        "LONG_PRESS_CENTER", //              = 114;
774        "PREVENT_TOUCH_ID", //               = 115;
775        "WEBCORE_NEED_TOUCH_EVENTS", //      = 116;
776        "INVAL_RECT_MSG_ID", //              = 117;
777        "REQUEST_KEYBOARD", //               = 118;
778        "DO_MOTION_UP", //                   = 119;
779        "SHOW_FULLSCREEN", //                = 120;
780        "HIDE_FULLSCREEN", //                = 121;
781        "DOM_FOCUS_CHANGED", //              = 122;
782        "REPLACE_BASE_CONTENT", //           = 123;
783        "FORM_DID_BLUR", //                  = 124;
784        "RETURN_LABEL", //                   = 125;
785        "FIND_AGAIN", //                     = 126;
786        "CENTER_FIT_RECT", //                = 127;
787        "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128;
788        "SET_SCROLLBAR_MODES", //            = 129;
789        "SELECTION_STRING_CHANGED", //       = 130;
790        "SET_TOUCH_HIGHLIGHT_RECTS", //      = 131;
791        "SAVE_WEBARCHIVE_FINISHED", //       = 132;
792        "SET_AUTOFILLABLE", //               = 133;
793        "AUTOFILL_COMPLETE", //              = 134;
794        "SELECT_AT", //                      = 135;
795        "SCREEN_ON", //                      = 136;
796        "ENTER_FULLSCREEN_VIDEO" //          = 137;
797    };
798
799    // If the site doesn't use the viewport meta tag to specify the viewport,
800    // use DEFAULT_VIEWPORT_WIDTH as the default viewport width
801    static final int DEFAULT_VIEWPORT_WIDTH = 980;
802
803    // normally we try to fit the content to the minimum preferred width
804    // calculated by the Webkit. To avoid the bad behavior when some site's
805    // minimum preferred width keeps growing when changing the viewport width or
806    // the minimum preferred width is huge, an upper limit is needed.
807    static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH;
808
809    // initial scale in percent. 0 means using default.
810    private int mInitialScaleInPercent = 0;
811
812    // Whether or not a scroll event should be sent to webkit.  This is only set
813    // to false when restoring the scroll position.
814    private boolean mSendScrollEvent = true;
815
816    private int mSnapScrollMode = SNAP_NONE;
817    private static final int SNAP_NONE = 0;
818    private static final int SNAP_LOCK = 1; // not a separate state
819    private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
820    private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
821    private boolean mSnapPositive;
822
823    // keep these in sync with their counterparts in WebView.cpp
824    private static final int DRAW_EXTRAS_NONE = 0;
825    private static final int DRAW_EXTRAS_FIND = 1;
826    private static final int DRAW_EXTRAS_SELECTION = 2;
827    private static final int DRAW_EXTRAS_CURSOR_RING = 3;
828
829    // keep this in sync with WebCore:ScrollbarMode in WebKit
830    private static final int SCROLLBAR_AUTO = 0;
831    private static final int SCROLLBAR_ALWAYSOFF = 1;
832    // as we auto fade scrollbar, this is ignored.
833    private static final int SCROLLBAR_ALWAYSON = 2;
834    private int mHorizontalScrollBarMode = SCROLLBAR_AUTO;
835    private int mVerticalScrollBarMode = SCROLLBAR_AUTO;
836
837    // constants for determining script injection strategy
838    private static final int ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED = -1;
839    private static final int ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT = 0;
840    private static final int ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED = 1;
841
842    // the alias via which accessibility JavaScript interface is exposed
843    private static final String ALIAS_ACCESSIBILITY_JS_INTERFACE = "accessibility";
844
845    // JavaScript to inject the script chooser which will
846    // pick the right script for the current URL
847    private static final String ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT =
848        "javascript:(function() {" +
849        "    var chooser = document.createElement('script');" +
850        "    chooser.type = 'text/javascript';" +
851        "    chooser.src = 'https://ssl.gstatic.com/accessibility/javascript/android/AndroidScriptChooser.user.js';" +
852        "    document.getElementsByTagName('head')[0].appendChild(chooser);" +
853        "  })();";
854
855    // Regular expression that matches the "axs" URL parameter.
856    // The value of 0 means the accessibility script is opted out
857    // The value of 1 means the accessibility script is already injected
858    private static final String PATTERN_MATCH_AXS_URL_PARAMETER = "(\\?axs=(0|1))|(&axs=(0|1))";
859
860    // TextToSpeech instance exposed to JavaScript to the injected screenreader.
861    private TextToSpeech mTextToSpeech;
862
863    // variable to cache the above pattern in case accessibility is enabled.
864    private Pattern mMatchAxsUrlParameterPattern;
865
866    /**
867     * Max distance to overscroll by in pixels.
868     * This how far content can be pulled beyond its normal bounds by the user.
869     */
870    private int mOverscrollDistance;
871
872    /**
873     * Max distance to overfling by in pixels.
874     * This is how far flinged content can move beyond the end of its normal bounds.
875     */
876    private int mOverflingDistance;
877
878    private OverScrollGlow mOverScrollGlow;
879
880    // Used to match key downs and key ups
881    private Vector<Integer> mKeysPressed;
882
883    /* package */ static boolean mLogEvent = true;
884
885    // for event log
886    private long mLastTouchUpTime = 0;
887
888    private WebViewCore.AutoFillData mAutoFillData;
889
890    private static boolean sNotificationsEnabled = true;
891
892    /**
893     * URI scheme for telephone number
894     */
895    public static final String SCHEME_TEL = "tel:";
896    /**
897     * URI scheme for email address
898     */
899    public static final String SCHEME_MAILTO = "mailto:";
900    /**
901     * URI scheme for map address
902     */
903    public static final String SCHEME_GEO = "geo:0,0?q=";
904
905    private int mBackgroundColor = Color.WHITE;
906
907    private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second
908    private int mAutoScrollX = 0;
909    private int mAutoScrollY = 0;
910    private int mMinAutoScrollX = 0;
911    private int mMaxAutoScrollX = 0;
912    private int mMinAutoScrollY = 0;
913    private int mMaxAutoScrollY = 0;
914    private Rect mScrollingLayerBounds = new Rect();
915    private boolean mSentAutoScrollMessage = false;
916
917    // Temporary hack to work around the context removal upon memory pressure
918    private static boolean mIncrementEGLContextHack = false;
919
920    // used for serializing asynchronously handled touch events.
921    private final TouchEventQueue mTouchEventQueue = new TouchEventQueue();
922
923    // Used to track whether picture updating was paused due to a window focus change.
924    private boolean mPictureUpdatePausedForFocusChange = false;
925
926    // Used to notify listeners of a new picture.
927    private PictureListener mPictureListener;
928    /**
929     * Interface to listen for new pictures as they change.
930     * @deprecated This interface is now obsolete.
931     */
932    @Deprecated
933    public interface PictureListener {
934        /**
935         * Notify the listener that the picture has changed.
936         * @param view The WebView that owns the picture.
937         * @param picture The new picture.
938         * @deprecated This method is now obsolete.
939         */
940        @Deprecated
941        public void onNewPicture(WebView view, Picture picture);
942    }
943
944    // FIXME: Want to make this public, but need to change the API file.
945    public /*static*/ class HitTestResult {
946        /**
947         * Default HitTestResult, where the target is unknown
948         */
949        public static final int UNKNOWN_TYPE = 0;
950        /**
951         * @deprecated This type is no longer used.
952         */
953        @Deprecated
954        public static final int ANCHOR_TYPE = 1;
955        /**
956         * HitTestResult for hitting a phone number
957         */
958        public static final int PHONE_TYPE = 2;
959        /**
960         * HitTestResult for hitting a map address
961         */
962        public static final int GEO_TYPE = 3;
963        /**
964         * HitTestResult for hitting an email address
965         */
966        public static final int EMAIL_TYPE = 4;
967        /**
968         * HitTestResult for hitting an HTML::img tag
969         */
970        public static final int IMAGE_TYPE = 5;
971        /**
972         * @deprecated This type is no longer used.
973         */
974        @Deprecated
975        public static final int IMAGE_ANCHOR_TYPE = 6;
976        /**
977         * HitTestResult for hitting a HTML::a tag with src=http
978         */
979        public static final int SRC_ANCHOR_TYPE = 7;
980        /**
981         * HitTestResult for hitting a HTML::a tag with src=http + HTML::img
982         */
983        public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
984        /**
985         * HitTestResult for hitting an edit text area
986         */
987        public static final int EDIT_TEXT_TYPE = 9;
988
989        private int mType;
990        private String mExtra;
991
992        HitTestResult() {
993            mType = UNKNOWN_TYPE;
994        }
995
996        private void setType(int type) {
997            mType = type;
998        }
999
1000        private void setExtra(String extra) {
1001            mExtra = extra;
1002        }
1003
1004        public int getType() {
1005            return mType;
1006        }
1007
1008        public String getExtra() {
1009            return mExtra;
1010        }
1011    }
1012
1013    /**
1014     * Construct a new WebView with a Context object.
1015     * @param context A Context object used to access application assets.
1016     */
1017    public WebView(Context context) {
1018        this(context, null);
1019    }
1020
1021    /**
1022     * Construct a new WebView with layout parameters.
1023     * @param context A Context object used to access application assets.
1024     * @param attrs An AttributeSet passed to our parent.
1025     */
1026    public WebView(Context context, AttributeSet attrs) {
1027        this(context, attrs, com.android.internal.R.attr.webViewStyle);
1028    }
1029
1030    /**
1031     * Construct a new WebView with layout parameters and a default style.
1032     * @param context A Context object used to access application assets.
1033     * @param attrs An AttributeSet passed to our parent.
1034     * @param defStyle The default style resource ID.
1035     */
1036    public WebView(Context context, AttributeSet attrs, int defStyle) {
1037        this(context, attrs, defStyle, false);
1038    }
1039
1040    /**
1041     * Construct a new WebView with layout parameters and a default style.
1042     * @param context A Context object used to access application assets.
1043     * @param attrs An AttributeSet passed to our parent.
1044     * @param defStyle The default style resource ID.
1045     */
1046    public WebView(Context context, AttributeSet attrs, int defStyle,
1047            boolean privateBrowsing) {
1048        this(context, attrs, defStyle, null, privateBrowsing);
1049    }
1050
1051    /**
1052     * Construct a new WebView with layout parameters, a default style and a set
1053     * of custom Javscript interfaces to be added to the WebView at initialization
1054     * time. This guarantees that these interfaces will be available when the JS
1055     * context is initialized.
1056     * @param context A Context object used to access application assets.
1057     * @param attrs An AttributeSet passed to our parent.
1058     * @param defStyle The default style resource ID.
1059     * @param javaScriptInterfaces is a Map of interface names, as keys, and
1060     * object implementing those interfaces, as values.
1061     * @hide pending API council approval.
1062     */
1063    protected WebView(Context context, AttributeSet attrs, int defStyle,
1064            Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
1065        super(context, attrs, defStyle);
1066        checkThread();
1067
1068        if (context == null) {
1069            throw new IllegalArgumentException("Invalid context argument");
1070        }
1071
1072        // Used by the chrome stack to find application paths
1073        JniUtil.setContext(context);
1074
1075        mCallbackProxy = new CallbackProxy(context, this);
1076        mViewManager = new ViewManager(this);
1077        L10nUtils.setApplicationContext(context.getApplicationContext());
1078        mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javaScriptInterfaces);
1079        mDatabase = WebViewDatabase.getInstance(context);
1080        mScroller = new OverScroller(context, null, 0, 0, false); //TODO Use OverScroller's flywheel
1081        mZoomManager = new ZoomManager(this, mCallbackProxy);
1082
1083        /* The init method must follow the creation of certain member variables,
1084         * such as the mZoomManager.
1085         */
1086        init();
1087        setupPackageListener(context);
1088        setupProxyListener(context);
1089        updateMultiTouchSupport(context);
1090
1091        if (privateBrowsing) {
1092            startPrivateBrowsing();
1093        }
1094
1095        mAutoFillData = new WebViewCore.AutoFillData();
1096    }
1097
1098    private static class ProxyReceiver extends BroadcastReceiver {
1099        @Override
1100        public void onReceive(Context context, Intent intent) {
1101            if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
1102                handleProxyBroadcast(intent);
1103            }
1104        }
1105    }
1106
1107    /*
1108     * Receiver for PROXY_CHANGE_ACTION, will be null when it is not added handling broadcasts.
1109     */
1110    private static ProxyReceiver sProxyReceiver;
1111
1112    /*
1113     * @param context This method expects this to be a valid context
1114     */
1115    private static synchronized void setupProxyListener(Context context) {
1116        if (sProxyReceiver != null || sNotificationsEnabled == false) {
1117            return;
1118        }
1119        IntentFilter filter = new IntentFilter();
1120        filter.addAction(Proxy.PROXY_CHANGE_ACTION);
1121        sProxyReceiver = new ProxyReceiver();
1122        Intent currentProxy = context.getApplicationContext().registerReceiver(
1123                sProxyReceiver, filter);
1124        if (currentProxy != null) {
1125            handleProxyBroadcast(currentProxy);
1126        }
1127    }
1128
1129    /*
1130     * @param context This method expects this to be a valid context
1131     */
1132    private static synchronized void disableProxyListener(Context context) {
1133        if (sProxyReceiver == null)
1134            return;
1135
1136        context.getApplicationContext().unregisterReceiver(sProxyReceiver);
1137        sProxyReceiver = null;
1138    }
1139
1140    private static void handleProxyBroadcast(Intent intent) {
1141        ProxyProperties proxyProperties = (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
1142        if (proxyProperties == null || proxyProperties.getHost() == null) {
1143            WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, null);
1144            return;
1145        }
1146        WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, proxyProperties);
1147    }
1148
1149    /*
1150     * A variable to track if there is a receiver added for ACTION_PACKAGE_ADDED
1151     * or ACTION_PACKAGE_REMOVED.
1152     */
1153    private static boolean sPackageInstallationReceiverAdded = false;
1154
1155    /*
1156     * A set of Google packages we monitor for the
1157     * navigator.isApplicationInstalled() API. Add additional packages as
1158     * needed.
1159     */
1160    private static Set<String> sGoogleApps;
1161    static {
1162        sGoogleApps = new HashSet<String>();
1163        sGoogleApps.add("com.google.android.youtube");
1164    }
1165
1166    private static class PackageListener extends BroadcastReceiver {
1167        @Override
1168        public void onReceive(Context context, Intent intent) {
1169            final String action = intent.getAction();
1170            final String packageName = intent.getData().getSchemeSpecificPart();
1171            final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1172            if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
1173                // if it is replacing, refreshPlugins() when adding
1174                return;
1175            }
1176
1177            if (sGoogleApps.contains(packageName)) {
1178                if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1179                    WebViewCore.sendStaticMessage(EventHub.ADD_PACKAGE_NAME, packageName);
1180                } else {
1181                    WebViewCore.sendStaticMessage(EventHub.REMOVE_PACKAGE_NAME, packageName);
1182                }
1183            }
1184
1185            PluginManager pm = PluginManager.getInstance(context);
1186            if (pm.containsPluginPermissionAndSignatures(packageName)) {
1187                pm.refreshPlugins(Intent.ACTION_PACKAGE_ADDED.equals(action));
1188            }
1189        }
1190    }
1191
1192    private void setupPackageListener(Context context) {
1193
1194        /*
1195         * we must synchronize the instance check and the creation of the
1196         * receiver to ensure that only ONE receiver exists for all WebView
1197         * instances.
1198         */
1199        synchronized (WebView.class) {
1200
1201            // if the receiver already exists then we do not need to register it
1202            // again
1203            if (sPackageInstallationReceiverAdded) {
1204                return;
1205            }
1206
1207            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1208            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1209            filter.addDataScheme("package");
1210            BroadcastReceiver packageListener = new PackageListener();
1211            context.getApplicationContext().registerReceiver(packageListener, filter);
1212            sPackageInstallationReceiverAdded = true;
1213        }
1214
1215        // check if any of the monitored apps are already installed
1216        AsyncTask<Void, Void, Set<String>> task = new AsyncTask<Void, Void, Set<String>>() {
1217
1218            @Override
1219            protected Set<String> doInBackground(Void... unused) {
1220                Set<String> installedPackages = new HashSet<String>();
1221                PackageManager pm = mContext.getPackageManager();
1222                for (String name : sGoogleApps) {
1223                    try {
1224                        PackageInfo pInfo = pm.getPackageInfo(name,
1225                                PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
1226                        installedPackages.add(name);
1227                    } catch (PackageManager.NameNotFoundException e) {
1228                        // package not found
1229                    }
1230                }
1231                return installedPackages;
1232            }
1233
1234            // Executes on the UI thread
1235            @Override
1236            protected void onPostExecute(Set<String> installedPackages) {
1237                if (mWebViewCore != null) {
1238                    mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, installedPackages);
1239                }
1240            }
1241        };
1242        task.execute();
1243    }
1244
1245    void updateMultiTouchSupport(Context context) {
1246        mZoomManager.updateMultiTouchSupport(context);
1247    }
1248
1249    private void init() {
1250        OnTrimMemoryListener.init(getContext());
1251
1252        setWillNotDraw(false);
1253        setFocusable(true);
1254        setFocusableInTouchMode(true);
1255        setClickable(true);
1256        setLongClickable(true);
1257
1258        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
1259        int slop = configuration.getScaledTouchSlop();
1260        mTouchSlopSquare = slop * slop;
1261        slop = configuration.getScaledDoubleTapSlop();
1262        mDoubleTapSlopSquare = slop * slop;
1263        final float density = getContext().getResources().getDisplayMetrics().density;
1264        // use one line height, 16 based on our current default font, for how
1265        // far we allow a touch be away from the edge of a link
1266        mNavSlop = (int) (16 * density);
1267        mZoomManager.init(density);
1268        mMaximumFling = configuration.getScaledMaximumFlingVelocity();
1269
1270        // Compute the inverse of the density squared.
1271        DRAG_LAYER_INVERSE_DENSITY_SQUARED = 1 / (density * density);
1272
1273        mOverscrollDistance = configuration.getScaledOverscrollDistance();
1274        mOverflingDistance = configuration.getScaledOverflingDistance();
1275
1276        setScrollBarStyle(super.getScrollBarStyle());
1277        // Initially use a size of two, since the user is likely to only hold
1278        // down two keys at a time (shift + another key)
1279        mKeysPressed = new Vector<Integer>(2);
1280        mHTML5VideoViewProxy = null ;
1281    }
1282
1283    @Override
1284    public boolean shouldDelayChildPressedState() {
1285        return true;
1286    }
1287
1288    /**
1289     * Adds accessibility APIs to JavaScript.
1290     *
1291     * Note: This method is responsible to performing the necessary
1292     *       check if the accessibility APIs should be exposed.
1293     */
1294    private void addAccessibilityApisToJavaScript() {
1295        if (AccessibilityManager.getInstance(mContext).isEnabled()
1296                && getSettings().getJavaScriptEnabled()) {
1297            // exposing the TTS for now ...
1298            mTextToSpeech = new TextToSpeech(getContext(), null);
1299            addJavascriptInterface(mTextToSpeech, ALIAS_ACCESSIBILITY_JS_INTERFACE);
1300        }
1301    }
1302
1303    /**
1304     * Removes accessibility APIs from JavaScript.
1305     */
1306    private void removeAccessibilityApisFromJavaScript() {
1307        // exposing the TTS for now ...
1308        if (mTextToSpeech != null) {
1309            removeJavascriptInterface(ALIAS_ACCESSIBILITY_JS_INTERFACE);
1310            mTextToSpeech.shutdown();
1311            mTextToSpeech = null;
1312        }
1313    }
1314
1315    @Override
1316    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
1317        super.onInitializeAccessibilityNodeInfo(info);
1318        info.setScrollable(isScrollableForAccessibility());
1319    }
1320
1321    @Override
1322    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
1323        super.onInitializeAccessibilityEvent(event);
1324        event.setScrollable(isScrollableForAccessibility());
1325        event.setScrollX(mScrollX);
1326        event.setScrollY(mScrollY);
1327        final int convertedContentWidth = contentToViewX(getContentWidth());
1328        final int adjustedViewWidth = getWidth() - mPaddingLeft - mPaddingRight;
1329        event.setMaxScrollX(Math.max(convertedContentWidth - adjustedViewWidth, 0));
1330        final int convertedContentHeight = contentToViewY(getContentHeight());
1331        final int adjustedViewHeight = getHeight() - mPaddingTop - mPaddingBottom;
1332        event.setMaxScrollY(Math.max(convertedContentHeight - adjustedViewHeight, 0));
1333    }
1334
1335    private boolean isScrollableForAccessibility() {
1336        return (contentToViewX(getContentWidth()) > getWidth() - mPaddingLeft - mPaddingRight
1337                || contentToViewY(getContentHeight()) > getHeight() - mPaddingTop - mPaddingBottom);
1338    }
1339
1340    @Override
1341    public void setOverScrollMode(int mode) {
1342        super.setOverScrollMode(mode);
1343        if (mode != OVER_SCROLL_NEVER) {
1344            if (mOverScrollGlow == null) {
1345                mOverScrollGlow = new OverScrollGlow(this);
1346            }
1347        } else {
1348            mOverScrollGlow = null;
1349        }
1350    }
1351
1352    /* package */ void adjustDefaultZoomDensity(int zoomDensity) {
1353        final float density = mContext.getResources().getDisplayMetrics().density
1354                * 100 / zoomDensity;
1355        updateDefaultZoomDensity(density);
1356    }
1357
1358    /* package */ void updateDefaultZoomDensity(float density) {
1359        mNavSlop = (int) (16 * density);
1360        mZoomManager.updateDefaultZoomDensity(density);
1361    }
1362
1363    /* package */ boolean onSavePassword(String schemePlusHost, String username,
1364            String password, final Message resumeMsg) {
1365       boolean rVal = false;
1366       if (resumeMsg == null) {
1367           // null resumeMsg implies saving password silently
1368           mDatabase.setUsernamePassword(schemePlusHost, username, password);
1369       } else {
1370            final Message remember = mPrivateHandler.obtainMessage(
1371                    REMEMBER_PASSWORD);
1372            remember.getData().putString("host", schemePlusHost);
1373            remember.getData().putString("username", username);
1374            remember.getData().putString("password", password);
1375            remember.obj = resumeMsg;
1376
1377            final Message neverRemember = mPrivateHandler.obtainMessage(
1378                    NEVER_REMEMBER_PASSWORD);
1379            neverRemember.getData().putString("host", schemePlusHost);
1380            neverRemember.getData().putString("username", username);
1381            neverRemember.getData().putString("password", password);
1382            neverRemember.obj = resumeMsg;
1383
1384            new AlertDialog.Builder(getContext())
1385                    .setTitle(com.android.internal.R.string.save_password_label)
1386                    .setMessage(com.android.internal.R.string.save_password_message)
1387                    .setPositiveButton(com.android.internal.R.string.save_password_notnow,
1388                    new DialogInterface.OnClickListener() {
1389                        public void onClick(DialogInterface dialog, int which) {
1390                            resumeMsg.sendToTarget();
1391                        }
1392                    })
1393                    .setNeutralButton(com.android.internal.R.string.save_password_remember,
1394                    new DialogInterface.OnClickListener() {
1395                        public void onClick(DialogInterface dialog, int which) {
1396                            remember.sendToTarget();
1397                        }
1398                    })
1399                    .setNegativeButton(com.android.internal.R.string.save_password_never,
1400                    new DialogInterface.OnClickListener() {
1401                        public void onClick(DialogInterface dialog, int which) {
1402                            neverRemember.sendToTarget();
1403                        }
1404                    })
1405                    .setOnCancelListener(new OnCancelListener() {
1406                        public void onCancel(DialogInterface dialog) {
1407                            resumeMsg.sendToTarget();
1408                        }
1409                    }).show();
1410            // Return true so that WebViewCore will pause while the dialog is
1411            // up.
1412            rVal = true;
1413        }
1414       return rVal;
1415    }
1416
1417    @Override
1418    public void setScrollBarStyle(int style) {
1419        if (style == View.SCROLLBARS_INSIDE_INSET
1420                || style == View.SCROLLBARS_OUTSIDE_INSET) {
1421            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
1422        } else {
1423            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
1424        }
1425        super.setScrollBarStyle(style);
1426    }
1427
1428    /**
1429     * Specify whether the horizontal scrollbar has overlay style.
1430     * @param overlay TRUE if horizontal scrollbar should have overlay style.
1431     */
1432    public void setHorizontalScrollbarOverlay(boolean overlay) {
1433        checkThread();
1434        mOverlayHorizontalScrollbar = overlay;
1435    }
1436
1437    /**
1438     * Specify whether the vertical scrollbar has overlay style.
1439     * @param overlay TRUE if vertical scrollbar should have overlay style.
1440     */
1441    public void setVerticalScrollbarOverlay(boolean overlay) {
1442        checkThread();
1443        mOverlayVerticalScrollbar = overlay;
1444    }
1445
1446    /**
1447     * Return whether horizontal scrollbar has overlay style
1448     * @return TRUE if horizontal scrollbar has overlay style.
1449     */
1450    public boolean overlayHorizontalScrollbar() {
1451        checkThread();
1452        return mOverlayHorizontalScrollbar;
1453    }
1454
1455    /**
1456     * Return whether vertical scrollbar has overlay style
1457     * @return TRUE if vertical scrollbar has overlay style.
1458     */
1459    public boolean overlayVerticalScrollbar() {
1460        checkThread();
1461        return mOverlayVerticalScrollbar;
1462    }
1463
1464    /*
1465     * Return the width of the view where the content of WebView should render
1466     * to.
1467     * Note: this can be called from WebCoreThread.
1468     */
1469    /* package */ int getViewWidth() {
1470        if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
1471            return getWidth();
1472        } else {
1473            return Math.max(0, getWidth() - getVerticalScrollbarWidth());
1474        }
1475    }
1476
1477    /**
1478     * returns the height of the titlebarview (if any). Does not care about
1479     * scrolling
1480     * @hide
1481     */
1482    protected int getTitleHeight() {
1483        return mTitleBar != null ? mTitleBar.getHeight() : 0;
1484    }
1485
1486    /**
1487     * Return the amount of the titlebarview (if any) that is visible
1488     *
1489     * @deprecated This method is now obsolete.
1490     */
1491    public int getVisibleTitleHeight() {
1492        checkThread();
1493        return getVisibleTitleHeightImpl();
1494    }
1495
1496    private int getVisibleTitleHeightImpl() {
1497        // need to restrict mScrollY due to over scroll
1498        return Math.max(getTitleHeight() - Math.max(0, mScrollY),
1499                getOverlappingActionModeHeight());
1500    }
1501
1502    private int mCachedOverlappingActionModeHeight = -1;
1503
1504    private int getOverlappingActionModeHeight() {
1505        if (mFindCallback == null) {
1506            return 0;
1507        }
1508        if (mCachedOverlappingActionModeHeight < 0) {
1509            getGlobalVisibleRect(mGlobalVisibleRect, mGlobalVisibleOffset);
1510            mCachedOverlappingActionModeHeight = Math.max(0,
1511                    mFindCallback.getActionModeGlobalBottom() - mGlobalVisibleRect.top);
1512        }
1513        return mCachedOverlappingActionModeHeight;
1514    }
1515
1516    /*
1517     * Return the height of the view where the content of WebView should render
1518     * to.  Note that this excludes mTitleBar, if there is one.
1519     * Note: this can be called from WebCoreThread.
1520     */
1521    /* package */ int getViewHeight() {
1522        return getViewHeightWithTitle() - getVisibleTitleHeightImpl();
1523    }
1524
1525    int getViewHeightWithTitle() {
1526        int height = getHeight();
1527        if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
1528            height -= getHorizontalScrollbarHeight();
1529        }
1530        return height;
1531    }
1532
1533    /**
1534     * @return The SSL certificate for the main top-level page or null if
1535     * there is no certificate (the site is not secure).
1536     */
1537    public SslCertificate getCertificate() {
1538        checkThread();
1539        return mCertificate;
1540    }
1541
1542    /**
1543     * Sets the SSL certificate for the main top-level page.
1544     */
1545    public void setCertificate(SslCertificate certificate) {
1546        checkThread();
1547        if (DebugFlags.WEB_VIEW) {
1548            Log.v(LOGTAG, "setCertificate=" + certificate);
1549        }
1550        // here, the certificate can be null (if the site is not secure)
1551        mCertificate = certificate;
1552    }
1553
1554    //-------------------------------------------------------------------------
1555    // Methods called by activity
1556    //-------------------------------------------------------------------------
1557
1558    /**
1559     * Save the username and password for a particular host in the WebView's
1560     * internal database.
1561     * @param host The host that required the credentials.
1562     * @param username The username for the given host.
1563     * @param password The password for the given host.
1564     */
1565    public void savePassword(String host, String username, String password) {
1566        checkThread();
1567        mDatabase.setUsernamePassword(host, username, password);
1568    }
1569
1570    /**
1571     * Set the HTTP authentication credentials for a given host and realm.
1572     *
1573     * @param host The host for the credentials.
1574     * @param realm The realm for the credentials.
1575     * @param username The username for the password. If it is null, it means
1576     *                 password can't be saved.
1577     * @param password The password
1578     */
1579    public void setHttpAuthUsernamePassword(String host, String realm,
1580            String username, String password) {
1581        checkThread();
1582        mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
1583    }
1584
1585    /**
1586     * Retrieve the HTTP authentication username and password for a given
1587     * host & realm pair
1588     *
1589     * @param host The host for which the credentials apply.
1590     * @param realm The realm for which the credentials apply.
1591     * @return String[] if found, String[0] is username, which can be null and
1592     *         String[1] is password. Return null if it can't find anything.
1593     */
1594    public String[] getHttpAuthUsernamePassword(String host, String realm) {
1595        checkThread();
1596        return mDatabase.getHttpAuthUsernamePassword(host, realm);
1597    }
1598
1599    /**
1600     * Remove Find or Select ActionModes, if active.
1601     */
1602    private void clearActionModes() {
1603        if (mSelectCallback != null) {
1604            mSelectCallback.finish();
1605        }
1606        if (mFindCallback != null) {
1607            mFindCallback.finish();
1608        }
1609    }
1610
1611    /**
1612     * Called to clear state when moving from one page to another, or changing
1613     * in some other way that makes elements associated with the current page
1614     * (such as WebTextView or ActionModes) no longer relevant.
1615     */
1616    private void clearHelpers() {
1617        clearTextEntry();
1618        clearActionModes();
1619        dismissFullScreenMode();
1620    }
1621
1622    /**
1623     * Destroy the internal state of the WebView. This method should be called
1624     * after the WebView has been removed from the view system. No other
1625     * methods may be called on a WebView after destroy.
1626     */
1627    public void destroy() {
1628        checkThread();
1629        destroyImpl();
1630    }
1631
1632    private void destroyImpl() {
1633        clearHelpers();
1634        if (mListBoxDialog != null) {
1635            mListBoxDialog.dismiss();
1636            mListBoxDialog = null;
1637        }
1638        // remove so that it doesn't cause events
1639        if (mWebTextView != null) {
1640            mWebTextView.remove();
1641            mWebTextView = null;
1642        }
1643        if (mNativeClass != 0) nativeStopGL();
1644        if (mWebViewCore != null) {
1645            // Set the handlers to null before destroying WebViewCore so no
1646            // more messages will be posted.
1647            mCallbackProxy.setWebViewClient(null);
1648            mCallbackProxy.setWebChromeClient(null);
1649            // Tell WebViewCore to destroy itself
1650            synchronized (this) {
1651                WebViewCore webViewCore = mWebViewCore;
1652                mWebViewCore = null; // prevent using partial webViewCore
1653                webViewCore.destroy();
1654            }
1655            // Remove any pending messages that might not be serviced yet.
1656            mPrivateHandler.removeCallbacksAndMessages(null);
1657            mCallbackProxy.removeCallbacksAndMessages(null);
1658            // Wake up the WebCore thread just in case it is waiting for a
1659            // JavaScript dialog.
1660            synchronized (mCallbackProxy) {
1661                mCallbackProxy.notify();
1662            }
1663        }
1664        if (mNativeClass != 0) {
1665            nativeDestroy();
1666            mNativeClass = 0;
1667        }
1668    }
1669
1670    /**
1671     * Enables platform notifications of data state and proxy changes.
1672     * Notifications are enabled by default.
1673     *
1674     * @deprecated This method is now obsolete.
1675     */
1676    @Deprecated
1677    public static void enablePlatformNotifications() {
1678        checkThread();
1679        synchronized (WebView.class) {
1680            Network.enablePlatformNotifications();
1681            sNotificationsEnabled = true;
1682            Context context = JniUtil.getContext();
1683            if (context != null)
1684                setupProxyListener(context);
1685        }
1686    }
1687
1688    /**
1689     * Disables platform notifications of data state and proxy changes.
1690     * Notifications are enabled by default.
1691     *
1692     * @deprecated This method is now obsolete.
1693     */
1694    @Deprecated
1695    public static void disablePlatformNotifications() {
1696        checkThread();
1697        synchronized (WebView.class) {
1698            Network.disablePlatformNotifications();
1699            sNotificationsEnabled = false;
1700            Context context = JniUtil.getContext();
1701            if (context != null)
1702                disableProxyListener(context);
1703        }
1704    }
1705
1706    /**
1707     * Sets JavaScript engine flags.
1708     *
1709     * @param flags JS engine flags in a String
1710     *
1711     * @hide pending API solidification
1712     */
1713    public void setJsFlags(String flags) {
1714        checkThread();
1715        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
1716    }
1717
1718    /**
1719     * Inform WebView of the network state. This is used to set
1720     * the JavaScript property window.navigator.isOnline and
1721     * generates the online/offline event as specified in HTML5, sec. 5.7.7
1722     * @param networkUp boolean indicating if network is available
1723     */
1724    public void setNetworkAvailable(boolean networkUp) {
1725        checkThread();
1726        mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
1727                networkUp ? 1 : 0, 0);
1728    }
1729
1730    /**
1731     * Inform WebView about the current network type.
1732     * {@hide}
1733     */
1734    public void setNetworkType(String type, String subtype) {
1735        checkThread();
1736        Map<String, String> map = new HashMap<String, String>();
1737        map.put("type", type);
1738        map.put("subtype", subtype);
1739        mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map);
1740    }
1741    /**
1742     * Save the state of this WebView used in
1743     * {@link android.app.Activity#onSaveInstanceState}. Please note that this
1744     * method no longer stores the display data for this WebView. The previous
1745     * behavior could potentially leak files if {@link #restoreState} was never
1746     * called. See {@link #savePicture} and {@link #restorePicture} for saving
1747     * and restoring the display data.
1748     * @param outState The Bundle to store the WebView state.
1749     * @return The same copy of the back/forward list used to save the state. If
1750     *         saveState fails, the returned list will be null.
1751     * @see #savePicture
1752     * @see #restorePicture
1753     */
1754    public WebBackForwardList saveState(Bundle outState) {
1755        checkThread();
1756        if (outState == null) {
1757            return null;
1758        }
1759        // We grab a copy of the back/forward list because a client of WebView
1760        // may have invalidated the history list by calling clearHistory.
1761        WebBackForwardList list = copyBackForwardList();
1762        final int currentIndex = list.getCurrentIndex();
1763        final int size = list.getSize();
1764        // We should fail saving the state if the list is empty or the index is
1765        // not in a valid range.
1766        if (currentIndex < 0 || currentIndex >= size || size == 0) {
1767            return null;
1768        }
1769        outState.putInt("index", currentIndex);
1770        // FIXME: This should just be a byte[][] instead of ArrayList but
1771        // Parcel.java does not have the code to handle multi-dimensional
1772        // arrays.
1773        ArrayList<byte[]> history = new ArrayList<byte[]>(size);
1774        for (int i = 0; i < size; i++) {
1775            WebHistoryItem item = list.getItemAtIndex(i);
1776            if (null == item) {
1777                // FIXME: this shouldn't happen
1778                // need to determine how item got set to null
1779                Log.w(LOGTAG, "saveState: Unexpected null history item.");
1780                return null;
1781            }
1782            byte[] data = item.getFlattenedData();
1783            if (data == null) {
1784                // It would be very odd to not have any data for a given history
1785                // item. And we will fail to rebuild the history list without
1786                // flattened data.
1787                return null;
1788            }
1789            history.add(data);
1790        }
1791        outState.putSerializable("history", history);
1792        if (mCertificate != null) {
1793            outState.putBundle("certificate",
1794                               SslCertificate.saveState(mCertificate));
1795        }
1796        outState.putBoolean("privateBrowsingEnabled", isPrivateBrowsingEnabled());
1797        mZoomManager.saveZoomState(outState);
1798        return list;
1799    }
1800
1801    /**
1802     * Save the current display data to the Bundle given. Used in conjunction
1803     * with {@link #saveState}.
1804     * @param b A Bundle to store the display data.
1805     * @param dest The file to store the serialized picture data. Will be
1806     *             overwritten with this WebView's picture data.
1807     * @return True if the picture was successfully saved.
1808     * @deprecated This method is now obsolete.
1809     */
1810    @Deprecated
1811    public boolean savePicture(Bundle b, final File dest) {
1812        checkThread();
1813        if (dest == null || b == null) {
1814            return false;
1815        }
1816        final Picture p = capturePicture();
1817        // Use a temporary file while writing to ensure the destination file
1818        // contains valid data.
1819        final File temp = new File(dest.getPath() + ".writing");
1820        new Thread(new Runnable() {
1821            public void run() {
1822                FileOutputStream out = null;
1823                try {
1824                    out = new FileOutputStream(temp);
1825                    p.writeToStream(out);
1826                    // Writing the picture succeeded, rename the temporary file
1827                    // to the destination.
1828                    temp.renameTo(dest);
1829                } catch (Exception e) {
1830                    // too late to do anything about it.
1831                } finally {
1832                    if (out != null) {
1833                        try {
1834                            out.close();
1835                        } catch (Exception e) {
1836                            // Can't do anything about that
1837                        }
1838                    }
1839                    temp.delete();
1840                }
1841            }
1842        }).start();
1843        // now update the bundle
1844        b.putInt("scrollX", mScrollX);
1845        b.putInt("scrollY", mScrollY);
1846        mZoomManager.saveZoomState(b);
1847        return true;
1848    }
1849
1850    private void restoreHistoryPictureFields(Picture p, Bundle b) {
1851        int sx = b.getInt("scrollX", 0);
1852        int sy = b.getInt("scrollY", 0);
1853
1854        mDrawHistory = true;
1855        mHistoryPicture = p;
1856
1857        mScrollX = sx;
1858        mScrollY = sy;
1859        mZoomManager.restoreZoomState(b);
1860        final float scale = mZoomManager.getScale();
1861        mHistoryWidth = Math.round(p.getWidth() * scale);
1862        mHistoryHeight = Math.round(p.getHeight() * scale);
1863
1864        invalidate();
1865    }
1866
1867    /**
1868     * Restore the display data that was save in {@link #savePicture}. Used in
1869     * conjunction with {@link #restoreState}.
1870     *
1871     * Note that this will not work if the WebView is hardware accelerated.
1872     * @param b A Bundle containing the saved display data.
1873     * @param src The file where the picture data was stored.
1874     * @return True if the picture was successfully restored.
1875     * @deprecated This method is now obsolete.
1876     */
1877    @Deprecated
1878    public boolean restorePicture(Bundle b, File src) {
1879        checkThread();
1880        if (src == null || b == null) {
1881            return false;
1882        }
1883        if (!src.exists()) {
1884            return false;
1885        }
1886        try {
1887            final FileInputStream in = new FileInputStream(src);
1888            final Bundle copy = new Bundle(b);
1889            new Thread(new Runnable() {
1890                public void run() {
1891                    try {
1892                        final Picture p = Picture.createFromStream(in);
1893                        if (p != null) {
1894                            // Post a runnable on the main thread to update the
1895                            // history picture fields.
1896                            mPrivateHandler.post(new Runnable() {
1897                                public void run() {
1898                                    restoreHistoryPictureFields(p, copy);
1899                                }
1900                            });
1901                        }
1902                    } finally {
1903                        try {
1904                            in.close();
1905                        } catch (Exception e) {
1906                            // Nothing we can do now.
1907                        }
1908                    }
1909                }
1910            }).start();
1911        } catch (FileNotFoundException e){
1912            e.printStackTrace();
1913        }
1914        return true;
1915    }
1916
1917    /**
1918     * Saves the view data to the output stream. The output is highly
1919     * version specific, and may not be able to be loaded by newer versions
1920     * of WebView.
1921     * @param stream The {@link OutputStream} to save to
1922     * @return True if saved successfully
1923     * @hide
1924     */
1925    public boolean saveViewState(OutputStream stream) {
1926        try {
1927            return ViewStateSerializer.serializeViewState(stream, this);
1928        } catch (IOException e) {
1929            Log.w(LOGTAG, "Failed to saveViewState", e);
1930        }
1931        return false;
1932    }
1933
1934    /**
1935     * Loads the view data from the input stream. See
1936     * {@link #saveViewState(OutputStream)} for more information.
1937     * @param stream The {@link InputStream} to load from
1938     * @return True if loaded successfully
1939     * @hide
1940     */
1941    public boolean loadViewState(InputStream stream) {
1942        try {
1943            mLoadedPicture = ViewStateSerializer.deserializeViewState(stream, this);
1944            mBlockWebkitViewMessages = true;
1945            setNewPicture(mLoadedPicture, true);
1946            mLoadedPicture.mViewState = null;
1947            return true;
1948        } catch (IOException e) {
1949            Log.w(LOGTAG, "Failed to loadViewState", e);
1950        }
1951        return false;
1952    }
1953
1954    /**
1955     * Clears the view state set with {@link #loadViewState(InputStream)}.
1956     * This WebView will then switch to showing the content from webkit
1957     * @hide
1958     */
1959    public void clearViewState() {
1960        mBlockWebkitViewMessages = false;
1961        mLoadedPicture = null;
1962        invalidate();
1963    }
1964
1965    /**
1966     * Restore the state of this WebView from the given map used in
1967     * {@link android.app.Activity#onRestoreInstanceState}. This method should
1968     * be called to restore the state of the WebView before using the object. If
1969     * it is called after the WebView has had a chance to build state (load
1970     * pages, create a back/forward list, etc.) there may be undesirable
1971     * side-effects. Please note that this method no longer restores the
1972     * display data for this WebView. See {@link #savePicture} and {@link
1973     * #restorePicture} for saving and restoring the display data.
1974     * @param inState The incoming Bundle of state.
1975     * @return The restored back/forward list or null if restoreState failed.
1976     * @see #savePicture
1977     * @see #restorePicture
1978     */
1979    public WebBackForwardList restoreState(Bundle inState) {
1980        checkThread();
1981        WebBackForwardList returnList = null;
1982        if (inState == null) {
1983            return returnList;
1984        }
1985        if (inState.containsKey("index") && inState.containsKey("history")) {
1986            mCertificate = SslCertificate.restoreState(
1987                inState.getBundle("certificate"));
1988
1989            final WebBackForwardList list = mCallbackProxy.getBackForwardList();
1990            final int index = inState.getInt("index");
1991            // We can't use a clone of the list because we need to modify the
1992            // shared copy, so synchronize instead to prevent concurrent
1993            // modifications.
1994            synchronized (list) {
1995                final List<byte[]> history =
1996                        (List<byte[]>) inState.getSerializable("history");
1997                final int size = history.size();
1998                // Check the index bounds so we don't crash in native code while
1999                // restoring the history index.
2000                if (index < 0 || index >= size) {
2001                    return null;
2002                }
2003                for (int i = 0; i < size; i++) {
2004                    byte[] data = history.remove(0);
2005                    if (data == null) {
2006                        // If we somehow have null data, we cannot reconstruct
2007                        // the item and thus our history list cannot be rebuilt.
2008                        return null;
2009                    }
2010                    WebHistoryItem item = new WebHistoryItem(data);
2011                    list.addHistoryItem(item);
2012                }
2013                // Grab the most recent copy to return to the caller.
2014                returnList = copyBackForwardList();
2015                // Update the copy to have the correct index.
2016                returnList.setCurrentIndex(index);
2017            }
2018            // Restore private browsing setting.
2019            if (inState.getBoolean("privateBrowsingEnabled")) {
2020                getSettings().setPrivateBrowsingEnabled(true);
2021            }
2022            mZoomManager.restoreZoomState(inState);
2023            // Remove all pending messages because we are restoring previous
2024            // state.
2025            mWebViewCore.removeMessages();
2026            // Send a restore state message.
2027            mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
2028        }
2029        return returnList;
2030    }
2031
2032    /**
2033     * Load the given URL with the specified additional HTTP headers.
2034     * @param url The URL of the resource to load.
2035     * @param additionalHttpHeaders The additional headers to be used in the
2036     *            HTTP request for this URL, specified as a map from name to
2037     *            value. Note that if this map contains any of the headers
2038     *            that are set by default by the WebView, such as those
2039     *            controlling caching, accept types or the User-Agent, their
2040     *            values may be overriden by the WebView's defaults.
2041     */
2042    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
2043        checkThread();
2044        loadUrlImpl(url, additionalHttpHeaders);
2045    }
2046
2047    private void loadUrlImpl(String url, Map<String, String> extraHeaders) {
2048        switchOutDrawHistory();
2049        WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData();
2050        arg.mUrl = url;
2051        arg.mExtraHeaders = extraHeaders;
2052        mWebViewCore.sendMessage(EventHub.LOAD_URL, arg);
2053        clearHelpers();
2054    }
2055
2056    /**
2057     * Load the given URL.
2058     * @param url The URL of the resource to load.
2059     */
2060    public void loadUrl(String url) {
2061        checkThread();
2062        loadUrlImpl(url);
2063    }
2064
2065    private void loadUrlImpl(String url) {
2066        if (url == null) {
2067            return;
2068        }
2069        loadUrlImpl(url, null);
2070    }
2071
2072    /**
2073     * Load the url with postData using "POST" method into the WebView. If url
2074     * is not a network url, it will be loaded with {link
2075     * {@link #loadUrl(String)} instead.
2076     *
2077     * @param url The url of the resource to load.
2078     * @param postData The data will be passed to "POST" request.
2079     */
2080    public void postUrl(String url, byte[] postData) {
2081        checkThread();
2082        if (URLUtil.isNetworkUrl(url)) {
2083            switchOutDrawHistory();
2084            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
2085            arg.mUrl = url;
2086            arg.mPostData = postData;
2087            mWebViewCore.sendMessage(EventHub.POST_URL, arg);
2088            clearHelpers();
2089        } else {
2090            loadUrlImpl(url);
2091        }
2092    }
2093
2094    /**
2095     * Load the given data into the WebView using a 'data' scheme URL.
2096     * <p>
2097     * Note that JavaScript's same origin policy means that script running in a
2098     * page loaded using this method will be unable to access content loaded
2099     * using any scheme other than 'data', including 'http(s)'. To avoid this
2100     * restriction, use {@link
2101     * #loadDataWithBaseURL(String,String,String,String,String)
2102     * loadDataWithBaseURL()} with an appropriate base URL.
2103     * <p>
2104     * If the value of the encoding parameter is 'base64', then the data must
2105     * be encoded as base64. Otherwise, the data must use ASCII encoding for
2106     * octets inside the range of safe URL characters and use the standard %xx
2107     * hex encoding of URLs for octets outside that range. For example,
2108     * '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
2109     * <p>
2110     * The 'data' scheme URL formed by this method uses the default US-ASCII
2111     * charset. If you need need to set a different charset, you should form a
2112     * 'data' scheme URL which explicitly specifies a charset parameter in the
2113     * mediatype portion of the URL and call {@link #loadUrl(String)} instead.
2114     * Note that the charset obtained from the mediatype portion of a data URL
2115     * always overrides that specified in the HTML or XML document itself.
2116     * @param data A String of data in the given encoding.
2117     * @param mimeType The MIME type of the data, e.g. 'text/html'.
2118     * @param encoding The encoding of the data.
2119     */
2120    public void loadData(String data, String mimeType, String encoding) {
2121        checkThread();
2122        loadDataImpl(data, mimeType, encoding);
2123    }
2124
2125    private void loadDataImpl(String data, String mimeType, String encoding) {
2126        StringBuilder dataUrl = new StringBuilder("data:");
2127        dataUrl.append(mimeType);
2128        if ("base64".equals(encoding)) {
2129            dataUrl.append(";base64");
2130        }
2131        dataUrl.append(",");
2132        dataUrl.append(data);
2133        loadUrlImpl(dataUrl.toString());
2134    }
2135
2136    /**
2137     * Load the given data into the WebView, using baseUrl as the base URL for
2138     * the content. The base URL is used both to resolve relative URLs and when
2139     * applying JavaScript's same origin policy. The historyUrl is used for the
2140     * history entry.
2141     * <p>
2142     * Note that content specified in this way can access local device files
2143     * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
2144     * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
2145     * <p>
2146     * If the base URL uses the data scheme, this method is equivalent to
2147     * calling {@link #loadData(String,String,String) loadData()} and the
2148     * historyUrl is ignored.
2149     * @param baseUrl URL to use as the page's base URL. If null defaults to
2150     *            'about:blank'
2151     * @param data A String of data in the given encoding.
2152     * @param mimeType The MIMEType of the data, e.g. 'text/html'. If null,
2153     *            defaults to 'text/html'.
2154     * @param encoding The encoding of the data.
2155     * @param historyUrl URL to use as the history entry, if null defaults to
2156     *            'about:blank'.
2157     */
2158    public void loadDataWithBaseURL(String baseUrl, String data,
2159            String mimeType, String encoding, String historyUrl) {
2160        checkThread();
2161
2162        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
2163            loadDataImpl(data, mimeType, encoding);
2164            return;
2165        }
2166        switchOutDrawHistory();
2167        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
2168        arg.mBaseUrl = baseUrl;
2169        arg.mData = data;
2170        arg.mMimeType = mimeType;
2171        arg.mEncoding = encoding;
2172        arg.mHistoryUrl = historyUrl;
2173        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
2174        clearHelpers();
2175    }
2176
2177    /**
2178     * Saves the current view as a web archive.
2179     *
2180     * @param filename The filename where the archive should be placed.
2181     */
2182    public void saveWebArchive(String filename) {
2183        checkThread();
2184        saveWebArchiveImpl(filename, false, null);
2185    }
2186
2187    /* package */ static class SaveWebArchiveMessage {
2188        SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback<String> callback) {
2189            mBasename = basename;
2190            mAutoname = autoname;
2191            mCallback = callback;
2192        }
2193
2194        /* package */ final String mBasename;
2195        /* package */ final boolean mAutoname;
2196        /* package */ final ValueCallback<String> mCallback;
2197        /* package */ String mResultFile;
2198    }
2199
2200    /**
2201     * Saves the current view as a web archive.
2202     *
2203     * @param basename The filename where the archive should be placed.
2204     * @param autoname If false, takes basename to be a file. If true, basename
2205     *                 is assumed to be a directory in which a filename will be
2206     *                 chosen according to the url of the current page.
2207     * @param callback Called after the web archive has been saved. The
2208     *                 parameter for onReceiveValue will either be the filename
2209     *                 under which the file was saved, or null if saving the
2210     *                 file failed.
2211     */
2212    public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
2213        checkThread();
2214        saveWebArchiveImpl(basename, autoname, callback);
2215    }
2216
2217    private void saveWebArchiveImpl(String basename, boolean autoname,
2218            ValueCallback<String> callback) {
2219        mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE,
2220            new SaveWebArchiveMessage(basename, autoname, callback));
2221    }
2222
2223    /**
2224     * Stop the current load.
2225     */
2226    public void stopLoading() {
2227        checkThread();
2228        // TODO: should we clear all the messages in the queue before sending
2229        // STOP_LOADING?
2230        switchOutDrawHistory();
2231        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
2232    }
2233
2234    /**
2235     * Reload the current url.
2236     */
2237    public void reload() {
2238        checkThread();
2239        clearHelpers();
2240        switchOutDrawHistory();
2241        mWebViewCore.sendMessage(EventHub.RELOAD);
2242    }
2243
2244    /**
2245     * Return true if this WebView has a back history item.
2246     * @return True iff this WebView has a back history item.
2247     */
2248    public boolean canGoBack() {
2249        checkThread();
2250        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2251        synchronized (l) {
2252            if (l.getClearPending()) {
2253                return false;
2254            } else {
2255                return l.getCurrentIndex() > 0;
2256            }
2257        }
2258    }
2259
2260    /**
2261     * Go back in the history of this WebView.
2262     */
2263    public void goBack() {
2264        checkThread();
2265        goBackOrForwardImpl(-1);
2266    }
2267
2268    /**
2269     * Return true if this WebView has a forward history item.
2270     * @return True iff this Webview has a forward history item.
2271     */
2272    public boolean canGoForward() {
2273        checkThread();
2274        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2275        synchronized (l) {
2276            if (l.getClearPending()) {
2277                return false;
2278            } else {
2279                return l.getCurrentIndex() < l.getSize() - 1;
2280            }
2281        }
2282    }
2283
2284    /**
2285     * Go forward in the history of this WebView.
2286     */
2287    public void goForward() {
2288        checkThread();
2289        goBackOrForwardImpl(1);
2290    }
2291
2292    /**
2293     * Return true if the page can go back or forward the given
2294     * number of steps.
2295     * @param steps The negative or positive number of steps to move the
2296     *              history.
2297     */
2298    public boolean canGoBackOrForward(int steps) {
2299        checkThread();
2300        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2301        synchronized (l) {
2302            if (l.getClearPending()) {
2303                return false;
2304            } else {
2305                int newIndex = l.getCurrentIndex() + steps;
2306                return newIndex >= 0 && newIndex < l.getSize();
2307            }
2308        }
2309    }
2310
2311    /**
2312     * Go to the history item that is the number of steps away from
2313     * the current item. Steps is negative if backward and positive
2314     * if forward.
2315     * @param steps The number of steps to take back or forward in the back
2316     *              forward list.
2317     */
2318    public void goBackOrForward(int steps) {
2319        checkThread();
2320        goBackOrForwardImpl(steps);
2321    }
2322
2323    private void goBackOrForwardImpl(int steps) {
2324        goBackOrForward(steps, false);
2325    }
2326
2327    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
2328        if (steps != 0) {
2329            clearHelpers();
2330            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
2331                    ignoreSnapshot ? 1 : 0);
2332        }
2333    }
2334
2335    /**
2336     * Returns true if private browsing is enabled in this WebView.
2337     */
2338    public boolean isPrivateBrowsingEnabled() {
2339        checkThread();
2340        return getSettings().isPrivateBrowsingEnabled();
2341    }
2342
2343    private void startPrivateBrowsing() {
2344        getSettings().setPrivateBrowsingEnabled(true);
2345    }
2346
2347    private boolean extendScroll(int y) {
2348        int finalY = mScroller.getFinalY();
2349        int newY = pinLocY(finalY + y);
2350        if (newY == finalY) return false;
2351        mScroller.setFinalY(newY);
2352        mScroller.extendDuration(computeDuration(0, y));
2353        return true;
2354    }
2355
2356    /**
2357     * Scroll the contents of the view up by half the view size
2358     * @param top true to jump to the top of the page
2359     * @return true if the page was scrolled
2360     */
2361    public boolean pageUp(boolean top) {
2362        checkThread();
2363        if (mNativeClass == 0) {
2364            return false;
2365        }
2366        nativeClearCursor(); // start next trackball movement from page edge
2367        if (top) {
2368            // go to the top of the document
2369            return pinScrollTo(mScrollX, 0, true, 0);
2370        }
2371        // Page up
2372        int h = getHeight();
2373        int y;
2374        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2375            y = -h + PAGE_SCROLL_OVERLAP;
2376        } else {
2377            y = -h / 2;
2378        }
2379        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2380                : extendScroll(y);
2381    }
2382
2383    /**
2384     * Scroll the contents of the view down by half the page size
2385     * @param bottom true to jump to bottom of page
2386     * @return true if the page was scrolled
2387     */
2388    public boolean pageDown(boolean bottom) {
2389        checkThread();
2390        if (mNativeClass == 0) {
2391            return false;
2392        }
2393        nativeClearCursor(); // start next trackball movement from page edge
2394        if (bottom) {
2395            return pinScrollTo(mScrollX, computeRealVerticalScrollRange(), true, 0);
2396        }
2397        // Page down.
2398        int h = getHeight();
2399        int y;
2400        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2401            y = h - PAGE_SCROLL_OVERLAP;
2402        } else {
2403            y = h / 2;
2404        }
2405        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2406                : extendScroll(y);
2407    }
2408
2409    /**
2410     * Clear the view so that onDraw() will draw nothing but white background,
2411     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
2412     */
2413    public void clearView() {
2414        checkThread();
2415        mContentWidth = 0;
2416        mContentHeight = 0;
2417        setBaseLayer(0, null, false, false, false);
2418        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
2419    }
2420
2421    /**
2422     * Return a new picture that captures the current display of the webview.
2423     * This is a copy of the display, and will be unaffected if the webview
2424     * later loads a different URL.
2425     *
2426     * @return a picture containing the current contents of the view. Note this
2427     *         picture is of the entire document, and is not restricted to the
2428     *         bounds of the view.
2429     */
2430    public Picture capturePicture() {
2431        checkThread();
2432        if (mNativeClass == 0) return null;
2433        Picture result = new Picture();
2434        nativeCopyBaseContentToPicture(result);
2435        return result;
2436    }
2437
2438    /**
2439     *  Return true if the browser is displaying a TextView for text input.
2440     */
2441    private boolean inEditingMode() {
2442        return mWebTextView != null && mWebTextView.getParent() != null;
2443    }
2444
2445    /**
2446     * Remove the WebTextView.
2447     */
2448    private void clearTextEntry() {
2449        if (inEditingMode()) {
2450            mWebTextView.remove();
2451        } else {
2452            // The keyboard may be open with the WebView as the served view
2453            hideSoftKeyboard();
2454        }
2455    }
2456
2457    /**
2458     * Return the current scale of the WebView
2459     * @return The current scale.
2460     */
2461    public float getScale() {
2462        checkThread();
2463        return mZoomManager.getScale();
2464    }
2465
2466    // Called by JNI. Returns the scale to apply to the text selection handles
2467    /* package */ float getTextHandleScale() {
2468        float density = mContext.getResources().getDisplayMetrics().density;
2469        return density / getScale();
2470    }
2471
2472    /**
2473     * Return the reading level scale of the WebView
2474     * @return The reading level scale.
2475     */
2476    /*package*/ float getReadingLevelScale() {
2477        return mZoomManager.getReadingLevelScale();
2478    }
2479
2480    /**
2481     * Set the initial scale for the WebView. 0 means default. If
2482     * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
2483     * way. Otherwise it starts with 100%. If initial scale is greater than 0,
2484     * WebView starts with this value as initial scale.
2485     * Please note that unlike the scale properties in the viewport meta tag,
2486     * this method doesn't take the screen density into account.
2487     *
2488     * @param scaleInPercent The initial scale in percent.
2489     */
2490    public void setInitialScale(int scaleInPercent) {
2491        checkThread();
2492        mZoomManager.setInitialScaleInPercent(scaleInPercent);
2493    }
2494
2495    /**
2496     * Invoke the graphical zoom picker widget for this WebView. This will
2497     * result in the zoom widget appearing on the screen to control the zoom
2498     * level of this WebView.
2499     */
2500    public void invokeZoomPicker() {
2501        checkThread();
2502        if (!getSettings().supportZoom()) {
2503            Log.w(LOGTAG, "This WebView doesn't support zoom.");
2504            return;
2505        }
2506        clearHelpers();
2507        mZoomManager.invokeZoomPicker();
2508    }
2509
2510    /**
2511     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
2512     * is found and the anchor has a non-JavaScript url, the HitTestResult type
2513     * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
2514     * anchor does not have a url or if it is a JavaScript url, the type will
2515     * be UNKNOWN_TYPE and the url has to be retrieved through
2516     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
2517     * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
2518     * the "extra" field. A type of
2519     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
2520     * a child node. If a phone number is found, the HitTestResult type is set
2521     * to PHONE_TYPE and the phone number is set in the "extra" field of
2522     * HitTestResult. If a map address is found, the HitTestResult type is set
2523     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
2524     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
2525     * and the email is set in the "extra" field of HitTestResult. Otherwise,
2526     * HitTestResult type is set to UNKNOWN_TYPE.
2527     */
2528    public HitTestResult getHitTestResult() {
2529        checkThread();
2530        return hitTestResult(mInitialHitTestResult);
2531    }
2532
2533    private HitTestResult hitTestResult(HitTestResult fallback) {
2534        if (mNativeClass == 0) {
2535            return null;
2536        }
2537
2538        HitTestResult result = new HitTestResult();
2539        if (nativeHasCursorNode()) {
2540            if (nativeCursorIsTextInput()) {
2541                result.setType(HitTestResult.EDIT_TEXT_TYPE);
2542            } else {
2543                String text = nativeCursorText();
2544                if (text != null) {
2545                    if (text.startsWith(SCHEME_TEL)) {
2546                        result.setType(HitTestResult.PHONE_TYPE);
2547                        result.setExtra(text.substring(SCHEME_TEL.length()));
2548                    } else if (text.startsWith(SCHEME_MAILTO)) {
2549                        result.setType(HitTestResult.EMAIL_TYPE);
2550                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
2551                    } else if (text.startsWith(SCHEME_GEO)) {
2552                        result.setType(HitTestResult.GEO_TYPE);
2553                        result.setExtra(URLDecoder.decode(text
2554                                .substring(SCHEME_GEO.length())));
2555                    } else if (nativeCursorIsAnchor()) {
2556                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
2557                        result.setExtra(text);
2558                    }
2559                }
2560            }
2561        } else if (fallback != null) {
2562            /* If webkit causes a rebuild while the long press is in progress,
2563             * the cursor node may be reset, even if it is still around. This
2564             * uses the cursor node saved when the touch began. Since the
2565             * nativeImageURI below only changes the result if it is successful,
2566             * this uses the data beneath the touch if available or the original
2567             * tap data otherwise.
2568             */
2569            Log.v(LOGTAG, "hitTestResult use fallback");
2570            result = fallback;
2571        }
2572        int type = result.getType();
2573        if (type == HitTestResult.UNKNOWN_TYPE
2574                || type == HitTestResult.SRC_ANCHOR_TYPE) {
2575            // Now check to see if it is an image.
2576            int contentX = viewToContentX(mLastTouchX + mScrollX);
2577            int contentY = viewToContentY(mLastTouchY + mScrollY);
2578            String text = nativeImageURI(contentX, contentY);
2579            if (text != null) {
2580                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
2581                        HitTestResult.IMAGE_TYPE :
2582                        HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
2583                result.setExtra(text);
2584            }
2585        }
2586        return result;
2587    }
2588
2589    // Called by JNI when the DOM has changed the focus.  Clear the focus so
2590    // that new keys will go to the newly focused field
2591    private void domChangedFocus() {
2592        if (inEditingMode()) {
2593            mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget();
2594        }
2595    }
2596    /**
2597     * Request the anchor or image element URL at the last tapped point.
2598     * If hrefMsg is null, this method returns immediately and does not
2599     * dispatch hrefMsg to its target. If the tapped point hits an image,
2600     * an anchor, or an image in an anchor, the message associates
2601     * strings in named keys in its data. The value paired with the key
2602     * may be an empty string.
2603     *
2604     * @param hrefMsg This message will be dispatched with the result of the
2605     *                request. The message data contains three keys:
2606     *                - "url" returns the anchor's href attribute.
2607     *                - "title" returns the anchor's text.
2608     *                - "src" returns the image's src attribute.
2609     */
2610    public void requestFocusNodeHref(Message hrefMsg) {
2611        checkThread();
2612        if (hrefMsg == null) {
2613            return;
2614        }
2615        int contentX = viewToContentX(mLastTouchX + mScrollX);
2616        int contentY = viewToContentY(mLastTouchY + mScrollY);
2617        if (nativeHasCursorNode()) {
2618            Rect cursorBounds = nativeGetCursorRingBounds();
2619            if (!cursorBounds.contains(contentX, contentY)) {
2620                int slop = viewToContentDimension(mNavSlop);
2621                cursorBounds.inset(-slop, -slop);
2622                if (cursorBounds.contains(contentX, contentY)) {
2623                    contentX = (int) cursorBounds.centerX();
2624                    contentY = (int) cursorBounds.centerY();
2625                }
2626            }
2627        }
2628        mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
2629                contentX, contentY, hrefMsg);
2630    }
2631
2632    /**
2633     * Request the url of the image last touched by the user. msg will be sent
2634     * to its target with a String representing the url as its object.
2635     *
2636     * @param msg This message will be dispatched with the result of the request
2637     *            as the data member with "url" as key. The result can be null.
2638     */
2639    public void requestImageRef(Message msg) {
2640        checkThread();
2641        if (0 == mNativeClass) return; // client isn't initialized
2642        int contentX = viewToContentX(mLastTouchX + mScrollX);
2643        int contentY = viewToContentY(mLastTouchY + mScrollY);
2644        String ref = nativeImageURI(contentX, contentY);
2645        Bundle data = msg.getData();
2646        data.putString("url", ref);
2647        msg.setData(data);
2648        msg.sendToTarget();
2649    }
2650
2651    static int pinLoc(int x, int viewMax, int docMax) {
2652//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
2653        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
2654            // pin the short document to the top/left of the screen
2655            x = 0;
2656//            Log.d(LOGTAG, "--- center " + x);
2657        } else if (x < 0) {
2658            x = 0;
2659//            Log.d(LOGTAG, "--- zero");
2660        } else if (x + viewMax > docMax) {
2661            x = docMax - viewMax;
2662//            Log.d(LOGTAG, "--- pin " + x);
2663        }
2664        return x;
2665    }
2666
2667    // Expects x in view coordinates
2668    int pinLocX(int x) {
2669        if (mInOverScrollMode) return x;
2670        return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange());
2671    }
2672
2673    // Expects y in view coordinates
2674    int pinLocY(int y) {
2675        if (mInOverScrollMode) return y;
2676        return pinLoc(y, getViewHeightWithTitle(),
2677                      computeRealVerticalScrollRange() + getTitleHeight());
2678    }
2679
2680    /**
2681     * A title bar which is embedded in this WebView, and scrolls along with it
2682     * vertically, but not horizontally.
2683     */
2684    private View mTitleBar;
2685
2686    /**
2687     * the title bar rendering gravity
2688     */
2689    private int mTitleGravity;
2690
2691    /**
2692     * Add or remove a title bar to be embedded into the WebView, and scroll
2693     * along with it vertically, while remaining in view horizontally. Pass
2694     * null to remove the title bar from the WebView, and return to drawing
2695     * the WebView normally without translating to account for the title bar.
2696     * @hide
2697     */
2698    public void setEmbeddedTitleBar(View v) {
2699        if (mTitleBar == v) return;
2700        if (mTitleBar != null) {
2701            removeView(mTitleBar);
2702        }
2703        if (null != v) {
2704            addView(v, new AbsoluteLayout.LayoutParams(
2705                    ViewGroup.LayoutParams.MATCH_PARENT,
2706                    ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
2707        }
2708        mTitleBar = v;
2709    }
2710
2711    /**
2712     * Set where to render the embedded title bar
2713     * NO_GRAVITY at the top of the page
2714     * TOP        at the top of the screen
2715     * @hide
2716     */
2717    public void setTitleBarGravity(int gravity) {
2718        mTitleGravity = gravity;
2719        // force refresh
2720        invalidate();
2721    }
2722
2723    /**
2724     * Given a distance in view space, convert it to content space. Note: this
2725     * does not reflect translation, just scaling, so this should not be called
2726     * with coordinates, but should be called for dimensions like width or
2727     * height.
2728     */
2729    private int viewToContentDimension(int d) {
2730        return Math.round(d * mZoomManager.getInvScale());
2731    }
2732
2733    /**
2734     * Given an x coordinate in view space, convert it to content space.  Also
2735     * may be used for absolute heights (such as for the WebTextView's
2736     * textSize, which is unaffected by the height of the title bar).
2737     */
2738    /*package*/ int viewToContentX(int x) {
2739        return viewToContentDimension(x);
2740    }
2741
2742    /**
2743     * Given a y coordinate in view space, convert it to content space.
2744     * Takes into account the height of the title bar if there is one
2745     * embedded into the WebView.
2746     */
2747    /*package*/ int viewToContentY(int y) {
2748        return viewToContentDimension(y - getTitleHeight());
2749    }
2750
2751    /**
2752     * Given a x coordinate in view space, convert it to content space.
2753     * Returns the result as a float.
2754     */
2755    private float viewToContentXf(int x) {
2756        return x * mZoomManager.getInvScale();
2757    }
2758
2759    /**
2760     * Given a y coordinate in view space, convert it to content space.
2761     * Takes into account the height of the title bar if there is one
2762     * embedded into the WebView. Returns the result as a float.
2763     */
2764    private float viewToContentYf(int y) {
2765        return (y - getTitleHeight()) * mZoomManager.getInvScale();
2766    }
2767
2768    /**
2769     * Given a distance in content space, convert it to view space. Note: this
2770     * does not reflect translation, just scaling, so this should not be called
2771     * with coordinates, but should be called for dimensions like width or
2772     * height.
2773     */
2774    /*package*/ int contentToViewDimension(int d) {
2775        return Math.round(d * mZoomManager.getScale());
2776    }
2777
2778    /**
2779     * Given an x coordinate in content space, convert it to view
2780     * space.
2781     */
2782    /*package*/ int contentToViewX(int x) {
2783        return contentToViewDimension(x);
2784    }
2785
2786    /**
2787     * Given a y coordinate in content space, convert it to view
2788     * space.  Takes into account the height of the title bar.
2789     */
2790    /*package*/ int contentToViewY(int y) {
2791        return contentToViewDimension(y) + getTitleHeight();
2792    }
2793
2794    private Rect contentToViewRect(Rect x) {
2795        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
2796                        contentToViewX(x.right), contentToViewY(x.bottom));
2797    }
2798
2799    /*  To invalidate a rectangle in content coordinates, we need to transform
2800        the rect into view coordinates, so we can then call invalidate(...).
2801
2802        Normally, we would just call contentToView[XY](...), which eventually
2803        calls Math.round(coordinate * mActualScale). However, for invalidates,
2804        we need to account for the slop that occurs with antialiasing. To
2805        address that, we are a little more liberal in the size of the rect that
2806        we invalidate.
2807
2808        This liberal calculation calls floor() for the top/left, and ceil() for
2809        the bottom/right coordinates. This catches the possible extra pixels of
2810        antialiasing that we might have missed with just round().
2811     */
2812
2813    // Called by JNI to invalidate the View, given rectangle coordinates in
2814    // content space
2815    private void viewInvalidate(int l, int t, int r, int b) {
2816        final float scale = mZoomManager.getScale();
2817        final int dy = getTitleHeight();
2818        invalidate((int)Math.floor(l * scale),
2819                   (int)Math.floor(t * scale) + dy,
2820                   (int)Math.ceil(r * scale),
2821                   (int)Math.ceil(b * scale) + dy);
2822    }
2823
2824    // Called by JNI to invalidate the View after a delay, given rectangle
2825    // coordinates in content space
2826    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
2827        final float scale = mZoomManager.getScale();
2828        final int dy = getTitleHeight();
2829        postInvalidateDelayed(delay,
2830                              (int)Math.floor(l * scale),
2831                              (int)Math.floor(t * scale) + dy,
2832                              (int)Math.ceil(r * scale),
2833                              (int)Math.ceil(b * scale) + dy);
2834    }
2835
2836    private void invalidateContentRect(Rect r) {
2837        viewInvalidate(r.left, r.top, r.right, r.bottom);
2838    }
2839
2840    // stop the scroll animation, and don't let a subsequent fling add
2841    // to the existing velocity
2842    private void abortAnimation() {
2843        mScroller.abortAnimation();
2844        mLastVelocity = 0;
2845    }
2846
2847    /* call from webcoreview.draw(), so we're still executing in the UI thread
2848    */
2849    private void recordNewContentSize(int w, int h, boolean updateLayout) {
2850
2851        // premature data from webkit, ignore
2852        if ((w | h) == 0) {
2853            return;
2854        }
2855
2856        // don't abort a scroll animation if we didn't change anything
2857        if (mContentWidth != w || mContentHeight != h) {
2858            // record new dimensions
2859            mContentWidth = w;
2860            mContentHeight = h;
2861            // If history Picture is drawn, don't update scroll. They will be
2862            // updated when we get out of that mode.
2863            if (!mDrawHistory) {
2864                // repin our scroll, taking into account the new content size
2865                updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY));
2866                if (!mScroller.isFinished()) {
2867                    // We are in the middle of a scroll.  Repin the final scroll
2868                    // position.
2869                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
2870                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
2871                }
2872            }
2873        }
2874        contentSizeChanged(updateLayout);
2875    }
2876
2877    // Used to avoid sending many visible rect messages.
2878    private Rect mLastVisibleRectSent = new Rect();
2879    private Rect mLastGlobalRect = new Rect();
2880    private Rect mVisibleRect = new Rect();
2881    private Rect mGlobalVisibleRect = new Rect();
2882    private Point mScrollOffset = new Point();
2883
2884    Rect sendOurVisibleRect() {
2885        if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
2886        calcOurContentVisibleRect(mVisibleRect);
2887        // Rect.equals() checks for null input.
2888        if (!mVisibleRect.equals(mLastVisibleRectSent)) {
2889            if (!mBlockWebkitViewMessages) {
2890                mScrollOffset.set(mVisibleRect.left, mVisibleRect.top);
2891                mWebViewCore.removeMessages(EventHub.SET_SCROLL_OFFSET);
2892                mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
2893                        nativeMoveGeneration(), mSendScrollEvent ? 1 : 0, mScrollOffset);
2894            }
2895            mLastVisibleRectSent.set(mVisibleRect);
2896            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
2897        }
2898        if (getGlobalVisibleRect(mGlobalVisibleRect)
2899                && !mGlobalVisibleRect.equals(mLastGlobalRect)) {
2900            if (DebugFlags.WEB_VIEW) {
2901                Log.v(LOGTAG, "sendOurVisibleRect=(" + mGlobalVisibleRect.left + ","
2902                        + mGlobalVisibleRect.top + ",r=" + mGlobalVisibleRect.right + ",b="
2903                        + mGlobalVisibleRect.bottom);
2904            }
2905            // TODO: the global offset is only used by windowRect()
2906            // in ChromeClientAndroid ; other clients such as touch
2907            // and mouse events could return view + screen relative points.
2908            if (!mBlockWebkitViewMessages) {
2909                mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, mGlobalVisibleRect);
2910            }
2911            mLastGlobalRect.set(mGlobalVisibleRect);
2912        }
2913        return mVisibleRect;
2914    }
2915
2916    private Point mGlobalVisibleOffset = new Point();
2917    // Sets r to be the visible rectangle of our webview in view coordinates
2918    private void calcOurVisibleRect(Rect r) {
2919        getGlobalVisibleRect(r, mGlobalVisibleOffset);
2920        r.offset(-mGlobalVisibleOffset.x, -mGlobalVisibleOffset.y);
2921    }
2922
2923    // Sets r to be our visible rectangle in content coordinates
2924    private void calcOurContentVisibleRect(Rect r) {
2925        calcOurVisibleRect(r);
2926        r.left = viewToContentX(r.left);
2927        // viewToContentY will remove the total height of the title bar.  Add
2928        // the visible height back in to account for the fact that if the title
2929        // bar is partially visible, the part of the visible rect which is
2930        // displaying our content is displaced by that amount.
2931        r.top = viewToContentY(r.top + getVisibleTitleHeightImpl());
2932        r.right = viewToContentX(r.right);
2933        r.bottom = viewToContentY(r.bottom);
2934    }
2935
2936    private Rect mContentVisibleRect = new Rect();
2937    // Sets r to be our visible rectangle in content coordinates. We use this
2938    // method on the native side to compute the position of the fixed layers.
2939    // Uses floating coordinates (necessary to correctly place elements when
2940    // the scale factor is not 1)
2941    private void calcOurContentVisibleRectF(RectF r) {
2942        calcOurVisibleRect(mContentVisibleRect);
2943        r.left = viewToContentXf(mContentVisibleRect.left);
2944        // viewToContentY will remove the total height of the title bar.  Add
2945        // the visible height back in to account for the fact that if the title
2946        // bar is partially visible, the part of the visible rect which is
2947        // displaying our content is displaced by that amount.
2948        r.top = viewToContentYf(mContentVisibleRect.top + getVisibleTitleHeightImpl());
2949        r.right = viewToContentXf(mContentVisibleRect.right);
2950        r.bottom = viewToContentYf(mContentVisibleRect.bottom);
2951    }
2952
2953    static class ViewSizeData {
2954        int mWidth;
2955        int mHeight;
2956        float mHeightWidthRatio;
2957        int mActualViewHeight;
2958        int mTextWrapWidth;
2959        int mAnchorX;
2960        int mAnchorY;
2961        float mScale;
2962        boolean mIgnoreHeight;
2963    }
2964
2965    /**
2966     * Compute unzoomed width and height, and if they differ from the last
2967     * values we sent, send them to webkit (to be used as new viewport)
2968     *
2969     * @param force ensures that the message is sent to webkit even if the width
2970     * or height has not changed since the last message
2971     *
2972     * @return true if new values were sent
2973     */
2974    boolean sendViewSizeZoom(boolean force) {
2975        if (mBlockWebkitViewMessages) return false;
2976        if (mZoomManager.isPreventingWebkitUpdates()) return false;
2977
2978        int viewWidth = getViewWidth();
2979        int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
2980        // This height could be fixed and be different from actual visible height.
2981        int viewHeight = getViewHeightWithTitle() - getTitleHeight();
2982        int newHeight = Math.round(viewHeight * mZoomManager.getInvScale());
2983        // Make the ratio more accurate than (newHeight / newWidth), since the
2984        // latter both are calculated and rounded.
2985        float heightWidthRatio = (float) viewHeight / viewWidth;
2986        /*
2987         * Because the native side may have already done a layout before the
2988         * View system was able to measure us, we have to send a height of 0 to
2989         * remove excess whitespace when we grow our width. This will trigger a
2990         * layout and a change in content size. This content size change will
2991         * mean that contentSizeChanged will either call this method directly or
2992         * indirectly from onSizeChanged.
2993         */
2994        if (newWidth > mLastWidthSent && mWrapContent) {
2995            newHeight = 0;
2996            heightWidthRatio = 0;
2997        }
2998        // Actual visible content height.
2999        int actualViewHeight = Math.round(getViewHeight() * mZoomManager.getInvScale());
3000        // Avoid sending another message if the dimensions have not changed.
3001        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force ||
3002                actualViewHeight != mLastActualHeightSent) {
3003            ViewSizeData data = new ViewSizeData();
3004            data.mWidth = newWidth;
3005            data.mHeight = newHeight;
3006            data.mHeightWidthRatio = heightWidthRatio;
3007            data.mActualViewHeight = actualViewHeight;
3008            data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
3009            data.mScale = mZoomManager.getScale();
3010            data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
3011                    && !mHeightCanMeasure;
3012            data.mAnchorX = mZoomManager.getDocumentAnchorX();
3013            data.mAnchorY = mZoomManager.getDocumentAnchorY();
3014            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
3015            mLastWidthSent = newWidth;
3016            mLastHeightSent = newHeight;
3017            mLastActualHeightSent = actualViewHeight;
3018            mZoomManager.clearDocumentAnchor();
3019            return true;
3020        }
3021        return false;
3022    }
3023
3024    /**
3025     * Update the double-tap zoom.
3026     */
3027    /* package */ void updateDoubleTapZoom(int doubleTapZoom) {
3028        mZoomManager.updateDoubleTapZoom(doubleTapZoom);
3029    }
3030
3031    private int computeRealHorizontalScrollRange() {
3032        if (mDrawHistory) {
3033            return mHistoryWidth;
3034        } else {
3035            // to avoid rounding error caused unnecessary scrollbar, use floor
3036            return (int) Math.floor(mContentWidth * mZoomManager.getScale());
3037        }
3038    }
3039
3040    @Override
3041    protected int computeHorizontalScrollRange() {
3042        int range = computeRealHorizontalScrollRange();
3043
3044        // Adjust reported range if overscrolled to compress the scroll bars
3045        final int scrollX = mScrollX;
3046        final int overscrollRight = computeMaxScrollX();
3047        if (scrollX < 0) {
3048            range -= scrollX;
3049        } else if (scrollX > overscrollRight) {
3050            range += scrollX - overscrollRight;
3051        }
3052
3053        return range;
3054    }
3055
3056    @Override
3057    protected int computeHorizontalScrollOffset() {
3058        return Math.max(mScrollX, 0);
3059    }
3060
3061    private int computeRealVerticalScrollRange() {
3062        if (mDrawHistory) {
3063            return mHistoryHeight;
3064        } else {
3065            // to avoid rounding error caused unnecessary scrollbar, use floor
3066            return (int) Math.floor(mContentHeight * mZoomManager.getScale());
3067        }
3068    }
3069
3070    @Override
3071    protected int computeVerticalScrollRange() {
3072        int range = computeRealVerticalScrollRange();
3073
3074        // Adjust reported range if overscrolled to compress the scroll bars
3075        final int scrollY = mScrollY;
3076        final int overscrollBottom = computeMaxScrollY();
3077        if (scrollY < 0) {
3078            range -= scrollY;
3079        } else if (scrollY > overscrollBottom) {
3080            range += scrollY - overscrollBottom;
3081        }
3082
3083        return range;
3084    }
3085
3086    @Override
3087    protected int computeVerticalScrollOffset() {
3088        return Math.max(mScrollY - getTitleHeight(), 0);
3089    }
3090
3091    @Override
3092    protected int computeVerticalScrollExtent() {
3093        return getViewHeight();
3094    }
3095
3096    /** @hide */
3097    @Override
3098    protected void onDrawVerticalScrollBar(Canvas canvas,
3099                                           Drawable scrollBar,
3100                                           int l, int t, int r, int b) {
3101        if (mScrollY < 0) {
3102            t -= mScrollY;
3103        }
3104        scrollBar.setBounds(l, t + getVisibleTitleHeightImpl(), r, b);
3105        scrollBar.draw(canvas);
3106    }
3107
3108    @Override
3109    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX,
3110            boolean clampedY) {
3111        // Special-case layer scrolling so that we do not trigger normal scroll
3112        // updating.
3113        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3114            scrollLayerTo(scrollX, scrollY);
3115            return;
3116        }
3117        mInOverScrollMode = false;
3118        int maxX = computeMaxScrollX();
3119        int maxY = computeMaxScrollY();
3120        if (maxX == 0) {
3121            // do not over scroll x if the page just fits the screen
3122            scrollX = pinLocX(scrollX);
3123        } else if (scrollX < 0 || scrollX > maxX) {
3124            mInOverScrollMode = true;
3125        }
3126        if (scrollY < 0 || scrollY > maxY) {
3127            mInOverScrollMode = true;
3128        }
3129
3130        int oldX = mScrollX;
3131        int oldY = mScrollY;
3132
3133        super.scrollTo(scrollX, scrollY);
3134
3135        if (mOverScrollGlow != null) {
3136            mOverScrollGlow.pullGlow(mScrollX, mScrollY, oldX, oldY, maxX, maxY);
3137        }
3138    }
3139
3140    /**
3141     * Get the url for the current page. This is not always the same as the url
3142     * passed to WebViewClient.onPageStarted because although the load for
3143     * that url has begun, the current page may not have changed.
3144     * @return The url for the current page.
3145     */
3146    public String getUrl() {
3147        checkThread();
3148        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3149        return h != null ? h.getUrl() : null;
3150    }
3151
3152    /**
3153     * Get the original url for the current page. This is not always the same
3154     * as the url passed to WebViewClient.onPageStarted because although the
3155     * load for that url has begun, the current page may not have changed.
3156     * Also, there may have been redirects resulting in a different url to that
3157     * originally requested.
3158     * @return The url that was originally requested for the current page.
3159     */
3160    public String getOriginalUrl() {
3161        checkThread();
3162        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3163        return h != null ? h.getOriginalUrl() : null;
3164    }
3165
3166    /**
3167     * Get the title for the current page. This is the title of the current page
3168     * until WebViewClient.onReceivedTitle is called.
3169     * @return The title for the current page.
3170     */
3171    public String getTitle() {
3172        checkThread();
3173        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3174        return h != null ? h.getTitle() : null;
3175    }
3176
3177    /**
3178     * Get the favicon for the current page. This is the favicon of the current
3179     * page until WebViewClient.onReceivedIcon is called.
3180     * @return The favicon for the current page.
3181     */
3182    public Bitmap getFavicon() {
3183        checkThread();
3184        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3185        return h != null ? h.getFavicon() : null;
3186    }
3187
3188    /**
3189     * Get the touch icon url for the apple-touch-icon <link> element, or
3190     * a URL on this site's server pointing to the standard location of a
3191     * touch icon.
3192     * @hide
3193     */
3194    public String getTouchIconUrl() {
3195        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3196        return h != null ? h.getTouchIconUrl() : null;
3197    }
3198
3199    /**
3200     * Get the progress for the current page.
3201     * @return The progress for the current page between 0 and 100.
3202     */
3203    public int getProgress() {
3204        checkThread();
3205        return mCallbackProxy.getProgress();
3206    }
3207
3208    /**
3209     * @return the height of the HTML content.
3210     */
3211    public int getContentHeight() {
3212        checkThread();
3213        return mContentHeight;
3214    }
3215
3216    /**
3217     * @return the width of the HTML content.
3218     * @hide
3219     */
3220    public int getContentWidth() {
3221        return mContentWidth;
3222    }
3223
3224    /**
3225     * @hide
3226     */
3227    public int getPageBackgroundColor() {
3228        return nativeGetBackgroundColor();
3229    }
3230
3231    /**
3232     * Pause all layout, parsing, and JavaScript timers for all webviews. This
3233     * is a global requests, not restricted to just this webview. This can be
3234     * useful if the application has been paused.
3235     */
3236    public void pauseTimers() {
3237        checkThread();
3238        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
3239    }
3240
3241    /**
3242     * Resume all layout, parsing, and JavaScript timers for all webviews.
3243     * This will resume dispatching all timers.
3244     */
3245    public void resumeTimers() {
3246        checkThread();
3247        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
3248    }
3249
3250    /**
3251     * Call this to pause any extra processing associated with this WebView and
3252     * its associated DOM, plugins, JavaScript etc. For example, if the WebView
3253     * is taken offscreen, this could be called to reduce unnecessary CPU or
3254     * network traffic. When the WebView is again "active", call onResume().
3255     *
3256     * Note that this differs from pauseTimers(), which affects all WebViews.
3257     */
3258    public void onPause() {
3259        checkThread();
3260        if (!mIsPaused) {
3261            mIsPaused = true;
3262            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
3263            // We want to pause the current playing video when switching out
3264            // from the current WebView/tab.
3265            if (mHTML5VideoViewProxy != null) {
3266                mHTML5VideoViewProxy.pauseAndDispatch();
3267            }
3268            if (mNativeClass != 0) {
3269                nativeSetPauseDrawing(mNativeClass, true);
3270            }
3271        }
3272    }
3273
3274    @Override
3275    protected void onWindowVisibilityChanged(int visibility) {
3276        super.onWindowVisibilityChanged(visibility);
3277        updateDrawingState();
3278    }
3279
3280    void updateDrawingState() {
3281        if (mNativeClass == 0 || mIsPaused) return;
3282        if (getWindowVisibility() != VISIBLE) {
3283            nativeSetPauseDrawing(mNativeClass, true);
3284        } else if (getVisibility() != VISIBLE) {
3285            nativeSetPauseDrawing(mNativeClass, true);
3286        } else {
3287            nativeSetPauseDrawing(mNativeClass, false);
3288        }
3289    }
3290
3291    /**
3292     * Call this to resume a WebView after a previous call to onPause().
3293     */
3294    public void onResume() {
3295        checkThread();
3296        if (mIsPaused) {
3297            mIsPaused = false;
3298            mWebViewCore.sendMessage(EventHub.ON_RESUME);
3299            if (mNativeClass != 0) {
3300                nativeSetPauseDrawing(mNativeClass, false);
3301            }
3302        }
3303    }
3304
3305    /**
3306     * Returns true if the view is paused, meaning onPause() was called. Calling
3307     * onResume() sets the paused state back to false.
3308     * @hide
3309     */
3310    public boolean isPaused() {
3311        return mIsPaused;
3312    }
3313
3314    /**
3315     * Call this to inform the view that memory is low so that it can
3316     * free any available memory.
3317     */
3318    public void freeMemory() {
3319        checkThread();
3320        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
3321    }
3322
3323    /**
3324     * Clear the resource cache. Note that the cache is per-application, so
3325     * this will clear the cache for all WebViews used.
3326     *
3327     * @param includeDiskFiles If false, only the RAM cache is cleared.
3328     */
3329    public void clearCache(boolean includeDiskFiles) {
3330        checkThread();
3331        // Note: this really needs to be a static method as it clears cache for all
3332        // WebView. But we need mWebViewCore to send message to WebCore thread, so
3333        // we can't make this static.
3334        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
3335                includeDiskFiles ? 1 : 0, 0);
3336    }
3337
3338    /**
3339     * Make sure that clearing the form data removes the adapter from the
3340     * currently focused textfield if there is one.
3341     */
3342    public void clearFormData() {
3343        checkThread();
3344        if (inEditingMode()) {
3345            mWebTextView.setAdapterCustom(null);
3346        }
3347    }
3348
3349    /**
3350     * Tell the WebView to clear its internal back/forward list.
3351     */
3352    public void clearHistory() {
3353        checkThread();
3354        mCallbackProxy.getBackForwardList().setClearPending();
3355        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
3356    }
3357
3358    /**
3359     * Clear the SSL preferences table stored in response to proceeding with SSL
3360     * certificate errors.
3361     */
3362    public void clearSslPreferences() {
3363        checkThread();
3364        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
3365    }
3366
3367    /**
3368     * Return the WebBackForwardList for this WebView. This contains the
3369     * back/forward list for use in querying each item in the history stack.
3370     * This is a copy of the private WebBackForwardList so it contains only a
3371     * snapshot of the current state. Multiple calls to this method may return
3372     * different objects. The object returned from this method will not be
3373     * updated to reflect any new state.
3374     */
3375    public WebBackForwardList copyBackForwardList() {
3376        checkThread();
3377        return mCallbackProxy.getBackForwardList().clone();
3378    }
3379
3380    /*
3381     * Highlight and scroll to the next occurance of String in findAll.
3382     * Wraps the page infinitely, and scrolls.  Must be called after
3383     * calling findAll.
3384     *
3385     * @param forward Direction to search.
3386     */
3387    public void findNext(boolean forward) {
3388        checkThread();
3389        if (0 == mNativeClass) return; // client isn't initialized
3390        nativeFindNext(forward);
3391    }
3392
3393    /*
3394     * Find all instances of find on the page and highlight them.
3395     * @param find  String to find.
3396     * @return int  The number of occurances of the String "find"
3397     *              that were found.
3398     */
3399    public int findAll(String find) {
3400        checkThread();
3401        if (0 == mNativeClass) return 0; // client isn't initialized
3402        int result = find != null ? nativeFindAll(find.toLowerCase(),
3403                find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0;
3404        invalidate();
3405        mLastFind = find;
3406        return result;
3407    }
3408
3409    /**
3410     * Start an ActionMode for finding text in this WebView.  Only works if this
3411     *              WebView is attached to the view system.
3412     * @param text If non-null, will be the initial text to search for.
3413     *             Otherwise, the last String searched for in this WebView will
3414     *             be used to start.
3415     * @param showIme If true, show the IME, assuming the user will begin typing.
3416     *             If false and text is non-null, perform a find all.
3417     * @return boolean True if the find dialog is shown, false otherwise.
3418     */
3419    public boolean showFindDialog(String text, boolean showIme) {
3420        checkThread();
3421        FindActionModeCallback callback = new FindActionModeCallback(mContext);
3422        if (getParent() == null || startActionMode(callback) == null) {
3423            // Could not start the action mode, so end Find on page
3424            return false;
3425        }
3426        mCachedOverlappingActionModeHeight = -1;
3427        mFindCallback = callback;
3428        setFindIsUp(true);
3429        mFindCallback.setWebView(this);
3430        if (showIme) {
3431            mFindCallback.showSoftInput();
3432        } else if (text != null) {
3433            mFindCallback.setText(text);
3434            mFindCallback.findAll();
3435            return true;
3436        }
3437        if (text == null) {
3438            text = mLastFind;
3439        }
3440        if (text != null) {
3441            mFindCallback.setText(text);
3442        }
3443        return true;
3444    }
3445
3446    /**
3447     * Keep track of the find callback so that we can remove its titlebar if
3448     * necessary.
3449     */
3450    private FindActionModeCallback mFindCallback;
3451
3452    /**
3453     * Toggle whether the find dialog is showing, for both native and Java.
3454     */
3455    private void setFindIsUp(boolean isUp) {
3456        mFindIsUp = isUp;
3457        if (0 == mNativeClass) return; // client isn't initialized
3458        nativeSetFindIsUp(isUp);
3459    }
3460
3461    /**
3462     * Return the index of the currently highlighted match.
3463     */
3464    int findIndex() {
3465        if (0 == mNativeClass) return -1;
3466        return nativeFindIndex();
3467    }
3468
3469    // Used to know whether the find dialog is open.  Affects whether
3470    // or not we draw the highlights for matches.
3471    private boolean mFindIsUp;
3472
3473    // Keep track of the last string sent, so we can search again when find is
3474    // reopened.
3475    private String mLastFind;
3476
3477    /**
3478     * Return the first substring consisting of the address of a physical
3479     * location. Currently, only addresses in the United States are detected,
3480     * and consist of:
3481     * - a house number
3482     * - a street name
3483     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3484     * - a city name
3485     * - a state or territory, either spelled out or two-letter abbr.
3486     * - an optional 5 digit or 9 digit zip code.
3487     *
3488     * All names must be correctly capitalized, and the zip code, if present,
3489     * must be valid for the state. The street type must be a standard USPS
3490     * spelling or abbreviation. The state or territory must also be spelled
3491     * or abbreviated using USPS standards. The house number may not exceed
3492     * five digits.
3493     * @param addr The string to search for addresses.
3494     *
3495     * @return the address, or if no address is found, return null.
3496     */
3497    public static String findAddress(String addr) {
3498        checkThread();
3499        return findAddress(addr, false);
3500    }
3501
3502    /**
3503     * @hide
3504     * Return the first substring consisting of the address of a physical
3505     * location. Currently, only addresses in the United States are detected,
3506     * and consist of:
3507     * - a house number
3508     * - a street name
3509     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3510     * - a city name
3511     * - a state or territory, either spelled out or two-letter abbr.
3512     * - an optional 5 digit or 9 digit zip code.
3513     *
3514     * Names are optionally capitalized, and the zip code, if present,
3515     * must be valid for the state. The street type must be a standard USPS
3516     * spelling or abbreviation. The state or territory must also be spelled
3517     * or abbreviated using USPS standards. The house number may not exceed
3518     * five digits.
3519     * @param addr The string to search for addresses.
3520     * @param caseInsensitive addr Set to true to make search ignore case.
3521     *
3522     * @return the address, or if no address is found, return null.
3523     */
3524    public static String findAddress(String addr, boolean caseInsensitive) {
3525        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
3526    }
3527
3528    /*
3529     * Clear the highlighting surrounding text matches created by findAll.
3530     */
3531    public void clearMatches() {
3532        checkThread();
3533        if (mNativeClass == 0)
3534            return;
3535        nativeSetFindIsEmpty();
3536        invalidate();
3537    }
3538
3539    /**
3540     * Called when the find ActionMode ends.
3541     */
3542    void notifyFindDialogDismissed() {
3543        mFindCallback = null;
3544        mCachedOverlappingActionModeHeight = -1;
3545        if (mWebViewCore == null) {
3546            return;
3547        }
3548        clearMatches();
3549        setFindIsUp(false);
3550        // Now that the dialog has been removed, ensure that we scroll to a
3551        // location that is not beyond the end of the page.
3552        pinScrollTo(mScrollX, mScrollY, false, 0);
3553        invalidate();
3554    }
3555
3556    /**
3557     * Query the document to see if it contains any image references. The
3558     * message object will be dispatched with arg1 being set to 1 if images
3559     * were found and 0 if the document does not reference any images.
3560     * @param response The message that will be dispatched with the result.
3561     */
3562    public void documentHasImages(Message response) {
3563        checkThread();
3564        if (response == null) {
3565            return;
3566        }
3567        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
3568    }
3569
3570    /**
3571     * Request the scroller to abort any ongoing animation
3572     *
3573     * @hide
3574     */
3575    public void stopScroll() {
3576        mScroller.forceFinished(true);
3577        mLastVelocity = 0;
3578    }
3579
3580    @Override
3581    public void computeScroll() {
3582        if (mScroller.computeScrollOffset()) {
3583            int oldX = mScrollX;
3584            int oldY = mScrollY;
3585            int x = mScroller.getCurrX();
3586            int y = mScroller.getCurrY();
3587            invalidate();  // So we draw again
3588
3589            if (!mScroller.isFinished()) {
3590                int rangeX = computeMaxScrollX();
3591                int rangeY = computeMaxScrollY();
3592                int overflingDistance = mOverflingDistance;
3593
3594                // Use the layer's scroll data if needed.
3595                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3596                    oldX = mScrollingLayerRect.left;
3597                    oldY = mScrollingLayerRect.top;
3598                    rangeX = mScrollingLayerRect.right;
3599                    rangeY = mScrollingLayerRect.bottom;
3600                    // No overscrolling for layers.
3601                    overflingDistance = 0;
3602                }
3603
3604                overScrollBy(x - oldX, y - oldY, oldX, oldY,
3605                        rangeX, rangeY,
3606                        overflingDistance, overflingDistance, false);
3607
3608                if (mOverScrollGlow != null) {
3609                    mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY);
3610                }
3611            } else {
3612                if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
3613                    mScrollX = x;
3614                    mScrollY = y;
3615                } else {
3616                    // Update the layer position instead of WebView.
3617                    scrollLayerTo(x, y);
3618                }
3619                abortAnimation();
3620                nativeSetIsScrolling(false);
3621                if (!mBlockWebkitViewMessages) {
3622                    WebViewCore.resumePriority();
3623                    if (!mSelectingText) {
3624                        WebViewCore.resumeUpdatePicture(mWebViewCore);
3625                    }
3626                }
3627                if (oldX != mScrollX || oldY != mScrollY) {
3628                    sendOurVisibleRect();
3629                }
3630            }
3631        } else {
3632            super.computeScroll();
3633        }
3634    }
3635
3636    private void scrollLayerTo(int x, int y) {
3637        if (x == mScrollingLayerRect.left && y == mScrollingLayerRect.top) {
3638            return;
3639        }
3640        nativeScrollLayer(mScrollingLayer, x, y);
3641        mScrollingLayerRect.left = x;
3642        mScrollingLayerRect.top = y;
3643        onScrollChanged(mScrollX, mScrollY, mScrollX, mScrollY);
3644        invalidate();
3645    }
3646
3647    private static int computeDuration(int dx, int dy) {
3648        int distance = Math.max(Math.abs(dx), Math.abs(dy));
3649        int duration = distance * 1000 / STD_SPEED;
3650        return Math.min(duration, MAX_DURATION);
3651    }
3652
3653    // helper to pin the scrollBy parameters (already in view coordinates)
3654    // returns true if the scroll was changed
3655    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
3656        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
3657    }
3658    // helper to pin the scrollTo parameters (already in view coordinates)
3659    // returns true if the scroll was changed
3660    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
3661        x = pinLocX(x);
3662        y = pinLocY(y);
3663        int dx = x - mScrollX;
3664        int dy = y - mScrollY;
3665
3666        if ((dx | dy) == 0) {
3667            return false;
3668        }
3669        abortAnimation();
3670        if (animate) {
3671            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
3672            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
3673                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
3674            awakenScrollBars(mScroller.getDuration());
3675            invalidate();
3676        } else {
3677            scrollTo(x, y);
3678        }
3679        return true;
3680    }
3681
3682    // Scale from content to view coordinates, and pin.
3683    // Also called by jni webview.cpp
3684    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
3685        if (mDrawHistory) {
3686            // disallow WebView to change the scroll position as History Picture
3687            // is used in the view system.
3688            // TODO: as we switchOutDrawHistory when trackball or navigation
3689            // keys are hit, this should be safe. Right?
3690            return false;
3691        }
3692        cx = contentToViewDimension(cx);
3693        cy = contentToViewDimension(cy);
3694        if (mHeightCanMeasure) {
3695            // move our visible rect according to scroll request
3696            if (cy != 0) {
3697                Rect tempRect = new Rect();
3698                calcOurVisibleRect(tempRect);
3699                tempRect.offset(cx, cy);
3700                requestRectangleOnScreen(tempRect);
3701            }
3702            // FIXME: We scroll horizontally no matter what because currently
3703            // ScrollView and ListView will not scroll horizontally.
3704            // FIXME: Why do we only scroll horizontally if there is no
3705            // vertical scroll?
3706//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
3707            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
3708        } else {
3709            return pinScrollBy(cx, cy, animate, 0);
3710        }
3711    }
3712
3713    /**
3714     * Called by CallbackProxy when the page starts loading.
3715     * @param url The URL of the page which has started loading.
3716     */
3717    /* package */ void onPageStarted(String url) {
3718        // every time we start a new page, we want to reset the
3719        // WebView certificate:  if the new site is secure, we
3720        // will reload it and get a new certificate set;
3721        // if the new site is not secure, the certificate must be
3722        // null, and that will be the case
3723        setCertificate(null);
3724
3725        // reset the flag since we set to true in if need after
3726        // loading is see onPageFinished(Url)
3727        mAccessibilityScriptInjected = false;
3728    }
3729
3730    /**
3731     * Called by CallbackProxy when the page finishes loading.
3732     * @param url The URL of the page which has finished loading.
3733     */
3734    /* package */ void onPageFinished(String url) {
3735        if (mPageThatNeedsToSlideTitleBarOffScreen != null) {
3736            // If the user is now on a different page, or has scrolled the page
3737            // past the point where the title bar is offscreen, ignore the
3738            // scroll request.
3739            if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url)
3740                    && mScrollX == 0 && mScrollY == 0) {
3741                pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true,
3742                        SLIDE_TITLE_DURATION);
3743            }
3744            mPageThatNeedsToSlideTitleBarOffScreen = null;
3745        }
3746        mZoomManager.onPageFinished(url);
3747        injectAccessibilityForUrl(url);
3748    }
3749
3750    /**
3751     * This method injects accessibility in the loaded document if accessibility
3752     * is enabled. If JavaScript is enabled we try to inject a URL specific script.
3753     * If no URL specific script is found or JavaScript is disabled we fallback to
3754     * the default {@link AccessibilityInjector} implementation.
3755     * </p>
3756     * If the URL has the "axs" paramter set to 1 it has already done the
3757     * script injection so we do nothing. If the parameter is set to 0
3758     * the URL opts out accessibility script injection so we fall back to
3759     * the default {@link AccessibilityInjector}.
3760     * </p>
3761     * Note: If the user has not opted-in the accessibility script injection no scripts
3762     * are injected rather the default {@link AccessibilityInjector} implementation
3763     * is used.
3764     *
3765     * @param url The URL loaded by this {@link WebView}.
3766     */
3767    private void injectAccessibilityForUrl(String url) {
3768        if (mWebViewCore == null) {
3769            return;
3770        }
3771        AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
3772
3773        if (!accessibilityManager.isEnabled()) {
3774            // it is possible that accessibility was turned off between reloads
3775            ensureAccessibilityScriptInjectorInstance(false);
3776            return;
3777        }
3778
3779        if (!getSettings().getJavaScriptEnabled()) {
3780            // no JS so we fallback to the basic buil-in support
3781            ensureAccessibilityScriptInjectorInstance(true);
3782            return;
3783        }
3784
3785        // check the URL "axs" parameter to choose appropriate action
3786        int axsParameterValue = getAxsUrlParameterValue(url);
3787        if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) {
3788            boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext
3789                    .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1);
3790            if (onDeviceScriptInjectionEnabled) {
3791                ensureAccessibilityScriptInjectorInstance(false);
3792                // neither script injected nor script injection opted out => we inject
3793                loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3794                // TODO: Set this flag after successfull script injection. Maybe upon injection
3795                // the chooser should update the meta tag and we check it to declare success
3796                mAccessibilityScriptInjected = true;
3797            } else {
3798                // injection disabled so we fallback to the basic built-in support
3799                ensureAccessibilityScriptInjectorInstance(true);
3800            }
3801        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) {
3802            // injection opted out so we fallback to the basic buil-in support
3803            ensureAccessibilityScriptInjectorInstance(true);
3804        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) {
3805            ensureAccessibilityScriptInjectorInstance(false);
3806            // the URL provides accessibility but we still need to add our generic script
3807            loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3808        } else {
3809            Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue);
3810        }
3811    }
3812
3813    /**
3814     * Ensures the instance of the {@link AccessibilityInjector} to be present ot not.
3815     *
3816     * @param present True to ensure an insance, false to ensure no instance.
3817     */
3818    private void ensureAccessibilityScriptInjectorInstance(boolean present) {
3819        if (present) {
3820            if (mAccessibilityInjector == null) {
3821                mAccessibilityInjector = new AccessibilityInjector(this);
3822            }
3823        } else {
3824            mAccessibilityInjector = null;
3825        }
3826    }
3827
3828    /**
3829     * Gets the "axs" URL parameter value.
3830     *
3831     * @param url A url to fetch the paramter from.
3832     * @return The parameter value if such, -1 otherwise.
3833     */
3834    private int getAxsUrlParameterValue(String url) {
3835        if (mMatchAxsUrlParameterPattern == null) {
3836            mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER);
3837        }
3838        Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url);
3839        if (matcher.find()) {
3840            String keyValuePair = url.substring(matcher.start(), matcher.end());
3841            return Integer.parseInt(keyValuePair.split("=")[1]);
3842        }
3843        return -1;
3844    }
3845
3846    /**
3847     * The URL of a page that sent a message to scroll the title bar off screen.
3848     *
3849     * Many mobile sites tell the page to scroll to (0,1) in order to scroll the
3850     * title bar off the screen.  Sometimes, the scroll position is set before
3851     * the page finishes loading.  Rather than scrolling while the page is still
3852     * loading, keep track of the URL and new scroll position so we can perform
3853     * the scroll once the page finishes loading.
3854     */
3855    private String mPageThatNeedsToSlideTitleBarOffScreen;
3856
3857    /**
3858     * The destination Y scroll position to be used when the page finishes
3859     * loading.  See mPageThatNeedsToSlideTitleBarOffScreen.
3860     */
3861    private int mYDistanceToSlideTitleOffScreen;
3862
3863    // scale from content to view coordinates, and pin
3864    // return true if pin caused the final x/y different than the request cx/cy,
3865    // and a future scroll may reach the request cx/cy after our size has
3866    // changed
3867    // return false if the view scroll to the exact position as it is requested,
3868    // where negative numbers are taken to mean 0
3869    private boolean setContentScrollTo(int cx, int cy) {
3870        if (mDrawHistory) {
3871            // disallow WebView to change the scroll position as History Picture
3872            // is used in the view system.
3873            // One known case where this is called is that WebCore tries to
3874            // restore the scroll position. As history Picture already uses the
3875            // saved scroll position, it is ok to skip this.
3876            return false;
3877        }
3878        int vx;
3879        int vy;
3880        if ((cx | cy) == 0) {
3881            // If the page is being scrolled to (0,0), do not add in the title
3882            // bar's height, and simply scroll to (0,0). (The only other work
3883            // in contentToView_ is to multiply, so this would not change 0.)
3884            vx = 0;
3885            vy = 0;
3886        } else {
3887            vx = contentToViewX(cx);
3888            vy = contentToViewY(cy);
3889        }
3890//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
3891//                      vx + " " + vy + "]");
3892        // Some mobile sites attempt to scroll the title bar off the page by
3893        // scrolling to (0,1).  If we are at the top left corner of the
3894        // page, assume this is an attempt to scroll off the title bar, and
3895        // animate the title bar off screen slowly enough that the user can see
3896        // it.
3897        if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0
3898                && mTitleBar != null) {
3899            // FIXME: 100 should be defined somewhere as our max progress.
3900            if (getProgress() < 100) {
3901                // Wait to scroll the title bar off screen until the page has
3902                // finished loading.  Keep track of the URL and the destination
3903                // Y position
3904                mPageThatNeedsToSlideTitleBarOffScreen = getUrl();
3905                mYDistanceToSlideTitleOffScreen = vy;
3906            } else {
3907                pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
3908            }
3909            // Since we are animating, we have not yet reached the desired
3910            // scroll position.  Do not return true to request another attempt
3911            return false;
3912        }
3913        pinScrollTo(vx, vy, false, 0);
3914        // If the request was to scroll to a negative coordinate, treat it as if
3915        // it was a request to scroll to 0
3916        if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
3917            return true;
3918        } else {
3919            return false;
3920        }
3921    }
3922
3923    // scale from content to view coordinates, and pin
3924    private void spawnContentScrollTo(int cx, int cy) {
3925        if (mDrawHistory) {
3926            // disallow WebView to change the scroll position as History Picture
3927            // is used in the view system.
3928            return;
3929        }
3930        int vx = contentToViewX(cx);
3931        int vy = contentToViewY(cy);
3932        pinScrollTo(vx, vy, true, 0);
3933    }
3934
3935    /**
3936     * These are from webkit, and are in content coordinate system (unzoomed)
3937     */
3938    private void contentSizeChanged(boolean updateLayout) {
3939        // suppress 0,0 since we usually see real dimensions soon after
3940        // this avoids drawing the prev content in a funny place. If we find a
3941        // way to consolidate these notifications, this check may become
3942        // obsolete
3943        if ((mContentWidth | mContentHeight) == 0) {
3944            return;
3945        }
3946
3947        if (mHeightCanMeasure) {
3948            if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
3949                    || updateLayout) {
3950                requestLayout();
3951            }
3952        } else if (mWidthCanMeasure) {
3953            if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
3954                    || updateLayout) {
3955                requestLayout();
3956            }
3957        } else {
3958            // If we don't request a layout, try to send our view size to the
3959            // native side to ensure that WebCore has the correct dimensions.
3960            sendViewSizeZoom(false);
3961        }
3962    }
3963
3964    /**
3965     * Set the WebViewClient that will receive various notifications and
3966     * requests. This will replace the current handler.
3967     * @param client An implementation of WebViewClient.
3968     */
3969    public void setWebViewClient(WebViewClient client) {
3970        checkThread();
3971        mCallbackProxy.setWebViewClient(client);
3972    }
3973
3974    /**
3975     * Gets the WebViewClient
3976     * @return the current WebViewClient instance.
3977     *
3978     *@hide pending API council approval.
3979     */
3980    public WebViewClient getWebViewClient() {
3981        return mCallbackProxy.getWebViewClient();
3982    }
3983
3984    /**
3985     * Register the interface to be used when content can not be handled by
3986     * the rendering engine, and should be downloaded instead. This will replace
3987     * the current handler.
3988     * @param listener An implementation of DownloadListener.
3989     */
3990    public void setDownloadListener(DownloadListener listener) {
3991        checkThread();
3992        mCallbackProxy.setDownloadListener(listener);
3993    }
3994
3995    /**
3996     * Set the chrome handler. This is an implementation of WebChromeClient for
3997     * use in handling JavaScript dialogs, favicons, titles, and the progress.
3998     * This will replace the current handler.
3999     * @param client An implementation of WebChromeClient.
4000     */
4001    public void setWebChromeClient(WebChromeClient client) {
4002        checkThread();
4003        mCallbackProxy.setWebChromeClient(client);
4004    }
4005
4006    /**
4007     * Gets the chrome handler.
4008     * @return the current WebChromeClient instance.
4009     *
4010     * @hide API council approval.
4011     */
4012    public WebChromeClient getWebChromeClient() {
4013        return mCallbackProxy.getWebChromeClient();
4014    }
4015
4016    /**
4017     * Set the back/forward list client. This is an implementation of
4018     * WebBackForwardListClient for handling new items and changes in the
4019     * history index.
4020     * @param client An implementation of WebBackForwardListClient.
4021     * {@hide}
4022     */
4023    public void setWebBackForwardListClient(WebBackForwardListClient client) {
4024        mCallbackProxy.setWebBackForwardListClient(client);
4025    }
4026
4027    /**
4028     * Gets the WebBackForwardListClient.
4029     * {@hide}
4030     */
4031    public WebBackForwardListClient getWebBackForwardListClient() {
4032        return mCallbackProxy.getWebBackForwardListClient();
4033    }
4034
4035    /**
4036     * Set the Picture listener. This is an interface used to receive
4037     * notifications of a new Picture.
4038     * @param listener An implementation of WebView.PictureListener.
4039     * @deprecated This method is now obsolete.
4040     */
4041    @Deprecated
4042    public void setPictureListener(PictureListener listener) {
4043        checkThread();
4044        mPictureListener = listener;
4045    }
4046
4047    /**
4048     * {@hide}
4049     */
4050    /* FIXME: Debug only! Remove for SDK! */
4051    public void externalRepresentation(Message callback) {
4052        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
4053    }
4054
4055    /**
4056     * {@hide}
4057     */
4058    /* FIXME: Debug only! Remove for SDK! */
4059    public void documentAsText(Message callback) {
4060        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
4061    }
4062
4063    /**
4064     * Use this function to bind an object to JavaScript so that the
4065     * methods can be accessed from JavaScript.
4066     * <p><strong>IMPORTANT:</strong>
4067     * <ul>
4068     * <li> Using addJavascriptInterface() allows JavaScript to control your
4069     * application. This can be a very useful feature or a dangerous security
4070     * issue. When the HTML in the WebView is untrustworthy (for example, part
4071     * or all of the HTML is provided by some person or process), then an
4072     * attacker could inject HTML that will execute your code and possibly any
4073     * code of the attacker's choosing.<br>
4074     * Do not use addJavascriptInterface() unless all of the HTML in this
4075     * WebView was written by you.</li>
4076     * <li> The Java object that is bound runs in another thread and not in
4077     * the thread that it was constructed in.</li>
4078     * </ul></p>
4079     * @param obj The class instance to bind to JavaScript, null instances are
4080     *            ignored.
4081     * @param interfaceName The name to used to expose the instance in
4082     *                      JavaScript.
4083     */
4084    public void addJavascriptInterface(Object obj, String interfaceName) {
4085        checkThread();
4086        if (obj == null) {
4087            return;
4088        }
4089        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
4090        arg.mObject = obj;
4091        arg.mInterfaceName = interfaceName;
4092        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
4093    }
4094
4095    /**
4096     * Removes a previously added JavaScript interface with the given name.
4097     * @param interfaceName The name of the interface to remove.
4098     */
4099    public void removeJavascriptInterface(String interfaceName) {
4100        checkThread();
4101        if (mWebViewCore != null) {
4102            WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
4103            arg.mInterfaceName = interfaceName;
4104            mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg);
4105        }
4106    }
4107
4108    /**
4109     * Return the WebSettings object used to control the settings for this
4110     * WebView.
4111     * @return A WebSettings object that can be used to control this WebView's
4112     *         settings.
4113     */
4114    public WebSettings getSettings() {
4115        checkThread();
4116        return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
4117    }
4118
4119   /**
4120    * Return the list of currently loaded plugins.
4121    * @return The list of currently loaded plugins.
4122    *
4123    * @hide
4124    * @deprecated This was used for Gears, which has been deprecated.
4125    */
4126    @Deprecated
4127    public static synchronized PluginList getPluginList() {
4128        checkThread();
4129        return new PluginList();
4130    }
4131
4132   /**
4133    * @hide
4134    * @deprecated This was used for Gears, which has been deprecated.
4135    */
4136    @Deprecated
4137    public void refreshPlugins(boolean reloadOpenPages) {
4138        checkThread();
4139    }
4140
4141    //-------------------------------------------------------------------------
4142    // Override View methods
4143    //-------------------------------------------------------------------------
4144
4145    @Override
4146    protected void finalize() throws Throwable {
4147        try {
4148            if (mNativeClass != 0) {
4149                mPrivateHandler.post(new Runnable() {
4150                    @Override
4151                    public void run() {
4152                        destroy();
4153                    }
4154                });
4155            }
4156        } finally {
4157            super.finalize();
4158        }
4159    }
4160
4161    @Override
4162    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
4163        if (child == mTitleBar) {
4164            // When drawing the title bar, move it horizontally to always show
4165            // at the top of the WebView.
4166            mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
4167            int newTop = 0;
4168            if (mTitleGravity == Gravity.NO_GRAVITY) {
4169                newTop = Math.min(0, mScrollY);
4170            } else if (mTitleGravity == Gravity.TOP) {
4171                newTop = mScrollY;
4172            }
4173            mTitleBar.setBottom(newTop + mTitleBar.getHeight());
4174            mTitleBar.setTop(newTop);
4175        }
4176        return super.drawChild(canvas, child, drawingTime);
4177    }
4178
4179    private void drawContent(Canvas canvas, boolean drawRings) {
4180        drawCoreAndCursorRing(canvas, mBackgroundColor,
4181                mDrawCursorRing && drawRings);
4182    }
4183
4184    /**
4185     * Draw the background when beyond bounds
4186     * @param canvas Canvas to draw into
4187     */
4188    private void drawOverScrollBackground(Canvas canvas) {
4189        if (mOverScrollBackground == null) {
4190            mOverScrollBackground = new Paint();
4191            Bitmap bm = BitmapFactory.decodeResource(
4192                    mContext.getResources(),
4193                    com.android.internal.R.drawable.status_bar_background);
4194            mOverScrollBackground.setShader(new BitmapShader(bm,
4195                    Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
4196            mOverScrollBorder = new Paint();
4197            mOverScrollBorder.setStyle(Paint.Style.STROKE);
4198            mOverScrollBorder.setStrokeWidth(0);
4199            mOverScrollBorder.setColor(0xffbbbbbb);
4200        }
4201
4202        int top = 0;
4203        int right = computeRealHorizontalScrollRange();
4204        int bottom = top + computeRealVerticalScrollRange();
4205        // first draw the background and anchor to the top of the view
4206        canvas.save();
4207        canvas.translate(mScrollX, mScrollY);
4208        canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom
4209                - mScrollY, Region.Op.DIFFERENCE);
4210        canvas.drawPaint(mOverScrollBackground);
4211        canvas.restore();
4212        // then draw the border
4213        canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder);
4214        // next clip the region for the content
4215        canvas.clipRect(0, top, right, bottom);
4216    }
4217
4218    @Override
4219    protected void onDraw(Canvas canvas) {
4220        // if mNativeClass is 0, the WebView is either destroyed or not
4221        // initialized. In either case, just draw the background color and return
4222        if (mNativeClass == 0) {
4223            canvas.drawColor(mBackgroundColor);
4224            return;
4225        }
4226
4227        // if both mContentWidth and mContentHeight are 0, it means there is no
4228        // valid Picture passed to WebView yet. This can happen when WebView
4229        // just starts. Draw the background and return.
4230        if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
4231            canvas.drawColor(mBackgroundColor);
4232            return;
4233        }
4234
4235        if (canvas.isHardwareAccelerated()) {
4236            if (mIncrementEGLContextHack == false) {
4237                mIncrementEGLContextHack = true;
4238                EGL10 egl = (EGL10) EGLContext.getEGL();
4239                EGLDisplay eglDisplay = egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
4240                int[] version = new int[2];
4241                egl.eglInitialize(eglDisplay, version);
4242            }
4243            mZoomManager.setHardwareAccelerated();
4244        }
4245
4246        int saveCount = canvas.save();
4247        if (mInOverScrollMode && !getSettings()
4248                .getUseWebViewBackgroundForOverscrollBackground()) {
4249            drawOverScrollBackground(canvas);
4250        }
4251        if (mTitleBar != null) {
4252            canvas.translate(0, getTitleHeight());
4253        }
4254        boolean drawJavaRings = !mTouchHighlightRegion.isEmpty()
4255                && (mTouchMode == TOUCH_INIT_MODE
4256                || mTouchMode == TOUCH_SHORTPRESS_START_MODE
4257                || mTouchMode == TOUCH_SHORTPRESS_MODE
4258                || mTouchMode == TOUCH_DONE_MODE);
4259        boolean drawNativeRings = !drawJavaRings;
4260        if (USE_WEBKIT_RINGS) {
4261            drawNativeRings = !drawJavaRings && !isInTouchMode();
4262        }
4263        drawContent(canvas, drawNativeRings);
4264        canvas.restoreToCount(saveCount);
4265
4266        if (AUTO_REDRAW_HACK && mAutoRedraw) {
4267            invalidate();
4268        }
4269        mWebViewCore.signalRepaintDone();
4270
4271        if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
4272            invalidate();
4273        }
4274
4275        // paint the highlight in the end
4276        if (drawJavaRings) {
4277            long delay = System.currentTimeMillis() - mTouchHighlightRequested;
4278            if (delay < ViewConfiguration.getTapTimeout()) {
4279                Rect r = mTouchHighlightRegion.getBounds();
4280                postInvalidateDelayed(delay, r.left, r.top, r.right, r.bottom);
4281            } else {
4282                if (mTouchHightlightPaint == null) {
4283                    mTouchHightlightPaint = new Paint();
4284                    mTouchHightlightPaint.setColor(HIGHLIGHT_COLOR);
4285                }
4286                RegionIterator iter = new RegionIterator(mTouchHighlightRegion);
4287                Rect r = new Rect();
4288                while (iter.next(r)) {
4289                    canvas.drawRect(r, mTouchHightlightPaint);
4290                }
4291            }
4292        }
4293        if (DEBUG_TOUCH_HIGHLIGHT) {
4294            if (getSettings().getNavDump()) {
4295                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
4296                    if (mTouchCrossHairColor == null) {
4297                        mTouchCrossHairColor = new Paint();
4298                        mTouchCrossHairColor.setColor(Color.RED);
4299                    }
4300                    canvas.drawLine(mTouchHighlightX - mNavSlop,
4301                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4302                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
4303                                    + 1, mTouchCrossHairColor);
4304                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
4305                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4306                                    - mNavSlop,
4307                            mTouchHighlightY + mNavSlop + 1,
4308                            mTouchCrossHairColor);
4309                }
4310            }
4311        }
4312    }
4313
4314    private void removeTouchHighlight() {
4315        mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS);
4316        mPrivateHandler.removeMessages(SET_TOUCH_HIGHLIGHT_RECTS);
4317        setTouchHighlightRects(null);
4318    }
4319
4320    @Override
4321    public void setLayoutParams(ViewGroup.LayoutParams params) {
4322        if (params.height == LayoutParams.WRAP_CONTENT) {
4323            mWrapContent = true;
4324        }
4325        super.setLayoutParams(params);
4326    }
4327
4328    @Override
4329    public boolean performLongClick() {
4330        // performLongClick() is the result of a delayed message. If we switch
4331        // to windows overview, the WebView will be temporarily removed from the
4332        // view system. In that case, do nothing.
4333        if (getParent() == null) return false;
4334
4335        // A multi-finger gesture can look like a long press; make sure we don't take
4336        // long press actions if we're scaling.
4337        final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
4338        if (detector != null && detector.isInProgress()) {
4339            return false;
4340        }
4341
4342        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
4343            // Send the click so that the textfield is in focus
4344            centerKeyPressOnTextField();
4345            rebuildWebTextView();
4346        } else {
4347            clearTextEntry();
4348        }
4349        if (inEditingMode()) {
4350            // Since we just called rebuildWebTextView, the layout is not set
4351            // properly.  Update it so it can correctly find the word to select.
4352            mWebTextView.ensureLayout();
4353            // Provide a touch down event to WebTextView, which will allow it
4354            // to store the location to use in performLongClick.
4355            AbsoluteLayout.LayoutParams params
4356                    = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams();
4357            MotionEvent fake = MotionEvent.obtain(mLastTouchTime,
4358                    mLastTouchTime, MotionEvent.ACTION_DOWN,
4359                    mLastTouchX - params.x + mScrollX,
4360                    mLastTouchY - params.y + mScrollY, 0);
4361            mWebTextView.dispatchTouchEvent(fake);
4362            return mWebTextView.performLongClick();
4363        }
4364        if (mSelectingText) return false; // long click does nothing on selection
4365        /* if long click brings up a context menu, the super function
4366         * returns true and we're done. Otherwise, nothing happened when
4367         * the user clicked. */
4368        if (super.performLongClick()) {
4369            return true;
4370        }
4371        /* In the case where the application hasn't already handled the long
4372         * click action, look for a word under the  click. If one is found,
4373         * animate the text selection into view.
4374         * FIXME: no animation code yet */
4375        final boolean isSelecting = selectText();
4376        if (isSelecting) {
4377            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4378        }
4379        return isSelecting;
4380    }
4381
4382    /**
4383     * Select the word at the last click point.
4384     *
4385     * @hide pending API council approval
4386     */
4387    public boolean selectText() {
4388        int x = viewToContentX(mLastTouchX + mScrollX);
4389        int y = viewToContentY(mLastTouchY + mScrollY);
4390        return selectText(x, y);
4391    }
4392
4393    /**
4394     * Select the word at the indicated content coordinates.
4395     */
4396    boolean selectText(int x, int y) {
4397        if (!setUpSelect(true, x, y)) {
4398            return false;
4399        }
4400        nativeSetExtendSelection();
4401        mDrawSelectionPointer = false;
4402        mTouchMode = TOUCH_DRAG_MODE;
4403        return true;
4404    }
4405
4406    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
4407
4408    @Override
4409    protected void onConfigurationChanged(Configuration newConfig) {
4410        mCachedOverlappingActionModeHeight = -1;
4411        if (mSelectingText && mOrientation != newConfig.orientation) {
4412            selectionDone();
4413        }
4414        mOrientation = newConfig.orientation;
4415        if (mWebViewCore != null && !mBlockWebkitViewMessages) {
4416            mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
4417        }
4418    }
4419
4420    /**
4421     * Keep track of the Callback so we can end its ActionMode or remove its
4422     * titlebar.
4423     */
4424    private SelectActionModeCallback mSelectCallback;
4425
4426    // These values are possible options for didUpdateWebTextViewDimensions.
4427    private static final int FULLY_ON_SCREEN = 0;
4428    private static final int INTERSECTS_SCREEN = 1;
4429    private static final int ANYWHERE = 2;
4430
4431    /**
4432     * Check to see if the focused textfield/textarea is still on screen.  If it
4433     * is, update the the dimensions and location of WebTextView.  Otherwise,
4434     * remove the WebTextView.  Should be called when the zoom level changes.
4435     * @param intersection How to determine whether the textfield/textarea is
4436     *        still on screen.
4437     * @return boolean True if the textfield/textarea is still on screen and the
4438     *         dimensions/location of WebTextView have been updated.
4439     */
4440    private boolean didUpdateWebTextViewDimensions(int intersection) {
4441        Rect contentBounds = nativeFocusCandidateNodeBounds();
4442        Rect vBox = contentToViewRect(contentBounds);
4443        Rect visibleRect = new Rect();
4444        calcOurVisibleRect(visibleRect);
4445        // If the textfield is on screen, place the WebTextView in
4446        // its new place, accounting for our new scroll/zoom values,
4447        // and adjust its textsize.
4448        boolean onScreen;
4449        switch (intersection) {
4450            case FULLY_ON_SCREEN:
4451                onScreen = visibleRect.contains(vBox);
4452                break;
4453            case INTERSECTS_SCREEN:
4454                onScreen = Rect.intersects(visibleRect, vBox);
4455                break;
4456            case ANYWHERE:
4457                onScreen = true;
4458                break;
4459            default:
4460                throw new AssertionError(
4461                        "invalid parameter passed to didUpdateWebTextViewDimensions");
4462        }
4463        if (onScreen) {
4464            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
4465                    vBox.height());
4466            mWebTextView.updateTextSize();
4467            updateWebTextViewPadding();
4468            return true;
4469        } else {
4470            // The textfield is now off screen.  The user probably
4471            // was not zooming to see the textfield better.  Remove
4472            // the WebTextView.  If the user types a key, and the
4473            // textfield is still in focus, we will reconstruct
4474            // the WebTextView and scroll it back on screen.
4475            mWebTextView.remove();
4476            return false;
4477        }
4478    }
4479
4480    void setBaseLayer(int layer, Region invalRegion, boolean showVisualIndicator,
4481            boolean isPictureAfterFirstLayout, boolean registerPageSwapCallback) {
4482        if (mNativeClass == 0)
4483            return;
4484        nativeSetBaseLayer(layer, invalRegion, showVisualIndicator,
4485                isPictureAfterFirstLayout, registerPageSwapCallback);
4486        if (mHTML5VideoViewProxy != null) {
4487            mHTML5VideoViewProxy.setBaseLayer(layer);
4488        }
4489    }
4490
4491    int getBaseLayer() {
4492        if (mNativeClass == 0) {
4493            return 0;
4494        }
4495        return nativeGetBaseLayer();
4496    }
4497
4498    private void onZoomAnimationStart() {
4499        // If it is in password mode, turn it off so it does not draw misplaced.
4500        if (inEditingMode()) {
4501            mWebTextView.setVisibility(INVISIBLE);
4502        }
4503    }
4504
4505    private void onZoomAnimationEnd() {
4506        // adjust the edit text view if needed
4507        if (inEditingMode()
4508                && didUpdateWebTextViewDimensions(FULLY_ON_SCREEN)) {
4509            // If it is a password field, start drawing the WebTextView once
4510            // again.
4511            mWebTextView.setVisibility(VISIBLE);
4512        }
4513    }
4514
4515    void onFixedLengthZoomAnimationStart() {
4516        WebViewCore.pauseUpdatePicture(getWebViewCore());
4517        onZoomAnimationStart();
4518    }
4519
4520    void onFixedLengthZoomAnimationEnd() {
4521        if (!mBlockWebkitViewMessages && !mSelectingText) {
4522            WebViewCore.resumeUpdatePicture(mWebViewCore);
4523        }
4524        onZoomAnimationEnd();
4525    }
4526
4527    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4528                                         Paint.DITHER_FLAG |
4529                                         Paint.SUBPIXEL_TEXT_FLAG;
4530    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
4531                                           Paint.DITHER_FLAG;
4532
4533    private final DrawFilter mZoomFilter =
4534            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4535    // If we need to trade better quality for speed, set mScrollFilter to null
4536    private final DrawFilter mScrollFilter =
4537            new PaintFlagsDrawFilter(SCROLL_BITS, 0);
4538
4539    private void drawCoreAndCursorRing(Canvas canvas, int color,
4540        boolean drawCursorRing) {
4541        if (mDrawHistory) {
4542            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4543            canvas.drawPicture(mHistoryPicture);
4544            return;
4545        }
4546        if (mNativeClass == 0) return;
4547
4548        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
4549        boolean animateScroll = ((!mScroller.isFinished()
4550                || mVelocityTracker != null)
4551                && (mTouchMode != TOUCH_DRAG_MODE ||
4552                mHeldMotionless != MOTIONLESS_TRUE))
4553                || mDeferTouchMode == TOUCH_DRAG_MODE;
4554        if (mTouchMode == TOUCH_DRAG_MODE) {
4555            if (mHeldMotionless == MOTIONLESS_PENDING) {
4556                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4557                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4558                mHeldMotionless = MOTIONLESS_FALSE;
4559            }
4560            if (mHeldMotionless == MOTIONLESS_FALSE) {
4561                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4562                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
4563                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4564                        .obtainMessage(AWAKEN_SCROLL_BARS),
4565                            ViewConfiguration.getScrollDefaultDelay());
4566                mHeldMotionless = MOTIONLESS_PENDING;
4567            }
4568        }
4569        int saveCount = canvas.save();
4570        if (animateZoom) {
4571            mZoomManager.animateZoom(canvas);
4572        } else if (!canvas.isHardwareAccelerated()) {
4573            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4574        }
4575
4576        boolean UIAnimationsRunning = false;
4577        // Currently for each draw we compute the animation values;
4578        // We may in the future decide to do that independently.
4579        if (mNativeClass != 0 && nativeEvaluateLayersAnimations(mNativeClass)) {
4580            UIAnimationsRunning = true;
4581            // If we have unfinished (or unstarted) animations,
4582            // we ask for a repaint. We only need to do this in software
4583            // rendering (with hardware rendering we already have a different
4584            // method of requesting a repaint)
4585            if (!canvas.isHardwareAccelerated())
4586                invalidate();
4587        }
4588
4589        // decide which adornments to draw
4590        int extras = DRAW_EXTRAS_NONE;
4591        if (mFindIsUp) {
4592            extras = DRAW_EXTRAS_FIND;
4593        } else if (mSelectingText && (!USE_JAVA_TEXT_SELECTION || DEBUG_TEXT_HANDLES)) {
4594            extras = DRAW_EXTRAS_SELECTION;
4595            nativeSetSelectionPointer(mNativeClass,
4596                    mDrawSelectionPointer,
4597                    mZoomManager.getInvScale(), mSelectX, mSelectY - getTitleHeight());
4598        } else if (drawCursorRing) {
4599            extras = DRAW_EXTRAS_CURSOR_RING;
4600        }
4601        if (DebugFlags.WEB_VIEW) {
4602            Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp
4603                    + " mSelectingText=" + mSelectingText
4604                    + " nativePageShouldHandleShiftAndArrows()="
4605                    + nativePageShouldHandleShiftAndArrows()
4606                    + " animateZoom=" + animateZoom
4607                    + " extras=" + extras);
4608        }
4609
4610        if (canvas.isHardwareAccelerated()) {
4611            int functor = nativeGetDrawGLFunction(mNativeClass,
4612                    mGLViewportEmpty ? null : mGLRectViewport, mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras);
4613            ((HardwareCanvas) canvas).callDrawGLFunction(functor);
4614
4615            if (mHardwareAccelSkia != getSettings().getHardwareAccelSkiaEnabled()) {
4616                mHardwareAccelSkia = getSettings().getHardwareAccelSkiaEnabled();
4617                nativeUseHardwareAccelSkia(mHardwareAccelSkia);
4618            }
4619
4620        } else {
4621            DrawFilter df = null;
4622            if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
4623                df = mZoomFilter;
4624            } else if (animateScroll) {
4625                df = mScrollFilter;
4626            }
4627            canvas.setDrawFilter(df);
4628            // XXX: Revisit splitting content.  Right now it causes a
4629            // synchronization problem with layers.
4630            int content = nativeDraw(canvas, color, extras, false);
4631            canvas.setDrawFilter(null);
4632            if (!mBlockWebkitViewMessages && content != 0) {
4633                mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
4634            }
4635        }
4636
4637        canvas.restoreToCount(saveCount);
4638        if (mSelectingText && USE_JAVA_TEXT_SELECTION) {
4639            drawTextSelectionHandles(canvas);
4640        }
4641
4642        if (extras == DRAW_EXTRAS_CURSOR_RING) {
4643            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
4644                mTouchMode = TOUCH_SHORTPRESS_MODE;
4645            }
4646        }
4647        if (mFocusSizeChanged) {
4648            mFocusSizeChanged = false;
4649            // If we are zooming, this will get handled above, when the zoom
4650            // finishes.  We also do not need to do this unless the WebTextView
4651            // is showing. With hardware acceleration, the pageSwapCallback()
4652            // updates the WebTextView position in sync with page swapping
4653            if (!canvas.isHardwareAccelerated() && !animateZoom && inEditingMode()) {
4654                didUpdateWebTextViewDimensions(ANYWHERE);
4655            }
4656        }
4657    }
4658
4659    private void drawTextSelectionHandles(Canvas canvas) {
4660        if (mTextSelectionPaint == null) {
4661            mTextSelectionPaint = new Paint();
4662            mTextSelectionPaint.setColor(HIGHLIGHT_COLOR);
4663        }
4664        mTextSelectionRegion.setEmpty();
4665        nativeGetTextSelectionRegion(mNativeClass, mTextSelectionRegion);
4666        Rect r = new Rect();
4667        RegionIterator iter = new RegionIterator(mTextSelectionRegion);
4668        Rect clip = canvas.getClipBounds();
4669        while (iter.next(r)) {
4670            r.set(contentToViewDimension(r.left),
4671                    contentToViewDimension(r.top),
4672                    contentToViewDimension(r.right),
4673                    contentToViewDimension(r.bottom));
4674            if (r.intersect(clip)) {
4675                canvas.drawRect(r, mTextSelectionPaint);
4676            }
4677        }
4678        if (mSelectHandleLeft == null) {
4679            mSelectHandleLeft = mContext.getResources().getDrawable(
4680                    com.android.internal.R.drawable.text_select_handle_left);
4681        }
4682        int[] handles = new int[4];
4683        nativeGetSelectionHandles(mNativeClass, handles);
4684        int start_x = contentToViewDimension(handles[0]);
4685        int start_y = contentToViewDimension(handles[1]);
4686        int end_x = contentToViewDimension(handles[2]);
4687        int end_y = contentToViewDimension(handles[3]);
4688        // Magic formula copied from TextView
4689        start_x -= (mSelectHandleLeft.getIntrinsicWidth() * 3) / 4;
4690        mSelectHandleLeft.setBounds(start_x, start_y,
4691                start_x + mSelectHandleLeft.getIntrinsicWidth(),
4692                start_y + mSelectHandleLeft.getIntrinsicHeight());
4693        if (mSelectHandleRight == null) {
4694            mSelectHandleRight = mContext.getResources().getDrawable(
4695                    com.android.internal.R.drawable.text_select_handle_right);
4696        }
4697        end_x -= mSelectHandleRight.getIntrinsicWidth() / 4;
4698        mSelectHandleRight.setBounds(end_x, end_y,
4699                end_x + mSelectHandleRight.getIntrinsicWidth(),
4700                end_y + mSelectHandleRight.getIntrinsicHeight());
4701        if (DEBUG_TEXT_HANDLES) {
4702            mSelectHandleLeft.setAlpha(125);
4703            mSelectHandleRight.setAlpha(125);
4704        }
4705        mSelectHandleLeft.draw(canvas);
4706        mSelectHandleRight.draw(canvas);
4707    }
4708
4709    // draw history
4710    private boolean mDrawHistory = false;
4711    private Picture mHistoryPicture = null;
4712    private int mHistoryWidth = 0;
4713    private int mHistoryHeight = 0;
4714
4715    // Only check the flag, can be called from WebCore thread
4716    boolean drawHistory() {
4717        return mDrawHistory;
4718    }
4719
4720    int getHistoryPictureWidth() {
4721        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
4722    }
4723
4724    // Should only be called in UI thread
4725    void switchOutDrawHistory() {
4726        if (null == mWebViewCore) return; // CallbackProxy may trigger this
4727        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
4728            mDrawHistory = false;
4729            mHistoryPicture = null;
4730            invalidate();
4731            int oldScrollX = mScrollX;
4732            int oldScrollY = mScrollY;
4733            mScrollX = pinLocX(mScrollX);
4734            mScrollY = pinLocY(mScrollY);
4735            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
4736                onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY);
4737            } else {
4738                sendOurVisibleRect();
4739            }
4740        }
4741    }
4742
4743    WebViewCore.CursorData cursorData() {
4744        WebViewCore.CursorData result = cursorDataNoPosition();
4745        Point position = nativeCursorPosition();
4746        result.mX = position.x;
4747        result.mY = position.y;
4748        return result;
4749    }
4750
4751    WebViewCore.CursorData cursorDataNoPosition() {
4752        WebViewCore.CursorData result = new WebViewCore.CursorData();
4753        result.mMoveGeneration = nativeMoveGeneration();
4754        result.mFrame = nativeCursorFramePointer();
4755        return result;
4756    }
4757
4758    /**
4759     *  Delete text from start to end in the focused textfield. If there is no
4760     *  focus, or if start == end, silently fail.  If start and end are out of
4761     *  order, swap them.
4762     *  @param  start   Beginning of selection to delete.
4763     *  @param  end     End of selection to delete.
4764     */
4765    /* package */ void deleteSelection(int start, int end) {
4766        mTextGeneration++;
4767        WebViewCore.TextSelectionData data
4768                = new WebViewCore.TextSelectionData(start, end);
4769        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
4770                data);
4771    }
4772
4773    /**
4774     *  Set the selection to (start, end) in the focused textfield. If start and
4775     *  end are out of order, swap them.
4776     *  @param  start   Beginning of selection.
4777     *  @param  end     End of selection.
4778     */
4779    /* package */ void setSelection(int start, int end) {
4780        if (mWebViewCore != null) {
4781            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
4782        }
4783    }
4784
4785    @Override
4786    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4787      InputConnection connection = super.onCreateInputConnection(outAttrs);
4788      outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN;
4789      return connection;
4790    }
4791
4792    /**
4793     * Called in response to a message from webkit telling us that the soft
4794     * keyboard should be launched.
4795     */
4796    private void displaySoftKeyboard(boolean isTextView) {
4797        InputMethodManager imm = (InputMethodManager)
4798                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
4799
4800        // bring it back to the default level scale so that user can enter text
4801        boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
4802        if (zoom) {
4803            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
4804            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
4805        }
4806        if (isTextView) {
4807            rebuildWebTextView();
4808            if (inEditingMode()) {
4809                imm.showSoftInput(mWebTextView, 0, mWebTextView.getResultReceiver());
4810                if (zoom) {
4811                    didUpdateWebTextViewDimensions(INTERSECTS_SCREEN);
4812                }
4813                return;
4814            }
4815        }
4816        // Used by plugins and contentEditable.
4817        // Also used if the navigation cache is out of date, and
4818        // does not recognize that a textfield is in focus.  In that
4819        // case, use WebView as the targeted view.
4820        // see http://b/issue?id=2457459
4821        imm.showSoftInput(this, 0);
4822    }
4823
4824    // Called by WebKit to instruct the UI to hide the keyboard
4825    private void hideSoftKeyboard() {
4826        InputMethodManager imm = InputMethodManager.peekInstance();
4827        if (imm != null && (imm.isActive(this)
4828                || (inEditingMode() && imm.isActive(mWebTextView)))) {
4829            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
4830        }
4831    }
4832
4833    /*
4834     * This method checks the current focus and cursor and potentially rebuilds
4835     * mWebTextView to have the appropriate properties, such as password,
4836     * multiline, and what text it contains.  It also removes it if necessary.
4837     */
4838    /* package */ void rebuildWebTextView() {
4839        // If the WebView does not have focus, do nothing until it gains focus.
4840        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
4841            return;
4842        }
4843        boolean alreadyThere = inEditingMode();
4844        // inEditingMode can only return true if mWebTextView is non-null,
4845        // so we can safely call remove() if (alreadyThere)
4846        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
4847            if (alreadyThere) {
4848                mWebTextView.remove();
4849            }
4850            return;
4851        }
4852        // At this point, we know we have found an input field, so go ahead
4853        // and create the WebTextView if necessary.
4854        if (mWebTextView == null) {
4855            mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId());
4856            // Initialize our generation number.
4857            mTextGeneration = 0;
4858        }
4859        mWebTextView.updateTextSize();
4860        updateWebTextViewPosition();
4861        String text = nativeFocusCandidateText();
4862        int nodePointer = nativeFocusCandidatePointer();
4863        // This needs to be called before setType, which may call
4864        // requestFormData, and it needs to have the correct nodePointer.
4865        mWebTextView.setNodePointer(nodePointer);
4866        mWebTextView.setType(nativeFocusCandidateType());
4867        // Gravity needs to be set after setType
4868        mWebTextView.setGravityForRtl(nativeFocusCandidateIsRtlText());
4869        if (null == text) {
4870            if (DebugFlags.WEB_VIEW) {
4871                Log.v(LOGTAG, "rebuildWebTextView null == text");
4872            }
4873            text = "";
4874        }
4875        mWebTextView.setTextAndKeepSelection(text);
4876        InputMethodManager imm = InputMethodManager.peekInstance();
4877        if (imm != null && imm.isActive(mWebTextView)) {
4878            imm.restartInput(mWebTextView);
4879            mWebTextView.clearComposingText();
4880        }
4881        if (isFocused()) {
4882            mWebTextView.requestFocus();
4883        }
4884    }
4885
4886    private void updateWebTextViewPosition() {
4887        Rect visibleRect = new Rect();
4888        calcOurContentVisibleRect(visibleRect);
4889        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
4890        // should be in content coordinates.
4891        Rect bounds = nativeFocusCandidateNodeBounds();
4892        Rect vBox = contentToViewRect(bounds);
4893        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
4894        if (!Rect.intersects(bounds, visibleRect)) {
4895            revealSelection();
4896        }
4897        updateWebTextViewPadding();
4898    }
4899
4900    /**
4901     * Update the padding of mWebTextView based on the native textfield/textarea
4902     */
4903    void updateWebTextViewPadding() {
4904        Rect paddingRect = nativeFocusCandidatePaddingRect();
4905        if (paddingRect != null) {
4906            // Use contentToViewDimension since these are the dimensions of
4907            // the padding.
4908            mWebTextView.setPadding(
4909                    contentToViewDimension(paddingRect.left),
4910                    contentToViewDimension(paddingRect.top),
4911                    contentToViewDimension(paddingRect.right),
4912                    contentToViewDimension(paddingRect.bottom));
4913        }
4914    }
4915
4916    /**
4917     * Tell webkit to put the cursor on screen.
4918     */
4919    /* package */ void revealSelection() {
4920        if (mWebViewCore != null) {
4921            mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION);
4922        }
4923    }
4924
4925    /**
4926     * Called by WebTextView to find saved form data associated with the
4927     * textfield
4928     * @param name Name of the textfield.
4929     * @param nodePointer Pointer to the node of the textfield, so it can be
4930     *          compared to the currently focused textfield when the data is
4931     *          retrieved.
4932     * @param autoFillable true if WebKit has determined this field is part of
4933     *          a form that can be auto filled.
4934     * @param autoComplete true if the attribute "autocomplete" is set to true
4935     *          on the textfield.
4936     */
4937    /* package */ void requestFormData(String name, int nodePointer,
4938            boolean autoFillable, boolean autoComplete) {
4939        if (mWebViewCore.getSettings().getSaveFormData()) {
4940            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
4941            update.arg1 = nodePointer;
4942            RequestFormData updater = new RequestFormData(name, getUrl(),
4943                    update, autoFillable, autoComplete);
4944            Thread t = new Thread(updater);
4945            t.start();
4946        }
4947    }
4948
4949    /**
4950     * Pass a message to find out the <label> associated with the <input>
4951     * identified by nodePointer
4952     * @param framePointer Pointer to the frame containing the <input> node
4953     * @param nodePointer Pointer to the node for which a <label> is desired.
4954     */
4955    /* package */ void requestLabel(int framePointer, int nodePointer) {
4956        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
4957                nodePointer);
4958    }
4959
4960    /*
4961     * This class requests an Adapter for the WebTextView which shows past
4962     * entries stored in the database.  It is a Runnable so that it can be done
4963     * in its own thread, without slowing down the UI.
4964     */
4965    private class RequestFormData implements Runnable {
4966        private String mName;
4967        private String mUrl;
4968        private Message mUpdateMessage;
4969        private boolean mAutoFillable;
4970        private boolean mAutoComplete;
4971        private WebSettings mWebSettings;
4972
4973        public RequestFormData(String name, String url, Message msg,
4974                boolean autoFillable, boolean autoComplete) {
4975            mName = name;
4976            mUrl = WebTextView.urlForAutoCompleteData(url);
4977            mUpdateMessage = msg;
4978            mAutoFillable = autoFillable;
4979            mAutoComplete = autoComplete;
4980            mWebSettings = getSettings();
4981        }
4982
4983        public void run() {
4984            ArrayList<String> pastEntries = new ArrayList<String>();
4985
4986            if (mAutoFillable) {
4987                // Note that code inside the adapter click handler in WebTextView depends
4988                // on the AutoFill item being at the top of the drop down list. If you change
4989                // the order, make sure to do it there too!
4990                if (mWebSettings != null && mWebSettings.getAutoFillProfile() != null) {
4991                    pastEntries.add(getResources().getText(
4992                            com.android.internal.R.string.autofill_this_form).toString() +
4993                            " " +
4994                            mAutoFillData.getPreviewString());
4995                    mWebTextView.setAutoFillProfileIsSet(true);
4996                } else {
4997                    // There is no autofill profile set up yet, so add an option that
4998                    // will invite the user to set their profile up.
4999                    pastEntries.add(getResources().getText(
5000                            com.android.internal.R.string.setup_autofill).toString());
5001                    mWebTextView.setAutoFillProfileIsSet(false);
5002                }
5003            }
5004
5005            if (mAutoComplete) {
5006                pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
5007            }
5008
5009            if (pastEntries.size() > 0) {
5010                AutoCompleteAdapter adapter = new
5011                        AutoCompleteAdapter(mContext, pastEntries);
5012                mUpdateMessage.obj = adapter;
5013                mUpdateMessage.sendToTarget();
5014            }
5015        }
5016    }
5017
5018    /**
5019     * Dump the display tree to "/sdcard/displayTree.txt"
5020     *
5021     * @hide debug only
5022     */
5023    public void dumpDisplayTree() {
5024        nativeDumpDisplayTree(getUrl());
5025    }
5026
5027    /**
5028     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
5029     * "/sdcard/domTree.txt"
5030     *
5031     * @hide debug only
5032     */
5033    public void dumpDomTree(boolean toFile) {
5034        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
5035    }
5036
5037    /**
5038     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
5039     * to "/sdcard/renderTree.txt"
5040     *
5041     * @hide debug only
5042     */
5043    public void dumpRenderTree(boolean toFile) {
5044        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
5045    }
5046
5047    /**
5048     * Called by DRT on UI thread, need to proxy to WebCore thread.
5049     *
5050     * @hide debug only
5051     */
5052    public void useMockDeviceOrientation() {
5053        mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
5054    }
5055
5056    /**
5057     * Called by DRT on WebCore thread.
5058     *
5059     * @hide debug only
5060     */
5061    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
5062            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
5063        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
5064                canProvideGamma, gamma);
5065    }
5066
5067    /**
5068     * Dump the V8 counters to standard output.
5069     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
5070     * true. Otherwise, this will do nothing.
5071     *
5072     * @hide debug only
5073     */
5074    public void dumpV8Counters() {
5075        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
5076    }
5077
5078    // This is used to determine long press with the center key.  Does not
5079    // affect long press with the trackball/touch.
5080    private boolean mGotCenterDown = false;
5081
5082    @Override
5083    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5084        if (mBlockWebkitViewMessages) {
5085            return false;
5086        }
5087        // send complex characters to webkit for use by JS and plugins
5088        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
5089            // pass the key to DOM
5090            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5091            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5092            // return true as DOM handles the key
5093            return true;
5094        }
5095        return false;
5096    }
5097
5098    private boolean isEnterActionKey(int keyCode) {
5099        return keyCode == KeyEvent.KEYCODE_DPAD_CENTER
5100                || keyCode == KeyEvent.KEYCODE_ENTER
5101                || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER;
5102    }
5103
5104    @Override
5105    public boolean onKeyDown(int keyCode, KeyEvent event) {
5106        if (DebugFlags.WEB_VIEW) {
5107            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
5108                    + "keyCode=" + keyCode
5109                    + ", " + event + ", unicode=" + event.getUnicodeChar());
5110        }
5111        if (mBlockWebkitViewMessages) {
5112            return false;
5113        }
5114
5115        // don't implement accelerator keys here; defer to host application
5116        if (event.isCtrlPressed()) {
5117            return false;
5118        }
5119
5120        if (mNativeClass == 0) {
5121            return false;
5122        }
5123
5124        // do this hack up front, so it always works, regardless of touch-mode
5125        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
5126            mAutoRedraw = !mAutoRedraw;
5127            if (mAutoRedraw) {
5128                invalidate();
5129            }
5130            return true;
5131        }
5132
5133        // Bubble up the key event if
5134        // 1. it is a system key; or
5135        // 2. the host application wants to handle it;
5136        if (event.isSystem()
5137                || mCallbackProxy.uiOverrideKeyEvent(event)) {
5138            return false;
5139        }
5140
5141        // accessibility support
5142        if (accessibilityScriptInjected()) {
5143            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5144                // if an accessibility script is injected we delegate to it the key handling.
5145                // this script is a screen reader which is a fully fledged solution for blind
5146                // users to navigate in and interact with web pages.
5147                mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5148                return true;
5149            } else {
5150                // Clean up if accessibility was disabled after loading the current URL.
5151                mAccessibilityScriptInjected = false;
5152            }
5153        } else if (mAccessibilityInjector != null) {
5154            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5155                if (mAccessibilityInjector.onKeyEvent(event)) {
5156                    // if an accessibility injector is present (no JavaScript enabled or the site
5157                    // opts out injecting our JavaScript screen reader) we let it decide whether
5158                    // to act on and consume the event.
5159                    return true;
5160                }
5161            } else {
5162                // Clean up if accessibility was disabled after loading the current URL.
5163                mAccessibilityInjector = null;
5164            }
5165        }
5166
5167        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
5168            if (event.hasNoModifiers()) {
5169                pageUp(false);
5170                return true;
5171            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
5172                pageUp(true);
5173                return true;
5174            }
5175        }
5176
5177        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
5178            if (event.hasNoModifiers()) {
5179                pageDown(false);
5180                return true;
5181            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
5182                pageDown(true);
5183                return true;
5184            }
5185        }
5186
5187        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) {
5188            pageUp(true);
5189            return true;
5190        }
5191
5192        if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) {
5193            pageDown(true);
5194            return true;
5195        }
5196
5197        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
5198                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
5199            switchOutDrawHistory();
5200            if (nativePageShouldHandleShiftAndArrows()) {
5201                letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState());
5202                return true;
5203            }
5204            if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
5205                switch (keyCode) {
5206                    case KeyEvent.KEYCODE_DPAD_UP:
5207                        pageUp(true);
5208                        return true;
5209                    case KeyEvent.KEYCODE_DPAD_DOWN:
5210                        pageDown(true);
5211                        return true;
5212                    case KeyEvent.KEYCODE_DPAD_LEFT:
5213                        nativeClearCursor(); // start next trackball movement from page edge
5214                        return pinScrollTo(0, mScrollY, true, 0);
5215                    case KeyEvent.KEYCODE_DPAD_RIGHT:
5216                        nativeClearCursor(); // start next trackball movement from page edge
5217                        return pinScrollTo(mContentWidth, mScrollY, true, 0);
5218                }
5219            }
5220            if (mSelectingText) {
5221                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
5222                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
5223                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
5224                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
5225                int multiplier = event.getRepeatCount() + 1;
5226                moveSelection(xRate * multiplier, yRate * multiplier);
5227                return true;
5228            }
5229            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
5230                playSoundEffect(keyCodeToSoundsEffect(keyCode));
5231                return true;
5232            }
5233            // Bubble up the key event as WebView doesn't handle it
5234            return false;
5235        }
5236
5237        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
5238            switchOutDrawHistory();
5239            boolean wantsKeyEvents = nativeCursorNodePointer() == 0
5240                || nativeCursorWantsKeyEvents();
5241            if (event.getRepeatCount() == 0) {
5242                if (mSelectingText) {
5243                    return true; // discard press if copy in progress
5244                }
5245                mGotCenterDown = true;
5246                mPrivateHandler.sendMessageDelayed(mPrivateHandler
5247                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
5248                if (!wantsKeyEvents) return true;
5249            }
5250            // Bubble up the key event as WebView doesn't handle it
5251            if (!wantsKeyEvents) return false;
5252        }
5253
5254        if (getSettings().getNavDump()) {
5255            switch (keyCode) {
5256                case KeyEvent.KEYCODE_4:
5257                    dumpDisplayTree();
5258                    break;
5259                case KeyEvent.KEYCODE_5:
5260                case KeyEvent.KEYCODE_6:
5261                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
5262                    break;
5263                case KeyEvent.KEYCODE_7:
5264                case KeyEvent.KEYCODE_8:
5265                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
5266                    break;
5267                case KeyEvent.KEYCODE_9:
5268                    nativeInstrumentReport();
5269                    return true;
5270            }
5271        }
5272
5273        if (nativeCursorIsTextInput()) {
5274            // This message will put the node in focus, for the DOM's notion
5275            // of focus.
5276            mWebViewCore.sendMessage(EventHub.FAKE_CLICK, nativeCursorFramePointer(),
5277                    nativeCursorNodePointer());
5278            // This will bring up the WebTextView and put it in focus, for
5279            // our view system's notion of focus
5280            rebuildWebTextView();
5281            // Now we need to pass the event to it
5282            if (inEditingMode()) {
5283                mWebTextView.setDefaultSelection();
5284                return mWebTextView.dispatchKeyEvent(event);
5285            }
5286        } else if (nativeHasFocusNode()) {
5287            // In this case, the cursor is not on a text input, but the focus
5288            // might be.  Check it, and if so, hand over to the WebTextView.
5289            rebuildWebTextView();
5290            if (inEditingMode()) {
5291                mWebTextView.setDefaultSelection();
5292                return mWebTextView.dispatchKeyEvent(event);
5293            }
5294        }
5295
5296        // TODO: should we pass all the keys to DOM or check the meta tag
5297        if (nativeCursorWantsKeyEvents() || true) {
5298            // pass the key to DOM
5299            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5300            // return true as DOM handles the key
5301            return true;
5302        }
5303
5304        // Bubble up the key event as WebView doesn't handle it
5305        return false;
5306    }
5307
5308    @Override
5309    public boolean onKeyUp(int keyCode, KeyEvent event) {
5310        if (DebugFlags.WEB_VIEW) {
5311            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
5312                    + ", " + event + ", unicode=" + event.getUnicodeChar());
5313        }
5314        if (mBlockWebkitViewMessages) {
5315            return false;
5316        }
5317
5318        if (mNativeClass == 0) {
5319            return false;
5320        }
5321
5322        // special CALL handling when cursor node's href is "tel:XXX"
5323        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
5324            String text = nativeCursorText();
5325            if (!nativeCursorIsTextInput() && text != null
5326                    && text.startsWith(SCHEME_TEL)) {
5327                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
5328                getContext().startActivity(intent);
5329                return true;
5330            }
5331        }
5332
5333        // Bubble up the key event if
5334        // 1. it is a system key; or
5335        // 2. the host application wants to handle it;
5336        if (event.isSystem()
5337                || mCallbackProxy.uiOverrideKeyEvent(event)) {
5338            return false;
5339        }
5340
5341        // accessibility support
5342        if (accessibilityScriptInjected()) {
5343            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5344                // if an accessibility script is injected we delegate to it the key handling.
5345                // this script is a screen reader which is a fully fledged solution for blind
5346                // users to navigate in and interact with web pages.
5347                mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5348                return true;
5349            } else {
5350                // Clean up if accessibility was disabled after loading the current URL.
5351                mAccessibilityScriptInjected = false;
5352            }
5353        } else if (mAccessibilityInjector != null) {
5354            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5355                if (mAccessibilityInjector.onKeyEvent(event)) {
5356                    // if an accessibility injector is present (no JavaScript enabled or the site
5357                    // opts out injecting our JavaScript screen reader) we let it decide whether to
5358                    // act on and consume the event.
5359                    return true;
5360                }
5361            } else {
5362                // Clean up if accessibility was disabled after loading the current URL.
5363                mAccessibilityInjector = null;
5364            }
5365        }
5366
5367        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
5368                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
5369            if (nativePageShouldHandleShiftAndArrows()) {
5370                letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState());
5371                return true;
5372            }
5373            // always handle the navigation keys in the UI thread
5374            // Bubble up the key event as WebView doesn't handle it
5375            return false;
5376        }
5377
5378        if (isEnterActionKey(keyCode)) {
5379            // remove the long press message first
5380            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5381            mGotCenterDown = false;
5382
5383            if (mSelectingText) {
5384                if (mExtendSelection) {
5385                    copySelection();
5386                    selectionDone();
5387                } else {
5388                    mExtendSelection = true;
5389                    nativeSetExtendSelection();
5390                    invalidate(); // draw the i-beam instead of the arrow
5391                }
5392                return true; // discard press if copy in progress
5393            }
5394
5395            // perform the single click
5396            Rect visibleRect = sendOurVisibleRect();
5397            // Note that sendOurVisibleRect calls viewToContent, so the
5398            // coordinates should be in content coordinates.
5399            if (!nativeCursorIntersects(visibleRect)) {
5400                return false;
5401            }
5402            WebViewCore.CursorData data = cursorData();
5403            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
5404            playSoundEffect(SoundEffectConstants.CLICK);
5405            if (nativeCursorIsTextInput()) {
5406                rebuildWebTextView();
5407                centerKeyPressOnTextField();
5408                if (inEditingMode()) {
5409                    mWebTextView.setDefaultSelection();
5410                }
5411                return true;
5412            }
5413            clearTextEntry();
5414            nativeShowCursorTimed();
5415            if (mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
5416                return true;
5417            }
5418            if (nativeCursorNodePointer() != 0 && !nativeCursorWantsKeyEvents()) {
5419                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
5420                        nativeCursorNodePointer());
5421                return true;
5422            }
5423        }
5424
5425        // TODO: should we pass all the keys to DOM or check the meta tag
5426        if (nativeCursorWantsKeyEvents() || true) {
5427            // pass the key to DOM
5428            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5429            // return true as DOM handles the key
5430            return true;
5431        }
5432
5433        // Bubble up the key event as WebView doesn't handle it
5434        return false;
5435    }
5436
5437    /*
5438     * Enter selecting text mode, and see if CAB should be shown.
5439     * Returns true if the WebView is now in
5440     * selecting text mode (including if it was already in that mode, and this
5441     * method did nothing).
5442     */
5443    private boolean setUpSelect(boolean selectWord, int x, int y) {
5444        if (0 == mNativeClass) return false; // client isn't initialized
5445        if (inFullScreenMode()) return false;
5446        if (mSelectingText) return true;
5447        nativeResetSelection();
5448        if (selectWord && !nativeWordSelection(x, y)) {
5449            selectionDone();
5450            return false;
5451        }
5452        mSelectCallback = new SelectActionModeCallback();
5453        mSelectCallback.setWebView(this);
5454        if (startActionMode(mSelectCallback) == null) {
5455            // There is no ActionMode, so do not allow the user to modify a
5456            // selection.
5457            selectionDone();
5458            return false;
5459        }
5460        mExtendSelection = false;
5461        mSelectingText = mDrawSelectionPointer = true;
5462        if (DEBUG_TEXT_HANDLES) {
5463            // Debugging text handles requires running in software mode
5464            setLayerType(LAYER_TYPE_SOFTWARE, null);
5465        }
5466        // don't let the picture change during text selection
5467        WebViewCore.pauseUpdatePicture(mWebViewCore);
5468        if (nativeHasCursorNode()) {
5469            Rect rect = nativeCursorNodeBounds();
5470            mSelectX = contentToViewX(rect.left);
5471            mSelectY = contentToViewY(rect.top);
5472        } else if (mLastTouchY > getVisibleTitleHeightImpl()) {
5473            mSelectX = mScrollX + mLastTouchX;
5474            mSelectY = mScrollY + mLastTouchY;
5475        } else {
5476            mSelectX = mScrollX + getViewWidth() / 2;
5477            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
5478        }
5479        nativeHideCursor();
5480        mMinAutoScrollX = 0;
5481        mMaxAutoScrollX = getViewWidth();
5482        mMinAutoScrollY = 0;
5483        mMaxAutoScrollY = getViewHeightWithTitle();
5484        mScrollingLayer = nativeScrollableLayer(viewToContentX(mSelectX),
5485                viewToContentY(mSelectY), mScrollingLayerRect,
5486                mScrollingLayerBounds);
5487        if (mScrollingLayer != 0) {
5488            if (mScrollingLayerRect.left != mScrollingLayerRect.right) {
5489                mMinAutoScrollX = Math.max(mMinAutoScrollX,
5490                        contentToViewX(mScrollingLayerBounds.left));
5491                mMaxAutoScrollX = Math.min(mMaxAutoScrollX,
5492                        contentToViewX(mScrollingLayerBounds.right));
5493            }
5494            if (mScrollingLayerRect.top != mScrollingLayerRect.bottom) {
5495                mMinAutoScrollY = Math.max(mMinAutoScrollY,
5496                        contentToViewY(mScrollingLayerBounds.top));
5497                mMaxAutoScrollY = Math.min(mMaxAutoScrollY,
5498                        contentToViewY(mScrollingLayerBounds.bottom));
5499            }
5500        }
5501        mMinAutoScrollX += SELECT_SCROLL;
5502        mMaxAutoScrollX -= SELECT_SCROLL;
5503        mMinAutoScrollY += SELECT_SCROLL;
5504        mMaxAutoScrollY -= SELECT_SCROLL;
5505        return true;
5506    }
5507
5508    /**
5509     * Use this method to put the WebView into text selection mode.
5510     * Do not rely on this functionality; it will be deprecated in the future.
5511     * @deprecated This method is now obsolete.
5512     */
5513    @Deprecated
5514    public void emulateShiftHeld() {
5515        checkThread();
5516        setUpSelect(false, 0, 0);
5517    }
5518
5519    /**
5520     * Select all of the text in this WebView.
5521     *
5522     * @hide pending API council approval.
5523     */
5524    public void selectAll() {
5525        if (0 == mNativeClass) return; // client isn't initialized
5526        if (inFullScreenMode()) return;
5527        if (!mSelectingText) {
5528            // retrieve a point somewhere within the text
5529            Point select = nativeSelectableText();
5530            if (!selectText(select.x, select.y)) return;
5531        }
5532        nativeSelectAll();
5533        mDrawSelectionPointer = false;
5534        mExtendSelection = true;
5535        invalidate();
5536    }
5537
5538    /**
5539     * Called when the selection has been removed.
5540     */
5541    void selectionDone() {
5542        if (mSelectingText) {
5543            mSelectingText = false;
5544            if (DEBUG_TEXT_HANDLES) {
5545                // Debugging text handles required running in software mode, set
5546                // back to default now
5547                setLayerType(LAYER_TYPE_NONE, null);
5548            }
5549            // finish is idempotent, so this is fine even if selectionDone was
5550            // called by mSelectCallback.onDestroyActionMode
5551            mSelectCallback.finish();
5552            mSelectCallback = null;
5553            WebViewCore.resumePriority();
5554            WebViewCore.resumeUpdatePicture(mWebViewCore);
5555            invalidate(); // redraw without selection
5556            mAutoScrollX = 0;
5557            mAutoScrollY = 0;
5558            mSentAutoScrollMessage = false;
5559        }
5560    }
5561
5562    /**
5563     * Copy the selection to the clipboard
5564     *
5565     * @hide pending API council approval.
5566     */
5567    public boolean copySelection() {
5568        boolean copiedSomething = false;
5569        String selection = getSelection();
5570        if (selection != null && selection != "") {
5571            if (DebugFlags.WEB_VIEW) {
5572                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
5573            }
5574            Toast.makeText(mContext
5575                    , com.android.internal.R.string.text_copied
5576                    , Toast.LENGTH_SHORT).show();
5577            copiedSomething = true;
5578            ClipboardManager cm = (ClipboardManager)getContext()
5579                    .getSystemService(Context.CLIPBOARD_SERVICE);
5580            cm.setText(selection);
5581        }
5582        invalidate(); // remove selection region and pointer
5583        return copiedSomething;
5584    }
5585
5586    /**
5587     * @hide pending API Council approval.
5588     */
5589    public SearchBox getSearchBox() {
5590        if ((mWebViewCore == null) || (mWebViewCore.getBrowserFrame() == null)) {
5591            return null;
5592        }
5593        return mWebViewCore.getBrowserFrame().getSearchBox();
5594    }
5595
5596    /**
5597     * Returns the currently highlighted text as a string.
5598     */
5599    String getSelection() {
5600        if (mNativeClass == 0) return "";
5601        return nativeGetSelection();
5602    }
5603
5604    @Override
5605    protected void onAttachedToWindow() {
5606        super.onAttachedToWindow();
5607        if (hasWindowFocus()) setActive(true);
5608        final ViewTreeObserver treeObserver = getViewTreeObserver();
5609        if (mGlobalLayoutListener == null) {
5610            mGlobalLayoutListener = new InnerGlobalLayoutListener();
5611            treeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);
5612        }
5613        if (mScrollChangedListener == null) {
5614            mScrollChangedListener = new InnerScrollChangedListener();
5615            treeObserver.addOnScrollChangedListener(mScrollChangedListener);
5616        }
5617
5618        addAccessibilityApisToJavaScript();
5619
5620        mTouchEventQueue.reset();
5621    }
5622
5623    @Override
5624    protected void onDetachedFromWindow() {
5625        clearHelpers();
5626        mZoomManager.dismissZoomPicker();
5627        if (hasWindowFocus()) setActive(false);
5628
5629        final ViewTreeObserver treeObserver = getViewTreeObserver();
5630        if (mGlobalLayoutListener != null) {
5631            treeObserver.removeGlobalOnLayoutListener(mGlobalLayoutListener);
5632            mGlobalLayoutListener = null;
5633        }
5634        if (mScrollChangedListener != null) {
5635            treeObserver.removeOnScrollChangedListener(mScrollChangedListener);
5636            mScrollChangedListener = null;
5637        }
5638
5639        removeAccessibilityApisFromJavaScript();
5640
5641        super.onDetachedFromWindow();
5642    }
5643
5644    @Override
5645    protected void onVisibilityChanged(View changedView, int visibility) {
5646        super.onVisibilityChanged(changedView, visibility);
5647        // The zoomManager may be null if the webview is created from XML that
5648        // specifies the view's visibility param as not visible (see http://b/2794841)
5649        if (visibility != View.VISIBLE && mZoomManager != null) {
5650            mZoomManager.dismissZoomPicker();
5651        }
5652        updateDrawingState();
5653    }
5654
5655    /**
5656     * @deprecated WebView no longer needs to implement
5657     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5658     */
5659    @Deprecated
5660    public void onChildViewAdded(View parent, View child) {}
5661
5662    /**
5663     * @deprecated WebView no longer needs to implement
5664     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5665     */
5666    @Deprecated
5667    public void onChildViewRemoved(View p, View child) {}
5668
5669    /**
5670     * @deprecated WebView should not have implemented
5671     * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
5672     */
5673    @Deprecated
5674    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
5675    }
5676
5677    void setActive(boolean active) {
5678        if (active) {
5679            if (hasFocus()) {
5680                // If our window regained focus, and we have focus, then begin
5681                // drawing the cursor ring
5682                mDrawCursorRing = true;
5683                setFocusControllerActive(true);
5684            } else {
5685                if (!inEditingMode()) {
5686                    // If our window gained focus, but we do not have it, do not
5687                    // draw the cursor ring.
5688                    mDrawCursorRing = false;
5689                    setFocusControllerActive(false);
5690                }
5691                // We do not call recordButtons here because we assume
5692                // that when we lost focus, or window focus, it got called with
5693                // false for the first parameter
5694            }
5695        } else {
5696            if (!mZoomManager.isZoomPickerVisible()) {
5697                /*
5698                 * The external zoom controls come in their own window, so our
5699                 * window loses focus. Our policy is to not draw the cursor ring
5700                 * if our window is not focused, but this is an exception since
5701                 * the user can still navigate the web page with the zoom
5702                 * controls showing.
5703                 */
5704                mDrawCursorRing = false;
5705            }
5706            mKeysPressed.clear();
5707            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5708            mTouchMode = TOUCH_DONE_MODE;
5709            setFocusControllerActive(false);
5710        }
5711        invalidate();
5712    }
5713
5714    // To avoid drawing the cursor ring, and remove the TextView when our window
5715    // loses focus.
5716    @Override
5717    public void onWindowFocusChanged(boolean hasWindowFocus) {
5718        setActive(hasWindowFocus);
5719        if (hasWindowFocus) {
5720            JWebCoreJavaBridge.setActiveWebView(this);
5721            if (mPictureUpdatePausedForFocusChange) {
5722                WebViewCore.resumeUpdatePicture(mWebViewCore);
5723                mPictureUpdatePausedForFocusChange = false;
5724            }
5725        } else {
5726            JWebCoreJavaBridge.removeActiveWebView(this);
5727            final WebSettings settings = getSettings();
5728            if (settings != null && settings.enableSmoothTransition() &&
5729                    mWebViewCore != null && !WebViewCore.isUpdatePicturePaused(mWebViewCore)) {
5730                WebViewCore.pauseUpdatePicture(mWebViewCore);
5731                mPictureUpdatePausedForFocusChange = true;
5732            }
5733        }
5734        super.onWindowFocusChanged(hasWindowFocus);
5735    }
5736
5737    /*
5738     * Pass a message to WebCore Thread, telling the WebCore::Page's
5739     * FocusController to be  "inactive" so that it will
5740     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
5741     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
5742     */
5743    /* package */ void setFocusControllerActive(boolean active) {
5744        if (mWebViewCore == null) return;
5745        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
5746        // Need to send this message after the document regains focus.
5747        if (active && mListBoxMessage != null) {
5748            mWebViewCore.sendMessage(mListBoxMessage);
5749            mListBoxMessage = null;
5750        }
5751    }
5752
5753    @Override
5754    protected void onFocusChanged(boolean focused, int direction,
5755            Rect previouslyFocusedRect) {
5756        if (DebugFlags.WEB_VIEW) {
5757            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
5758        }
5759        if (focused) {
5760            // When we regain focus, if we have window focus, resume drawing
5761            // the cursor ring
5762            if (hasWindowFocus()) {
5763                mDrawCursorRing = true;
5764                setFocusControllerActive(true);
5765            //} else {
5766                // The WebView has gained focus while we do not have
5767                // windowfocus.  When our window lost focus, we should have
5768                // called recordButtons(false...)
5769            }
5770        } else {
5771            // When we lost focus, unless focus went to the TextView (which is
5772            // true if we are in editing mode), stop drawing the cursor ring.
5773            if (!inEditingMode()) {
5774                mDrawCursorRing = false;
5775                setFocusControllerActive(false);
5776            }
5777            mKeysPressed.clear();
5778        }
5779
5780        super.onFocusChanged(focused, direction, previouslyFocusedRect);
5781    }
5782
5783    void setGLRectViewport() {
5784        // Use the getGlobalVisibleRect() to get the intersection among the parents
5785        // visible == false means we're clipped - send a null rect down to indicate that
5786        // we should not draw
5787        boolean visible = getGlobalVisibleRect(mGLRectViewport);
5788        if (visible) {
5789            // Then need to invert the Y axis, just for GL
5790            View rootView = getRootView();
5791            int rootViewHeight = rootView.getHeight();
5792            mViewRectViewport.set(mGLRectViewport);
5793            int savedWebViewBottom = mGLRectViewport.bottom;
5794            mGLRectViewport.bottom = rootViewHeight - mGLRectViewport.top - getVisibleTitleHeightImpl();
5795            mGLRectViewport.top = rootViewHeight - savedWebViewBottom;
5796            mGLViewportEmpty = false;
5797        } else {
5798            mGLViewportEmpty = true;
5799        }
5800        nativeUpdateDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport,
5801                mGLViewportEmpty ? null : mViewRectViewport);
5802    }
5803
5804    /**
5805     * @hide
5806     */
5807    @Override
5808    protected boolean setFrame(int left, int top, int right, int bottom) {
5809        boolean changed = super.setFrame(left, top, right, bottom);
5810        if (!changed && mHeightCanMeasure) {
5811            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
5812            // in WebViewCore after we get the first layout. We do call
5813            // requestLayout() when we get contentSizeChanged(). But the View
5814            // system won't call onSizeChanged if the dimension is not changed.
5815            // In this case, we need to call sendViewSizeZoom() explicitly to
5816            // notify the WebKit about the new dimensions.
5817            sendViewSizeZoom(false);
5818        }
5819        setGLRectViewport();
5820        return changed;
5821    }
5822
5823    @Override
5824    protected void onSizeChanged(int w, int h, int ow, int oh) {
5825        super.onSizeChanged(w, h, ow, oh);
5826
5827        // adjust the max viewport width depending on the view dimensions. This
5828        // is to ensure the scaling is not going insane. So do not shrink it if
5829        // the view size is temporarily smaller, e.g. when soft keyboard is up.
5830        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
5831        if (newMaxViewportWidth > sMaxViewportWidth) {
5832            sMaxViewportWidth = newMaxViewportWidth;
5833        }
5834
5835        mZoomManager.onSizeChanged(w, h, ow, oh);
5836
5837        if (mLoadedPicture != null && mDelaySetPicture == null) {
5838            // Size changes normally result in a new picture
5839            // Re-set the loaded picture to simulate that
5840            // However, do not update the base layer as that hasn't changed
5841            setNewPicture(mLoadedPicture, false);
5842        }
5843    }
5844
5845    @Override
5846    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5847        super.onScrollChanged(l, t, oldl, oldt);
5848        if (!mInOverScrollMode) {
5849            sendOurVisibleRect();
5850            // update WebKit if visible title bar height changed. The logic is same
5851            // as getVisibleTitleHeightImpl.
5852            int titleHeight = getTitleHeight();
5853            if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
5854                sendViewSizeZoom(false);
5855            }
5856        }
5857    }
5858
5859    @Override
5860    public boolean dispatchKeyEvent(KeyEvent event) {
5861        switch (event.getAction()) {
5862            case KeyEvent.ACTION_DOWN:
5863                mKeysPressed.add(Integer.valueOf(event.getKeyCode()));
5864                break;
5865            case KeyEvent.ACTION_MULTIPLE:
5866                // Always accept the action.
5867                break;
5868            case KeyEvent.ACTION_UP:
5869                int location = mKeysPressed.indexOf(Integer.valueOf(event.getKeyCode()));
5870                if (location == -1) {
5871                    // We did not receive the key down for this key, so do not
5872                    // handle the key up.
5873                    return false;
5874                } else {
5875                    // We did receive the key down.  Handle the key up, and
5876                    // remove it from our pressed keys.
5877                    mKeysPressed.remove(location);
5878                }
5879                break;
5880            default:
5881                // Accept the action.  This should not happen, unless a new
5882                // action is added to KeyEvent.
5883                break;
5884        }
5885        if (inEditingMode() && mWebTextView.isFocused()) {
5886            // Ensure that the WebTextView gets the event, even if it does
5887            // not currently have a bounds.
5888            return mWebTextView.dispatchKeyEvent(event);
5889        } else {
5890            return super.dispatchKeyEvent(event);
5891        }
5892    }
5893
5894    /*
5895     * Here is the snap align logic:
5896     * 1. If it starts nearly horizontally or vertically, snap align;
5897     * 2. If there is a dramitic direction change, let it go;
5898     *
5899     * Adjustable parameters. Angle is the radians on a unit circle, limited
5900     * to quadrant 1. Values range from 0f (horizontal) to PI/2 (vertical)
5901     */
5902    private static final float HSLOPE_TO_START_SNAP = .25f;
5903    private static final float HSLOPE_TO_BREAK_SNAP = .4f;
5904    private static final float VSLOPE_TO_START_SNAP = 1.25f;
5905    private static final float VSLOPE_TO_BREAK_SNAP = .95f;
5906    /*
5907     *  These values are used to influence the average angle when entering
5908     *  snap mode. If is is the first movement entering snap, we set the average
5909     *  to the appropriate ideal. If the user is entering into snap after the
5910     *  first movement, then we average the average angle with these values.
5911     */
5912    private static final float ANGLE_VERT = 2f;
5913    private static final float ANGLE_HORIZ = 0f;
5914    /*
5915     *  The modified moving average weight.
5916     *  Formula: MAV[t]=MAV[t-1] + (P[t]-MAV[t-1])/n
5917     */
5918    private static final float MMA_WEIGHT_N = 5;
5919
5920    private boolean hitFocusedPlugin(int contentX, int contentY) {
5921        if (DebugFlags.WEB_VIEW) {
5922            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
5923            Rect r = nativeFocusNodeBounds();
5924            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
5925                    + ", " + r.right + ", " + r.bottom + ")");
5926        }
5927        return nativeFocusIsPlugin()
5928                && nativeFocusNodeBounds().contains(contentX, contentY);
5929    }
5930
5931    private boolean shouldForwardTouchEvent() {
5932        if (mFullScreenHolder != null) return true;
5933        if (mBlockWebkitViewMessages) return false;
5934        return mForwardTouchEvents
5935                && !mSelectingText
5936                && mPreventDefault != PREVENT_DEFAULT_IGNORE
5937                && mPreventDefault != PREVENT_DEFAULT_NO;
5938    }
5939
5940    private boolean inFullScreenMode() {
5941        return mFullScreenHolder != null;
5942    }
5943
5944    private void dismissFullScreenMode() {
5945        if (inFullScreenMode()) {
5946            mFullScreenHolder.hide();
5947            mFullScreenHolder = null;
5948        }
5949    }
5950
5951    void onPinchToZoomAnimationStart() {
5952        // cancel the single touch handling
5953        cancelTouch();
5954        onZoomAnimationStart();
5955    }
5956
5957    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
5958        onZoomAnimationEnd();
5959        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
5960        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
5961        // as it may trigger the unwanted fling.
5962        mTouchMode = TOUCH_PINCH_DRAG;
5963        mConfirmMove = true;
5964        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
5965    }
5966
5967    // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a
5968    // layer is found.
5969    private void startScrollingLayer(float x, float y) {
5970        int contentX = viewToContentX((int) x + mScrollX);
5971        int contentY = viewToContentY((int) y + mScrollY);
5972        mScrollingLayer = nativeScrollableLayer(contentX, contentY,
5973                mScrollingLayerRect, mScrollingLayerBounds);
5974        if (mScrollingLayer != 0) {
5975            mTouchMode = TOUCH_DRAG_LAYER_MODE;
5976        }
5977    }
5978
5979    // 1/(density * density) used to compute the distance between points.
5980    // Computed in init().
5981    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
5982
5983    // The distance between two points reported in onTouchEvent scaled by the
5984    // density of the screen.
5985    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
5986
5987    @Override
5988    public boolean onHoverEvent(MotionEvent event) {
5989        if (mNativeClass == 0) {
5990            return false;
5991        }
5992        WebViewCore.CursorData data = cursorDataNoPosition();
5993        data.mX = viewToContentX((int) event.getX() + mScrollX);
5994        data.mY = viewToContentY((int) event.getY() + mScrollY);
5995        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
5996        return true;
5997    }
5998
5999    @Override
6000    public boolean onTouchEvent(MotionEvent ev) {
6001        if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) {
6002            return false;
6003        }
6004
6005        if (DebugFlags.WEB_VIEW) {
6006            Log.v(LOGTAG, ev + " at " + ev.getEventTime()
6007                + " mTouchMode=" + mTouchMode
6008                + " numPointers=" + ev.getPointerCount());
6009        }
6010
6011        // If WebKit wasn't interested in this multitouch gesture, enqueue
6012        // the event for handling directly rather than making the round trip
6013        // to WebKit and back.
6014        if (ev.getPointerCount() > 1 && mPreventDefault != PREVENT_DEFAULT_NO) {
6015            passMultiTouchToWebKit(ev, mTouchEventQueue.nextTouchSequence());
6016        } else {
6017            mTouchEventQueue.enqueueTouchEvent(ev);
6018        }
6019
6020        // Since all events are handled asynchronously, we always want the gesture stream.
6021        return true;
6022    }
6023
6024    private float calculateDragAngle(int dx, int dy) {
6025        dx = Math.abs(dx);
6026        dy = Math.abs(dy);
6027        return (float) Math.atan2(dy, dx);
6028    }
6029
6030    /*
6031     * Common code for single touch and multi-touch.
6032     * (x, y) denotes current focus point, which is the touch point for single touch
6033     * and the middle point for multi-touch.
6034     */
6035    private boolean handleTouchEventCommon(MotionEvent ev, int action, int x, int y) {
6036        long eventTime = ev.getEventTime();
6037
6038        // Due to the touch screen edge effect, a touch closer to the edge
6039        // always snapped to the edge. As getViewWidth() can be different from
6040        // getWidth() due to the scrollbar, adjusting the point to match
6041        // getViewWidth(). Same applied to the height.
6042        x = Math.min(x, getViewWidth() - 1);
6043        y = Math.min(y, getViewHeightWithTitle() - 1);
6044
6045        int deltaX = mLastTouchX - x;
6046        int deltaY = mLastTouchY - y;
6047        int contentX = viewToContentX(x + mScrollX);
6048        int contentY = viewToContentY(y + mScrollY);
6049
6050        switch (action) {
6051            case MotionEvent.ACTION_DOWN: {
6052                mPreventDefault = PREVENT_DEFAULT_NO;
6053                mConfirmMove = false;
6054                mInitialHitTestResult = null;
6055                if (!mScroller.isFinished()) {
6056                    // stop the current scroll animation, but if this is
6057                    // the start of a fling, allow it to add to the current
6058                    // fling's velocity
6059                    mScroller.abortAnimation();
6060                    mTouchMode = TOUCH_DRAG_START_MODE;
6061                    mConfirmMove = true;
6062                    nativeSetIsScrolling(false);
6063                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
6064                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
6065                    if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) {
6066                        removeTouchHighlight();
6067                    }
6068                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
6069                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
6070                    } else {
6071                        // commit the short press action for the previous tap
6072                        doShortPress();
6073                        mTouchMode = TOUCH_INIT_MODE;
6074                        mDeferTouchProcess = !mBlockWebkitViewMessages
6075                                && (!inFullScreenMode() && mForwardTouchEvents)
6076                                ? hitFocusedPlugin(contentX, contentY)
6077                                : false;
6078                    }
6079                } else { // the normal case
6080                    mTouchMode = TOUCH_INIT_MODE;
6081                    mDeferTouchProcess = !mBlockWebkitViewMessages
6082                            && (!inFullScreenMode() && mForwardTouchEvents)
6083                            ? hitFocusedPlugin(contentX, contentY)
6084                            : false;
6085                    if (!mBlockWebkitViewMessages) {
6086                        mWebViewCore.sendMessage(
6087                                EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
6088                    }
6089                    if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) {
6090                        TouchHighlightData data = new TouchHighlightData();
6091                        data.mX = contentX;
6092                        data.mY = contentY;
6093                        data.mNativeLayerRect = new Rect();
6094                        data.mNativeLayer = nativeScrollableLayer(
6095                                contentX, contentY, data.mNativeLayerRect, null);
6096                        data.mSlop = viewToContentDimension(mNavSlop);
6097                        mTouchHighlightRegion.setEmpty();
6098                        if (!mBlockWebkitViewMessages) {
6099                            mTouchHighlightRequested = System.currentTimeMillis();
6100                            mWebViewCore.sendMessageAtFrontOfQueue(
6101                                    EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data);
6102                        }
6103                        if (DEBUG_TOUCH_HIGHLIGHT) {
6104                            if (getSettings().getNavDump()) {
6105                                mTouchHighlightX = (int) x + mScrollX;
6106                                mTouchHighlightY = (int) y + mScrollY;
6107                                mPrivateHandler.postDelayed(new Runnable() {
6108                                    public void run() {
6109                                        mTouchHighlightX = mTouchHighlightY = 0;
6110                                        invalidate();
6111                                    }
6112                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
6113                            }
6114                        }
6115                    }
6116                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
6117                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
6118                                (eventTime - mLastTouchUpTime), eventTime);
6119                    }
6120                    if (mSelectingText) {
6121                        mDrawSelectionPointer = false;
6122                        mSelectionStarted = nativeStartSelection(contentX, contentY);
6123                        if (DebugFlags.WEB_VIEW) {
6124                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
6125                        }
6126                        invalidate();
6127                    }
6128                }
6129                // Trigger the link
6130                if (!mSelectingText && (mTouchMode == TOUCH_INIT_MODE
6131                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE)) {
6132                    mPrivateHandler.sendEmptyMessageDelayed(
6133                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
6134                    mPrivateHandler.sendEmptyMessageDelayed(
6135                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
6136                    if (inFullScreenMode() || mDeferTouchProcess) {
6137                        mPreventDefault = PREVENT_DEFAULT_YES;
6138                    } else if (!mBlockWebkitViewMessages && mForwardTouchEvents) {
6139                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
6140                    } else {
6141                        mPreventDefault = PREVENT_DEFAULT_NO;
6142                    }
6143                    // pass the touch events from UI thread to WebCore thread
6144                    if (shouldForwardTouchEvent()) {
6145                        TouchEventData ted = new TouchEventData();
6146                        ted.mAction = action;
6147                        ted.mIds = new int[1];
6148                        ted.mIds[0] = ev.getPointerId(0);
6149                        ted.mPoints = new Point[1];
6150                        ted.mPoints[0] = new Point(contentX, contentY);
6151                        ted.mPointsInView = new Point[1];
6152                        ted.mPointsInView[0] = new Point(x, y);
6153                        ted.mMetaState = ev.getMetaState();
6154                        ted.mReprocess = mDeferTouchProcess;
6155                        ted.mNativeLayer = nativeScrollableLayer(
6156                                contentX, contentY, ted.mNativeLayerRect, null);
6157                        ted.mSequence = mTouchEventQueue.nextTouchSequence();
6158                        mTouchEventQueue.preQueueTouchEventData(ted);
6159                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6160                        if (mDeferTouchProcess) {
6161                            // still needs to set them for compute deltaX/Y
6162                            mLastTouchX = x;
6163                            mLastTouchY = y;
6164                            break;
6165                        }
6166                        if (!inFullScreenMode()) {
6167                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
6168                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
6169                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
6170                                            action, 0), TAP_TIMEOUT);
6171                        }
6172                    }
6173                }
6174                startTouch(x, y, eventTime);
6175                break;
6176            }
6177            case MotionEvent.ACTION_MOVE: {
6178                boolean firstMove = false;
6179                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
6180                        >= mTouchSlopSquare) {
6181                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6182                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6183                    mConfirmMove = true;
6184                    firstMove = true;
6185                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
6186                        mTouchMode = TOUCH_INIT_MODE;
6187                    }
6188                    if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) {
6189                        removeTouchHighlight();
6190                    }
6191                }
6192                // pass the touch events from UI thread to WebCore thread
6193                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
6194                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
6195                    TouchEventData ted = new TouchEventData();
6196                    ted.mAction = action;
6197                    ted.mIds = new int[1];
6198                    ted.mIds[0] = ev.getPointerId(0);
6199                    ted.mPoints = new Point[1];
6200                    ted.mPoints[0] = new Point(contentX, contentY);
6201                    ted.mPointsInView = new Point[1];
6202                    ted.mPointsInView[0] = new Point(x, y);
6203                    ted.mMetaState = ev.getMetaState();
6204                    ted.mReprocess = mDeferTouchProcess;
6205                    ted.mNativeLayer = mScrollingLayer;
6206                    ted.mNativeLayerRect.set(mScrollingLayerRect);
6207                    ted.mSequence = mTouchEventQueue.nextTouchSequence();
6208                    mTouchEventQueue.preQueueTouchEventData(ted);
6209                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6210                    mLastSentTouchTime = eventTime;
6211                    if (mDeferTouchProcess) {
6212                        break;
6213                    }
6214                    if (firstMove && !inFullScreenMode()) {
6215                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
6216                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
6217                                        action, 0), TAP_TIMEOUT);
6218                    }
6219                }
6220                if (mTouchMode == TOUCH_DONE_MODE
6221                        || mPreventDefault == PREVENT_DEFAULT_YES) {
6222                    // no dragging during scroll zoom animation, or when prevent
6223                    // default is yes
6224                    break;
6225                }
6226                if (mVelocityTracker == null) {
6227                    Log.e(LOGTAG, "Got null mVelocityTracker when "
6228                            + "mPreventDefault = " + mPreventDefault
6229                            + " mDeferTouchProcess = " + mDeferTouchProcess
6230                            + " mTouchMode = " + mTouchMode);
6231                } else {
6232                    mVelocityTracker.addMovement(ev);
6233                }
6234                if (mSelectingText && mSelectionStarted) {
6235                    if (DebugFlags.WEB_VIEW) {
6236                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
6237                    }
6238                    ViewParent parent = getParent();
6239                    if (parent != null) {
6240                        parent.requestDisallowInterceptTouchEvent(true);
6241                    }
6242                    mAutoScrollX = x <= mMinAutoScrollX ? -SELECT_SCROLL
6243                            : x >= mMaxAutoScrollX ? SELECT_SCROLL : 0;
6244                    mAutoScrollY = y <= mMinAutoScrollY ? -SELECT_SCROLL
6245                            : y >= mMaxAutoScrollY ? SELECT_SCROLL : 0;
6246                    if ((mAutoScrollX != 0 || mAutoScrollY != 0)
6247                            && !mSentAutoScrollMessage) {
6248                        mSentAutoScrollMessage = true;
6249                        mPrivateHandler.sendEmptyMessageDelayed(
6250                                SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
6251                    }
6252                    if (deltaX != 0 || deltaY != 0) {
6253                        nativeExtendSelection(contentX, contentY);
6254                        invalidate();
6255                    }
6256                    break;
6257                }
6258
6259                if (mTouchMode != TOUCH_DRAG_MODE &&
6260                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6261
6262                    if (!mConfirmMove) {
6263                        break;
6264                    }
6265
6266                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
6267                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
6268                        // track mLastTouchTime as we may need to do fling at
6269                        // ACTION_UP
6270                        mLastTouchTime = eventTime;
6271                        break;
6272                    }
6273
6274                    // Only lock dragging to one axis if we don't have a scale in progress.
6275                    // Scaling implies free-roaming movement. Note this is only ever a question
6276                    // if mZoomManager.supportsPanDuringZoom() is true.
6277                    final ScaleGestureDetector detector =
6278                      mZoomManager.getMultiTouchGestureDetector();
6279                    mAverageAngle = calculateDragAngle(deltaX, deltaY);
6280                    if (detector == null || !detector.isInProgress()) {
6281                        // if it starts nearly horizontal or vertical, enforce it
6282                        if (mAverageAngle < HSLOPE_TO_START_SNAP) {
6283                            mSnapScrollMode = SNAP_X;
6284                            mSnapPositive = deltaX > 0;
6285                            mAverageAngle = ANGLE_HORIZ;
6286                        } else if (mAverageAngle > VSLOPE_TO_START_SNAP) {
6287                            mSnapScrollMode = SNAP_Y;
6288                            mSnapPositive = deltaY > 0;
6289                            mAverageAngle = ANGLE_VERT;
6290                        }
6291                    }
6292
6293                    mTouchMode = TOUCH_DRAG_MODE;
6294                    mLastTouchX = x;
6295                    mLastTouchY = y;
6296                    deltaX = 0;
6297                    deltaY = 0;
6298
6299                    startScrollingLayer(x, y);
6300                    startDrag();
6301                }
6302
6303                // do pan
6304                boolean done = false;
6305                boolean keepScrollBarsVisible = false;
6306                if (deltaX == 0 && deltaY == 0) {
6307                    keepScrollBarsVisible = done = true;
6308                } else {
6309                    mAverageAngle +=
6310                        (calculateDragAngle(deltaX, deltaY) - mAverageAngle)
6311                        / MMA_WEIGHT_N;
6312                    if (mSnapScrollMode != SNAP_NONE) {
6313                        if (mSnapScrollMode == SNAP_Y) {
6314                            // radical change means getting out of snap mode
6315                            if (mAverageAngle < VSLOPE_TO_BREAK_SNAP) {
6316                                mSnapScrollMode = SNAP_NONE;
6317                            }
6318                        }
6319                        if (mSnapScrollMode == SNAP_X) {
6320                            // radical change means getting out of snap mode
6321                            if (mAverageAngle > HSLOPE_TO_BREAK_SNAP) {
6322                                mSnapScrollMode = SNAP_NONE;
6323                            }
6324                        }
6325                    } else {
6326                        if (mAverageAngle < HSLOPE_TO_START_SNAP) {
6327                            mSnapScrollMode = SNAP_X;
6328                            mSnapPositive = deltaX > 0;
6329                            mAverageAngle = (mAverageAngle + ANGLE_HORIZ) / 2;
6330                        } else if (mAverageAngle > VSLOPE_TO_START_SNAP) {
6331                            mSnapScrollMode = SNAP_Y;
6332                            mSnapPositive = deltaY > 0;
6333                            mAverageAngle = (mAverageAngle + ANGLE_VERT) / 2;
6334                        }
6335                    }
6336                    if (mSnapScrollMode != SNAP_NONE) {
6337                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6338                            deltaY = 0;
6339                        } else {
6340                            deltaX = 0;
6341                        }
6342                    }
6343                    mLastTouchX = x;
6344                    mLastTouchY = y;
6345
6346                    if (deltaX * deltaX + deltaY * deltaY > mTouchSlopSquare) {
6347                        mHeldMotionless = MOTIONLESS_FALSE;
6348                        nativeSetIsScrolling(true);
6349                    } else {
6350                        mHeldMotionless = MOTIONLESS_TRUE;
6351                        nativeSetIsScrolling(false);
6352                        keepScrollBarsVisible = true;
6353                    }
6354
6355                    mLastTouchTime = eventTime;
6356                }
6357
6358                doDrag(deltaX, deltaY);
6359
6360                // Turn off scrollbars when dragging a layer.
6361                if (keepScrollBarsVisible &&
6362                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6363                    if (mHeldMotionless != MOTIONLESS_TRUE) {
6364                        mHeldMotionless = MOTIONLESS_TRUE;
6365                        invalidate();
6366                    }
6367                    // keep the scrollbar on the screen even there is no scroll
6368                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
6369                            false);
6370                    // Post a message so that we'll keep them alive while we're not scrolling.
6371                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
6372                            .obtainMessage(AWAKEN_SCROLL_BARS),
6373                            ViewConfiguration.getScrollDefaultDelay());
6374                    // return false to indicate that we can't pan out of the
6375                    // view space
6376                    return !done;
6377                } else {
6378                    mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6379                }
6380                break;
6381            }
6382            case MotionEvent.ACTION_UP: {
6383                if (!isFocused()) requestFocus();
6384                // pass the touch events from UI thread to WebCore thread
6385                if (shouldForwardTouchEvent()) {
6386                    TouchEventData ted = new TouchEventData();
6387                    ted.mIds = new int[1];
6388                    ted.mIds[0] = ev.getPointerId(0);
6389                    ted.mAction = action;
6390                    ted.mPoints = new Point[1];
6391                    ted.mPoints[0] = new Point(contentX, contentY);
6392                    ted.mPointsInView = new Point[1];
6393                    ted.mPointsInView[0] = new Point(x, y);
6394                    ted.mMetaState = ev.getMetaState();
6395                    ted.mReprocess = mDeferTouchProcess;
6396                    ted.mNativeLayer = mScrollingLayer;
6397                    ted.mNativeLayerRect.set(mScrollingLayerRect);
6398                    ted.mSequence = mTouchEventQueue.nextTouchSequence();
6399                    mTouchEventQueue.preQueueTouchEventData(ted);
6400                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6401                }
6402                mLastTouchUpTime = eventTime;
6403                if (mSentAutoScrollMessage) {
6404                    mAutoScrollX = mAutoScrollY = 0;
6405                }
6406                switch (mTouchMode) {
6407                    case TOUCH_DOUBLE_TAP_MODE: // double tap
6408                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6409                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6410                        if (inFullScreenMode() || mDeferTouchProcess) {
6411                            TouchEventData ted = new TouchEventData();
6412                            ted.mIds = new int[1];
6413                            ted.mIds[0] = ev.getPointerId(0);
6414                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
6415                            ted.mPoints = new Point[1];
6416                            ted.mPoints[0] = new Point(contentX, contentY);
6417                            ted.mPointsInView = new Point[1];
6418                            ted.mPointsInView[0] = new Point(x, y);
6419                            ted.mMetaState = ev.getMetaState();
6420                            ted.mReprocess = mDeferTouchProcess;
6421                            ted.mNativeLayer = nativeScrollableLayer(
6422                                    contentX, contentY,
6423                                    ted.mNativeLayerRect, null);
6424                            ted.mSequence = mTouchEventQueue.nextTouchSequence();
6425                            mTouchEventQueue.preQueueTouchEventData(ted);
6426                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6427                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
6428                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
6429                            mTouchMode = TOUCH_DONE_MODE;
6430                        }
6431                        break;
6432                    case TOUCH_INIT_MODE: // tap
6433                    case TOUCH_SHORTPRESS_START_MODE:
6434                    case TOUCH_SHORTPRESS_MODE:
6435                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6436                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6437                        if (mConfirmMove) {
6438                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
6439                                    " WebCore's response for touch down.");
6440                            if (mPreventDefault != PREVENT_DEFAULT_YES
6441                                    && (computeMaxScrollX() > 0
6442                                            || computeMaxScrollY() > 0)) {
6443                                // If the user has performed a very quick touch
6444                                // sequence it is possible that we may get here
6445                                // before WebCore has had a chance to process the events.
6446                                // In this case, any call to preventDefault in the
6447                                // JS touch handler will not have been executed yet.
6448                                // Hence we will see both the UI (now) and WebCore
6449                                // (when context switches) handling the event,
6450                                // regardless of whether the web developer actually
6451                                // doeses preventDefault in their touch handler. This
6452                                // is the nature of our asynchronous touch model.
6453
6454                                // we will not rewrite drag code here, but we
6455                                // will try fling if it applies.
6456                                WebViewCore.reducePriority();
6457                                // to get better performance, pause updating the
6458                                // picture
6459                                WebViewCore.pauseUpdatePicture(mWebViewCore);
6460                                // fall through to TOUCH_DRAG_MODE
6461                            } else {
6462                                // WebKit may consume the touch event and modify
6463                                // DOM. drawContentPicture() will be called with
6464                                // animateSroll as true for better performance.
6465                                // Force redraw in high-quality.
6466                                invalidate();
6467                                break;
6468                            }
6469                        } else {
6470                            if (mSelectingText) {
6471                                // tapping on selection or controls does nothing
6472                                if (!nativeHitSelection(contentX, contentY)) {
6473                                    selectionDone();
6474                                }
6475                                break;
6476                            }
6477                            // only trigger double tap if the WebView is
6478                            // scalable
6479                            if (mTouchMode == TOUCH_INIT_MODE
6480                                    && (canZoomIn() || canZoomOut())) {
6481                                mPrivateHandler.sendEmptyMessageDelayed(
6482                                        RELEASE_SINGLE_TAP, ViewConfiguration
6483                                                .getDoubleTapTimeout());
6484                            } else {
6485                                doShortPress();
6486                            }
6487                            break;
6488                        }
6489                    case TOUCH_DRAG_MODE:
6490                    case TOUCH_DRAG_LAYER_MODE:
6491                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6492                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6493                        // if the user waits a while w/o moving before the
6494                        // up, we don't want to do a fling
6495                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
6496                            if (mVelocityTracker == null) {
6497                                Log.e(LOGTAG, "Got null mVelocityTracker when "
6498                                        + "mPreventDefault = "
6499                                        + mPreventDefault
6500                                        + " mDeferTouchProcess = "
6501                                        + mDeferTouchProcess);
6502                            } else {
6503                                mVelocityTracker.addMovement(ev);
6504                            }
6505                            // set to MOTIONLESS_IGNORE so that it won't keep
6506                            // removing and sending message in
6507                            // drawCoreAndCursorRing()
6508                            mHeldMotionless = MOTIONLESS_IGNORE;
6509                            doFling();
6510                            break;
6511                        } else {
6512                            if (mScroller.springBack(mScrollX, mScrollY, 0,
6513                                    computeMaxScrollX(), 0,
6514                                    computeMaxScrollY())) {
6515                                invalidate();
6516                            }
6517                        }
6518                        // redraw in high-quality, as we're done dragging
6519                        mHeldMotionless = MOTIONLESS_TRUE;
6520                        invalidate();
6521                        // fall through
6522                    case TOUCH_DRAG_START_MODE:
6523                        // TOUCH_DRAG_START_MODE should not happen for the real
6524                        // device as we almost certain will get a MOVE. But this
6525                        // is possible on emulator.
6526                        mLastVelocity = 0;
6527                        WebViewCore.resumePriority();
6528                        if (!mSelectingText) {
6529                            WebViewCore.resumeUpdatePicture(mWebViewCore);
6530                        }
6531                        break;
6532                }
6533                stopTouch();
6534                break;
6535            }
6536            case MotionEvent.ACTION_CANCEL: {
6537                if (mTouchMode == TOUCH_DRAG_MODE) {
6538                    mScroller.springBack(mScrollX, mScrollY, 0,
6539                            computeMaxScrollX(), 0, computeMaxScrollY());
6540                    invalidate();
6541                }
6542                cancelWebCoreTouchEvent(contentX, contentY, false);
6543                cancelTouch();
6544                break;
6545            }
6546        }
6547        return true;
6548    }
6549
6550    private void passMultiTouchToWebKit(MotionEvent ev, long sequence) {
6551        TouchEventData ted = new TouchEventData();
6552        ted.mAction = ev.getActionMasked();
6553        final int count = ev.getPointerCount();
6554        ted.mIds = new int[count];
6555        ted.mPoints = new Point[count];
6556        ted.mPointsInView = new Point[count];
6557        for (int c = 0; c < count; c++) {
6558            ted.mIds[c] = ev.getPointerId(c);
6559            int x = viewToContentX((int) ev.getX(c) + mScrollX);
6560            int y = viewToContentY((int) ev.getY(c) + mScrollY);
6561            ted.mPoints[c] = new Point(x, y);
6562            ted.mPointsInView[c] = new Point((int) ev.getX(c), (int) ev.getY(c));
6563        }
6564        if (ted.mAction == MotionEvent.ACTION_POINTER_DOWN
6565            || ted.mAction == MotionEvent.ACTION_POINTER_UP) {
6566            ted.mActionIndex = ev.getActionIndex();
6567        }
6568        ted.mMetaState = ev.getMetaState();
6569        ted.mReprocess = true;
6570        ted.mMotionEvent = MotionEvent.obtain(ev);
6571        ted.mSequence = sequence;
6572        mTouchEventQueue.preQueueTouchEventData(ted);
6573        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6574        cancelLongPress();
6575        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6576    }
6577
6578    void handleMultiTouchInWebView(MotionEvent ev) {
6579        if (DebugFlags.WEB_VIEW) {
6580            Log.v(LOGTAG, "multi-touch: " + ev + " at " + ev.getEventTime()
6581                + " mTouchMode=" + mTouchMode
6582                + " numPointers=" + ev.getPointerCount()
6583                + " scrolloffset=(" + mScrollX + "," + mScrollY + ")");
6584        }
6585
6586        final ScaleGestureDetector detector =
6587            mZoomManager.getMultiTouchGestureDetector();
6588
6589        // A few apps use WebView but don't instantiate gesture detector.
6590        // We don't need to support multi touch for them.
6591        if (detector == null) return;
6592
6593        float x = ev.getX();
6594        float y = ev.getY();
6595
6596        if (mPreventDefault != PREVENT_DEFAULT_YES) {
6597            detector.onTouchEvent(ev);
6598
6599            if (detector.isInProgress()) {
6600                if (DebugFlags.WEB_VIEW) {
6601                    Log.v(LOGTAG, "detector is in progress");
6602                }
6603                mLastTouchTime = ev.getEventTime();
6604                x = detector.getFocusX();
6605                y = detector.getFocusY();
6606
6607                cancelLongPress();
6608                mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6609                if (!mZoomManager.supportsPanDuringZoom()) {
6610                    return;
6611                }
6612                mTouchMode = TOUCH_DRAG_MODE;
6613                if (mVelocityTracker == null) {
6614                    mVelocityTracker = VelocityTracker.obtain();
6615                }
6616            }
6617        }
6618
6619        int action = ev.getActionMasked();
6620        if (action == MotionEvent.ACTION_POINTER_DOWN) {
6621            cancelTouch();
6622            action = MotionEvent.ACTION_DOWN;
6623        } else if (action == MotionEvent.ACTION_POINTER_UP && ev.getPointerCount() >= 2) {
6624            // set mLastTouchX/Y to the remaining points for multi-touch.
6625            mLastTouchX = Math.round(x);
6626            mLastTouchY = Math.round(y);
6627        } else if (action == MotionEvent.ACTION_MOVE) {
6628            // negative x or y indicate it is on the edge, skip it.
6629            if (x < 0 || y < 0) {
6630                return;
6631            }
6632        }
6633
6634        handleTouchEventCommon(ev, action, Math.round(x), Math.round(y));
6635    }
6636
6637    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
6638        if (shouldForwardTouchEvent()) {
6639            if (removeEvents) {
6640                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
6641            }
6642            TouchEventData ted = new TouchEventData();
6643            ted.mIds = new int[1];
6644            ted.mIds[0] = 0;
6645            ted.mPoints = new Point[1];
6646            ted.mPoints[0] = new Point(x, y);
6647            ted.mPointsInView = new Point[1];
6648            int viewX = contentToViewX(x) - mScrollX;
6649            int viewY = contentToViewY(y) - mScrollY;
6650            ted.mPointsInView[0] = new Point(viewX, viewY);
6651            ted.mAction = MotionEvent.ACTION_CANCEL;
6652            ted.mNativeLayer = nativeScrollableLayer(
6653                    x, y, ted.mNativeLayerRect, null);
6654            ted.mSequence = mTouchEventQueue.nextTouchSequence();
6655            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6656            mPreventDefault = PREVENT_DEFAULT_IGNORE;
6657
6658            if (removeEvents) {
6659                // Mark this after sending the message above; we should
6660                // be willing to ignore the cancel event that we just sent.
6661                mTouchEventQueue.ignoreCurrentlyMissingEvents();
6662            }
6663        }
6664    }
6665
6666    private void startTouch(float x, float y, long eventTime) {
6667        // Remember where the motion event started
6668        mStartTouchX = mLastTouchX = Math.round(x);
6669        mStartTouchY = mLastTouchY = Math.round(y);
6670        mLastTouchTime = eventTime;
6671        mVelocityTracker = VelocityTracker.obtain();
6672        mSnapScrollMode = SNAP_NONE;
6673        mPrivateHandler.sendEmptyMessageDelayed(UPDATE_SELECTION,
6674                ViewConfiguration.getTapTimeout());
6675    }
6676
6677    private void startDrag() {
6678        WebViewCore.reducePriority();
6679        // to get better performance, pause updating the picture
6680        WebViewCore.pauseUpdatePicture(mWebViewCore);
6681        nativeSetIsScrolling(true);
6682
6683        if (!mDragFromTextInput) {
6684            nativeHideCursor();
6685        }
6686
6687        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
6688                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
6689            mZoomManager.invokeZoomPicker();
6690        }
6691    }
6692
6693    private void doDrag(int deltaX, int deltaY) {
6694        if ((deltaX | deltaY) != 0) {
6695            int oldX = mScrollX;
6696            int oldY = mScrollY;
6697            int rangeX = computeMaxScrollX();
6698            int rangeY = computeMaxScrollY();
6699            int overscrollDistance = mOverscrollDistance;
6700
6701            // Check for the original scrolling layer in case we change
6702            // directions.  mTouchMode might be TOUCH_DRAG_MODE if we have
6703            // reached the edge of a layer but mScrollingLayer will be non-zero
6704            // if we initiated the drag on a layer.
6705            if (mScrollingLayer != 0) {
6706                final int contentX = viewToContentDimension(deltaX);
6707                final int contentY = viewToContentDimension(deltaY);
6708
6709                // Check the scrolling bounds to see if we will actually do any
6710                // scrolling.  The rectangle is in document coordinates.
6711                final int maxX = mScrollingLayerRect.right;
6712                final int maxY = mScrollingLayerRect.bottom;
6713                final int resultX = Math.max(0,
6714                        Math.min(mScrollingLayerRect.left + contentX, maxX));
6715                final int resultY = Math.max(0,
6716                        Math.min(mScrollingLayerRect.top + contentY, maxY));
6717
6718                if (resultX != mScrollingLayerRect.left ||
6719                        resultY != mScrollingLayerRect.top) {
6720                    // In case we switched to dragging the page.
6721                    mTouchMode = TOUCH_DRAG_LAYER_MODE;
6722                    deltaX = contentX;
6723                    deltaY = contentY;
6724                    oldX = mScrollingLayerRect.left;
6725                    oldY = mScrollingLayerRect.top;
6726                    rangeX = maxX;
6727                    rangeY = maxY;
6728                } else {
6729                    // Scroll the main page if we are not going to scroll the
6730                    // layer.  This does not reset mScrollingLayer in case the
6731                    // user changes directions and the layer can scroll the
6732                    // other way.
6733                    mTouchMode = TOUCH_DRAG_MODE;
6734                }
6735            }
6736
6737            if (mOverScrollGlow != null) {
6738                mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
6739            }
6740
6741            overScrollBy(deltaX, deltaY, oldX, oldY,
6742                    rangeX, rangeY,
6743                    mOverscrollDistance, mOverscrollDistance, true);
6744            if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
6745                invalidate();
6746            }
6747        }
6748        mZoomManager.keepZoomPickerVisible();
6749    }
6750
6751    private void stopTouch() {
6752        if (mScroller.isFinished() && !mSelectingText
6753                && (mTouchMode == TOUCH_DRAG_MODE || mTouchMode == TOUCH_DRAG_LAYER_MODE)) {
6754            WebViewCore.resumePriority();
6755            WebViewCore.resumeUpdatePicture(mWebViewCore);
6756            nativeSetIsScrolling(false);
6757        }
6758
6759        // we also use mVelocityTracker == null to tell us that we are
6760        // not "moving around", so we can take the slower/prettier
6761        // mode in the drawing code
6762        if (mVelocityTracker != null) {
6763            mVelocityTracker.recycle();
6764            mVelocityTracker = null;
6765        }
6766
6767        // Release any pulled glows
6768        if (mOverScrollGlow != null) {
6769            mOverScrollGlow.releaseAll();
6770        }
6771    }
6772
6773    private void cancelTouch() {
6774        // we also use mVelocityTracker == null to tell us that we are
6775        // not "moving around", so we can take the slower/prettier
6776        // mode in the drawing code
6777        if (mVelocityTracker != null) {
6778            mVelocityTracker.recycle();
6779            mVelocityTracker = null;
6780        }
6781
6782        if ((mTouchMode == TOUCH_DRAG_MODE
6783                || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
6784            WebViewCore.resumePriority();
6785            WebViewCore.resumeUpdatePicture(mWebViewCore);
6786            nativeSetIsScrolling(false);
6787        }
6788        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6789        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6790        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6791        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6792        if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) {
6793            removeTouchHighlight();
6794        }
6795        mHeldMotionless = MOTIONLESS_TRUE;
6796        mTouchMode = TOUCH_DONE_MODE;
6797        nativeHideCursor();
6798    }
6799
6800    @Override
6801    public boolean onGenericMotionEvent(MotionEvent event) {
6802        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6803            switch (event.getAction()) {
6804                case MotionEvent.ACTION_SCROLL: {
6805                    final float vscroll;
6806                    final float hscroll;
6807                    if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
6808                        vscroll = 0;
6809                        hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6810                    } else {
6811                        vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6812                        hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
6813                    }
6814                    if (hscroll != 0 || vscroll != 0) {
6815                        final int vdelta = (int) (vscroll * getVerticalScrollFactor());
6816                        final int hdelta = (int) (hscroll * getHorizontalScrollFactor());
6817                        if (pinScrollBy(hdelta, vdelta, false, 0)) {
6818                            return true;
6819                        }
6820                    }
6821                }
6822            }
6823        }
6824        return super.onGenericMotionEvent(event);
6825    }
6826
6827    private long mTrackballFirstTime = 0;
6828    private long mTrackballLastTime = 0;
6829    private float mTrackballRemainsX = 0.0f;
6830    private float mTrackballRemainsY = 0.0f;
6831    private int mTrackballXMove = 0;
6832    private int mTrackballYMove = 0;
6833    private boolean mSelectingText = false;
6834    private boolean mSelectionStarted = false;
6835    private boolean mExtendSelection = false;
6836    private boolean mDrawSelectionPointer = false;
6837    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
6838    private static final int TRACKBALL_TIMEOUT = 200;
6839    private static final int TRACKBALL_WAIT = 100;
6840    private static final int TRACKBALL_SCALE = 400;
6841    private static final int TRACKBALL_SCROLL_COUNT = 5;
6842    private static final int TRACKBALL_MOVE_COUNT = 10;
6843    private static final int TRACKBALL_MULTIPLIER = 3;
6844    private static final int SELECT_CURSOR_OFFSET = 16;
6845    private static final int SELECT_SCROLL = 5;
6846    private int mSelectX = 0;
6847    private int mSelectY = 0;
6848    private boolean mFocusSizeChanged = false;
6849    private boolean mTrackballDown = false;
6850    private long mTrackballUpTime = 0;
6851    private long mLastCursorTime = 0;
6852    private Rect mLastCursorBounds;
6853
6854    // Set by default; BrowserActivity clears to interpret trackball data
6855    // directly for movement. Currently, the framework only passes
6856    // arrow key events, not trackball events, from one child to the next
6857    private boolean mMapTrackballToArrowKeys = true;
6858
6859    private DrawData mDelaySetPicture;
6860    private DrawData mLoadedPicture;
6861
6862    public void setMapTrackballToArrowKeys(boolean setMap) {
6863        checkThread();
6864        mMapTrackballToArrowKeys = setMap;
6865    }
6866
6867    void resetTrackballTime() {
6868        mTrackballLastTime = 0;
6869    }
6870
6871    @Override
6872    public boolean onTrackballEvent(MotionEvent ev) {
6873        long time = ev.getEventTime();
6874        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
6875            if (ev.getY() > 0) pageDown(true);
6876            if (ev.getY() < 0) pageUp(true);
6877            return true;
6878        }
6879        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
6880            if (mSelectingText) {
6881                return true; // discard press if copy in progress
6882            }
6883            mTrackballDown = true;
6884            if (mNativeClass == 0) {
6885                return false;
6886            }
6887            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
6888                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
6889                nativeSelectBestAt(mLastCursorBounds);
6890            }
6891            if (DebugFlags.WEB_VIEW) {
6892                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
6893                        + " time=" + time
6894                        + " mLastCursorTime=" + mLastCursorTime);
6895            }
6896            if (isInTouchMode()) requestFocusFromTouch();
6897            return false; // let common code in onKeyDown at it
6898        }
6899        if (ev.getAction() == MotionEvent.ACTION_UP) {
6900            // LONG_PRESS_CENTER is set in common onKeyDown
6901            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
6902            mTrackballDown = false;
6903            mTrackballUpTime = time;
6904            if (mSelectingText) {
6905                if (mExtendSelection) {
6906                    copySelection();
6907                    selectionDone();
6908                } else {
6909                    mExtendSelection = true;
6910                    nativeSetExtendSelection();
6911                    invalidate(); // draw the i-beam instead of the arrow
6912                }
6913                return true; // discard press if copy in progress
6914            }
6915            if (DebugFlags.WEB_VIEW) {
6916                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
6917                        + " time=" + time
6918                );
6919            }
6920            return false; // let common code in onKeyUp at it
6921        }
6922        if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
6923                AccessibilityManager.getInstance(mContext).isEnabled()) {
6924            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
6925            return false;
6926        }
6927        if (mTrackballDown) {
6928            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
6929            return true; // discard move if trackball is down
6930        }
6931        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
6932            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
6933            return true;
6934        }
6935        // TODO: alternatively we can do panning as touch does
6936        switchOutDrawHistory();
6937        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
6938            if (DebugFlags.WEB_VIEW) {
6939                Log.v(LOGTAG, "onTrackballEvent time="
6940                        + time + " last=" + mTrackballLastTime);
6941            }
6942            mTrackballFirstTime = time;
6943            mTrackballXMove = mTrackballYMove = 0;
6944        }
6945        mTrackballLastTime = time;
6946        if (DebugFlags.WEB_VIEW) {
6947            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
6948        }
6949        mTrackballRemainsX += ev.getX();
6950        mTrackballRemainsY += ev.getY();
6951        doTrackball(time, ev.getMetaState());
6952        return true;
6953    }
6954
6955    void moveSelection(float xRate, float yRate) {
6956        if (mNativeClass == 0)
6957            return;
6958        int width = getViewWidth();
6959        int height = getViewHeight();
6960        mSelectX += xRate;
6961        mSelectY += yRate;
6962        int maxX = width + mScrollX;
6963        int maxY = height + mScrollY;
6964        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
6965                , mSelectX));
6966        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
6967                , mSelectY));
6968        if (DebugFlags.WEB_VIEW) {
6969            Log.v(LOGTAG, "moveSelection"
6970                    + " mSelectX=" + mSelectX
6971                    + " mSelectY=" + mSelectY
6972                    + " mScrollX=" + mScrollX
6973                    + " mScrollY=" + mScrollY
6974                    + " xRate=" + xRate
6975                    + " yRate=" + yRate
6976                    );
6977        }
6978        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
6979        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
6980                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6981                : 0;
6982        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
6983                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6984                : 0;
6985        pinScrollBy(scrollX, scrollY, true, 0);
6986        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
6987        requestRectangleOnScreen(select);
6988        invalidate();
6989   }
6990
6991    private int scaleTrackballX(float xRate, int width) {
6992        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
6993        int nextXMove = xMove;
6994        if (xMove > 0) {
6995            if (xMove > mTrackballXMove) {
6996                xMove -= mTrackballXMove;
6997            }
6998        } else if (xMove < mTrackballXMove) {
6999            xMove -= mTrackballXMove;
7000        }
7001        mTrackballXMove = nextXMove;
7002        return xMove;
7003    }
7004
7005    private int scaleTrackballY(float yRate, int height) {
7006        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
7007        int nextYMove = yMove;
7008        if (yMove > 0) {
7009            if (yMove > mTrackballYMove) {
7010                yMove -= mTrackballYMove;
7011            }
7012        } else if (yMove < mTrackballYMove) {
7013            yMove -= mTrackballYMove;
7014        }
7015        mTrackballYMove = nextYMove;
7016        return yMove;
7017    }
7018
7019    private int keyCodeToSoundsEffect(int keyCode) {
7020        switch(keyCode) {
7021            case KeyEvent.KEYCODE_DPAD_UP:
7022                return SoundEffectConstants.NAVIGATION_UP;
7023            case KeyEvent.KEYCODE_DPAD_RIGHT:
7024                return SoundEffectConstants.NAVIGATION_RIGHT;
7025            case KeyEvent.KEYCODE_DPAD_DOWN:
7026                return SoundEffectConstants.NAVIGATION_DOWN;
7027            case KeyEvent.KEYCODE_DPAD_LEFT:
7028                return SoundEffectConstants.NAVIGATION_LEFT;
7029        }
7030        throw new IllegalArgumentException("keyCode must be one of " +
7031                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
7032                "KEYCODE_DPAD_LEFT}.");
7033    }
7034
7035    private void doTrackball(long time, int metaState) {
7036        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
7037        if (elapsed == 0) {
7038            elapsed = TRACKBALL_TIMEOUT;
7039        }
7040        float xRate = mTrackballRemainsX * 1000 / elapsed;
7041        float yRate = mTrackballRemainsY * 1000 / elapsed;
7042        int viewWidth = getViewWidth();
7043        int viewHeight = getViewHeight();
7044        if (mSelectingText) {
7045            if (!mDrawSelectionPointer) {
7046                // The last selection was made by touch, disabling drawing the
7047                // selection pointer. Allow the trackball to adjust the
7048                // position of the touch control.
7049                mSelectX = contentToViewX(nativeSelectionX());
7050                mSelectY = contentToViewY(nativeSelectionY());
7051                mDrawSelectionPointer = mExtendSelection = true;
7052                nativeSetExtendSelection();
7053            }
7054            moveSelection(scaleTrackballX(xRate, viewWidth),
7055                    scaleTrackballY(yRate, viewHeight));
7056            mTrackballRemainsX = mTrackballRemainsY = 0;
7057            return;
7058        }
7059        float ax = Math.abs(xRate);
7060        float ay = Math.abs(yRate);
7061        float maxA = Math.max(ax, ay);
7062        if (DebugFlags.WEB_VIEW) {
7063            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
7064                    + " xRate=" + xRate
7065                    + " yRate=" + yRate
7066                    + " mTrackballRemainsX=" + mTrackballRemainsX
7067                    + " mTrackballRemainsY=" + mTrackballRemainsY);
7068        }
7069        int width = mContentWidth - viewWidth;
7070        int height = mContentHeight - viewHeight;
7071        if (width < 0) width = 0;
7072        if (height < 0) height = 0;
7073        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
7074        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
7075        maxA = Math.max(ax, ay);
7076        int count = Math.max(0, (int) maxA);
7077        int oldScrollX = mScrollX;
7078        int oldScrollY = mScrollY;
7079        if (count > 0) {
7080            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
7081                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
7082                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
7083                    KeyEvent.KEYCODE_DPAD_RIGHT;
7084            count = Math.min(count, TRACKBALL_MOVE_COUNT);
7085            if (DebugFlags.WEB_VIEW) {
7086                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
7087                        + " count=" + count
7088                        + " mTrackballRemainsX=" + mTrackballRemainsX
7089                        + " mTrackballRemainsY=" + mTrackballRemainsY);
7090            }
7091            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
7092                for (int i = 0; i < count; i++) {
7093                    letPageHandleNavKey(selectKeyCode, time, true, metaState);
7094                }
7095                letPageHandleNavKey(selectKeyCode, time, false, metaState);
7096            } else if (navHandledKey(selectKeyCode, count, false, time)) {
7097                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
7098            }
7099            mTrackballRemainsX = mTrackballRemainsY = 0;
7100        }
7101        if (count >= TRACKBALL_SCROLL_COUNT) {
7102            int xMove = scaleTrackballX(xRate, width);
7103            int yMove = scaleTrackballY(yRate, height);
7104            if (DebugFlags.WEB_VIEW) {
7105                Log.v(LOGTAG, "doTrackball pinScrollBy"
7106                        + " count=" + count
7107                        + " xMove=" + xMove + " yMove=" + yMove
7108                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
7109                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
7110                        );
7111            }
7112            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
7113                xMove = 0;
7114            }
7115            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
7116                yMove = 0;
7117            }
7118            if (xMove != 0 || yMove != 0) {
7119                pinScrollBy(xMove, yMove, true, 0);
7120            }
7121        }
7122    }
7123
7124    /**
7125     * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
7126     * @return Maximum horizontal scroll position within real content
7127     */
7128    int computeMaxScrollX() {
7129        return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
7130    }
7131
7132    /**
7133     * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
7134     * @return Maximum vertical scroll position within real content
7135     */
7136    int computeMaxScrollY() {
7137        return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
7138                - getViewHeightWithTitle(), 0);
7139    }
7140
7141    boolean updateScrollCoordinates(int x, int y) {
7142        int oldX = mScrollX;
7143        int oldY = mScrollY;
7144        mScrollX = x;
7145        mScrollY = y;
7146        if (oldX != mScrollX || oldY != mScrollY) {
7147            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
7148            return true;
7149        } else {
7150            return false;
7151        }
7152    }
7153
7154    public void flingScroll(int vx, int vy) {
7155        checkThread();
7156        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
7157                computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
7158        invalidate();
7159    }
7160
7161    private void doFling() {
7162        if (mVelocityTracker == null) {
7163            return;
7164        }
7165        int maxX = computeMaxScrollX();
7166        int maxY = computeMaxScrollY();
7167
7168        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
7169        int vx = (int) mVelocityTracker.getXVelocity();
7170        int vy = (int) mVelocityTracker.getYVelocity();
7171
7172        int scrollX = mScrollX;
7173        int scrollY = mScrollY;
7174        int overscrollDistance = mOverscrollDistance;
7175        int overflingDistance = mOverflingDistance;
7176
7177        // Use the layer's scroll data if applicable.
7178        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
7179            scrollX = mScrollingLayerRect.left;
7180            scrollY = mScrollingLayerRect.top;
7181            maxX = mScrollingLayerRect.right;
7182            maxY = mScrollingLayerRect.bottom;
7183            // No overscrolling for layers.
7184            overscrollDistance = overflingDistance = 0;
7185        }
7186
7187        if (mSnapScrollMode != SNAP_NONE) {
7188            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
7189                vy = 0;
7190            } else {
7191                vx = 0;
7192            }
7193        }
7194        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
7195            WebViewCore.resumePriority();
7196            if (!mSelectingText) {
7197                WebViewCore.resumeUpdatePicture(mWebViewCore);
7198            }
7199            if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) {
7200                invalidate();
7201            }
7202            return;
7203        }
7204        float currentVelocity = mScroller.getCurrVelocity();
7205        float velocity = (float) Math.hypot(vx, vy);
7206        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
7207                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
7208            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
7209                    - Math.atan2(vy, vx)));
7210            final float circle = (float) (Math.PI) * 2.0f;
7211            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
7212                vx += currentVelocity * mLastVelX / mLastVelocity;
7213                vy += currentVelocity * mLastVelY / mLastVelocity;
7214                velocity = (float) Math.hypot(vx, vy);
7215                if (DebugFlags.WEB_VIEW) {
7216                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
7217                }
7218            } else if (DebugFlags.WEB_VIEW) {
7219                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
7220            }
7221        } else if (DebugFlags.WEB_VIEW) {
7222            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
7223                    + " current=" + currentVelocity
7224                    + " vx=" + vx + " vy=" + vy
7225                    + " maxX=" + maxX + " maxY=" + maxY
7226                    + " scrollX=" + scrollX + " scrollY=" + scrollY
7227                    + " layer=" + mScrollingLayer);
7228        }
7229
7230        // Allow sloppy flings without overscrolling at the edges.
7231        if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
7232            vx = 0;
7233        }
7234        if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
7235            vy = 0;
7236        }
7237
7238        if (overscrollDistance < overflingDistance) {
7239            if ((vx > 0 && scrollX == -overscrollDistance) ||
7240                    (vx < 0 && scrollX == maxX + overscrollDistance)) {
7241                vx = 0;
7242            }
7243            if ((vy > 0 && scrollY == -overscrollDistance) ||
7244                    (vy < 0 && scrollY == maxY + overscrollDistance)) {
7245                vy = 0;
7246            }
7247        }
7248
7249        mLastVelX = vx;
7250        mLastVelY = vy;
7251        mLastVelocity = velocity;
7252
7253        // no horizontal overscroll if the content just fits
7254        mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY,
7255                maxX == 0 ? 0 : overflingDistance, overflingDistance);
7256        // Duration is calculated based on velocity. With range boundaries and overscroll
7257        // we may not know how long the final animation will take. (Hence the deprecation
7258        // warning on the call below.) It's not a big deal for scroll bars but if webcore
7259        // resumes during this effect we will take a performance hit. See computeScroll;
7260        // we resume webcore there when the animation is finished.
7261        final int time = mScroller.getDuration();
7262
7263        // Suppress scrollbars for layer scrolling.
7264        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
7265            awakenScrollBars(time);
7266        }
7267
7268        invalidate();
7269    }
7270
7271    /**
7272     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
7273     * in charge of installing this view to the view hierarchy. This view will
7274     * become visible when the user starts scrolling via touch and fade away if
7275     * the user does not interact with it.
7276     * <p/>
7277     * API version 3 introduces a built-in zoom mechanism that is shown
7278     * automatically by the MapView. This is the preferred approach for
7279     * showing the zoom UI.
7280     *
7281     * @deprecated The built-in zoom mechanism is preferred, see
7282     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
7283     */
7284    @Deprecated
7285    public View getZoomControls() {
7286        checkThread();
7287        if (!getSettings().supportZoom()) {
7288            Log.w(LOGTAG, "This WebView doesn't support zoom.");
7289            return null;
7290        }
7291        return mZoomManager.getExternalZoomPicker();
7292    }
7293
7294    void dismissZoomControl() {
7295        mZoomManager.dismissZoomPicker();
7296    }
7297
7298    float getDefaultZoomScale() {
7299        return mZoomManager.getDefaultScale();
7300    }
7301
7302    /**
7303     * Return the overview scale of the WebView
7304     * @return The overview scale.
7305     */
7306    float getZoomOverviewScale() {
7307        return mZoomManager.getZoomOverviewScale();
7308    }
7309
7310    /**
7311     * @return TRUE if the WebView can be zoomed in.
7312     */
7313    public boolean canZoomIn() {
7314        checkThread();
7315        return mZoomManager.canZoomIn();
7316    }
7317
7318    /**
7319     * @return TRUE if the WebView can be zoomed out.
7320     */
7321    public boolean canZoomOut() {
7322        checkThread();
7323        return mZoomManager.canZoomOut();
7324    }
7325
7326    /**
7327     * Perform zoom in in the webview
7328     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
7329     */
7330    public boolean zoomIn() {
7331        checkThread();
7332        return mZoomManager.zoomIn();
7333    }
7334
7335    /**
7336     * Perform zoom out in the webview
7337     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
7338     */
7339    public boolean zoomOut() {
7340        checkThread();
7341        return mZoomManager.zoomOut();
7342    }
7343
7344    /**
7345     * This selects the best clickable target at mLastTouchX and mLastTouchY
7346     * and calls showCursorTimed on the native side
7347     */
7348    private void updateSelection() {
7349        if (mNativeClass == 0) {
7350            return;
7351        }
7352        mPrivateHandler.removeMessages(UPDATE_SELECTION);
7353        // mLastTouchX and mLastTouchY are the point in the current viewport
7354        int contentX = viewToContentX(mLastTouchX + mScrollX);
7355        int contentY = viewToContentY(mLastTouchY + mScrollY);
7356        int slop = viewToContentDimension(mNavSlop);
7357        Rect rect = new Rect(contentX - slop, contentY - slop,
7358                contentX + slop, contentY + slop);
7359        nativeSelectBestAt(rect);
7360        mInitialHitTestResult = hitTestResult(null);
7361    }
7362
7363    /**
7364     * Scroll the focused text field to match the WebTextView
7365     * @param xPercent New x position of the WebTextView from 0 to 1.
7366     */
7367    /*package*/ void scrollFocusedTextInputX(float xPercent) {
7368        if (!inEditingMode() || mWebViewCore == null) {
7369            return;
7370        }
7371        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0,
7372                new Float(xPercent));
7373    }
7374
7375    /**
7376     * Scroll the focused textarea vertically to match the WebTextView
7377     * @param y New y position of the WebTextView in view coordinates
7378     */
7379    /* package */ void scrollFocusedTextInputY(int y) {
7380        if (!inEditingMode() || mWebViewCore == null) {
7381            return;
7382        }
7383        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0, viewToContentDimension(y));
7384    }
7385
7386    /**
7387     * Set our starting point and time for a drag from the WebTextView.
7388     */
7389    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
7390        if (!inEditingMode()) {
7391            return;
7392        }
7393        mLastTouchX = Math.round(x + mWebTextView.getLeft() - mScrollX);
7394        mLastTouchY = Math.round(y + mWebTextView.getTop() - mScrollY);
7395        mLastTouchTime = eventTime;
7396        if (!mScroller.isFinished()) {
7397            abortAnimation();
7398        }
7399        mSnapScrollMode = SNAP_NONE;
7400        mVelocityTracker = VelocityTracker.obtain();
7401        mTouchMode = TOUCH_DRAG_START_MODE;
7402    }
7403
7404    /**
7405     * Given a motion event from the WebTextView, set its location to our
7406     * coordinates, and handle the event.
7407     */
7408    /*package*/ boolean textFieldDrag(MotionEvent event) {
7409        if (!inEditingMode()) {
7410            return false;
7411        }
7412        mDragFromTextInput = true;
7413        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
7414                (float) (mWebTextView.getTop() - mScrollY));
7415        boolean result = onTouchEvent(event);
7416        mDragFromTextInput = false;
7417        return result;
7418    }
7419
7420    /**
7421     * Due a touch up from a WebTextView.  This will be handled by webkit to
7422     * change the selection.
7423     * @param event MotionEvent in the WebTextView's coordinates.
7424     */
7425    /*package*/ void touchUpOnTextField(MotionEvent event) {
7426        if (!inEditingMode()) {
7427            return;
7428        }
7429        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
7430        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
7431        int slop = viewToContentDimension(mNavSlop);
7432        nativeMotionUp(x, y, slop);
7433    }
7434
7435    /**
7436     * Called when pressing the center key or trackball on a textfield.
7437     */
7438    /*package*/ void centerKeyPressOnTextField() {
7439        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
7440                    nativeCursorNodePointer());
7441    }
7442
7443    private void doShortPress() {
7444        if (mNativeClass == 0) {
7445            return;
7446        }
7447        if (mPreventDefault == PREVENT_DEFAULT_YES) {
7448            return;
7449        }
7450        mTouchMode = TOUCH_DONE_MODE;
7451        updateSelection();
7452        switchOutDrawHistory();
7453        // mLastTouchX and mLastTouchY are the point in the current viewport
7454        int contentX = viewToContentX(mLastTouchX + mScrollX);
7455        int contentY = viewToContentY(mLastTouchY + mScrollY);
7456        int slop = viewToContentDimension(mNavSlop);
7457        if (USE_WEBKIT_RINGS && !mTouchHighlightRegion.isEmpty()) {
7458            // set mTouchHighlightRequested to 0 to cause an immediate
7459            // drawing of the touch rings
7460            mTouchHighlightRequested = 0;
7461            invalidate(mTouchHighlightRegion.getBounds());
7462            mPrivateHandler.postDelayed(new Runnable() {
7463                @Override
7464                public void run() {
7465                    removeTouchHighlight();
7466                }
7467            }, ViewConfiguration.getPressedStateDuration());
7468        }
7469        if (getSettings().supportTouchOnly()) {
7470            removeTouchHighlight();
7471            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7472            // use "0" as generation id to inform WebKit to use the same x/y as
7473            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
7474            touchUpData.mMoveGeneration = 0;
7475            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7476        } else if (nativePointInNavCache(contentX, contentY, slop)) {
7477            WebViewCore.MotionUpData motionUpData = new WebViewCore
7478                    .MotionUpData();
7479            motionUpData.mFrame = nativeCacheHitFramePointer();
7480            motionUpData.mNode = nativeCacheHitNodePointer();
7481            motionUpData.mBounds = nativeCacheHitNodeBounds();
7482            motionUpData.mX = contentX;
7483            motionUpData.mY = contentY;
7484            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
7485                    motionUpData);
7486        } else {
7487            doMotionUp(contentX, contentY);
7488        }
7489    }
7490
7491    private void doMotionUp(int contentX, int contentY) {
7492        int slop = viewToContentDimension(mNavSlop);
7493        if (nativeMotionUp(contentX, contentY, slop) && mLogEvent) {
7494            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
7495        }
7496        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
7497            playSoundEffect(SoundEffectConstants.CLICK);
7498        }
7499    }
7500
7501    void sendPluginDrawMsg() {
7502        mWebViewCore.sendMessage(EventHub.PLUGIN_SURFACE_READY);
7503    }
7504
7505    /**
7506     * Returns plugin bounds if x/y in content coordinates corresponds to a
7507     * plugin. Otherwise a NULL rectangle is returned.
7508     */
7509    Rect getPluginBounds(int x, int y) {
7510        int slop = viewToContentDimension(mNavSlop);
7511        if (nativePointInNavCache(x, y, slop) && nativeCacheHitIsPlugin()) {
7512            return nativeCacheHitNodeBounds();
7513        } else {
7514            return null;
7515        }
7516    }
7517
7518    /*
7519     * Return true if the rect (e.g. plugin) is fully visible and maximized
7520     * inside the WebView.
7521     */
7522    boolean isRectFitOnScreen(Rect rect) {
7523        final int rectWidth = rect.width();
7524        final int rectHeight = rect.height();
7525        final int viewWidth = getViewWidth();
7526        final int viewHeight = getViewHeightWithTitle();
7527        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight);
7528        scale = mZoomManager.computeScaleWithLimits(scale);
7529        return !mZoomManager.willScaleTriggerZoom(scale)
7530                && contentToViewX(rect.left) >= mScrollX
7531                && contentToViewX(rect.right) <= mScrollX + viewWidth
7532                && contentToViewY(rect.top) >= mScrollY
7533                && contentToViewY(rect.bottom) <= mScrollY + viewHeight;
7534    }
7535
7536    /*
7537     * Maximize and center the rectangle, specified in the document coordinate
7538     * space, inside the WebView. If the zoom doesn't need to be changed, do an
7539     * animated scroll to center it. If the zoom needs to be changed, find the
7540     * zoom center and do a smooth zoom transition. The rect is in document
7541     * coordinates
7542     */
7543    void centerFitRect(Rect rect) {
7544        final int rectWidth = rect.width();
7545        final int rectHeight = rect.height();
7546        final int viewWidth = getViewWidth();
7547        final int viewHeight = getViewHeightWithTitle();
7548        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight
7549                / rectHeight);
7550        scale = mZoomManager.computeScaleWithLimits(scale);
7551        if (!mZoomManager.willScaleTriggerZoom(scale)) {
7552            pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2,
7553                    contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2,
7554                    true, 0);
7555        } else {
7556            float actualScale = mZoomManager.getScale();
7557            float oldScreenX = rect.left * actualScale - mScrollX;
7558            float rectViewX = rect.left * scale;
7559            float rectViewWidth = rectWidth * scale;
7560            float newMaxWidth = mContentWidth * scale;
7561            float newScreenX = (viewWidth - rectViewWidth) / 2;
7562            // pin the newX to the WebView
7563            if (newScreenX > rectViewX) {
7564                newScreenX = rectViewX;
7565            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
7566                newScreenX = viewWidth - (newMaxWidth - rectViewX);
7567            }
7568            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
7569                    / (scale - actualScale);
7570            float oldScreenY = rect.top * actualScale + getTitleHeight()
7571                    - mScrollY;
7572            float rectViewY = rect.top * scale + getTitleHeight();
7573            float rectViewHeight = rectHeight * scale;
7574            float newMaxHeight = mContentHeight * scale + getTitleHeight();
7575            float newScreenY = (viewHeight - rectViewHeight) / 2;
7576            // pin the newY to the WebView
7577            if (newScreenY > rectViewY) {
7578                newScreenY = rectViewY;
7579            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
7580                newScreenY = viewHeight - (newMaxHeight - rectViewY);
7581            }
7582            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
7583                    / (scale - actualScale);
7584            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
7585            mZoomManager.startZoomAnimation(scale, false);
7586        }
7587    }
7588
7589    // Called by JNI to handle a touch on a node representing an email address,
7590    // address, or phone number
7591    private void overrideLoading(String url) {
7592        mCallbackProxy.uiOverrideUrlLoading(url);
7593    }
7594
7595    @Override
7596    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7597        // FIXME: If a subwindow is showing find, and the user touches the
7598        // background window, it can steal focus.
7599        if (mFindIsUp) return false;
7600        boolean result = false;
7601        if (inEditingMode()) {
7602            result = mWebTextView.requestFocus(direction,
7603                    previouslyFocusedRect);
7604        } else {
7605            result = super.requestFocus(direction, previouslyFocusedRect);
7606            if (mWebViewCore.getSettings().getNeedInitialFocus() && !isInTouchMode()) {
7607                // For cases such as GMail, where we gain focus from a direction,
7608                // we want to move to the first available link.
7609                // FIXME: If there are no visible links, we may not want to
7610                int fakeKeyDirection = 0;
7611                switch(direction) {
7612                    case View.FOCUS_UP:
7613                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
7614                        break;
7615                    case View.FOCUS_DOWN:
7616                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
7617                        break;
7618                    case View.FOCUS_LEFT:
7619                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
7620                        break;
7621                    case View.FOCUS_RIGHT:
7622                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
7623                        break;
7624                    default:
7625                        return result;
7626                }
7627                if (mNativeClass != 0 && !nativeHasCursorNode()) {
7628                    navHandledKey(fakeKeyDirection, 1, true, 0);
7629                }
7630            }
7631        }
7632        return result;
7633    }
7634
7635    @Override
7636    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7637        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
7638
7639        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
7640        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
7641        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
7642        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
7643
7644        int measuredHeight = heightSize;
7645        int measuredWidth = widthSize;
7646
7647        // Grab the content size from WebViewCore.
7648        int contentHeight = contentToViewDimension(mContentHeight);
7649        int contentWidth = contentToViewDimension(mContentWidth);
7650
7651//        Log.d(LOGTAG, "------- measure " + heightMode);
7652
7653        if (heightMode != MeasureSpec.EXACTLY) {
7654            mHeightCanMeasure = true;
7655            measuredHeight = contentHeight;
7656            if (heightMode == MeasureSpec.AT_MOST) {
7657                // If we are larger than the AT_MOST height, then our height can
7658                // no longer be measured and we should scroll internally.
7659                if (measuredHeight > heightSize) {
7660                    measuredHeight = heightSize;
7661                    mHeightCanMeasure = false;
7662                    measuredHeight |= MEASURED_STATE_TOO_SMALL;
7663                }
7664            }
7665        } else {
7666            mHeightCanMeasure = false;
7667        }
7668        if (mNativeClass != 0) {
7669            nativeSetHeightCanMeasure(mHeightCanMeasure);
7670        }
7671        // For the width, always use the given size unless unspecified.
7672        if (widthMode == MeasureSpec.UNSPECIFIED) {
7673            mWidthCanMeasure = true;
7674            measuredWidth = contentWidth;
7675        } else {
7676            if (measuredWidth < contentWidth) {
7677                measuredWidth |= MEASURED_STATE_TOO_SMALL;
7678            }
7679            mWidthCanMeasure = false;
7680        }
7681
7682        synchronized (this) {
7683            setMeasuredDimension(measuredWidth, measuredHeight);
7684        }
7685    }
7686
7687    @Override
7688    public boolean requestChildRectangleOnScreen(View child,
7689                                                 Rect rect,
7690                                                 boolean immediate) {
7691        if (mNativeClass == 0) {
7692            return false;
7693        }
7694        // don't scroll while in zoom animation. When it is done, we will adjust
7695        // the necessary components (e.g., WebTextView if it is in editing mode)
7696        if (mZoomManager.isFixedLengthAnimationInProgress()) {
7697            return false;
7698        }
7699
7700        rect.offset(child.getLeft() - child.getScrollX(),
7701                child.getTop() - child.getScrollY());
7702
7703        Rect content = new Rect(viewToContentX(mScrollX),
7704                viewToContentY(mScrollY),
7705                viewToContentX(mScrollX + getWidth()
7706                - getVerticalScrollbarWidth()),
7707                viewToContentY(mScrollY + getViewHeightWithTitle()));
7708        content = nativeSubtractLayers(content);
7709        int screenTop = contentToViewY(content.top);
7710        int screenBottom = contentToViewY(content.bottom);
7711        int height = screenBottom - screenTop;
7712        int scrollYDelta = 0;
7713
7714        if (rect.bottom > screenBottom) {
7715            int oneThirdOfScreenHeight = height / 3;
7716            if (rect.height() > 2 * oneThirdOfScreenHeight) {
7717                // If the rectangle is too tall to fit in the bottom two thirds
7718                // of the screen, place it at the top.
7719                scrollYDelta = rect.top - screenTop;
7720            } else {
7721                // If the rectangle will still fit on screen, we want its
7722                // top to be in the top third of the screen.
7723                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
7724            }
7725        } else if (rect.top < screenTop) {
7726            scrollYDelta = rect.top - screenTop;
7727        }
7728
7729        int screenLeft = contentToViewX(content.left);
7730        int screenRight = contentToViewX(content.right);
7731        int width = screenRight - screenLeft;
7732        int scrollXDelta = 0;
7733
7734        if (rect.right > screenRight && rect.left > screenLeft) {
7735            if (rect.width() > width) {
7736                scrollXDelta += (rect.left - screenLeft);
7737            } else {
7738                scrollXDelta += (rect.right - screenRight);
7739            }
7740        } else if (rect.left < screenLeft) {
7741            scrollXDelta -= (screenLeft - rect.left);
7742        }
7743
7744        if ((scrollYDelta | scrollXDelta) != 0) {
7745            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
7746        }
7747
7748        return false;
7749    }
7750
7751    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
7752            String replace, int newStart, int newEnd) {
7753        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
7754        arg.mReplace = replace;
7755        arg.mNewStart = newStart;
7756        arg.mNewEnd = newEnd;
7757        mTextGeneration++;
7758        arg.mTextGeneration = mTextGeneration;
7759        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
7760    }
7761
7762    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
7763        // check if mWebViewCore has been destroyed
7764        if (mWebViewCore == null) {
7765            return;
7766        }
7767        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
7768        arg.mEvent = event;
7769        arg.mCurrentText = currentText;
7770        // Increase our text generation number, and pass it to webcore thread
7771        mTextGeneration++;
7772        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
7773        // WebKit's document state is not saved until about to leave the page.
7774        // To make sure the host application, like Browser, has the up to date
7775        // document state when it goes to background, we force to save the
7776        // document state.
7777        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
7778        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
7779                cursorData(), 1000);
7780    }
7781
7782    /**
7783     * @hide
7784     */
7785    public synchronized WebViewCore getWebViewCore() {
7786        return mWebViewCore;
7787    }
7788
7789    /**
7790     * Used only by TouchEventQueue to store pending touch events.
7791     */
7792    private static class QueuedTouch {
7793        long mSequence;
7794        MotionEvent mEvent; // Optional
7795        TouchEventData mTed; // Optional
7796
7797        QueuedTouch mNext;
7798
7799        public QueuedTouch set(TouchEventData ted) {
7800            mSequence = ted.mSequence;
7801            mTed = ted;
7802            mEvent = null;
7803            mNext = null;
7804            return this;
7805        }
7806
7807        public QueuedTouch set(MotionEvent ev, long sequence) {
7808            mEvent = MotionEvent.obtain(ev);
7809            mSequence = sequence;
7810            mTed = null;
7811            mNext = null;
7812            return this;
7813        }
7814
7815        public QueuedTouch add(QueuedTouch other) {
7816            if (other.mSequence < mSequence) {
7817                other.mNext = this;
7818                return other;
7819            }
7820
7821            QueuedTouch insertAt = this;
7822            while (insertAt.mNext != null && insertAt.mNext.mSequence < other.mSequence) {
7823                insertAt = insertAt.mNext;
7824            }
7825            other.mNext = insertAt.mNext;
7826            insertAt.mNext = other;
7827            return this;
7828        }
7829    }
7830
7831    /**
7832     * WebView handles touch events asynchronously since some events must be passed to WebKit
7833     * for potentially slower processing. TouchEventQueue serializes touch events regardless
7834     * of which path they take to ensure that no events are ever processed out of order
7835     * by WebView.
7836     */
7837    private class TouchEventQueue {
7838        private long mNextTouchSequence = Long.MIN_VALUE + 1;
7839        private long mLastHandledTouchSequence = Long.MIN_VALUE;
7840        private long mIgnoreUntilSequence = Long.MIN_VALUE + 1;
7841
7842        // Events waiting to be processed.
7843        private QueuedTouch mTouchEventQueue;
7844
7845        // Known events that are waiting on a response before being enqueued.
7846        private QueuedTouch mPreQueue;
7847
7848        // Pool of QueuedTouch objects saved for later use.
7849        private QueuedTouch mQueuedTouchRecycleBin;
7850        private int mQueuedTouchRecycleCount;
7851
7852        private long mLastEventTime = Long.MAX_VALUE;
7853        private static final int MAX_RECYCLED_QUEUED_TOUCH = 15;
7854
7855        // milliseconds until we abandon hope of getting all of a previous gesture
7856        private static final int QUEUED_GESTURE_TIMEOUT = 1000;
7857
7858        private QueuedTouch obtainQueuedTouch() {
7859            if (mQueuedTouchRecycleBin != null) {
7860                QueuedTouch result = mQueuedTouchRecycleBin;
7861                mQueuedTouchRecycleBin = result.mNext;
7862                mQueuedTouchRecycleCount--;
7863                return result;
7864            }
7865            return new QueuedTouch();
7866        }
7867
7868        /**
7869         * Allow events with any currently missing sequence numbers to be skipped in processing.
7870         */
7871        public void ignoreCurrentlyMissingEvents() {
7872            mIgnoreUntilSequence = mNextTouchSequence;
7873
7874            // Run any events we have available and complete, pre-queued or otherwise.
7875            runQueuedAndPreQueuedEvents();
7876        }
7877
7878        private void runQueuedAndPreQueuedEvents() {
7879            QueuedTouch qd = mPreQueue;
7880            boolean fromPreQueue = true;
7881            while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) {
7882                handleQueuedTouch(qd);
7883                QueuedTouch recycleMe = qd;
7884                if (fromPreQueue) {
7885                    mPreQueue = qd.mNext;
7886                } else {
7887                    mTouchEventQueue = qd.mNext;
7888                }
7889                recycleQueuedTouch(recycleMe);
7890                mLastHandledTouchSequence++;
7891
7892                long nextPre = mPreQueue != null ? mPreQueue.mSequence : Long.MAX_VALUE;
7893                long nextQueued = mTouchEventQueue != null ?
7894                        mTouchEventQueue.mSequence : Long.MAX_VALUE;
7895                fromPreQueue = nextPre < nextQueued;
7896                qd = fromPreQueue ? mPreQueue : mTouchEventQueue;
7897            }
7898        }
7899
7900        /**
7901         * Add a TouchEventData to the pre-queue.
7902         *
7903         * An event in the pre-queue is an event that we know about that
7904         * has been sent to webkit, but that we haven't received back and
7905         * enqueued into the normal touch queue yet. If webkit ever times
7906         * out and we need to ignore currently missing events, we'll run
7907         * events from the pre-queue to patch the holes.
7908         *
7909         * @param ted TouchEventData to pre-queue
7910         */
7911        public void preQueueTouchEventData(TouchEventData ted) {
7912            QueuedTouch newTouch = obtainQueuedTouch().set(ted);
7913            if (mPreQueue == null) {
7914                mPreQueue = newTouch;
7915            } else {
7916                QueuedTouch insertionPoint = mPreQueue;
7917                while (insertionPoint.mNext != null &&
7918                        insertionPoint.mNext.mSequence < newTouch.mSequence) {
7919                    insertionPoint = insertionPoint.mNext;
7920                }
7921                newTouch.mNext = insertionPoint.mNext;
7922                insertionPoint.mNext = newTouch;
7923            }
7924        }
7925
7926        private void recycleQueuedTouch(QueuedTouch qd) {
7927            if (mQueuedTouchRecycleCount < MAX_RECYCLED_QUEUED_TOUCH) {
7928                qd.mNext = mQueuedTouchRecycleBin;
7929                mQueuedTouchRecycleBin = qd;
7930                mQueuedTouchRecycleCount++;
7931            }
7932        }
7933
7934        /**
7935         * Reset the touch event queue. This will dump any pending events
7936         * and reset the sequence numbering.
7937         */
7938        public void reset() {
7939            mNextTouchSequence = Long.MIN_VALUE + 1;
7940            mLastHandledTouchSequence = Long.MIN_VALUE;
7941            mIgnoreUntilSequence = Long.MIN_VALUE + 1;
7942            while (mTouchEventQueue != null) {
7943                QueuedTouch recycleMe = mTouchEventQueue;
7944                mTouchEventQueue = mTouchEventQueue.mNext;
7945                recycleQueuedTouch(recycleMe);
7946            }
7947            while (mPreQueue != null) {
7948                QueuedTouch recycleMe = mPreQueue;
7949                mPreQueue = mPreQueue.mNext;
7950                recycleQueuedTouch(recycleMe);
7951            }
7952        }
7953
7954        /**
7955         * Return the next valid sequence number for tagging incoming touch events.
7956         * @return The next touch event sequence number
7957         */
7958        public long nextTouchSequence() {
7959            return mNextTouchSequence++;
7960        }
7961
7962        /**
7963         * Enqueue a touch event in the form of TouchEventData.
7964         * The sequence number will be read from the mSequence field of the argument.
7965         *
7966         * If the touch event's sequence number is the next in line to be processed, it will
7967         * be handled before this method returns. Any subsequent events that have already
7968         * been queued will also be processed in their proper order.
7969         *
7970         * @param ted Touch data to be processed in order.
7971         * @return true if the event was processed before returning, false if it was just enqueued.
7972         */
7973        public boolean enqueueTouchEvent(TouchEventData ted) {
7974            // Remove from the pre-queue if present
7975            QueuedTouch preQueue = mPreQueue;
7976            if (preQueue != null) {
7977                // On exiting this block, preQueue is set to the pre-queued QueuedTouch object
7978                // if it was present in the pre-queue, and removed from the pre-queue itself.
7979                if (preQueue.mSequence == ted.mSequence) {
7980                    mPreQueue = preQueue.mNext;
7981                } else {
7982                    QueuedTouch prev = preQueue;
7983                    preQueue = null;
7984                    while (prev.mNext != null) {
7985                        if (prev.mNext.mSequence == ted.mSequence) {
7986                            preQueue = prev.mNext;
7987                            prev.mNext = preQueue.mNext;
7988                            break;
7989                        } else {
7990                            prev = prev.mNext;
7991                        }
7992                    }
7993                }
7994            }
7995
7996            if (ted.mSequence < mLastHandledTouchSequence) {
7997                // Stale event and we already moved on; drop it. (Should not be common.)
7998                Log.w(LOGTAG, "Stale touch event " + MotionEvent.actionToString(ted.mAction) +
7999                        " received from webcore; ignoring");
8000                return false;
8001            }
8002
8003            if (dropStaleGestures(ted.mMotionEvent, ted.mSequence)) {
8004                return false;
8005            }
8006
8007            // dropStaleGestures above might have fast-forwarded us to
8008            // an event we have already.
8009            runNextQueuedEvents();
8010
8011            if (mLastHandledTouchSequence + 1 == ted.mSequence) {
8012                if (preQueue != null) {
8013                    recycleQueuedTouch(preQueue);
8014                    preQueue = null;
8015                }
8016                handleQueuedTouchEventData(ted);
8017
8018                mLastHandledTouchSequence++;
8019
8020                // Do we have any more? Run them if so.
8021                runNextQueuedEvents();
8022            } else {
8023                // Reuse the pre-queued object if we had it.
8024                QueuedTouch qd = preQueue != null ? preQueue : obtainQueuedTouch().set(ted);
8025                mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd);
8026            }
8027            return true;
8028        }
8029
8030        /**
8031         * Enqueue a touch event in the form of a MotionEvent from the framework.
8032         *
8033         * If the touch event's sequence number is the next in line to be processed, it will
8034         * be handled before this method returns. Any subsequent events that have already
8035         * been queued will also be processed in their proper order.
8036         *
8037         * @param ev MotionEvent to be processed in order
8038         */
8039        public void enqueueTouchEvent(MotionEvent ev) {
8040            final long sequence = nextTouchSequence();
8041
8042            if (dropStaleGestures(ev, sequence)) {
8043                return;
8044            }
8045
8046            // dropStaleGestures above might have fast-forwarded us to
8047            // an event we have already.
8048            runNextQueuedEvents();
8049
8050            if (mLastHandledTouchSequence + 1 == sequence) {
8051                handleQueuedMotionEvent(ev);
8052
8053                mLastHandledTouchSequence++;
8054
8055                // Do we have any more? Run them if so.
8056                runNextQueuedEvents();
8057            } else {
8058                QueuedTouch qd = obtainQueuedTouch().set(ev, sequence);
8059                mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd);
8060            }
8061        }
8062
8063        private void runNextQueuedEvents() {
8064            QueuedTouch qd = mTouchEventQueue;
8065            while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) {
8066                handleQueuedTouch(qd);
8067                QueuedTouch recycleMe = qd;
8068                qd = qd.mNext;
8069                recycleQueuedTouch(recycleMe);
8070                mLastHandledTouchSequence++;
8071            }
8072            mTouchEventQueue = qd;
8073        }
8074
8075        private boolean dropStaleGestures(MotionEvent ev, long sequence) {
8076            if (ev != null && ev.getAction() == MotionEvent.ACTION_MOVE && !mConfirmMove) {
8077                // This is to make sure that we don't attempt to process a tap
8078                // or long press when webkit takes too long to get back to us.
8079                // The movement will be properly confirmed when we process the
8080                // enqueued event later.
8081                final int dx = Math.round(ev.getX()) - mLastTouchX;
8082                final int dy = Math.round(ev.getY()) - mLastTouchY;
8083                if (dx * dx + dy * dy > mTouchSlopSquare) {
8084                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
8085                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
8086                }
8087            }
8088
8089            if (mTouchEventQueue == null) {
8090                return sequence <= mLastHandledTouchSequence;
8091            }
8092
8093            // If we have a new down event and it's been a while since the last event
8094            // we saw, catch up as best we can and keep going.
8095            if (ev != null && ev.getAction() == MotionEvent.ACTION_DOWN) {
8096                long eventTime = ev.getEventTime();
8097                long lastHandledEventTime = mLastEventTime;
8098                if (eventTime > lastHandledEventTime + QUEUED_GESTURE_TIMEOUT) {
8099                    Log.w(LOGTAG, "Got ACTION_DOWN but still waiting on stale event. " +
8100                            "Catching up.");
8101                    runQueuedAndPreQueuedEvents();
8102
8103                    // Drop leftovers that we truly don't have.
8104                    QueuedTouch qd = mTouchEventQueue;
8105                    while (qd != null && qd.mSequence < sequence) {
8106                        QueuedTouch recycleMe = qd;
8107                        qd = qd.mNext;
8108                        recycleQueuedTouch(recycleMe);
8109                    }
8110                    mTouchEventQueue = qd;
8111                    mLastHandledTouchSequence = sequence - 1;
8112                }
8113            }
8114
8115            if (mIgnoreUntilSequence - 1 > mLastHandledTouchSequence) {
8116                QueuedTouch qd = mTouchEventQueue;
8117                while (qd != null && qd.mSequence < mIgnoreUntilSequence) {
8118                    QueuedTouch recycleMe = qd;
8119                    qd = qd.mNext;
8120                    recycleQueuedTouch(recycleMe);
8121                }
8122                mTouchEventQueue = qd;
8123                mLastHandledTouchSequence = mIgnoreUntilSequence - 1;
8124            }
8125
8126            if (mPreQueue != null) {
8127                // Drop stale prequeued events
8128                QueuedTouch qd = mPreQueue;
8129                while (qd != null && qd.mSequence < mIgnoreUntilSequence) {
8130                    QueuedTouch recycleMe = qd;
8131                    qd = qd.mNext;
8132                    recycleQueuedTouch(recycleMe);
8133                }
8134                mPreQueue = qd;
8135            }
8136
8137            return sequence <= mLastHandledTouchSequence;
8138        }
8139
8140        private void handleQueuedTouch(QueuedTouch qt) {
8141            if (qt.mTed != null) {
8142                handleQueuedTouchEventData(qt.mTed);
8143            } else {
8144                handleQueuedMotionEvent(qt.mEvent);
8145                qt.mEvent.recycle();
8146            }
8147        }
8148
8149        private void handleQueuedMotionEvent(MotionEvent ev) {
8150            mLastEventTime = ev.getEventTime();
8151            int action = ev.getActionMasked();
8152            if (ev.getPointerCount() > 1) {  // Multi-touch
8153                handleMultiTouchInWebView(ev);
8154            } else {
8155                final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
8156                if (detector != null && mPreventDefault != PREVENT_DEFAULT_YES) {
8157                    // ScaleGestureDetector needs a consistent event stream to operate properly.
8158                    // It won't take any action with fewer than two pointers, but it needs to
8159                    // update internal bookkeeping state.
8160                    detector.onTouchEvent(ev);
8161                }
8162
8163                handleTouchEventCommon(ev, action, Math.round(ev.getX()), Math.round(ev.getY()));
8164            }
8165        }
8166
8167        private void handleQueuedTouchEventData(TouchEventData ted) {
8168            if (ted.mMotionEvent != null) {
8169                mLastEventTime = ted.mMotionEvent.getEventTime();
8170            }
8171            if (!ted.mReprocess) {
8172                if (ted.mAction == MotionEvent.ACTION_DOWN
8173                        && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
8174                    // if prevent default is called from WebCore, UI
8175                    // will not handle the rest of the touch events any
8176                    // more.
8177                    mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES
8178                            : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
8179                } else if (ted.mAction == MotionEvent.ACTION_MOVE
8180                        && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
8181                    // the return for the first ACTION_MOVE will decide
8182                    // whether UI will handle touch or not. Currently no
8183                    // support for alternating prevent default
8184                    mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES
8185                            : PREVENT_DEFAULT_NO;
8186                }
8187                if (mPreventDefault == PREVENT_DEFAULT_YES) {
8188                    mTouchHighlightRegion.setEmpty();
8189                }
8190            } else {
8191                if (ted.mPoints.length > 1) {  // multi-touch
8192                    if (!ted.mNativeResult && mPreventDefault != PREVENT_DEFAULT_YES) {
8193                        mPreventDefault = PREVENT_DEFAULT_NO;
8194                        handleMultiTouchInWebView(ted.mMotionEvent);
8195                    } else {
8196                        mPreventDefault = PREVENT_DEFAULT_YES;
8197                    }
8198                    return;
8199                }
8200
8201                // prevent default is not called in WebCore, so the
8202                // message needs to be reprocessed in UI
8203                if (!ted.mNativeResult) {
8204                    // Following is for single touch.
8205                    switch (ted.mAction) {
8206                        case MotionEvent.ACTION_DOWN:
8207                            mLastDeferTouchX = ted.mPointsInView[0].x;
8208                            mLastDeferTouchY = ted.mPointsInView[0].y;
8209                            mDeferTouchMode = TOUCH_INIT_MODE;
8210                            break;
8211                        case MotionEvent.ACTION_MOVE: {
8212                            // no snapping in defer process
8213                            int x = ted.mPointsInView[0].x;
8214                            int y = ted.mPointsInView[0].y;
8215
8216                            if (mDeferTouchMode != TOUCH_DRAG_MODE) {
8217                                mDeferTouchMode = TOUCH_DRAG_MODE;
8218                                mLastDeferTouchX = x;
8219                                mLastDeferTouchY = y;
8220                                startScrollingLayer(x, y);
8221                                startDrag();
8222                            }
8223                            int deltaX = pinLocX((int) (mScrollX
8224                                    + mLastDeferTouchX - x))
8225                                    - mScrollX;
8226                            int deltaY = pinLocY((int) (mScrollY
8227                                    + mLastDeferTouchY - y))
8228                                    - mScrollY;
8229                            doDrag(deltaX, deltaY);
8230                            if (deltaX != 0) mLastDeferTouchX = x;
8231                            if (deltaY != 0) mLastDeferTouchY = y;
8232                            break;
8233                        }
8234                        case MotionEvent.ACTION_UP:
8235                        case MotionEvent.ACTION_CANCEL:
8236                            if (mDeferTouchMode == TOUCH_DRAG_MODE) {
8237                                // no fling in defer process
8238                                mScroller.springBack(mScrollX, mScrollY, 0,
8239                                        computeMaxScrollX(), 0,
8240                                        computeMaxScrollY());
8241                                invalidate();
8242                                WebViewCore.resumePriority();
8243                                WebViewCore.resumeUpdatePicture(mWebViewCore);
8244                            }
8245                            mDeferTouchMode = TOUCH_DONE_MODE;
8246                            break;
8247                        case WebViewCore.ACTION_DOUBLETAP:
8248                            // doDoubleTap() needs mLastTouchX/Y as anchor
8249                            mLastDeferTouchX = ted.mPointsInView[0].x;
8250                            mLastDeferTouchY = ted.mPointsInView[0].y;
8251                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
8252                            mDeferTouchMode = TOUCH_DONE_MODE;
8253                            break;
8254                        case WebViewCore.ACTION_LONGPRESS:
8255                            HitTestResult hitTest = getHitTestResult();
8256                            if (hitTest != null && hitTest.mType
8257                                    != HitTestResult.UNKNOWN_TYPE) {
8258                                performLongClick();
8259                            }
8260                            mDeferTouchMode = TOUCH_DONE_MODE;
8261                            break;
8262                    }
8263                }
8264            }
8265        }
8266    }
8267
8268    //-------------------------------------------------------------------------
8269    // Methods can be called from a separate thread, like WebViewCore
8270    // If it needs to call the View system, it has to send message.
8271    //-------------------------------------------------------------------------
8272
8273    /**
8274     * General handler to receive message coming from webkit thread
8275     */
8276    class PrivateHandler extends Handler {
8277        @Override
8278        public void handleMessage(Message msg) {
8279            // exclude INVAL_RECT_MSG_ID since it is frequently output
8280            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
8281                if (msg.what >= FIRST_PRIVATE_MSG_ID
8282                        && msg.what <= LAST_PRIVATE_MSG_ID) {
8283                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
8284                            - FIRST_PRIVATE_MSG_ID]);
8285                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
8286                        && msg.what <= LAST_PACKAGE_MSG_ID) {
8287                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
8288                            - FIRST_PACKAGE_MSG_ID]);
8289                } else {
8290                    Log.v(LOGTAG, Integer.toString(msg.what));
8291                }
8292            }
8293            if (mWebViewCore == null) {
8294                // after WebView's destroy() is called, skip handling messages.
8295                return;
8296            }
8297            if (mBlockWebkitViewMessages
8298                    && msg.what != WEBCORE_INITIALIZED_MSG_ID) {
8299                // Blocking messages from webkit
8300                return;
8301            }
8302            switch (msg.what) {
8303                case REMEMBER_PASSWORD: {
8304                    mDatabase.setUsernamePassword(
8305                            msg.getData().getString("host"),
8306                            msg.getData().getString("username"),
8307                            msg.getData().getString("password"));
8308                    ((Message) msg.obj).sendToTarget();
8309                    break;
8310                }
8311                case NEVER_REMEMBER_PASSWORD: {
8312                    mDatabase.setUsernamePassword(
8313                            msg.getData().getString("host"), null, null);
8314                    ((Message) msg.obj).sendToTarget();
8315                    break;
8316                }
8317                case PREVENT_DEFAULT_TIMEOUT: {
8318                    // if timeout happens, cancel it so that it won't block UI
8319                    // to continue handling touch events
8320                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
8321                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
8322                            || (msg.arg1 == MotionEvent.ACTION_MOVE
8323                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
8324                        cancelWebCoreTouchEvent(
8325                                viewToContentX(mLastTouchX + mScrollX),
8326                                viewToContentY(mLastTouchY + mScrollY),
8327                                true);
8328                    }
8329                    break;
8330                }
8331                case SCROLL_SELECT_TEXT: {
8332                    if (mAutoScrollX == 0 && mAutoScrollY == 0) {
8333                        mSentAutoScrollMessage = false;
8334                        break;
8335                    }
8336                    if (mScrollingLayer == 0) {
8337                        pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
8338                    } else {
8339                        scrollLayerTo(mScrollingLayerRect.left + mAutoScrollX,
8340                                mScrollingLayerRect.top + mAutoScrollY);
8341                    }
8342                    sendEmptyMessageDelayed(
8343                            SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
8344                    break;
8345                }
8346                case UPDATE_SELECTION: {
8347                    if (mTouchMode == TOUCH_INIT_MODE
8348                            || mTouchMode == TOUCH_SHORTPRESS_MODE
8349                            || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
8350                        updateSelection();
8351                    }
8352                    break;
8353                }
8354                case SWITCH_TO_SHORTPRESS: {
8355                    mInitialHitTestResult = null; // set by updateSelection()
8356                    if (mTouchMode == TOUCH_INIT_MODE) {
8357                        if (!getSettings().supportTouchOnly()
8358                                && mPreventDefault != PREVENT_DEFAULT_YES) {
8359                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
8360                            updateSelection();
8361                        } else {
8362                            // set to TOUCH_SHORTPRESS_MODE so that it won't
8363                            // trigger double tap any more
8364                            mTouchMode = TOUCH_SHORTPRESS_MODE;
8365                        }
8366                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
8367                        mTouchMode = TOUCH_DONE_MODE;
8368                    }
8369                    break;
8370                }
8371                case SWITCH_TO_LONGPRESS: {
8372                    if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) {
8373                        removeTouchHighlight();
8374                    }
8375                    if (inFullScreenMode() || mDeferTouchProcess) {
8376                        TouchEventData ted = new TouchEventData();
8377                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
8378                        ted.mIds = new int[1];
8379                        ted.mIds[0] = 0;
8380                        ted.mPoints = new Point[1];
8381                        ted.mPoints[0] = new Point(viewToContentX(mLastTouchX + mScrollX),
8382                                                   viewToContentY(mLastTouchY + mScrollY));
8383                        ted.mPointsInView = new Point[1];
8384                        ted.mPointsInView[0] = new Point(mLastTouchX, mLastTouchY);
8385                        // metaState for long press is tricky. Should it be the
8386                        // state when the press started or when the press was
8387                        // released? Or some intermediary key state? For
8388                        // simplicity for now, we don't set it.
8389                        ted.mMetaState = 0;
8390                        ted.mReprocess = mDeferTouchProcess;
8391                        ted.mNativeLayer = nativeScrollableLayer(
8392                                ted.mPoints[0].x, ted.mPoints[0].y,
8393                                ted.mNativeLayerRect, null);
8394                        ted.mSequence = mTouchEventQueue.nextTouchSequence();
8395                        mTouchEventQueue.preQueueTouchEventData(ted);
8396                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
8397                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
8398                        mTouchMode = TOUCH_DONE_MODE;
8399                        performLongClick();
8400                    }
8401                    break;
8402                }
8403                case RELEASE_SINGLE_TAP: {
8404                    doShortPress();
8405                    break;
8406                }
8407                case SCROLL_TO_MSG_ID: {
8408                    // arg1 = animate, arg2 = onlyIfImeIsShowing
8409                    // obj = Point(x, y)
8410                    if (msg.arg2 == 1) {
8411                        // This scroll is intended to bring the textfield into
8412                        // view, but is only necessary if the IME is showing
8413                        InputMethodManager imm = InputMethodManager.peekInstance();
8414                        if (imm == null || !imm.isAcceptingText()
8415                                || (!imm.isActive(WebView.this) && (!inEditingMode()
8416                                || !imm.isActive(mWebTextView)))) {
8417                            break;
8418                        }
8419                    }
8420                    final Point p = (Point) msg.obj;
8421                    if (msg.arg1 == 1) {
8422                        spawnContentScrollTo(p.x, p.y);
8423                    } else {
8424                        setContentScrollTo(p.x, p.y);
8425                    }
8426                    break;
8427                }
8428                case UPDATE_ZOOM_RANGE: {
8429                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
8430                    // mScrollX contains the new minPrefWidth
8431                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
8432                    break;
8433                }
8434                case REPLACE_BASE_CONTENT: {
8435                    nativeReplaceBaseContent(msg.arg1);
8436                    break;
8437                }
8438                case NEW_PICTURE_MSG_ID: {
8439                    // called for new content
8440                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
8441                    setNewPicture(draw, true);
8442                    break;
8443                }
8444                case WEBCORE_INITIALIZED_MSG_ID:
8445                    // nativeCreate sets mNativeClass to a non-zero value
8446                    String drawableDir = BrowserFrame.getRawResFilename(
8447                            BrowserFrame.DRAWABLEDIR, mContext);
8448                    nativeCreate(msg.arg1, drawableDir);
8449                    if (mDelaySetPicture != null) {
8450                        setNewPicture(mDelaySetPicture, true);
8451                        mDelaySetPicture = null;
8452                    }
8453                    if (mIsPaused) {
8454                        nativeSetPauseDrawing(mNativeClass, true);
8455                    }
8456                    break;
8457                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
8458                    // Make sure that the textfield is currently focused
8459                    // and representing the same node as the pointer.
8460                    if (inEditingMode() &&
8461                            mWebTextView.isSameTextField(msg.arg1)) {
8462                        if (msg.arg2 == mTextGeneration) {
8463                            String text = (String) msg.obj;
8464                            if (null == text) {
8465                                text = "";
8466                            }
8467                            mWebTextView.setTextAndKeepSelection(text);
8468                        }
8469                    }
8470                    break;
8471                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
8472                    displaySoftKeyboard(true);
8473                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
8474                case UPDATE_TEXT_SELECTION_MSG_ID:
8475                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
8476                            (WebViewCore.TextSelectionData) msg.obj);
8477                    break;
8478                case FORM_DID_BLUR:
8479                    if (inEditingMode()
8480                            && mWebTextView.isSameTextField(msg.arg1)) {
8481                        hideSoftKeyboard();
8482                    }
8483                    break;
8484                case RETURN_LABEL:
8485                    if (inEditingMode()
8486                            && mWebTextView.isSameTextField(msg.arg1)) {
8487                        mWebTextView.setHint((String) msg.obj);
8488                        InputMethodManager imm
8489                                = InputMethodManager.peekInstance();
8490                        // The hint is propagated to the IME in
8491                        // onCreateInputConnection.  If the IME is already
8492                        // active, restart it so that its hint text is updated.
8493                        if (imm != null && imm.isActive(mWebTextView)) {
8494                            imm.restartInput(mWebTextView);
8495                        }
8496                    }
8497                    break;
8498                case UNHANDLED_NAV_KEY:
8499                    navHandledKey(msg.arg1, 1, false, 0);
8500                    break;
8501                case UPDATE_TEXT_ENTRY_MSG_ID:
8502                    // this is sent after finishing resize in WebViewCore. Make
8503                    // sure the text edit box is still on the  screen.
8504                    if (inEditingMode() && nativeCursorIsTextInput()) {
8505                        updateWebTextViewPosition();
8506                    }
8507                    break;
8508                case CLEAR_TEXT_ENTRY:
8509                    clearTextEntry();
8510                    break;
8511                case INVAL_RECT_MSG_ID: {
8512                    Rect r = (Rect)msg.obj;
8513                    if (r == null) {
8514                        invalidate();
8515                    } else {
8516                        // we need to scale r from content into view coords,
8517                        // which viewInvalidate() does for us
8518                        viewInvalidate(r.left, r.top, r.right, r.bottom);
8519                    }
8520                    break;
8521                }
8522                case REQUEST_FORM_DATA:
8523                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
8524                    if (mWebTextView.isSameTextField(msg.arg1)) {
8525                        mWebTextView.setAdapterCustom(adapter);
8526                    }
8527                    break;
8528
8529                case LONG_PRESS_CENTER:
8530                    // as this is shared by keydown and trackballdown, reset all
8531                    // the states
8532                    mGotCenterDown = false;
8533                    mTrackballDown = false;
8534                    performLongClick();
8535                    break;
8536
8537                case WEBCORE_NEED_TOUCH_EVENTS:
8538                    mForwardTouchEvents = (msg.arg1 != 0);
8539                    break;
8540
8541                case PREVENT_TOUCH_ID:
8542                    if (inFullScreenMode()) {
8543                        break;
8544                    }
8545                    TouchEventData ted = (TouchEventData) msg.obj;
8546
8547                    if (mTouchEventQueue.enqueueTouchEvent(ted)) {
8548                        // WebCore is responding to us; remove pending timeout.
8549                        // It will be re-posted when needed.
8550                        removeMessages(PREVENT_DEFAULT_TIMEOUT);
8551                    }
8552                    break;
8553
8554                case REQUEST_KEYBOARD:
8555                    if (msg.arg1 == 0) {
8556                        hideSoftKeyboard();
8557                    } else {
8558                        displaySoftKeyboard(false);
8559                    }
8560                    break;
8561
8562                case FIND_AGAIN:
8563                    // Ignore if find has been dismissed.
8564                    if (mFindIsUp && mFindCallback != null) {
8565                        mFindCallback.findAll();
8566                    }
8567                    break;
8568
8569                case DRAG_HELD_MOTIONLESS:
8570                    mHeldMotionless = MOTIONLESS_TRUE;
8571                    invalidate();
8572                    // fall through to keep scrollbars awake
8573
8574                case AWAKEN_SCROLL_BARS:
8575                    if (mTouchMode == TOUCH_DRAG_MODE
8576                            && mHeldMotionless == MOTIONLESS_TRUE) {
8577                        awakenScrollBars(ViewConfiguration
8578                                .getScrollDefaultDelay(), false);
8579                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
8580                                .obtainMessage(AWAKEN_SCROLL_BARS),
8581                                ViewConfiguration.getScrollDefaultDelay());
8582                    }
8583                    break;
8584
8585                case DO_MOTION_UP:
8586                    doMotionUp(msg.arg1, msg.arg2);
8587                    break;
8588
8589                case SCREEN_ON:
8590                    setKeepScreenOn(msg.arg1 == 1);
8591                    break;
8592
8593                case ENTER_FULLSCREEN_VIDEO:
8594                    int layerId = msg.arg1;
8595
8596                    String url = (String) msg.obj;
8597                    if (mHTML5VideoViewProxy != null) {
8598                        mHTML5VideoViewProxy.enterFullScreenVideo(layerId, url);
8599                    }
8600                    break;
8601
8602                case SHOW_FULLSCREEN: {
8603                    View view = (View) msg.obj;
8604                    int orientation = msg.arg1;
8605                    int npp = msg.arg2;
8606
8607                    if (inFullScreenMode()) {
8608                        Log.w(LOGTAG, "Should not have another full screen.");
8609                        dismissFullScreenMode();
8610                    }
8611                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, orientation, npp);
8612                    mFullScreenHolder.setContentView(view);
8613                    mFullScreenHolder.show();
8614
8615                    break;
8616                }
8617                case HIDE_FULLSCREEN:
8618                    dismissFullScreenMode();
8619                    break;
8620
8621                case DOM_FOCUS_CHANGED:
8622                    if (inEditingMode()) {
8623                        nativeClearCursor();
8624                        rebuildWebTextView();
8625                    }
8626                    break;
8627
8628                case SHOW_RECT_MSG_ID: {
8629                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
8630                    int x = mScrollX;
8631                    int left = contentToViewX(data.mLeft);
8632                    int width = contentToViewDimension(data.mWidth);
8633                    int maxWidth = contentToViewDimension(data.mContentWidth);
8634                    int viewWidth = getViewWidth();
8635                    if (width < viewWidth) {
8636                        // center align
8637                        x += left + width / 2 - mScrollX - viewWidth / 2;
8638                    } else {
8639                        x += (int) (left + data.mXPercentInDoc * width
8640                                - mScrollX - data.mXPercentInView * viewWidth);
8641                    }
8642                    if (DebugFlags.WEB_VIEW) {
8643                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
8644                              width + ",maxWidth=" + maxWidth +
8645                              ",viewWidth=" + viewWidth + ",x="
8646                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
8647                              ",xPercentInView=" + data.mXPercentInView+ ")");
8648                    }
8649                    // use the passing content width to cap x as the current
8650                    // mContentWidth may not be updated yet
8651                    x = Math.max(0,
8652                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
8653                    int top = contentToViewY(data.mTop);
8654                    int height = contentToViewDimension(data.mHeight);
8655                    int maxHeight = contentToViewDimension(data.mContentHeight);
8656                    int viewHeight = getViewHeight();
8657                    int y = (int) (top + data.mYPercentInDoc * height -
8658                                   data.mYPercentInView * viewHeight);
8659                    if (DebugFlags.WEB_VIEW) {
8660                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
8661                              height + ",maxHeight=" + maxHeight +
8662                              ",viewHeight=" + viewHeight + ",y="
8663                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
8664                              ",yPercentInView=" + data.mYPercentInView+ ")");
8665                    }
8666                    // use the passing content height to cap y as the current
8667                    // mContentHeight may not be updated yet
8668                    y = Math.max(0,
8669                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
8670                    // We need to take into account the visible title height
8671                    // when scrolling since y is an absolute view position.
8672                    y = Math.max(0, y - getVisibleTitleHeightImpl());
8673                    scrollTo(x, y);
8674                    }
8675                    break;
8676
8677                case CENTER_FIT_RECT:
8678                    centerFitRect((Rect)msg.obj);
8679                    break;
8680
8681                case SET_SCROLLBAR_MODES:
8682                    mHorizontalScrollBarMode = msg.arg1;
8683                    mVerticalScrollBarMode = msg.arg2;
8684                    break;
8685
8686                case SELECTION_STRING_CHANGED:
8687                    if (mAccessibilityInjector != null) {
8688                        String selectionString = (String) msg.obj;
8689                        mAccessibilityInjector.onSelectionStringChange(selectionString);
8690                    }
8691                    break;
8692
8693                case SET_TOUCH_HIGHLIGHT_RECTS:
8694                    @SuppressWarnings("unchecked")
8695                    ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
8696                    setTouchHighlightRects(rects);
8697                    break;
8698
8699                case SAVE_WEBARCHIVE_FINISHED:
8700                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
8701                    if (saveMessage.mCallback != null) {
8702                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
8703                    }
8704                    break;
8705
8706                case SET_AUTOFILLABLE:
8707                    mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
8708                    if (mWebTextView != null) {
8709                        mWebTextView.setAutoFillable(mAutoFillData.getQueryId());
8710                        rebuildWebTextView();
8711                    }
8712                    break;
8713
8714                case AUTOFILL_COMPLETE:
8715                    if (mWebTextView != null) {
8716                        // Clear the WebTextView adapter when AutoFill finishes
8717                        // so that the drop down gets cleared.
8718                        mWebTextView.setAdapterCustom(null);
8719                    }
8720                    break;
8721
8722                case SELECT_AT:
8723                    nativeSelectAt(msg.arg1, msg.arg2);
8724                    break;
8725
8726                default:
8727                    super.handleMessage(msg);
8728                    break;
8729            }
8730        }
8731    }
8732
8733    private void setTouchHighlightRects(ArrayList<Rect> rects) {
8734        invalidate(mTouchHighlightRegion.getBounds());
8735        mTouchHighlightRegion.setEmpty();
8736        if (rects != null) {
8737            for (Rect rect : rects) {
8738                Rect viewRect = contentToViewRect(rect);
8739                // some sites, like stories in nytimes.com, set
8740                // mouse event handler in the top div. It is not
8741                // user friendly to highlight the div if it covers
8742                // more than half of the screen.
8743                if (viewRect.width() < getWidth() >> 1
8744                        || viewRect.height() < getHeight() >> 1) {
8745                    mTouchHighlightRegion.union(viewRect);
8746                } else {
8747                    Log.w(LOGTAG, "Skip the huge selection rect:"
8748                            + viewRect);
8749                }
8750            }
8751            invalidate(mTouchHighlightRegion.getBounds());
8752        }
8753    }
8754
8755    /** @hide Called by JNI when pages are swapped (only occurs with hardware
8756     * acceleration) */
8757    protected void pageSwapCallback() {
8758        if (inEditingMode()) {
8759            didUpdateWebTextViewDimensions(ANYWHERE);
8760        }
8761    }
8762
8763    void setNewPicture(final WebViewCore.DrawData draw, boolean updateBaseLayer) {
8764        if (mNativeClass == 0) {
8765            if (mDelaySetPicture != null) {
8766                throw new IllegalStateException("Tried to setNewPicture with"
8767                        + " a delay picture already set! (memory leak)");
8768            }
8769            // Not initialized yet, delay set
8770            mDelaySetPicture = draw;
8771            return;
8772        }
8773        WebViewCore.ViewState viewState = draw.mViewState;
8774        boolean isPictureAfterFirstLayout = viewState != null;
8775
8776        if (updateBaseLayer) {
8777            // Request a callback on pageSwap (to reposition the webtextview)
8778            boolean registerPageSwapCallback =
8779                !mZoomManager.isFixedLengthAnimationInProgress() && inEditingMode();
8780
8781            setBaseLayer(draw.mBaseLayer, draw.mInvalRegion,
8782                    getSettings().getShowVisualIndicator(),
8783                    isPictureAfterFirstLayout, registerPageSwapCallback);
8784        }
8785        final Point viewSize = draw.mViewSize;
8786        // We update the layout (i.e. request a layout from the
8787        // view system) if the last view size that we sent to
8788        // WebCore matches the view size of the picture we just
8789        // received in the fixed dimension.
8790        final boolean updateLayout = viewSize.x == mLastWidthSent
8791                && viewSize.y == mLastHeightSent;
8792        // Don't send scroll event for picture coming from webkit,
8793        // since the new picture may cause a scroll event to override
8794        // the saved history scroll position.
8795        mSendScrollEvent = false;
8796        recordNewContentSize(draw.mContentSize.x,
8797                draw.mContentSize.y, updateLayout);
8798
8799        if (isPictureAfterFirstLayout) {
8800            // Reset the last sent data here since dealing with new page.
8801            mLastWidthSent = 0;
8802            mZoomManager.onFirstLayout(draw);
8803            int scrollX = viewState.mShouldStartScrolledRight
8804                    ? getContentWidth() : viewState.mScrollX;
8805            int scrollY = viewState.mScrollY;
8806            setContentScrollTo(scrollX, scrollY);
8807            if (!mDrawHistory) {
8808                // As we are on a new page, remove the WebTextView. This
8809                // is necessary for page loads driven by webkit, and in
8810                // particular when the user was on a password field, so
8811                // the WebTextView was visible.
8812                clearTextEntry();
8813            }
8814        }
8815        mSendScrollEvent = true;
8816
8817        if (DebugFlags.WEB_VIEW) {
8818            Rect b = draw.mInvalRegion.getBounds();
8819            Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
8820                    b.left+","+b.top+","+b.right+","+b.bottom+"}");
8821        }
8822        invalidateContentRect(draw.mInvalRegion.getBounds());
8823
8824        if (mPictureListener != null) {
8825            mPictureListener.onNewPicture(WebView.this, capturePicture());
8826        }
8827
8828        // update the zoom information based on the new picture
8829        mZoomManager.onNewPicture(draw);
8830
8831        if (draw.mFocusSizeChanged && inEditingMode()) {
8832            mFocusSizeChanged = true;
8833        }
8834        if (isPictureAfterFirstLayout) {
8835            mViewManager.postReadyToDrawAll();
8836        }
8837    }
8838
8839    /**
8840     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
8841     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
8842     */
8843    private void updateTextSelectionFromMessage(int nodePointer,
8844            int textGeneration, WebViewCore.TextSelectionData data) {
8845        if (inEditingMode()
8846                && mWebTextView.isSameTextField(nodePointer)
8847                && textGeneration == mTextGeneration) {
8848            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
8849        }
8850    }
8851
8852    // Class used to use a dropdown for a <select> element
8853    private class InvokeListBox implements Runnable {
8854        // Whether the listbox allows multiple selection.
8855        private boolean     mMultiple;
8856        // Passed in to a list with multiple selection to tell
8857        // which items are selected.
8858        private int[]       mSelectedArray;
8859        // Passed in to a list with single selection to tell
8860        // where the initial selection is.
8861        private int         mSelection;
8862
8863        private Container[] mContainers;
8864
8865        // Need these to provide stable ids to my ArrayAdapter,
8866        // which normally does not have stable ids. (Bug 1250098)
8867        private class Container extends Object {
8868            /**
8869             * Possible values for mEnabled.  Keep in sync with OptionStatus in
8870             * WebViewCore.cpp
8871             */
8872            final static int OPTGROUP = -1;
8873            final static int OPTION_DISABLED = 0;
8874            final static int OPTION_ENABLED = 1;
8875
8876            String  mString;
8877            int     mEnabled;
8878            int     mId;
8879
8880            @Override
8881            public String toString() {
8882                return mString;
8883            }
8884        }
8885
8886        /**
8887         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
8888         *  and allow filtering.
8889         */
8890        private class MyArrayListAdapter extends ArrayAdapter<Container> {
8891            public MyArrayListAdapter() {
8892                super(mContext,
8893                        mMultiple ? com.android.internal.R.layout.select_dialog_multichoice :
8894                        com.android.internal.R.layout.webview_select_singlechoice,
8895                        mContainers);
8896            }
8897
8898            @Override
8899            public View getView(int position, View convertView,
8900                    ViewGroup parent) {
8901                // Always pass in null so that we will get a new CheckedTextView
8902                // Otherwise, an item which was previously used as an <optgroup>
8903                // element (i.e. has no check), could get used as an <option>
8904                // element, which needs a checkbox/radio, but it would not have
8905                // one.
8906                convertView = super.getView(position, null, parent);
8907                Container c = item(position);
8908                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
8909                    // ListView does not draw dividers between disabled and
8910                    // enabled elements.  Use a LinearLayout to provide dividers
8911                    LinearLayout layout = new LinearLayout(mContext);
8912                    layout.setOrientation(LinearLayout.VERTICAL);
8913                    if (position > 0) {
8914                        View dividerTop = new View(mContext);
8915                        dividerTop.setBackgroundResource(
8916                                android.R.drawable.divider_horizontal_bright);
8917                        layout.addView(dividerTop);
8918                    }
8919
8920                    if (Container.OPTGROUP == c.mEnabled) {
8921                        // Currently select_dialog_multichoice uses CheckedTextViews.
8922                        // If that changes, the class cast will no longer be valid.
8923                        if (mMultiple) {
8924                            Assert.assertTrue(convertView instanceof CheckedTextView);
8925                            ((CheckedTextView) convertView).setCheckMarkDrawable(null);
8926                        }
8927                    } else {
8928                        // c.mEnabled == Container.OPTION_DISABLED
8929                        // Draw the disabled element in a disabled state.
8930                        convertView.setEnabled(false);
8931                    }
8932
8933                    layout.addView(convertView);
8934                    if (position < getCount() - 1) {
8935                        View dividerBottom = new View(mContext);
8936                        dividerBottom.setBackgroundResource(
8937                                android.R.drawable.divider_horizontal_bright);
8938                        layout.addView(dividerBottom);
8939                    }
8940                    return layout;
8941                }
8942                return convertView;
8943            }
8944
8945            @Override
8946            public boolean hasStableIds() {
8947                // AdapterView's onChanged method uses this to determine whether
8948                // to restore the old state.  Return false so that the old (out
8949                // of date) state does not replace the new, valid state.
8950                return false;
8951            }
8952
8953            private Container item(int position) {
8954                if (position < 0 || position >= getCount()) {
8955                    return null;
8956                }
8957                return (Container) getItem(position);
8958            }
8959
8960            @Override
8961            public long getItemId(int position) {
8962                Container item = item(position);
8963                if (item == null) {
8964                    return -1;
8965                }
8966                return item.mId;
8967            }
8968
8969            @Override
8970            public boolean areAllItemsEnabled() {
8971                return false;
8972            }
8973
8974            @Override
8975            public boolean isEnabled(int position) {
8976                Container item = item(position);
8977                if (item == null) {
8978                    return false;
8979                }
8980                return Container.OPTION_ENABLED == item.mEnabled;
8981            }
8982        }
8983
8984        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
8985            mMultiple = true;
8986            mSelectedArray = selected;
8987
8988            int length = array.length;
8989            mContainers = new Container[length];
8990            for (int i = 0; i < length; i++) {
8991                mContainers[i] = new Container();
8992                mContainers[i].mString = array[i];
8993                mContainers[i].mEnabled = enabled[i];
8994                mContainers[i].mId = i;
8995            }
8996        }
8997
8998        private InvokeListBox(String[] array, int[] enabled, int selection) {
8999            mSelection = selection;
9000            mMultiple = false;
9001
9002            int length = array.length;
9003            mContainers = new Container[length];
9004            for (int i = 0; i < length; i++) {
9005                mContainers[i] = new Container();
9006                mContainers[i].mString = array[i];
9007                mContainers[i].mEnabled = enabled[i];
9008                mContainers[i].mId = i;
9009            }
9010        }
9011
9012        /*
9013         * Whenever the data set changes due to filtering, this class ensures
9014         * that the checked item remains checked.
9015         */
9016        private class SingleDataSetObserver extends DataSetObserver {
9017            private long        mCheckedId;
9018            private ListView    mListView;
9019            private Adapter     mAdapter;
9020
9021            /*
9022             * Create a new observer.
9023             * @param id The ID of the item to keep checked.
9024             * @param l ListView for getting and clearing the checked states
9025             * @param a Adapter for getting the IDs
9026             */
9027            public SingleDataSetObserver(long id, ListView l, Adapter a) {
9028                mCheckedId = id;
9029                mListView = l;
9030                mAdapter = a;
9031            }
9032
9033            @Override
9034            public void onChanged() {
9035                // The filter may have changed which item is checked.  Find the
9036                // item that the ListView thinks is checked.
9037                int position = mListView.getCheckedItemPosition();
9038                long id = mAdapter.getItemId(position);
9039                if (mCheckedId != id) {
9040                    // Clear the ListView's idea of the checked item, since
9041                    // it is incorrect
9042                    mListView.clearChoices();
9043                    // Search for mCheckedId.  If it is in the filtered list,
9044                    // mark it as checked
9045                    int count = mAdapter.getCount();
9046                    for (int i = 0; i < count; i++) {
9047                        if (mAdapter.getItemId(i) == mCheckedId) {
9048                            mListView.setItemChecked(i, true);
9049                            break;
9050                        }
9051                    }
9052                }
9053            }
9054        }
9055
9056        public void run() {
9057            final ListView listView = (ListView) LayoutInflater.from(mContext)
9058                    .inflate(com.android.internal.R.layout.select_dialog, null);
9059            final MyArrayListAdapter adapter = new MyArrayListAdapter();
9060            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
9061                    .setView(listView).setCancelable(true)
9062                    .setInverseBackgroundForced(true);
9063
9064            if (mMultiple) {
9065                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
9066                    public void onClick(DialogInterface dialog, int which) {
9067                        mWebViewCore.sendMessage(
9068                                EventHub.LISTBOX_CHOICES,
9069                                adapter.getCount(), 0,
9070                                listView.getCheckedItemPositions());
9071                    }});
9072                b.setNegativeButton(android.R.string.cancel,
9073                        new DialogInterface.OnClickListener() {
9074                    public void onClick(DialogInterface dialog, int which) {
9075                        mWebViewCore.sendMessage(
9076                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
9077                }});
9078            }
9079            mListBoxDialog = b.create();
9080            listView.setAdapter(adapter);
9081            listView.setFocusableInTouchMode(true);
9082            // There is a bug (1250103) where the checks in a ListView with
9083            // multiple items selected are associated with the positions, not
9084            // the ids, so the items do not properly retain their checks when
9085            // filtered.  Do not allow filtering on multiple lists until
9086            // that bug is fixed.
9087
9088            listView.setTextFilterEnabled(!mMultiple);
9089            if (mMultiple) {
9090                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
9091                int length = mSelectedArray.length;
9092                for (int i = 0; i < length; i++) {
9093                    listView.setItemChecked(mSelectedArray[i], true);
9094                }
9095            } else {
9096                listView.setOnItemClickListener(new OnItemClickListener() {
9097                    public void onItemClick(AdapterView<?> parent, View v,
9098                            int position, long id) {
9099                        // Rather than sending the message right away, send it
9100                        // after the page regains focus.
9101                        mListBoxMessage = Message.obtain(null,
9102                                EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0);
9103                        mListBoxDialog.dismiss();
9104                        mListBoxDialog = null;
9105                    }
9106                });
9107                if (mSelection != -1) {
9108                    listView.setSelection(mSelection);
9109                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
9110                    listView.setItemChecked(mSelection, true);
9111                    DataSetObserver observer = new SingleDataSetObserver(
9112                            adapter.getItemId(mSelection), listView, adapter);
9113                    adapter.registerDataSetObserver(observer);
9114                }
9115            }
9116            mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
9117                public void onCancel(DialogInterface dialog) {
9118                    mWebViewCore.sendMessage(
9119                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
9120                    mListBoxDialog = null;
9121                }
9122            });
9123            mListBoxDialog.show();
9124        }
9125    }
9126
9127    private Message mListBoxMessage;
9128
9129    /*
9130     * Request a dropdown menu for a listbox with multiple selection.
9131     *
9132     * @param array Labels for the listbox.
9133     * @param enabledArray  State for each element in the list.  See static
9134     *      integers in Container class.
9135     * @param selectedArray Which positions are initally selected.
9136     */
9137    void requestListBox(String[] array, int[] enabledArray, int[]
9138            selectedArray) {
9139        mPrivateHandler.post(
9140                new InvokeListBox(array, enabledArray, selectedArray));
9141    }
9142
9143    /*
9144     * Request a dropdown menu for a listbox with single selection or a single
9145     * <select> element.
9146     *
9147     * @param array Labels for the listbox.
9148     * @param enabledArray  State for each element in the list.  See static
9149     *      integers in Container class.
9150     * @param selection Which position is initally selected.
9151     */
9152    void requestListBox(String[] array, int[] enabledArray, int selection) {
9153        mPrivateHandler.post(
9154                new InvokeListBox(array, enabledArray, selection));
9155    }
9156
9157    // called by JNI
9158    private void sendMoveFocus(int frame, int node) {
9159        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
9160                new WebViewCore.CursorData(frame, node, 0, 0));
9161    }
9162
9163    // called by JNI
9164    private void sendMoveMouse(int frame, int node, int x, int y) {
9165        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
9166                new WebViewCore.CursorData(frame, node, x, y));
9167    }
9168
9169    /*
9170     * Send a mouse move event to the webcore thread.
9171     *
9172     * @param removeFocus Pass true to remove the WebTextView, if present.
9173     * @param stopPaintingCaret Stop drawing the blinking caret if true.
9174     * called by JNI
9175     */
9176    @SuppressWarnings("unused")
9177    private void sendMoveMouseIfLatest(boolean removeFocus, boolean stopPaintingCaret) {
9178        if (removeFocus) {
9179            clearTextEntry();
9180        }
9181        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
9182                stopPaintingCaret ? 1 : 0, 0,
9183                cursorData());
9184    }
9185
9186    /**
9187     * Called by JNI to send a message to the webcore thread that the user
9188     * touched the webpage.
9189     * @param touchGeneration Generation number of the touch, to ignore touches
9190     *      after a new one has been generated.
9191     * @param frame Pointer to the frame holding the node that was touched.
9192     * @param node Pointer to the node touched.
9193     * @param x x-position of the touch.
9194     * @param y y-position of the touch.
9195     */
9196    private void sendMotionUp(int touchGeneration,
9197            int frame, int node, int x, int y) {
9198        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
9199        touchUpData.mMoveGeneration = touchGeneration;
9200        touchUpData.mFrame = frame;
9201        touchUpData.mNode = node;
9202        touchUpData.mX = x;
9203        touchUpData.mY = y;
9204        touchUpData.mNativeLayer = nativeScrollableLayer(
9205                x, y, touchUpData.mNativeLayerRect, null);
9206        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
9207    }
9208
9209
9210    private int getScaledMaxXScroll() {
9211        int width;
9212        if (mHeightCanMeasure == false) {
9213            width = getViewWidth() / 4;
9214        } else {
9215            Rect visRect = new Rect();
9216            calcOurVisibleRect(visRect);
9217            width = visRect.width() / 2;
9218        }
9219        // FIXME the divisor should be retrieved from somewhere
9220        return viewToContentX(width);
9221    }
9222
9223    private int getScaledMaxYScroll() {
9224        int height;
9225        if (mHeightCanMeasure == false) {
9226            height = getViewHeight() / 4;
9227        } else {
9228            Rect visRect = new Rect();
9229            calcOurVisibleRect(visRect);
9230            height = visRect.height() / 2;
9231        }
9232        // FIXME the divisor should be retrieved from somewhere
9233        // the closest thing today is hard-coded into ScrollView.java
9234        // (from ScrollView.java, line 363)   int maxJump = height/2;
9235        return Math.round(height * mZoomManager.getInvScale());
9236    }
9237
9238    /**
9239     * Called by JNI to invalidate view
9240     */
9241    private void viewInvalidate() {
9242        invalidate();
9243    }
9244
9245    /**
9246     * Pass the key directly to the page.  This assumes that
9247     * nativePageShouldHandleShiftAndArrows() returned true.
9248     */
9249    private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
9250        int keyEventAction;
9251        int eventHubAction;
9252        if (down) {
9253            keyEventAction = KeyEvent.ACTION_DOWN;
9254            eventHubAction = EventHub.KEY_DOWN;
9255            playSoundEffect(keyCodeToSoundsEffect(keyCode));
9256        } else {
9257            keyEventAction = KeyEvent.ACTION_UP;
9258            eventHubAction = EventHub.KEY_UP;
9259        }
9260
9261        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
9262                1, (metaState & KeyEvent.META_SHIFT_ON)
9263                | (metaState & KeyEvent.META_ALT_ON)
9264                | (metaState & KeyEvent.META_SYM_ON)
9265                , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
9266        mWebViewCore.sendMessage(eventHubAction, event);
9267    }
9268
9269    // return true if the key was handled
9270    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
9271            long time) {
9272        if (mNativeClass == 0) {
9273            return false;
9274        }
9275        mInitialHitTestResult = null;
9276        mLastCursorTime = time;
9277        mLastCursorBounds = nativeGetCursorRingBounds();
9278        boolean keyHandled
9279                = nativeMoveCursor(keyCode, count, noScroll) == false;
9280        if (DebugFlags.WEB_VIEW) {
9281            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
9282                    + " mLastCursorTime=" + mLastCursorTime
9283                    + " handled=" + keyHandled);
9284        }
9285        if (keyHandled == false) {
9286            return keyHandled;
9287        }
9288        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
9289        if (contentCursorRingBounds.isEmpty()) return keyHandled;
9290        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
9291        // set last touch so that context menu related functions will work
9292        mLastTouchX = (viewCursorRingBounds.left + viewCursorRingBounds.right) / 2;
9293        mLastTouchY = (viewCursorRingBounds.top + viewCursorRingBounds.bottom) / 2;
9294        if (mHeightCanMeasure == false) {
9295            return keyHandled;
9296        }
9297        Rect visRect = new Rect();
9298        calcOurVisibleRect(visRect);
9299        Rect outset = new Rect(visRect);
9300        int maxXScroll = visRect.width() / 2;
9301        int maxYScroll = visRect.height() / 2;
9302        outset.inset(-maxXScroll, -maxYScroll);
9303        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
9304            return keyHandled;
9305        }
9306        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
9307        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
9308                maxXScroll);
9309        if (maxH > 0) {
9310            pinScrollBy(maxH, 0, true, 0);
9311        } else {
9312            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
9313                    -maxXScroll);
9314            if (maxH < 0) {
9315                pinScrollBy(maxH, 0, true, 0);
9316            }
9317        }
9318        if (mLastCursorBounds.isEmpty()) return keyHandled;
9319        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
9320            return keyHandled;
9321        }
9322        if (DebugFlags.WEB_VIEW) {
9323            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
9324                    + contentCursorRingBounds);
9325        }
9326        requestRectangleOnScreen(viewCursorRingBounds);
9327        return keyHandled;
9328    }
9329
9330    /**
9331     * @return Whether accessibility script has been injected.
9332     */
9333    private boolean accessibilityScriptInjected() {
9334        // TODO: Maybe the injected script should announce its presence in
9335        // the page meta-tag so the nativePageShouldHandleShiftAndArrows
9336        // will check that as one of the conditions it looks for
9337        return mAccessibilityScriptInjected;
9338    }
9339
9340    /**
9341     * Set the background color. It's white by default. Pass
9342     * zero to make the view transparent.
9343     * @param color   the ARGB color described by Color.java
9344     */
9345    @Override
9346    public void setBackgroundColor(int color) {
9347        mBackgroundColor = color;
9348        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
9349    }
9350
9351    /**
9352     * @deprecated This method is now obsolete.
9353     */
9354    @Deprecated
9355    public void debugDump() {
9356        checkThread();
9357        nativeDebugDump();
9358        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
9359    }
9360
9361    /**
9362     * Draw the HTML page into the specified canvas. This call ignores any
9363     * view-specific zoom, scroll offset, or other changes. It does not draw
9364     * any view-specific chrome, such as progress or URL bars.
9365     *
9366     * @hide only needs to be accessible to Browser and testing
9367     */
9368    public void drawPage(Canvas canvas) {
9369        nativeDraw(canvas, 0, 0, false);
9370    }
9371
9372    /**
9373     * Enable the communication b/t the webView and VideoViewProxy
9374     *
9375     * @hide only used by the Browser
9376     */
9377    public void setHTML5VideoViewProxy(HTML5VideoViewProxy proxy) {
9378        mHTML5VideoViewProxy = proxy;
9379    }
9380
9381    /**
9382     * Set the time to wait between passing touches to WebCore. See also the
9383     * TOUCH_SENT_INTERVAL member for further discussion.
9384     *
9385     * @hide This is only used by the DRT test application.
9386     */
9387    public void setTouchInterval(int interval) {
9388        mCurrentTouchInterval = interval;
9389    }
9390
9391    /**
9392     *  Update our cache with updatedText.
9393     *  @param updatedText  The new text to put in our cache.
9394     *  @hide
9395     */
9396    protected void updateCachedTextfield(String updatedText) {
9397        // Also place our generation number so that when we look at the cache
9398        // we recognize that it is up to date.
9399        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
9400    }
9401
9402    /*package*/ void autoFillForm(int autoFillQueryId) {
9403        mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0);
9404    }
9405
9406    /* package */ ViewManager getViewManager() {
9407        return mViewManager;
9408    }
9409
9410    private static void checkThread() {
9411        if (Looper.myLooper() != Looper.getMainLooper()) {
9412            Throwable throwable = new Throwable(
9413                    "Warning: A WebView method was called on thread '" +
9414                    Thread.currentThread().getName() + "'. " +
9415                    "All WebView methods must be called on the UI thread. " +
9416                    "Future versions of WebView may not support use on other threads.");
9417            Log.w(LOGTAG, Log.getStackTraceString(throwable));
9418            StrictMode.onWebViewMethodCalledOnWrongThread(throwable);
9419        }
9420    }
9421
9422    /** @hide send content invalidate */
9423    protected void contentInvalidateAll() {
9424        if (mWebViewCore != null && !mBlockWebkitViewMessages) {
9425            mWebViewCore.sendMessage(EventHub.CONTENT_INVALIDATE_ALL);
9426        }
9427    }
9428
9429    /** @hide call pageSwapCallback upon next page swap */
9430    protected void registerPageSwapCallback() {
9431        nativeRegisterPageSwapCallback();
9432    }
9433
9434    /**
9435     * Begin collecting per-tile profiling data
9436     *
9437     * @hide only used by profiling tests
9438     */
9439    public void tileProfilingStart() {
9440        nativeTileProfilingStart();
9441    }
9442    /**
9443     * Return per-tile profiling data
9444     *
9445     * @hide only used by profiling tests
9446     */
9447    public float tileProfilingStop() {
9448        return nativeTileProfilingStop();
9449    }
9450
9451    /** @hide only used by profiling tests */
9452    public void tileProfilingClear() {
9453        nativeTileProfilingClear();
9454    }
9455    /** @hide only used by profiling tests */
9456    public int tileProfilingNumFrames() {
9457        return nativeTileProfilingNumFrames();
9458    }
9459    /** @hide only used by profiling tests */
9460    public int tileProfilingNumTilesInFrame(int frame) {
9461        return nativeTileProfilingNumTilesInFrame(frame);
9462    }
9463    /** @hide only used by profiling tests */
9464    public int tileProfilingGetInt(int frame, int tile, String key) {
9465        return nativeTileProfilingGetInt(frame, tile, key);
9466    }
9467    /** @hide only used by profiling tests */
9468    public float tileProfilingGetFloat(int frame, int tile, String key) {
9469        return nativeTileProfilingGetFloat(frame, tile, key);
9470    }
9471
9472    private native int nativeCacheHitFramePointer();
9473    private native boolean  nativeCacheHitIsPlugin();
9474    private native Rect nativeCacheHitNodeBounds();
9475    private native int nativeCacheHitNodePointer();
9476    /* package */ native void nativeClearCursor();
9477    private native void     nativeCreate(int ptr, String drawableDir);
9478    private native int      nativeCursorFramePointer();
9479    private native Rect     nativeCursorNodeBounds();
9480    private native int nativeCursorNodePointer();
9481    private native boolean  nativeCursorIntersects(Rect visibleRect);
9482    private native boolean  nativeCursorIsAnchor();
9483    private native boolean  nativeCursorIsTextInput();
9484    private native Point    nativeCursorPosition();
9485    private native String   nativeCursorText();
9486    /**
9487     * Returns true if the native cursor node says it wants to handle key events
9488     * (ala plugins). This can only be called if mNativeClass is non-zero!
9489     */
9490    private native boolean  nativeCursorWantsKeyEvents();
9491    private native void     nativeDebugDump();
9492    private native void     nativeDestroy();
9493
9494    /**
9495     * Draw the picture set with a background color and extra. If
9496     * "splitIfNeeded" is true and the return value is not 0, the return value
9497     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
9498     * native allocation can be freed.
9499     */
9500    private native int nativeDraw(Canvas canvas, int color, int extra,
9501            boolean splitIfNeeded);
9502    private native void     nativeDumpDisplayTree(String urlOrNull);
9503    private native boolean  nativeEvaluateLayersAnimations(int nativeInstance);
9504    private native int      nativeGetDrawGLFunction(int nativeInstance, Rect rect,
9505            Rect viewRect, float scale, int extras);
9506    private native void     nativeUpdateDrawGLFunction(Rect rect, Rect viewRect);
9507    private native void     nativeExtendSelection(int x, int y);
9508    private native int      nativeFindAll(String findLower, String findUpper,
9509            boolean sameAsLastSearch);
9510    private native void     nativeFindNext(boolean forward);
9511    /* package */ native int      nativeFocusCandidateFramePointer();
9512    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
9513    /* package */ native boolean  nativeFocusCandidateIsPassword();
9514    private native boolean  nativeFocusCandidateIsRtlText();
9515    private native boolean  nativeFocusCandidateIsTextInput();
9516    /* package */ native int      nativeFocusCandidateMaxLength();
9517    /* package */ native boolean  nativeFocusCandidateIsAutoComplete();
9518    /* package */ native boolean  nativeFocusCandidateIsSpellcheck();
9519    /* package */ native String   nativeFocusCandidateName();
9520    private native Rect     nativeFocusCandidateNodeBounds();
9521    /**
9522     * @return A Rect with left, top, right, bottom set to the corresponding
9523     * padding values in the focus candidate, if it is a textfield/textarea with
9524     * a style.  Otherwise return null.  This is not actually a rectangle; Rect
9525     * is being used to pass four integers.
9526     */
9527    private native Rect     nativeFocusCandidatePaddingRect();
9528    /* package */ native int      nativeFocusCandidatePointer();
9529    private native String   nativeFocusCandidateText();
9530    /* package */ native float    nativeFocusCandidateTextSize();
9531    /* package */ native int nativeFocusCandidateLineHeight();
9532    /**
9533     * Returns an integer corresponding to WebView.cpp::type.
9534     * See WebTextView.setType()
9535     */
9536    private native int      nativeFocusCandidateType();
9537    private native boolean  nativeFocusIsPlugin();
9538    private native Rect     nativeFocusNodeBounds();
9539    /* package */ native int nativeFocusNodePointer();
9540    private native Rect     nativeGetCursorRingBounds();
9541    private native String   nativeGetSelection();
9542    private native boolean  nativeHasCursorNode();
9543    private native boolean  nativeHasFocusNode();
9544    private native void     nativeHideCursor();
9545    private native boolean  nativeHitSelection(int x, int y);
9546    private native String   nativeImageURI(int x, int y);
9547    private native void     nativeInstrumentReport();
9548    private native Rect     nativeLayerBounds(int layer);
9549    /* package */ native boolean nativeMoveCursorToNextTextInput();
9550    // return true if the page has been scrolled
9551    private native boolean  nativeMotionUp(int x, int y, int slop);
9552    // returns false if it handled the key
9553    private native boolean  nativeMoveCursor(int keyCode, int count,
9554            boolean noScroll);
9555    private native int      nativeMoveGeneration();
9556    private native void     nativeMoveSelection(int x, int y);
9557    /**
9558     * @return true if the page should get the shift and arrow keys, rather
9559     * than select text/navigation.
9560     *
9561     * If the focus is a plugin, or if the focus and cursor match and are
9562     * a contentEditable element, then the page should handle these keys.
9563     */
9564    private native boolean  nativePageShouldHandleShiftAndArrows();
9565    private native boolean  nativePointInNavCache(int x, int y, int slop);
9566    // Like many other of our native methods, you must make sure that
9567    // mNativeClass is not null before calling this method.
9568    private native void     nativeResetSelection();
9569    private native Point    nativeSelectableText();
9570    private native void     nativeSelectAll();
9571    private native void     nativeSelectBestAt(Rect rect);
9572    private native void     nativeSelectAt(int x, int y);
9573    private native int      nativeSelectionX();
9574    private native int      nativeSelectionY();
9575    private native int      nativeFindIndex();
9576    private native void     nativeSetExtendSelection();
9577    private native void     nativeSetFindIsEmpty();
9578    private native void     nativeSetFindIsUp(boolean isUp);
9579    private native void     nativeSetHeightCanMeasure(boolean measure);
9580    private native void     nativeSetBaseLayer(int layer, Region invalRegion,
9581            boolean showVisualIndicator, boolean isPictureAfterFirstLayout,
9582            boolean registerPageSwapCallback);
9583    private native int      nativeGetBaseLayer();
9584    private native void     nativeShowCursorTimed();
9585    private native void     nativeReplaceBaseContent(int content);
9586    private native void     nativeCopyBaseContentToPicture(Picture pict);
9587    private native boolean  nativeHasContent();
9588    private native void     nativeSetSelectionPointer(int nativeInstance,
9589            boolean set, float scale, int x, int y);
9590    private native boolean  nativeStartSelection(int x, int y);
9591    private native void     nativeStopGL();
9592    private native Rect     nativeSubtractLayers(Rect content);
9593    private native int      nativeTextGeneration();
9594    private native void     nativeRegisterPageSwapCallback();
9595    private native void     nativeTileProfilingStart();
9596    private native float    nativeTileProfilingStop();
9597    private native void     nativeTileProfilingClear();
9598    private native int      nativeTileProfilingNumFrames();
9599    private native int      nativeTileProfilingNumTilesInFrame(int frame);
9600    private native int      nativeTileProfilingGetInt(int frame, int tile, String key);
9601    private native float    nativeTileProfilingGetFloat(int frame, int tile, String key);
9602    // Never call this version except by updateCachedTextfield(String) -
9603    // we always want to pass in our generation number.
9604    private native void     nativeUpdateCachedTextfield(String updatedText,
9605            int generation);
9606    private native boolean  nativeWordSelection(int x, int y);
9607    // return NO_LEFTEDGE means failure.
9608    static final int NO_LEFTEDGE = -1;
9609    native int nativeGetBlockLeftEdge(int x, int y, float scale);
9610
9611    private native void     nativeUseHardwareAccelSkia(boolean enabled);
9612
9613    // Returns a pointer to the scrollable LayerAndroid at the given point.
9614    private native int      nativeScrollableLayer(int x, int y, Rect scrollRect,
9615            Rect scrollBounds);
9616    /**
9617     * Scroll the specified layer.
9618     * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer.
9619     * @param newX Destination x position to which to scroll.
9620     * @param newY Destination y position to which to scroll.
9621     * @return True if the layer is successfully scrolled.
9622     */
9623    private native boolean  nativeScrollLayer(int layer, int newX, int newY);
9624    private native void     nativeSetIsScrolling(boolean isScrolling);
9625    private native int      nativeGetBackgroundColor();
9626    native boolean  nativeSetProperty(String key, String value);
9627    native String   nativeGetProperty(String key);
9628    private native void     nativeGetTextSelectionRegion(int instance, Region region);
9629    private native void     nativeGetSelectionHandles(int instance, int[] handles);
9630    /**
9631     * See {@link ComponentCallbacks2} for the trim levels and descriptions
9632     */
9633    private static native void     nativeOnTrimMemory(int level);
9634    private static native void nativeSetPauseDrawing(int instance, boolean pause);
9635}
9636