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