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