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