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