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