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