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