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