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