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