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