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