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