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