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