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