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