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