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