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