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