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