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