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