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