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