WebView.java revision 24f2936d352e8938a02ec10ace57cac8671fc68f
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.
1975     * <p>
1976     * Note that JavaScript's same origin policy means that script running in a
1977     * page loaded using this method will be unable to access content loaded
1978     * using any scheme other than 'data', including 'http(s)'. To avoid this
1979     * restriction, use {@link
1980     * #loadDataWithBaseURL(String,String,String,String,String)
1981     * loadDataWithBaseURL()} with an appropriate base URL.
1982     * <p>
1983     * If the value of the encoding parameter is 'base64', then the data must
1984     * be encoded as base64. Otherwise, the data must use ASCII encoding for
1985     * octets inside the range of safe URL characters and use the standard %xx
1986     * hex encoding of URLs for octets outside that range.
1987     * @param data A String of data in the given encoding.
1988     * @param mimeType The MIMEType of the data, e.g. 'text/html'.
1989     * @param encoding The encoding of the data.
1990     */
1991    public void loadData(String data, String mimeType, String encoding) {
1992        checkThread();
1993        loadDataImpl(data, mimeType, encoding);
1994    }
1995
1996    private void loadDataImpl(String data, String mimeType, String encoding) {
1997        StringBuilder dataUrl = new StringBuilder("data:");
1998        dataUrl.append(mimeType);
1999        if ("base64".equals(encoding)) {
2000            dataUrl.append(";base64");
2001        }
2002        dataUrl.append(",");
2003        dataUrl.append(data);
2004        loadUrlImpl(dataUrl.toString());
2005    }
2006
2007    /**
2008     * Load the given data into the WebView, using baseUrl as the base URL for
2009     * the content. The base URL is used both to resolve relative URLs and when
2010     * applying JavaScript's same origin policy. The historyUrl is used for the
2011     * history entry.
2012     * <p>
2013     * Note that content specified in this way can access local device files
2014     * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
2015     * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
2016     * <p>
2017     * If the base URL uses the data scheme, this method is equivalent to
2018     * calling {@link #loadData(String,String,String) loadData()} and the
2019     * historyUrl is ignored.
2020     * @param baseUrl URL to use as the page's base URL. If null defaults to
2021     *            'about:blank'
2022     * @param data A String of data in the given encoding.
2023     * @param mimeType The MIMEType of the data, e.g. 'text/html'. If null,
2024     *            defaults to 'text/html'.
2025     * @param encoding The encoding of the data.
2026     * @param historyUrl URL to use as the history entry, if null defaults to
2027     *            'about:blank'.
2028     */
2029    public void loadDataWithBaseURL(String baseUrl, String data,
2030            String mimeType, String encoding, String historyUrl) {
2031        checkThread();
2032
2033        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
2034            loadDataImpl(data, mimeType, encoding);
2035            return;
2036        }
2037        switchOutDrawHistory();
2038        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
2039        arg.mBaseUrl = baseUrl;
2040        arg.mData = data;
2041        arg.mMimeType = mimeType;
2042        arg.mEncoding = encoding;
2043        arg.mHistoryUrl = historyUrl;
2044        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
2045        clearHelpers();
2046    }
2047
2048    /**
2049     * Saves the current view as a web archive.
2050     *
2051     * @param filename The filename where the archive should be placed.
2052     */
2053    public void saveWebArchive(String filename) {
2054        checkThread();
2055        saveWebArchiveImpl(filename, false, null);
2056    }
2057
2058    /* package */ static class SaveWebArchiveMessage {
2059        SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback<String> callback) {
2060            mBasename = basename;
2061            mAutoname = autoname;
2062            mCallback = callback;
2063        }
2064
2065        /* package */ final String mBasename;
2066        /* package */ final boolean mAutoname;
2067        /* package */ final ValueCallback<String> mCallback;
2068        /* package */ String mResultFile;
2069    }
2070
2071    /**
2072     * Saves the current view as a web archive.
2073     *
2074     * @param basename The filename where the archive should be placed.
2075     * @param autoname If false, takes basename to be a file. If true, basename
2076     *                 is assumed to be a directory in which a filename will be
2077     *                 chosen according to the url of the current page.
2078     * @param callback Called after the web archive has been saved. The
2079     *                 parameter for onReceiveValue will either be the filename
2080     *                 under which the file was saved, or null if saving the
2081     *                 file failed.
2082     */
2083    public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
2084        checkThread();
2085        saveWebArchiveImpl(basename, autoname, callback);
2086    }
2087
2088    private void saveWebArchiveImpl(String basename, boolean autoname,
2089            ValueCallback<String> callback) {
2090        mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE,
2091            new SaveWebArchiveMessage(basename, autoname, callback));
2092    }
2093
2094    /**
2095     * Stop the current load.
2096     */
2097    public void stopLoading() {
2098        checkThread();
2099        // TODO: should we clear all the messages in the queue before sending
2100        // STOP_LOADING?
2101        switchOutDrawHistory();
2102        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
2103    }
2104
2105    /**
2106     * Reload the current url.
2107     */
2108    public void reload() {
2109        checkThread();
2110        clearHelpers();
2111        switchOutDrawHistory();
2112        mWebViewCore.sendMessage(EventHub.RELOAD);
2113    }
2114
2115    /**
2116     * Return true if this WebView has a back history item.
2117     * @return True iff this WebView has a back history item.
2118     */
2119    public boolean canGoBack() {
2120        checkThread();
2121        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2122        synchronized (l) {
2123            if (l.getClearPending()) {
2124                return false;
2125            } else {
2126                return l.getCurrentIndex() > 0;
2127            }
2128        }
2129    }
2130
2131    /**
2132     * Go back in the history of this WebView.
2133     */
2134    public void goBack() {
2135        checkThread();
2136        goBackOrForwardImpl(-1);
2137    }
2138
2139    /**
2140     * Return true if this WebView has a forward history item.
2141     * @return True iff this Webview has a forward history item.
2142     */
2143    public boolean canGoForward() {
2144        checkThread();
2145        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2146        synchronized (l) {
2147            if (l.getClearPending()) {
2148                return false;
2149            } else {
2150                return l.getCurrentIndex() < l.getSize() - 1;
2151            }
2152        }
2153    }
2154
2155    /**
2156     * Go forward in the history of this WebView.
2157     */
2158    public void goForward() {
2159        checkThread();
2160        goBackOrForwardImpl(1);
2161    }
2162
2163    /**
2164     * Return true if the page can go back or forward the given
2165     * number of steps.
2166     * @param steps The negative or positive number of steps to move the
2167     *              history.
2168     */
2169    public boolean canGoBackOrForward(int steps) {
2170        checkThread();
2171        WebBackForwardList l = mCallbackProxy.getBackForwardList();
2172        synchronized (l) {
2173            if (l.getClearPending()) {
2174                return false;
2175            } else {
2176                int newIndex = l.getCurrentIndex() + steps;
2177                return newIndex >= 0 && newIndex < l.getSize();
2178            }
2179        }
2180    }
2181
2182    /**
2183     * Go to the history item that is the number of steps away from
2184     * the current item. Steps is negative if backward and positive
2185     * if forward.
2186     * @param steps The number of steps to take back or forward in the back
2187     *              forward list.
2188     */
2189    public void goBackOrForward(int steps) {
2190        checkThread();
2191        goBackOrForwardImpl(steps);
2192    }
2193
2194    private void goBackOrForwardImpl(int steps) {
2195        goBackOrForward(steps, false);
2196    }
2197
2198    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
2199        if (steps != 0) {
2200            clearHelpers();
2201            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
2202                    ignoreSnapshot ? 1 : 0);
2203        }
2204    }
2205
2206    /**
2207     * Returns true if private browsing is enabled in this WebView.
2208     */
2209    public boolean isPrivateBrowsingEnabled() {
2210        checkThread();
2211        return getSettings().isPrivateBrowsingEnabled();
2212    }
2213
2214    private void startPrivateBrowsing() {
2215        getSettings().setPrivateBrowsingEnabled(true);
2216    }
2217
2218    private boolean extendScroll(int y) {
2219        int finalY = mScroller.getFinalY();
2220        int newY = pinLocY(finalY + y);
2221        if (newY == finalY) return false;
2222        mScroller.setFinalY(newY);
2223        mScroller.extendDuration(computeDuration(0, y));
2224        return true;
2225    }
2226
2227    /**
2228     * Scroll the contents of the view up by half the view size
2229     * @param top true to jump to the top of the page
2230     * @return true if the page was scrolled
2231     */
2232    public boolean pageUp(boolean top) {
2233        checkThread();
2234        if (mNativeClass == 0) {
2235            return false;
2236        }
2237        nativeClearCursor(); // start next trackball movement from page edge
2238        if (top) {
2239            // go to the top of the document
2240            return pinScrollTo(mScrollX, 0, true, 0);
2241        }
2242        // Page up
2243        int h = getHeight();
2244        int y;
2245        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2246            y = -h + PAGE_SCROLL_OVERLAP;
2247        } else {
2248            y = -h / 2;
2249        }
2250        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2251                : extendScroll(y);
2252    }
2253
2254    /**
2255     * Scroll the contents of the view down by half the page size
2256     * @param bottom true to jump to bottom of page
2257     * @return true if the page was scrolled
2258     */
2259    public boolean pageDown(boolean bottom) {
2260        checkThread();
2261        if (mNativeClass == 0) {
2262            return false;
2263        }
2264        nativeClearCursor(); // start next trackball movement from page edge
2265        if (bottom) {
2266            return pinScrollTo(mScrollX, computeRealVerticalScrollRange(), true, 0);
2267        }
2268        // Page down.
2269        int h = getHeight();
2270        int y;
2271        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2272            y = h - PAGE_SCROLL_OVERLAP;
2273        } else {
2274            y = h / 2;
2275        }
2276        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2277                : extendScroll(y);
2278    }
2279
2280    /**
2281     * Clear the view so that onDraw() will draw nothing but white background,
2282     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
2283     */
2284    public void clearView() {
2285        checkThread();
2286        mContentWidth = 0;
2287        mContentHeight = 0;
2288        setBaseLayer(0, null, false, false);
2289        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
2290    }
2291
2292    /**
2293     * Return a new picture that captures the current display of the webview.
2294     * This is a copy of the display, and will be unaffected if the webview
2295     * later loads a different URL.
2296     *
2297     * @return a picture containing the current contents of the view. Note this
2298     *         picture is of the entire document, and is not restricted to the
2299     *         bounds of the view.
2300     */
2301    public Picture capturePicture() {
2302        checkThread();
2303        if (mNativeClass == 0) return null;
2304        Picture result = new Picture();
2305        nativeCopyBaseContentToPicture(result);
2306        return result;
2307    }
2308
2309    /**
2310     *  Return true if the browser is displaying a TextView for text input.
2311     */
2312    private boolean inEditingMode() {
2313        return mWebTextView != null && mWebTextView.getParent() != null;
2314    }
2315
2316    /**
2317     * Remove the WebTextView.
2318     */
2319    private void clearTextEntry() {
2320        if (inEditingMode()) {
2321            mWebTextView.remove();
2322        } else {
2323            // The keyboard may be open with the WebView as the served view
2324            hideSoftKeyboard();
2325        }
2326    }
2327
2328    /**
2329     * Return the current scale of the WebView
2330     * @return The current scale.
2331     */
2332    public float getScale() {
2333        checkThread();
2334        return mZoomManager.getScale();
2335    }
2336
2337    /**
2338     * Set the initial scale for the WebView. 0 means default. If
2339     * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
2340     * way. Otherwise it starts with 100%. If initial scale is greater than 0,
2341     * WebView starts will this value as initial scale.
2342     *
2343     * @param scaleInPercent The initial scale in percent.
2344     */
2345    public void setInitialScale(int scaleInPercent) {
2346        checkThread();
2347        mZoomManager.setInitialScaleInPercent(scaleInPercent);
2348    }
2349
2350    /**
2351     * Invoke the graphical zoom picker widget for this WebView. This will
2352     * result in the zoom widget appearing on the screen to control the zoom
2353     * level of this WebView.
2354     */
2355    public void invokeZoomPicker() {
2356        checkThread();
2357        if (!getSettings().supportZoom()) {
2358            Log.w(LOGTAG, "This WebView doesn't support zoom.");
2359            return;
2360        }
2361        clearHelpers();
2362        mZoomManager.invokeZoomPicker();
2363    }
2364
2365    /**
2366     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
2367     * is found and the anchor has a non-JavaScript url, the HitTestResult type
2368     * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
2369     * anchor does not have a url or if it is a JavaScript url, the type will
2370     * be UNKNOWN_TYPE and the url has to be retrieved through
2371     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
2372     * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
2373     * the "extra" field. A type of
2374     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
2375     * a child node. If a phone number is found, the HitTestResult type is set
2376     * to PHONE_TYPE and the phone number is set in the "extra" field of
2377     * HitTestResult. If a map address is found, the HitTestResult type is set
2378     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
2379     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
2380     * and the email is set in the "extra" field of HitTestResult. Otherwise,
2381     * HitTestResult type is set to UNKNOWN_TYPE.
2382     */
2383    public HitTestResult getHitTestResult() {
2384        checkThread();
2385        return hitTestResult(mInitialHitTestResult);
2386    }
2387
2388    private HitTestResult hitTestResult(HitTestResult fallback) {
2389        if (mNativeClass == 0) {
2390            return null;
2391        }
2392
2393        HitTestResult result = new HitTestResult();
2394        if (nativeHasCursorNode()) {
2395            if (nativeCursorIsTextInput()) {
2396                result.setType(HitTestResult.EDIT_TEXT_TYPE);
2397            } else {
2398                String text = nativeCursorText();
2399                if (text != null) {
2400                    if (text.startsWith(SCHEME_TEL)) {
2401                        result.setType(HitTestResult.PHONE_TYPE);
2402                        result.setExtra(text.substring(SCHEME_TEL.length()));
2403                    } else if (text.startsWith(SCHEME_MAILTO)) {
2404                        result.setType(HitTestResult.EMAIL_TYPE);
2405                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
2406                    } else if (text.startsWith(SCHEME_GEO)) {
2407                        result.setType(HitTestResult.GEO_TYPE);
2408                        result.setExtra(URLDecoder.decode(text
2409                                .substring(SCHEME_GEO.length())));
2410                    } else if (nativeCursorIsAnchor()) {
2411                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
2412                        result.setExtra(text);
2413                    }
2414                }
2415            }
2416        } else if (fallback != null) {
2417            /* If webkit causes a rebuild while the long press is in progress,
2418             * the cursor node may be reset, even if it is still around. This
2419             * uses the cursor node saved when the touch began. Since the
2420             * nativeImageURI below only changes the result if it is successful,
2421             * this uses the data beneath the touch if available or the original
2422             * tap data otherwise.
2423             */
2424            Log.v(LOGTAG, "hitTestResult use fallback");
2425            result = fallback;
2426        }
2427        int type = result.getType();
2428        if (type == HitTestResult.UNKNOWN_TYPE
2429                || type == HitTestResult.SRC_ANCHOR_TYPE) {
2430            // Now check to see if it is an image.
2431            int contentX = viewToContentX(mLastTouchX + mScrollX);
2432            int contentY = viewToContentY(mLastTouchY + mScrollY);
2433            String text = nativeImageURI(contentX, contentY);
2434            if (text != null) {
2435                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
2436                        HitTestResult.IMAGE_TYPE :
2437                        HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
2438                result.setExtra(text);
2439            }
2440        }
2441        return result;
2442    }
2443
2444    // Called by JNI when the DOM has changed the focus.  Clear the focus so
2445    // that new keys will go to the newly focused field
2446    private void domChangedFocus() {
2447        if (inEditingMode()) {
2448            mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget();
2449        }
2450    }
2451    /**
2452     * Request the anchor or image element URL at the last tapped point.
2453     * If hrefMsg is null, this method returns immediately and does not
2454     * dispatch hrefMsg to its target. If the tapped point hits an image,
2455     * an anchor, or an image in an anchor, the message associates
2456     * strings in named keys in its data. The value paired with the key
2457     * may be an empty string.
2458     *
2459     * @param hrefMsg This message will be dispatched with the result of the
2460     *                request. The message data contains three keys:
2461     *                - "url" returns the anchor's href attribute.
2462     *                - "title" returns the anchor's text.
2463     *                - "src" returns the image's src attribute.
2464     */
2465    public void requestFocusNodeHref(Message hrefMsg) {
2466        checkThread();
2467        if (hrefMsg == null) {
2468            return;
2469        }
2470        int contentX = viewToContentX(mLastTouchX + mScrollX);
2471        int contentY = viewToContentY(mLastTouchY + mScrollY);
2472        if (nativeHasCursorNode()) {
2473            Rect cursorBounds = nativeGetCursorRingBounds();
2474            if (!cursorBounds.contains(contentX, contentY)) {
2475                int slop = viewToContentDimension(mNavSlop);
2476                cursorBounds.inset(-slop, -slop);
2477                if (cursorBounds.contains(contentX, contentY)) {
2478                    contentX = (int) cursorBounds.centerX();
2479                    contentY = (int) cursorBounds.centerY();
2480                }
2481            }
2482        }
2483        mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
2484                contentX, contentY, hrefMsg);
2485    }
2486
2487    /**
2488     * Request the url of the image last touched by the user. msg will be sent
2489     * to its target with a String representing the url as its object.
2490     *
2491     * @param msg This message will be dispatched with the result of the request
2492     *            as the data member with "url" as key. The result can be null.
2493     */
2494    public void requestImageRef(Message msg) {
2495        checkThread();
2496        if (0 == mNativeClass) return; // client isn't initialized
2497        int contentX = viewToContentX(mLastTouchX + mScrollX);
2498        int contentY = viewToContentY(mLastTouchY + mScrollY);
2499        String ref = nativeImageURI(contentX, contentY);
2500        Bundle data = msg.getData();
2501        data.putString("url", ref);
2502        msg.setData(data);
2503        msg.sendToTarget();
2504    }
2505
2506    static int pinLoc(int x, int viewMax, int docMax) {
2507//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
2508        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
2509            // pin the short document to the top/left of the screen
2510            x = 0;
2511//            Log.d(LOGTAG, "--- center " + x);
2512        } else if (x < 0) {
2513            x = 0;
2514//            Log.d(LOGTAG, "--- zero");
2515        } else if (x + viewMax > docMax) {
2516            x = docMax - viewMax;
2517//            Log.d(LOGTAG, "--- pin " + x);
2518        }
2519        return x;
2520    }
2521
2522    // Expects x in view coordinates
2523    int pinLocX(int x) {
2524        if (mInOverScrollMode) return x;
2525        return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange());
2526    }
2527
2528    // Expects y in view coordinates
2529    int pinLocY(int y) {
2530        if (mInOverScrollMode) return y;
2531        return pinLoc(y, getViewHeightWithTitle(),
2532                      computeRealVerticalScrollRange() + getTitleHeight());
2533    }
2534
2535    /**
2536     * A title bar which is embedded in this WebView, and scrolls along with it
2537     * vertically, but not horizontally.
2538     */
2539    private View mTitleBar;
2540
2541    /**
2542     * the title bar rendering gravity
2543     */
2544    private int mTitleGravity;
2545
2546    /**
2547     * Add or remove a title bar to be embedded into the WebView, and scroll
2548     * along with it vertically, while remaining in view horizontally. Pass
2549     * null to remove the title bar from the WebView, and return to drawing
2550     * the WebView normally without translating to account for the title bar.
2551     * @hide
2552     */
2553    public void setEmbeddedTitleBar(View v) {
2554        if (mTitleBar == v) return;
2555        if (mTitleBar != null) {
2556            removeView(mTitleBar);
2557        }
2558        if (null != v) {
2559            addView(v, new AbsoluteLayout.LayoutParams(
2560                    ViewGroup.LayoutParams.MATCH_PARENT,
2561                    ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
2562        }
2563        mTitleBar = v;
2564    }
2565
2566    /**
2567     * Set where to render the embedded title bar
2568     * NO_GRAVITY at the top of the page
2569     * TOP        at the top of the screen
2570     * @hide
2571     */
2572    public void setTitleBarGravity(int gravity) {
2573        mTitleGravity = gravity;
2574        // force refresh
2575        invalidate();
2576    }
2577
2578    /**
2579     * Given a distance in view space, convert it to content space. Note: this
2580     * does not reflect translation, just scaling, so this should not be called
2581     * with coordinates, but should be called for dimensions like width or
2582     * height.
2583     */
2584    private int viewToContentDimension(int d) {
2585        return Math.round(d * mZoomManager.getInvScale());
2586    }
2587
2588    /**
2589     * Given an x coordinate in view space, convert it to content space.  Also
2590     * may be used for absolute heights (such as for the WebTextView's
2591     * textSize, which is unaffected by the height of the title bar).
2592     */
2593    /*package*/ int viewToContentX(int x) {
2594        return viewToContentDimension(x);
2595    }
2596
2597    /**
2598     * Given a y coordinate in view space, convert it to content space.
2599     * Takes into account the height of the title bar if there is one
2600     * embedded into the WebView.
2601     */
2602    /*package*/ int viewToContentY(int y) {
2603        return viewToContentDimension(y - getTitleHeight());
2604    }
2605
2606    /**
2607     * Given a x coordinate in view space, convert it to content space.
2608     * Returns the result as a float.
2609     */
2610    private float viewToContentXf(int x) {
2611        return x * mZoomManager.getInvScale();
2612    }
2613
2614    /**
2615     * Given a y coordinate in view space, convert it to content space.
2616     * Takes into account the height of the title bar if there is one
2617     * embedded into the WebView. Returns the result as a float.
2618     */
2619    private float viewToContentYf(int y) {
2620        return (y - getTitleHeight()) * mZoomManager.getInvScale();
2621    }
2622
2623    /**
2624     * Given a distance in content space, convert it to view space. Note: this
2625     * does not reflect translation, just scaling, so this should not be called
2626     * with coordinates, but should be called for dimensions like width or
2627     * height.
2628     */
2629    /*package*/ int contentToViewDimension(int d) {
2630        return Math.round(d * mZoomManager.getScale());
2631    }
2632
2633    /**
2634     * Given an x coordinate in content space, convert it to view
2635     * space.
2636     */
2637    /*package*/ int contentToViewX(int x) {
2638        return contentToViewDimension(x);
2639    }
2640
2641    /**
2642     * Given a y coordinate in content space, convert it to view
2643     * space.  Takes into account the height of the title bar.
2644     */
2645    /*package*/ int contentToViewY(int y) {
2646        return contentToViewDimension(y) + getTitleHeight();
2647    }
2648
2649    private Rect contentToViewRect(Rect x) {
2650        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
2651                        contentToViewX(x.right), contentToViewY(x.bottom));
2652    }
2653
2654    /*  To invalidate a rectangle in content coordinates, we need to transform
2655        the rect into view coordinates, so we can then call invalidate(...).
2656
2657        Normally, we would just call contentToView[XY](...), which eventually
2658        calls Math.round(coordinate * mActualScale). However, for invalidates,
2659        we need to account for the slop that occurs with antialiasing. To
2660        address that, we are a little more liberal in the size of the rect that
2661        we invalidate.
2662
2663        This liberal calculation calls floor() for the top/left, and ceil() for
2664        the bottom/right coordinates. This catches the possible extra pixels of
2665        antialiasing that we might have missed with just round().
2666     */
2667
2668    // Called by JNI to invalidate the View, given rectangle coordinates in
2669    // content space
2670    private void viewInvalidate(int l, int t, int r, int b) {
2671        final float scale = mZoomManager.getScale();
2672        final int dy = getTitleHeight();
2673        invalidate((int)Math.floor(l * scale),
2674                   (int)Math.floor(t * scale) + dy,
2675                   (int)Math.ceil(r * scale),
2676                   (int)Math.ceil(b * scale) + dy);
2677    }
2678
2679    // Called by JNI to invalidate the View after a delay, given rectangle
2680    // coordinates in content space
2681    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
2682        final float scale = mZoomManager.getScale();
2683        final int dy = getTitleHeight();
2684        postInvalidateDelayed(delay,
2685                              (int)Math.floor(l * scale),
2686                              (int)Math.floor(t * scale) + dy,
2687                              (int)Math.ceil(r * scale),
2688                              (int)Math.ceil(b * scale) + dy);
2689    }
2690
2691    private void invalidateContentRect(Rect r) {
2692        viewInvalidate(r.left, r.top, r.right, r.bottom);
2693    }
2694
2695    // stop the scroll animation, and don't let a subsequent fling add
2696    // to the existing velocity
2697    private void abortAnimation() {
2698        mScroller.abortAnimation();
2699        mLastVelocity = 0;
2700    }
2701
2702    /* call from webcoreview.draw(), so we're still executing in the UI thread
2703    */
2704    private void recordNewContentSize(int w, int h, boolean updateLayout) {
2705
2706        // premature data from webkit, ignore
2707        if ((w | h) == 0) {
2708            return;
2709        }
2710
2711        // don't abort a scroll animation if we didn't change anything
2712        if (mContentWidth != w || mContentHeight != h) {
2713            // record new dimensions
2714            mContentWidth = w;
2715            mContentHeight = h;
2716            // If history Picture is drawn, don't update scroll. They will be
2717            // updated when we get out of that mode.
2718            if (!mDrawHistory) {
2719                // repin our scroll, taking into account the new content size
2720                updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY));
2721                if (!mScroller.isFinished()) {
2722                    // We are in the middle of a scroll.  Repin the final scroll
2723                    // position.
2724                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
2725                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
2726                }
2727            }
2728        }
2729        contentSizeChanged(updateLayout);
2730    }
2731
2732    // Used to avoid sending many visible rect messages.
2733    private Rect mLastVisibleRectSent;
2734    private Rect mLastGlobalRect;
2735
2736    Rect sendOurVisibleRect() {
2737        if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
2738        Rect rect = new Rect();
2739        calcOurContentVisibleRect(rect);
2740        // Rect.equals() checks for null input.
2741        if (!rect.equals(mLastVisibleRectSent)) {
2742            if (!mBlockWebkitViewMessages) {
2743                Point pos = new Point(rect.left, rect.top);
2744                mWebViewCore.removeMessages(EventHub.SET_SCROLL_OFFSET);
2745                mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
2746                        nativeMoveGeneration(), mSendScrollEvent ? 1 : 0, pos);
2747            }
2748            mLastVisibleRectSent = rect;
2749            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
2750        }
2751        Rect globalRect = new Rect();
2752        if (getGlobalVisibleRect(globalRect)
2753                && !globalRect.equals(mLastGlobalRect)) {
2754            if (DebugFlags.WEB_VIEW) {
2755                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2756                        + globalRect.top + ",r=" + globalRect.right + ",b="
2757                        + globalRect.bottom);
2758            }
2759            // TODO: the global offset is only used by windowRect()
2760            // in ChromeClientAndroid ; other clients such as touch
2761            // and mouse events could return view + screen relative points.
2762            if (!mBlockWebkitViewMessages) {
2763                mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2764            }
2765            mLastGlobalRect = globalRect;
2766        }
2767        return rect;
2768    }
2769
2770    // Sets r to be the visible rectangle of our webview in view coordinates
2771    private void calcOurVisibleRect(Rect r) {
2772        Point p = new Point();
2773        getGlobalVisibleRect(r, p);
2774        r.offset(-p.x, -p.y);
2775    }
2776
2777    // Sets r to be our visible rectangle in content coordinates
2778    private void calcOurContentVisibleRect(Rect r) {
2779        calcOurVisibleRect(r);
2780        r.left = viewToContentX(r.left);
2781        // viewToContentY will remove the total height of the title bar.  Add
2782        // the visible height back in to account for the fact that if the title
2783        // bar is partially visible, the part of the visible rect which is
2784        // displaying our content is displaced by that amount.
2785        r.top = viewToContentY(r.top + getVisibleTitleHeightImpl());
2786        r.right = viewToContentX(r.right);
2787        r.bottom = viewToContentY(r.bottom);
2788    }
2789
2790    // Sets r to be our visible rectangle in content coordinates. We use this
2791    // method on the native side to compute the position of the fixed layers.
2792    // Uses floating coordinates (necessary to correctly place elements when
2793    // the scale factor is not 1)
2794    private void calcOurContentVisibleRectF(RectF r) {
2795        Rect ri = new Rect(0,0,0,0);
2796        calcOurVisibleRect(ri);
2797        r.left = viewToContentXf(ri.left);
2798        // viewToContentY will remove the total height of the title bar.  Add
2799        // the visible height back in to account for the fact that if the title
2800        // bar is partially visible, the part of the visible rect which is
2801        // displaying our content is displaced by that amount.
2802        r.top = viewToContentYf(ri.top + getVisibleTitleHeightImpl());
2803        r.right = viewToContentXf(ri.right);
2804        r.bottom = viewToContentYf(ri.bottom);
2805    }
2806
2807    static class ViewSizeData {
2808        int mWidth;
2809        int mHeight;
2810        float mHeightWidthRatio;
2811        int mActualViewHeight;
2812        int mTextWrapWidth;
2813        int mAnchorX;
2814        int mAnchorY;
2815        float mScale;
2816        boolean mIgnoreHeight;
2817    }
2818
2819    /**
2820     * Compute unzoomed width and height, and if they differ from the last
2821     * values we sent, send them to webkit (to be used as new viewport)
2822     *
2823     * @param force ensures that the message is sent to webkit even if the width
2824     * or height has not changed since the last message
2825     *
2826     * @return true if new values were sent
2827     */
2828    boolean sendViewSizeZoom(boolean force) {
2829        if (mBlockWebkitViewMessages) return false;
2830        if (mZoomManager.isPreventingWebkitUpdates()) return false;
2831
2832        int viewWidth = getViewWidth();
2833        int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
2834        // This height could be fixed and be different from actual visible height.
2835        int viewHeight = getViewHeightWithTitle() - getTitleHeight();
2836        int newHeight = Math.round(viewHeight * mZoomManager.getInvScale());
2837        // Make the ratio more accurate than (newHeight / newWidth), since the
2838        // latter both are calculated and rounded.
2839        float heightWidthRatio = (float) viewHeight / viewWidth;
2840        /*
2841         * Because the native side may have already done a layout before the
2842         * View system was able to measure us, we have to send a height of 0 to
2843         * remove excess whitespace when we grow our width. This will trigger a
2844         * layout and a change in content size. This content size change will
2845         * mean that contentSizeChanged will either call this method directly or
2846         * indirectly from onSizeChanged.
2847         */
2848        if (newWidth > mLastWidthSent && mWrapContent) {
2849            newHeight = 0;
2850            heightWidthRatio = 0;
2851        }
2852        // Actual visible content height.
2853        int actualViewHeight = Math.round(getViewHeight() * mZoomManager.getInvScale());
2854        // Avoid sending another message if the dimensions have not changed.
2855        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force ||
2856                actualViewHeight != mLastActualHeightSent) {
2857            ViewSizeData data = new ViewSizeData();
2858            data.mWidth = newWidth;
2859            data.mHeight = newHeight;
2860            data.mHeightWidthRatio = heightWidthRatio;
2861            data.mActualViewHeight = actualViewHeight;
2862            data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
2863            data.mScale = mZoomManager.getScale();
2864            data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
2865                    && !mHeightCanMeasure;
2866            data.mAnchorX = mZoomManager.getDocumentAnchorX();
2867            data.mAnchorY = mZoomManager.getDocumentAnchorY();
2868            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
2869            mLastWidthSent = newWidth;
2870            mLastHeightSent = newHeight;
2871            mLastActualHeightSent = actualViewHeight;
2872            mZoomManager.clearDocumentAnchor();
2873            return true;
2874        }
2875        return false;
2876    }
2877
2878    private int computeRealHorizontalScrollRange() {
2879        if (mDrawHistory) {
2880            return mHistoryWidth;
2881        } else {
2882            // to avoid rounding error caused unnecessary scrollbar, use floor
2883            return (int) Math.floor(mContentWidth * mZoomManager.getScale());
2884        }
2885    }
2886
2887    @Override
2888    protected int computeHorizontalScrollRange() {
2889        int range = computeRealHorizontalScrollRange();
2890
2891        // Adjust reported range if overscrolled to compress the scroll bars
2892        final int scrollX = mScrollX;
2893        final int overscrollRight = computeMaxScrollX();
2894        if (scrollX < 0) {
2895            range -= scrollX;
2896        } else if (scrollX > overscrollRight) {
2897            range += scrollX - overscrollRight;
2898        }
2899
2900        return range;
2901    }
2902
2903    @Override
2904    protected int computeHorizontalScrollOffset() {
2905        return Math.max(mScrollX, 0);
2906    }
2907
2908    private int computeRealVerticalScrollRange() {
2909        if (mDrawHistory) {
2910            return mHistoryHeight;
2911        } else {
2912            // to avoid rounding error caused unnecessary scrollbar, use floor
2913            return (int) Math.floor(mContentHeight * mZoomManager.getScale());
2914        }
2915    }
2916
2917    @Override
2918    protected int computeVerticalScrollRange() {
2919        int range = computeRealVerticalScrollRange();
2920
2921        // Adjust reported range if overscrolled to compress the scroll bars
2922        final int scrollY = mScrollY;
2923        final int overscrollBottom = computeMaxScrollY();
2924        if (scrollY < 0) {
2925            range -= scrollY;
2926        } else if (scrollY > overscrollBottom) {
2927            range += scrollY - overscrollBottom;
2928        }
2929
2930        return range;
2931    }
2932
2933    @Override
2934    protected int computeVerticalScrollOffset() {
2935        return Math.max(mScrollY - getTitleHeight(), 0);
2936    }
2937
2938    @Override
2939    protected int computeVerticalScrollExtent() {
2940        return getViewHeight();
2941    }
2942
2943    /** @hide */
2944    @Override
2945    protected void onDrawVerticalScrollBar(Canvas canvas,
2946                                           Drawable scrollBar,
2947                                           int l, int t, int r, int b) {
2948        if (mScrollY < 0) {
2949            t -= mScrollY;
2950        }
2951        scrollBar.setBounds(l, t + getVisibleTitleHeightImpl(), r, b);
2952        scrollBar.draw(canvas);
2953    }
2954
2955    @Override
2956    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX,
2957            boolean clampedY) {
2958        // Special-case layer scrolling so that we do not trigger normal scroll
2959        // updating.
2960        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
2961            nativeScrollLayer(mScrollingLayer, scrollX, scrollY);
2962            mScrollingLayerRect.left = scrollX;
2963            mScrollingLayerRect.top = scrollY;
2964            invalidate();
2965            return;
2966        }
2967        mInOverScrollMode = false;
2968        int maxX = computeMaxScrollX();
2969        int maxY = computeMaxScrollY();
2970        if (maxX == 0) {
2971            // do not over scroll x if the page just fits the screen
2972            scrollX = pinLocX(scrollX);
2973        } else if (scrollX < 0 || scrollX > maxX) {
2974            mInOverScrollMode = true;
2975        }
2976        if (scrollY < 0 || scrollY > maxY) {
2977            mInOverScrollMode = true;
2978        }
2979
2980        int oldX = mScrollX;
2981        int oldY = mScrollY;
2982
2983        super.scrollTo(scrollX, scrollY);
2984
2985        if (mOverScrollGlow != null) {
2986            mOverScrollGlow.pullGlow(mScrollX, mScrollY, oldX, oldY, maxX, maxY);
2987        }
2988    }
2989
2990    /**
2991     * Get the url for the current page. This is not always the same as the url
2992     * passed to WebViewClient.onPageStarted because although the load for
2993     * that url has begun, the current page may not have changed.
2994     * @return The url for the current page.
2995     */
2996    public String getUrl() {
2997        checkThread();
2998        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2999        return h != null ? h.getUrl() : null;
3000    }
3001
3002    /**
3003     * Get the original url for the current page. This is not always the same
3004     * as the url passed to WebViewClient.onPageStarted because although the
3005     * load for that url has begun, the current page may not have changed.
3006     * Also, there may have been redirects resulting in a different url to that
3007     * originally requested.
3008     * @return The url that was originally requested for the current page.
3009     */
3010    public String getOriginalUrl() {
3011        checkThread();
3012        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3013        return h != null ? h.getOriginalUrl() : null;
3014    }
3015
3016    /**
3017     * Get the title for the current page. This is the title of the current page
3018     * until WebViewClient.onReceivedTitle is called.
3019     * @return The title for the current page.
3020     */
3021    public String getTitle() {
3022        checkThread();
3023        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3024        return h != null ? h.getTitle() : null;
3025    }
3026
3027    /**
3028     * Get the favicon for the current page. This is the favicon of the current
3029     * page until WebViewClient.onReceivedIcon is called.
3030     * @return The favicon for the current page.
3031     */
3032    public Bitmap getFavicon() {
3033        checkThread();
3034        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3035        return h != null ? h.getFavicon() : null;
3036    }
3037
3038    /**
3039     * Get the touch icon url for the apple-touch-icon <link> element, or
3040     * a URL on this site's server pointing to the standard location of a
3041     * touch icon.
3042     * @hide
3043     */
3044    public String getTouchIconUrl() {
3045        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3046        return h != null ? h.getTouchIconUrl() : null;
3047    }
3048
3049    /**
3050     * Get the progress for the current page.
3051     * @return The progress for the current page between 0 and 100.
3052     */
3053    public int getProgress() {
3054        checkThread();
3055        return mCallbackProxy.getProgress();
3056    }
3057
3058    /**
3059     * @return the height of the HTML content.
3060     */
3061    public int getContentHeight() {
3062        checkThread();
3063        return mContentHeight;
3064    }
3065
3066    /**
3067     * @return the width of the HTML content.
3068     * @hide
3069     */
3070    public int getContentWidth() {
3071        return mContentWidth;
3072    }
3073
3074    /**
3075     * @hide
3076     */
3077    public int getPageBackgroundColor() {
3078        return nativeGetBackgroundColor();
3079    }
3080
3081    /**
3082     * Pause all layout, parsing, and JavaScript timers for all webviews. This
3083     * is a global requests, not restricted to just this webview. This can be
3084     * useful if the application has been paused.
3085     */
3086    public void pauseTimers() {
3087        checkThread();
3088        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
3089    }
3090
3091    /**
3092     * Resume all layout, parsing, and JavaScript timers for all webviews.
3093     * This will resume dispatching all timers.
3094     */
3095    public void resumeTimers() {
3096        checkThread();
3097        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
3098    }
3099
3100    /**
3101     * Call this to pause any extra processing associated with this WebView and
3102     * its associated DOM, plugins, JavaScript etc. For example, if the WebView
3103     * is taken offscreen, this could be called to reduce unnecessary CPU or
3104     * network traffic. When the WebView is again "active", call onResume().
3105     *
3106     * Note that this differs from pauseTimers(), which affects all WebViews.
3107     */
3108    public void onPause() {
3109        checkThread();
3110        if (!mIsPaused) {
3111            mIsPaused = true;
3112            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
3113            // We want to pause the current playing video when switching out
3114            // from the current WebView/tab.
3115            if (mHTML5VideoViewProxy != null) {
3116                mHTML5VideoViewProxy.pauseAndDispatch();
3117            }
3118        }
3119    }
3120
3121    /**
3122     * Call this to resume a WebView after a previous call to onPause().
3123     */
3124    public void onResume() {
3125        checkThread();
3126        if (mIsPaused) {
3127            mIsPaused = false;
3128            mWebViewCore.sendMessage(EventHub.ON_RESUME);
3129        }
3130    }
3131
3132    /**
3133     * Returns true if the view is paused, meaning onPause() was called. Calling
3134     * onResume() sets the paused state back to false.
3135     * @hide
3136     */
3137    public boolean isPaused() {
3138        return mIsPaused;
3139    }
3140
3141    /**
3142     * Call this to inform the view that memory is low so that it can
3143     * free any available memory.
3144     */
3145    public void freeMemory() {
3146        checkThread();
3147        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
3148    }
3149
3150    /**
3151     * Clear the resource cache. Note that the cache is per-application, so
3152     * this will clear the cache for all WebViews used.
3153     *
3154     * @param includeDiskFiles If false, only the RAM cache is cleared.
3155     */
3156    public void clearCache(boolean includeDiskFiles) {
3157        checkThread();
3158        // Note: this really needs to be a static method as it clears cache for all
3159        // WebView. But we need mWebViewCore to send message to WebCore thread, so
3160        // we can't make this static.
3161        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
3162                includeDiskFiles ? 1 : 0, 0);
3163    }
3164
3165    /**
3166     * Make sure that clearing the form data removes the adapter from the
3167     * currently focused textfield if there is one.
3168     */
3169    public void clearFormData() {
3170        checkThread();
3171        if (inEditingMode()) {
3172            AutoCompleteAdapter adapter = null;
3173            mWebTextView.setAdapterCustom(adapter);
3174        }
3175    }
3176
3177    /**
3178     * Tell the WebView to clear its internal back/forward list.
3179     */
3180    public void clearHistory() {
3181        checkThread();
3182        mCallbackProxy.getBackForwardList().setClearPending();
3183        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
3184    }
3185
3186    /**
3187     * Clear the SSL preferences table stored in response to proceeding with SSL
3188     * certificate errors.
3189     */
3190    public void clearSslPreferences() {
3191        checkThread();
3192        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
3193    }
3194
3195    /**
3196     * Return the WebBackForwardList for this WebView. This contains the
3197     * back/forward list for use in querying each item in the history stack.
3198     * This is a copy of the private WebBackForwardList so it contains only a
3199     * snapshot of the current state. Multiple calls to this method may return
3200     * different objects. The object returned from this method will not be
3201     * updated to reflect any new state.
3202     */
3203    public WebBackForwardList copyBackForwardList() {
3204        checkThread();
3205        return mCallbackProxy.getBackForwardList().clone();
3206    }
3207
3208    /*
3209     * Highlight and scroll to the next occurance of String in findAll.
3210     * Wraps the page infinitely, and scrolls.  Must be called after
3211     * calling findAll.
3212     *
3213     * @param forward Direction to search.
3214     */
3215    public void findNext(boolean forward) {
3216        checkThread();
3217        if (0 == mNativeClass) return; // client isn't initialized
3218        nativeFindNext(forward);
3219    }
3220
3221    /*
3222     * Find all instances of find on the page and highlight them.
3223     * @param find  String to find.
3224     * @return int  The number of occurances of the String "find"
3225     *              that were found.
3226     */
3227    public int findAll(String find) {
3228        checkThread();
3229        if (0 == mNativeClass) return 0; // client isn't initialized
3230        int result = find != null ? nativeFindAll(find.toLowerCase(),
3231                find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0;
3232        invalidate();
3233        mLastFind = find;
3234        return result;
3235    }
3236
3237    /**
3238     * Start an ActionMode for finding text in this WebView.  Only works if this
3239     *              WebView is attached to the view system.
3240     * @param text If non-null, will be the initial text to search for.
3241     *             Otherwise, the last String searched for in this WebView will
3242     *             be used to start.
3243     * @param showIme If true, show the IME, assuming the user will begin typing.
3244     *             If false and text is non-null, perform a find all.
3245     * @return boolean True if the find dialog is shown, false otherwise.
3246     */
3247    public boolean showFindDialog(String text, boolean showIme) {
3248        checkThread();
3249        FindActionModeCallback callback = new FindActionModeCallback(mContext);
3250        if (getParent() == null || startActionMode(callback) == null) {
3251            // Could not start the action mode, so end Find on page
3252            return false;
3253        }
3254        mFindCallback = callback;
3255        setFindIsUp(true);
3256        mFindCallback.setWebView(this);
3257        if (showIme) {
3258            mFindCallback.showSoftInput();
3259        } else if (text != null) {
3260            mFindCallback.setText(text);
3261            mFindCallback.findAll();
3262            return true;
3263        }
3264        if (text == null) {
3265            text = mLastFind;
3266        }
3267        if (text != null) {
3268            mFindCallback.setText(text);
3269        }
3270        return true;
3271    }
3272
3273    /**
3274     * Keep track of the find callback so that we can remove its titlebar if
3275     * necessary.
3276     */
3277    private FindActionModeCallback mFindCallback;
3278
3279    /**
3280     * Toggle whether the find dialog is showing, for both native and Java.
3281     */
3282    private void setFindIsUp(boolean isUp) {
3283        mFindIsUp = isUp;
3284        if (0 == mNativeClass) return; // client isn't initialized
3285        nativeSetFindIsUp(isUp);
3286    }
3287
3288    /**
3289     * Return the index of the currently highlighted match.
3290     */
3291    int findIndex() {
3292        if (0 == mNativeClass) return -1;
3293        return nativeFindIndex();
3294    }
3295
3296    // Used to know whether the find dialog is open.  Affects whether
3297    // or not we draw the highlights for matches.
3298    private boolean mFindIsUp;
3299
3300    // Keep track of the last string sent, so we can search again when find is
3301    // reopened.
3302    private String mLastFind;
3303
3304    /**
3305     * Return the first substring consisting of the address of a physical
3306     * location. Currently, only addresses in the United States are detected,
3307     * and consist of:
3308     * - a house number
3309     * - a street name
3310     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3311     * - a city name
3312     * - a state or territory, either spelled out or two-letter abbr.
3313     * - an optional 5 digit or 9 digit zip code.
3314     *
3315     * All names must be correctly capitalized, and the zip code, if present,
3316     * must be valid for the state. The street type must be a standard USPS
3317     * spelling or abbreviation. The state or territory must also be spelled
3318     * or abbreviated using USPS standards. The house number may not exceed
3319     * five digits.
3320     * @param addr The string to search for addresses.
3321     *
3322     * @return the address, or if no address is found, return null.
3323     */
3324    public static String findAddress(String addr) {
3325        checkThread();
3326        return findAddress(addr, false);
3327    }
3328
3329    /**
3330     * @hide
3331     * Return the first substring consisting of the address of a physical
3332     * location. Currently, only addresses in the United States are detected,
3333     * and consist of:
3334     * - a house number
3335     * - a street name
3336     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3337     * - a city name
3338     * - a state or territory, either spelled out or two-letter abbr.
3339     * - an optional 5 digit or 9 digit zip code.
3340     *
3341     * Names are optionally capitalized, and the zip code, if present,
3342     * must be valid for the state. The street type must be a standard USPS
3343     * spelling or abbreviation. The state or territory must also be spelled
3344     * or abbreviated using USPS standards. The house number may not exceed
3345     * five digits.
3346     * @param addr The string to search for addresses.
3347     * @param caseInsensitive addr Set to true to make search ignore case.
3348     *
3349     * @return the address, or if no address is found, return null.
3350     */
3351    public static String findAddress(String addr, boolean caseInsensitive) {
3352        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
3353    }
3354
3355    /*
3356     * Clear the highlighting surrounding text matches created by findAll.
3357     */
3358    public void clearMatches() {
3359        checkThread();
3360        if (mNativeClass == 0)
3361            return;
3362        nativeSetFindIsEmpty();
3363        invalidate();
3364    }
3365
3366    /**
3367     * Called when the find ActionMode ends.
3368     */
3369    void notifyFindDialogDismissed() {
3370        mFindCallback = null;
3371        if (mWebViewCore == null) {
3372            return;
3373        }
3374        clearMatches();
3375        setFindIsUp(false);
3376        // Now that the dialog has been removed, ensure that we scroll to a
3377        // location that is not beyond the end of the page.
3378        pinScrollTo(mScrollX, mScrollY, false, 0);
3379        invalidate();
3380    }
3381
3382    /**
3383     * Query the document to see if it contains any image references. The
3384     * message object will be dispatched with arg1 being set to 1 if images
3385     * were found and 0 if the document does not reference any images.
3386     * @param response The message that will be dispatched with the result.
3387     */
3388    public void documentHasImages(Message response) {
3389        checkThread();
3390        if (response == null) {
3391            return;
3392        }
3393        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
3394    }
3395
3396    /**
3397     * Request the scroller to abort any ongoing animation
3398     *
3399     * @hide
3400     */
3401    public void stopScroll() {
3402        mScroller.forceFinished(true);
3403        mLastVelocity = 0;
3404    }
3405
3406    @Override
3407    public void computeScroll() {
3408        if (mScroller.computeScrollOffset()) {
3409            int oldX = mScrollX;
3410            int oldY = mScrollY;
3411            int x = mScroller.getCurrX();
3412            int y = mScroller.getCurrY();
3413            invalidate();  // So we draw again
3414
3415            if (!mScroller.isFinished()) {
3416                int rangeX = computeMaxScrollX();
3417                int rangeY = computeMaxScrollY();
3418                int overflingDistance = mOverflingDistance;
3419
3420                // Use the layer's scroll data if needed.
3421                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3422                    oldX = mScrollingLayerRect.left;
3423                    oldY = mScrollingLayerRect.top;
3424                    rangeX = mScrollingLayerRect.right;
3425                    rangeY = mScrollingLayerRect.bottom;
3426                    // No overscrolling for layers.
3427                    overflingDistance = 0;
3428                }
3429
3430                overScrollBy(x - oldX, y - oldY, oldX, oldY,
3431                        rangeX, rangeY,
3432                        overflingDistance, overflingDistance, false);
3433
3434                if (mOverScrollGlow != null) {
3435                    mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY);
3436                }
3437            } else {
3438                if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
3439                    mScrollX = x;
3440                    mScrollY = y;
3441                } else {
3442                    // Update the layer position instead of WebView.
3443                    nativeScrollLayer(mScrollingLayer, x, y);
3444                    mScrollingLayerRect.left = x;
3445                    mScrollingLayerRect.top = y;
3446                }
3447                abortAnimation();
3448                mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
3449                if (!mBlockWebkitViewMessages) {
3450                    WebViewCore.resumePriority();
3451                    if (!mSelectingText) {
3452                        WebViewCore.resumeUpdatePicture(mWebViewCore);
3453                    }
3454                }
3455                if (oldX != mScrollX || oldY != mScrollY) {
3456                    sendOurVisibleRect();
3457                }
3458            }
3459        } else {
3460            super.computeScroll();
3461        }
3462    }
3463
3464    private static int computeDuration(int dx, int dy) {
3465        int distance = Math.max(Math.abs(dx), Math.abs(dy));
3466        int duration = distance * 1000 / STD_SPEED;
3467        return Math.min(duration, MAX_DURATION);
3468    }
3469
3470    // helper to pin the scrollBy parameters (already in view coordinates)
3471    // returns true if the scroll was changed
3472    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
3473        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
3474    }
3475    // helper to pin the scrollTo parameters (already in view coordinates)
3476    // returns true if the scroll was changed
3477    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
3478        x = pinLocX(x);
3479        y = pinLocY(y);
3480        int dx = x - mScrollX;
3481        int dy = y - mScrollY;
3482
3483        if ((dx | dy) == 0) {
3484            return false;
3485        }
3486        abortAnimation();
3487        if (animate) {
3488            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
3489            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
3490                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
3491            awakenScrollBars(mScroller.getDuration());
3492            invalidate();
3493        } else {
3494            scrollTo(x, y);
3495        }
3496        return true;
3497    }
3498
3499    // Scale from content to view coordinates, and pin.
3500    // Also called by jni webview.cpp
3501    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
3502        if (mDrawHistory) {
3503            // disallow WebView to change the scroll position as History Picture
3504            // is used in the view system.
3505            // TODO: as we switchOutDrawHistory when trackball or navigation
3506            // keys are hit, this should be safe. Right?
3507            return false;
3508        }
3509        cx = contentToViewDimension(cx);
3510        cy = contentToViewDimension(cy);
3511        if (mHeightCanMeasure) {
3512            // move our visible rect according to scroll request
3513            if (cy != 0) {
3514                Rect tempRect = new Rect();
3515                calcOurVisibleRect(tempRect);
3516                tempRect.offset(cx, cy);
3517                requestRectangleOnScreen(tempRect);
3518            }
3519            // FIXME: We scroll horizontally no matter what because currently
3520            // ScrollView and ListView will not scroll horizontally.
3521            // FIXME: Why do we only scroll horizontally if there is no
3522            // vertical scroll?
3523//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
3524            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
3525        } else {
3526            return pinScrollBy(cx, cy, animate, 0);
3527        }
3528    }
3529
3530    /**
3531     * Called by CallbackProxy when the page starts loading.
3532     * @param url The URL of the page which has started loading.
3533     */
3534    /* package */ void onPageStarted(String url) {
3535        // every time we start a new page, we want to reset the
3536        // WebView certificate:  if the new site is secure, we
3537        // will reload it and get a new certificate set;
3538        // if the new site is not secure, the certificate must be
3539        // null, and that will be the case
3540        setCertificate(null);
3541
3542        // reset the flag since we set to true in if need after
3543        // loading is see onPageFinished(Url)
3544        mAccessibilityScriptInjected = false;
3545    }
3546
3547    /**
3548     * Called by CallbackProxy when the page finishes loading.
3549     * @param url The URL of the page which has finished loading.
3550     */
3551    /* package */ void onPageFinished(String url) {
3552        if (mPageThatNeedsToSlideTitleBarOffScreen != null) {
3553            // If the user is now on a different page, or has scrolled the page
3554            // past the point where the title bar is offscreen, ignore the
3555            // scroll request.
3556            if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url)
3557                    && mScrollX == 0 && mScrollY == 0) {
3558                pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true,
3559                        SLIDE_TITLE_DURATION);
3560            }
3561            mPageThatNeedsToSlideTitleBarOffScreen = null;
3562        }
3563        mZoomManager.onPageFinished(url);
3564        injectAccessibilityForUrl(url);
3565    }
3566
3567    /**
3568     * This method injects accessibility in the loaded document if accessibility
3569     * is enabled. If JavaScript is enabled we try to inject a URL specific script.
3570     * If no URL specific script is found or JavaScript is disabled we fallback to
3571     * the default {@link AccessibilityInjector} implementation.
3572     * </p>
3573     * If the URL has the "axs" paramter set to 1 it has already done the
3574     * script injection so we do nothing. If the parameter is set to 0
3575     * the URL opts out accessibility script injection so we fall back to
3576     * the default {@link AccessibilityInjector}.
3577     * </p>
3578     * Note: If the user has not opted-in the accessibility script injection no scripts
3579     * are injected rather the default {@link AccessibilityInjector} implementation
3580     * is used.
3581     *
3582     * @param url The URL loaded by this {@link WebView}.
3583     */
3584    private void injectAccessibilityForUrl(String url) {
3585        if (mWebViewCore == null) {
3586            return;
3587        }
3588        AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
3589
3590        if (!accessibilityManager.isEnabled()) {
3591            // it is possible that accessibility was turned off between reloads
3592            ensureAccessibilityScriptInjectorInstance(false);
3593            return;
3594        }
3595
3596        if (!getSettings().getJavaScriptEnabled()) {
3597            // no JS so we fallback to the basic buil-in support
3598            ensureAccessibilityScriptInjectorInstance(true);
3599            return;
3600        }
3601
3602        // check the URL "axs" parameter to choose appropriate action
3603        int axsParameterValue = getAxsUrlParameterValue(url);
3604        if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) {
3605            boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext
3606                    .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1);
3607            if (onDeviceScriptInjectionEnabled) {
3608                ensureAccessibilityScriptInjectorInstance(false);
3609                // neither script injected nor script injection opted out => we inject
3610                loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3611                // TODO: Set this flag after successfull script injection. Maybe upon injection
3612                // the chooser should update the meta tag and we check it to declare success
3613                mAccessibilityScriptInjected = true;
3614            } else {
3615                // injection disabled so we fallback to the basic built-in support
3616                ensureAccessibilityScriptInjectorInstance(true);
3617            }
3618        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) {
3619            // injection opted out so we fallback to the basic buil-in support
3620            ensureAccessibilityScriptInjectorInstance(true);
3621        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) {
3622            ensureAccessibilityScriptInjectorInstance(false);
3623            // the URL provides accessibility but we still need to add our generic script
3624            loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3625        } else {
3626            Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue);
3627        }
3628    }
3629
3630    /**
3631     * Ensures the instance of the {@link AccessibilityInjector} to be present ot not.
3632     *
3633     * @param present True to ensure an insance, false to ensure no instance.
3634     */
3635    private void ensureAccessibilityScriptInjectorInstance(boolean present) {
3636        if (present) {
3637            if (mAccessibilityInjector == null) {
3638                mAccessibilityInjector = new AccessibilityInjector(this);
3639            }
3640        } else {
3641            mAccessibilityInjector = null;
3642        }
3643    }
3644
3645    /**
3646     * Gets the "axs" URL parameter value.
3647     *
3648     * @param url A url to fetch the paramter from.
3649     * @return The parameter value if such, -1 otherwise.
3650     */
3651    private int getAxsUrlParameterValue(String url) {
3652        if (mMatchAxsUrlParameterPattern == null) {
3653            mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER);
3654        }
3655        Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url);
3656        if (matcher.find()) {
3657            String keyValuePair = url.substring(matcher.start(), matcher.end());
3658            return Integer.parseInt(keyValuePair.split("=")[1]);
3659        }
3660        return -1;
3661    }
3662
3663    /**
3664     * The URL of a page that sent a message to scroll the title bar off screen.
3665     *
3666     * Many mobile sites tell the page to scroll to (0,1) in order to scroll the
3667     * title bar off the screen.  Sometimes, the scroll position is set before
3668     * the page finishes loading.  Rather than scrolling while the page is still
3669     * loading, keep track of the URL and new scroll position so we can perform
3670     * the scroll once the page finishes loading.
3671     */
3672    private String mPageThatNeedsToSlideTitleBarOffScreen;
3673
3674    /**
3675     * The destination Y scroll position to be used when the page finishes
3676     * loading.  See mPageThatNeedsToSlideTitleBarOffScreen.
3677     */
3678    private int mYDistanceToSlideTitleOffScreen;
3679
3680    // scale from content to view coordinates, and pin
3681    // return true if pin caused the final x/y different than the request cx/cy,
3682    // and a future scroll may reach the request cx/cy after our size has
3683    // changed
3684    // return false if the view scroll to the exact position as it is requested,
3685    // where negative numbers are taken to mean 0
3686    private boolean setContentScrollTo(int cx, int cy) {
3687        if (mDrawHistory) {
3688            // disallow WebView to change the scroll position as History Picture
3689            // is used in the view system.
3690            // One known case where this is called is that WebCore tries to
3691            // restore the scroll position. As history Picture already uses the
3692            // saved scroll position, it is ok to skip this.
3693            return false;
3694        }
3695        int vx;
3696        int vy;
3697        if ((cx | cy) == 0) {
3698            // If the page is being scrolled to (0,0), do not add in the title
3699            // bar's height, and simply scroll to (0,0). (The only other work
3700            // in contentToView_ is to multiply, so this would not change 0.)
3701            vx = 0;
3702            vy = 0;
3703        } else {
3704            vx = contentToViewX(cx);
3705            vy = contentToViewY(cy);
3706        }
3707//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
3708//                      vx + " " + vy + "]");
3709        // Some mobile sites attempt to scroll the title bar off the page by
3710        // scrolling to (0,1).  If we are at the top left corner of the
3711        // page, assume this is an attempt to scroll off the title bar, and
3712        // animate the title bar off screen slowly enough that the user can see
3713        // it.
3714        if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0
3715                && mTitleBar != null) {
3716            // FIXME: 100 should be defined somewhere as our max progress.
3717            if (getProgress() < 100) {
3718                // Wait to scroll the title bar off screen until the page has
3719                // finished loading.  Keep track of the URL and the destination
3720                // Y position
3721                mPageThatNeedsToSlideTitleBarOffScreen = getUrl();
3722                mYDistanceToSlideTitleOffScreen = vy;
3723            } else {
3724                pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
3725            }
3726            // Since we are animating, we have not yet reached the desired
3727            // scroll position.  Do not return true to request another attempt
3728            return false;
3729        }
3730        pinScrollTo(vx, vy, false, 0);
3731        // If the request was to scroll to a negative coordinate, treat it as if
3732        // it was a request to scroll to 0
3733        if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
3734            return true;
3735        } else {
3736            return false;
3737        }
3738    }
3739
3740    // scale from content to view coordinates, and pin
3741    private void spawnContentScrollTo(int cx, int cy) {
3742        if (mDrawHistory) {
3743            // disallow WebView to change the scroll position as History Picture
3744            // is used in the view system.
3745            return;
3746        }
3747        int vx = contentToViewX(cx);
3748        int vy = contentToViewY(cy);
3749        pinScrollTo(vx, vy, true, 0);
3750    }
3751
3752    /**
3753     * These are from webkit, and are in content coordinate system (unzoomed)
3754     */
3755    private void contentSizeChanged(boolean updateLayout) {
3756        // suppress 0,0 since we usually see real dimensions soon after
3757        // this avoids drawing the prev content in a funny place. If we find a
3758        // way to consolidate these notifications, this check may become
3759        // obsolete
3760        if ((mContentWidth | mContentHeight) == 0) {
3761            return;
3762        }
3763
3764        if (mHeightCanMeasure) {
3765            if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
3766                    || updateLayout) {
3767                requestLayout();
3768            }
3769        } else if (mWidthCanMeasure) {
3770            if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
3771                    || updateLayout) {
3772                requestLayout();
3773            }
3774        } else {
3775            // If we don't request a layout, try to send our view size to the
3776            // native side to ensure that WebCore has the correct dimensions.
3777            sendViewSizeZoom(false);
3778        }
3779    }
3780
3781    /**
3782     * Set the WebViewClient that will receive various notifications and
3783     * requests. This will replace the current handler.
3784     * @param client An implementation of WebViewClient.
3785     */
3786    public void setWebViewClient(WebViewClient client) {
3787        checkThread();
3788        mCallbackProxy.setWebViewClient(client);
3789    }
3790
3791    /**
3792     * Gets the WebViewClient
3793     * @return the current WebViewClient instance.
3794     *
3795     *@hide pending API council approval.
3796     */
3797    public WebViewClient getWebViewClient() {
3798        return mCallbackProxy.getWebViewClient();
3799    }
3800
3801    /**
3802     * Register the interface to be used when content can not be handled by
3803     * the rendering engine, and should be downloaded instead. This will replace
3804     * the current handler.
3805     * @param listener An implementation of DownloadListener.
3806     */
3807    public void setDownloadListener(DownloadListener listener) {
3808        checkThread();
3809        mCallbackProxy.setDownloadListener(listener);
3810    }
3811
3812    /**
3813     * Set the chrome handler. This is an implementation of WebChromeClient for
3814     * use in handling JavaScript dialogs, favicons, titles, and the progress.
3815     * This will replace the current handler.
3816     * @param client An implementation of WebChromeClient.
3817     */
3818    public void setWebChromeClient(WebChromeClient client) {
3819        checkThread();
3820        mCallbackProxy.setWebChromeClient(client);
3821    }
3822
3823    /**
3824     * Gets the chrome handler.
3825     * @return the current WebChromeClient instance.
3826     *
3827     * @hide API council approval.
3828     */
3829    public WebChromeClient getWebChromeClient() {
3830        return mCallbackProxy.getWebChromeClient();
3831    }
3832
3833    /**
3834     * Set the back/forward list client. This is an implementation of
3835     * WebBackForwardListClient for handling new items and changes in the
3836     * history index.
3837     * @param client An implementation of WebBackForwardListClient.
3838     * {@hide}
3839     */
3840    public void setWebBackForwardListClient(WebBackForwardListClient client) {
3841        mCallbackProxy.setWebBackForwardListClient(client);
3842    }
3843
3844    /**
3845     * Gets the WebBackForwardListClient.
3846     * {@hide}
3847     */
3848    public WebBackForwardListClient getWebBackForwardListClient() {
3849        return mCallbackProxy.getWebBackForwardListClient();
3850    }
3851
3852    /**
3853     * Set the Picture listener. This is an interface used to receive
3854     * notifications of a new Picture.
3855     * @param listener An implementation of WebView.PictureListener.
3856     * @deprecated This method is now obsolete.
3857     */
3858    @Deprecated
3859    public void setPictureListener(PictureListener listener) {
3860        checkThread();
3861        mPictureListener = listener;
3862    }
3863
3864    /**
3865     * {@hide}
3866     */
3867    /* FIXME: Debug only! Remove for SDK! */
3868    public void externalRepresentation(Message callback) {
3869        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
3870    }
3871
3872    /**
3873     * {@hide}
3874     */
3875    /* FIXME: Debug only! Remove for SDK! */
3876    public void documentAsText(Message callback) {
3877        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
3878    }
3879
3880    /**
3881     * Use this function to bind an object to JavaScript so that the
3882     * methods can be accessed from JavaScript.
3883     * <p><strong>IMPORTANT:</strong>
3884     * <ul>
3885     * <li> Using addJavascriptInterface() allows JavaScript to control your
3886     * application. This can be a very useful feature or a dangerous security
3887     * issue. When the HTML in the WebView is untrustworthy (for example, part
3888     * or all of the HTML is provided by some person or process), then an
3889     * attacker could inject HTML that will execute your code and possibly any
3890     * code of the attacker's choosing.<br>
3891     * Do not use addJavascriptInterface() unless all of the HTML in this
3892     * WebView was written by you.</li>
3893     * <li> The Java object that is bound runs in another thread and not in
3894     * the thread that it was constructed in.</li>
3895     * </ul></p>
3896     * @param obj The class instance to bind to JavaScript, null instances are
3897     *            ignored.
3898     * @param interfaceName The name to used to expose the instance in
3899     *                      JavaScript.
3900     */
3901    public void addJavascriptInterface(Object obj, String interfaceName) {
3902        checkThread();
3903        if (obj == null) {
3904            return;
3905        }
3906        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3907        arg.mObject = obj;
3908        arg.mInterfaceName = interfaceName;
3909        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
3910    }
3911
3912    /**
3913     * Removes a previously added JavaScript interface with the given name.
3914     * @param interfaceName The name of the interface to remove.
3915     */
3916    public void removeJavascriptInterface(String interfaceName) {
3917        checkThread();
3918        if (mWebViewCore != null) {
3919            WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3920            arg.mInterfaceName = interfaceName;
3921            mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg);
3922        }
3923    }
3924
3925    /**
3926     * Return the WebSettings object used to control the settings for this
3927     * WebView.
3928     * @return A WebSettings object that can be used to control this WebView's
3929     *         settings.
3930     */
3931    public WebSettings getSettings() {
3932        checkThread();
3933        return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
3934    }
3935
3936   /**
3937    * Return the list of currently loaded plugins.
3938    * @return The list of currently loaded plugins.
3939    *
3940    * @hide
3941    * @deprecated This was used for Gears, which has been deprecated.
3942    */
3943    @Deprecated
3944    public static synchronized PluginList getPluginList() {
3945        checkThread();
3946        return new PluginList();
3947    }
3948
3949   /**
3950    * @hide
3951    * @deprecated This was used for Gears, which has been deprecated.
3952    */
3953    @Deprecated
3954    public void refreshPlugins(boolean reloadOpenPages) {
3955        checkThread();
3956    }
3957
3958    //-------------------------------------------------------------------------
3959    // Override View methods
3960    //-------------------------------------------------------------------------
3961
3962    @Override
3963    protected void finalize() throws Throwable {
3964        try {
3965            destroyImpl();
3966        } finally {
3967            super.finalize();
3968        }
3969    }
3970
3971    @Override
3972    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3973        if (child == mTitleBar) {
3974            // When drawing the title bar, move it horizontally to always show
3975            // at the top of the WebView.
3976            mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
3977            int newTop = 0;
3978            if (mTitleGravity == Gravity.NO_GRAVITY) {
3979                newTop = Math.min(0, mScrollY);
3980            } else if (mTitleGravity == Gravity.TOP) {
3981                newTop = mScrollY;
3982            }
3983            mTitleBar.setBottom(newTop + mTitleBar.getHeight());
3984            mTitleBar.setTop(newTop);
3985        }
3986        return super.drawChild(canvas, child, drawingTime);
3987    }
3988
3989    private void drawContent(Canvas canvas) {
3990        // Update the buttons in the picture, so when we draw the picture
3991        // to the screen, they are in the correct state.
3992        // Tell the native side if user is a) touching the screen,
3993        // b) pressing the trackball down, or c) pressing the enter key
3994        // If the cursor is on a button, we need to draw it in the pressed
3995        // state.
3996        // If mNativeClass is 0, we should not reach here, so we do not
3997        // need to check it again.
3998        nativeRecordButtons(hasFocus() && hasWindowFocus(),
3999                            mTouchMode == TOUCH_SHORTPRESS_START_MODE
4000                            || mTrackballDown || mGotCenterDown, false);
4001        drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
4002    }
4003
4004    /**
4005     * Draw the background when beyond bounds
4006     * @param canvas Canvas to draw into
4007     */
4008    private void drawOverScrollBackground(Canvas canvas) {
4009        if (mOverScrollBackground == null) {
4010            mOverScrollBackground = new Paint();
4011            Bitmap bm = BitmapFactory.decodeResource(
4012                    mContext.getResources(),
4013                    com.android.internal.R.drawable.status_bar_background);
4014            mOverScrollBackground.setShader(new BitmapShader(bm,
4015                    Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
4016            mOverScrollBorder = new Paint();
4017            mOverScrollBorder.setStyle(Paint.Style.STROKE);
4018            mOverScrollBorder.setStrokeWidth(0);
4019            mOverScrollBorder.setColor(0xffbbbbbb);
4020        }
4021
4022        int top = 0;
4023        int right = computeRealHorizontalScrollRange();
4024        int bottom = top + computeRealVerticalScrollRange();
4025        // first draw the background and anchor to the top of the view
4026        canvas.save();
4027        canvas.translate(mScrollX, mScrollY);
4028        canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom
4029                - mScrollY, Region.Op.DIFFERENCE);
4030        canvas.drawPaint(mOverScrollBackground);
4031        canvas.restore();
4032        // then draw the border
4033        canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder);
4034        // next clip the region for the content
4035        canvas.clipRect(0, top, right, bottom);
4036    }
4037
4038    @Override
4039    protected void onDraw(Canvas canvas) {
4040        // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
4041        if (mNativeClass == 0) {
4042            return;
4043        }
4044
4045        // if both mContentWidth and mContentHeight are 0, it means there is no
4046        // valid Picture passed to WebView yet. This can happen when WebView
4047        // just starts. Draw the background and return.
4048        if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
4049            canvas.drawColor(mBackgroundColor);
4050            return;
4051        }
4052
4053        if (canvas.isHardwareAccelerated()) {
4054            mZoomManager.setHardwareAccelerated();
4055        }
4056
4057        int saveCount = canvas.save();
4058        if (mInOverScrollMode && !getSettings()
4059                .getUseWebViewBackgroundForOverscrollBackground()) {
4060            drawOverScrollBackground(canvas);
4061        }
4062        if (mTitleBar != null) {
4063            canvas.translate(0, getTitleHeight());
4064        }
4065        drawContent(canvas);
4066        canvas.restoreToCount(saveCount);
4067
4068        if (AUTO_REDRAW_HACK && mAutoRedraw) {
4069            invalidate();
4070        }
4071        mWebViewCore.signalRepaintDone();
4072
4073        if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
4074            invalidate();
4075        }
4076
4077        // paint the highlight in the end
4078        if (!mTouchHighlightRegion.isEmpty()) {
4079            if (mTouchHightlightPaint == null) {
4080                mTouchHightlightPaint = new Paint();
4081                mTouchHightlightPaint.setColor(mHightlightColor);
4082                mTouchHightlightPaint.setAntiAlias(true);
4083                mTouchHightlightPaint.setPathEffect(new CornerPathEffect(
4084                        TOUCH_HIGHLIGHT_ARC));
4085            }
4086            canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(),
4087                    mTouchHightlightPaint);
4088        }
4089        if (DEBUG_TOUCH_HIGHLIGHT) {
4090            if (getSettings().getNavDump()) {
4091                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
4092                    if (mTouchCrossHairColor == null) {
4093                        mTouchCrossHairColor = new Paint();
4094                        mTouchCrossHairColor.setColor(Color.RED);
4095                    }
4096                    canvas.drawLine(mTouchHighlightX - mNavSlop,
4097                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4098                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
4099                                    + 1, mTouchCrossHairColor);
4100                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
4101                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4102                                    - mNavSlop,
4103                            mTouchHighlightY + mNavSlop + 1,
4104                            mTouchCrossHairColor);
4105                }
4106            }
4107        }
4108    }
4109
4110    private void removeTouchHighlight(boolean removePendingMessage) {
4111        if (removePendingMessage) {
4112            mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS);
4113        }
4114        mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS);
4115    }
4116
4117    @Override
4118    public void setLayoutParams(ViewGroup.LayoutParams params) {
4119        if (params.height == LayoutParams.WRAP_CONTENT) {
4120            mWrapContent = true;
4121        }
4122        super.setLayoutParams(params);
4123    }
4124
4125    @Override
4126    public boolean performLongClick() {
4127        // performLongClick() is the result of a delayed message. If we switch
4128        // to windows overview, the WebView will be temporarily removed from the
4129        // view system. In that case, do nothing.
4130        if (getParent() == null) return false;
4131
4132        // A multi-finger gesture can look like a long press; make sure we don't take
4133        // long press actions if we're scaling.
4134        final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
4135        if (detector != null && detector.isInProgress()) {
4136            return false;
4137        }
4138
4139        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
4140            // Send the click so that the textfield is in focus
4141            centerKeyPressOnTextField();
4142            rebuildWebTextView();
4143        } else {
4144            clearTextEntry();
4145        }
4146        if (inEditingMode()) {
4147            // Since we just called rebuildWebTextView, the layout is not set
4148            // properly.  Update it so it can correctly find the word to select.
4149            mWebTextView.ensureLayout();
4150            // Provide a touch down event to WebTextView, which will allow it
4151            // to store the location to use in performLongClick.
4152            AbsoluteLayout.LayoutParams params
4153                    = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams();
4154            MotionEvent fake = MotionEvent.obtain(mLastTouchTime,
4155                    mLastTouchTime, MotionEvent.ACTION_DOWN,
4156                    mLastTouchX - params.x + mScrollX,
4157                    mLastTouchY - params.y + mScrollY, 0);
4158            mWebTextView.dispatchTouchEvent(fake);
4159            return mWebTextView.performLongClick();
4160        }
4161        if (mSelectingText) return false; // long click does nothing on selection
4162        /* if long click brings up a context menu, the super function
4163         * returns true and we're done. Otherwise, nothing happened when
4164         * the user clicked. */
4165        if (super.performLongClick()) {
4166            return true;
4167        }
4168        /* In the case where the application hasn't already handled the long
4169         * click action, look for a word under the  click. If one is found,
4170         * animate the text selection into view.
4171         * FIXME: no animation code yet */
4172        return selectText();
4173    }
4174
4175    /**
4176     * Select the word at the last click point.
4177     *
4178     * @hide pending API council approval
4179     */
4180    public boolean selectText() {
4181        int x = viewToContentX(mLastTouchX + mScrollX);
4182        int y = viewToContentY(mLastTouchY + mScrollY);
4183        return selectText(x, y);
4184    }
4185
4186    /**
4187     * Select the word at the indicated content coordinates.
4188     */
4189    boolean selectText(int x, int y) {
4190        if (!setUpSelect(true, x, y)) {
4191            return false;
4192        }
4193        nativeSetExtendSelection();
4194        mDrawSelectionPointer = false;
4195        mSelectionStarted = true;
4196        mTouchMode = TOUCH_DRAG_MODE;
4197        return true;
4198    }
4199
4200    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
4201
4202    @Override
4203    protected void onConfigurationChanged(Configuration newConfig) {
4204        if (mSelectingText && mOrientation != newConfig.orientation) {
4205            selectionDone();
4206        }
4207        mOrientation = newConfig.orientation;
4208    }
4209
4210    /**
4211     * Keep track of the Callback so we can end its ActionMode or remove its
4212     * titlebar.
4213     */
4214    private SelectActionModeCallback mSelectCallback;
4215
4216    // These values are possible options for didUpdateWebTextViewDimensions.
4217    private static final int FULLY_ON_SCREEN = 0;
4218    private static final int INTERSECTS_SCREEN = 1;
4219    private static final int ANYWHERE = 2;
4220
4221    /**
4222     * Check to see if the focused textfield/textarea is still on screen.  If it
4223     * is, update the the dimensions and location of WebTextView.  Otherwise,
4224     * remove the WebTextView.  Should be called when the zoom level changes.
4225     * @param intersection How to determine whether the textfield/textarea is
4226     *        still on screen.
4227     * @return boolean True if the textfield/textarea is still on screen and the
4228     *         dimensions/location of WebTextView have been updated.
4229     */
4230    private boolean didUpdateWebTextViewDimensions(int intersection) {
4231        Rect contentBounds = nativeFocusCandidateNodeBounds();
4232        Rect vBox = contentToViewRect(contentBounds);
4233        Rect visibleRect = new Rect();
4234        calcOurVisibleRect(visibleRect);
4235        // If the textfield is on screen, place the WebTextView in
4236        // its new place, accounting for our new scroll/zoom values,
4237        // and adjust its textsize.
4238        boolean onScreen;
4239        switch (intersection) {
4240            case FULLY_ON_SCREEN:
4241                onScreen = visibleRect.contains(vBox);
4242                break;
4243            case INTERSECTS_SCREEN:
4244                onScreen = Rect.intersects(visibleRect, vBox);
4245                break;
4246            case ANYWHERE:
4247                onScreen = true;
4248                break;
4249            default:
4250                throw new AssertionError(
4251                        "invalid parameter passed to didUpdateWebTextViewDimensions");
4252        }
4253        if (onScreen) {
4254            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
4255                    vBox.height());
4256            mWebTextView.updateTextSize();
4257            updateWebTextViewPadding();
4258            return true;
4259        } else {
4260            // The textfield is now off screen.  The user probably
4261            // was not zooming to see the textfield better.  Remove
4262            // the WebTextView.  If the user types a key, and the
4263            // textfield is still in focus, we will reconstruct
4264            // the WebTextView and scroll it back on screen.
4265            mWebTextView.remove();
4266            return false;
4267        }
4268    }
4269
4270    void setBaseLayer(int layer, Region invalRegion, boolean showVisualIndicator,
4271            boolean isPictureAfterFirstLayout) {
4272        if (mNativeClass == 0)
4273            return;
4274        nativeSetBaseLayer(layer, invalRegion, showVisualIndicator,
4275                isPictureAfterFirstLayout);
4276        if (mHTML5VideoViewProxy != null) {
4277            mHTML5VideoViewProxy.setBaseLayer(layer);
4278        }
4279    }
4280
4281    int getBaseLayer() {
4282        return nativeGetBaseLayer();
4283    }
4284
4285    private void onZoomAnimationStart() {
4286        // If it is in password mode, turn it off so it does not draw misplaced.
4287        if (inEditingMode()) {
4288            mWebTextView.setVisibility(INVISIBLE);
4289        }
4290    }
4291
4292    private void onZoomAnimationEnd() {
4293        // adjust the edit text view if needed
4294        if (inEditingMode()
4295                && didUpdateWebTextViewDimensions(FULLY_ON_SCREEN)) {
4296            // If it is a password field, start drawing the WebTextView once
4297            // again.
4298            mWebTextView.setVisibility(VISIBLE);
4299        }
4300    }
4301
4302    void onFixedLengthZoomAnimationStart() {
4303        WebViewCore.pauseUpdatePicture(getWebViewCore());
4304        onZoomAnimationStart();
4305    }
4306
4307    void onFixedLengthZoomAnimationEnd() {
4308        if (!mBlockWebkitViewMessages && !mSelectingText) {
4309            WebViewCore.resumeUpdatePicture(mWebViewCore);
4310        }
4311        onZoomAnimationEnd();
4312    }
4313
4314    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4315                                         Paint.DITHER_FLAG |
4316                                         Paint.SUBPIXEL_TEXT_FLAG;
4317    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
4318                                           Paint.DITHER_FLAG;
4319
4320    private final DrawFilter mZoomFilter =
4321            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4322    // If we need to trade better quality for speed, set mScrollFilter to null
4323    private final DrawFilter mScrollFilter =
4324            new PaintFlagsDrawFilter(SCROLL_BITS, 0);
4325
4326    private void drawCoreAndCursorRing(Canvas canvas, int color,
4327        boolean drawCursorRing) {
4328        if (mDrawHistory) {
4329            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4330            canvas.drawPicture(mHistoryPicture);
4331            return;
4332        }
4333        if (mNativeClass == 0) return;
4334
4335        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
4336        boolean animateScroll = ((!mScroller.isFinished()
4337                || mVelocityTracker != null)
4338                && (mTouchMode != TOUCH_DRAG_MODE ||
4339                mHeldMotionless != MOTIONLESS_TRUE))
4340                || mDeferTouchMode == TOUCH_DRAG_MODE;
4341        if (mTouchMode == TOUCH_DRAG_MODE) {
4342            if (mHeldMotionless == MOTIONLESS_PENDING) {
4343                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4344                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4345                mHeldMotionless = MOTIONLESS_FALSE;
4346            }
4347            if (mHeldMotionless == MOTIONLESS_FALSE) {
4348                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4349                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
4350                mHeldMotionless = MOTIONLESS_PENDING;
4351            }
4352        }
4353        if (animateZoom) {
4354            mZoomManager.animateZoom(canvas);
4355        } else if (!canvas.isHardwareAccelerated()) {
4356            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4357        }
4358
4359        boolean UIAnimationsRunning = false;
4360        // Currently for each draw we compute the animation values;
4361        // We may in the future decide to do that independently.
4362        if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) {
4363            UIAnimationsRunning = true;
4364            // If we have unfinished (or unstarted) animations,
4365            // we ask for a repaint. We only need to do this in software
4366            // rendering (with hardware rendering we already have a different
4367            // method of requesting a repaint)
4368            if (!canvas.isHardwareAccelerated())
4369                invalidate();
4370        }
4371
4372        // decide which adornments to draw
4373        int extras = DRAW_EXTRAS_NONE;
4374        if (mFindIsUp) {
4375            extras = DRAW_EXTRAS_FIND;
4376        } else if (mSelectingText) {
4377            extras = DRAW_EXTRAS_SELECTION;
4378            nativeSetSelectionPointer(mDrawSelectionPointer,
4379                    mZoomManager.getInvScale(),
4380                    mSelectX, mSelectY - getTitleHeight());
4381        } else if (drawCursorRing) {
4382            extras = DRAW_EXTRAS_CURSOR_RING;
4383        }
4384        if (DebugFlags.WEB_VIEW) {
4385            Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp
4386                    + " mSelectingText=" + mSelectingText
4387                    + " nativePageShouldHandleShiftAndArrows()="
4388                    + nativePageShouldHandleShiftAndArrows()
4389                    + " animateZoom=" + animateZoom
4390                    + " extras=" + extras);
4391        }
4392
4393        if (canvas.isHardwareAccelerated()) {
4394            int functor = nativeGetDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport,
4395                    mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras);
4396            ((HardwareCanvas) canvas).callDrawGLFunction(functor);
4397        } else {
4398            DrawFilter df = null;
4399            if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
4400                df = mZoomFilter;
4401            } else if (animateScroll) {
4402                df = mScrollFilter;
4403            }
4404            canvas.setDrawFilter(df);
4405            // XXX: Revisit splitting content.  Right now it causes a
4406            // synchronization problem with layers.
4407            int content = nativeDraw(canvas, color, extras, false);
4408            canvas.setDrawFilter(null);
4409            if (!mBlockWebkitViewMessages && content != 0) {
4410                mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
4411            }
4412        }
4413
4414        if (extras == DRAW_EXTRAS_CURSOR_RING) {
4415            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
4416                mTouchMode = TOUCH_SHORTPRESS_MODE;
4417            }
4418        }
4419        if (mFocusSizeChanged) {
4420            mFocusSizeChanged = false;
4421            // If we are zooming, this will get handled above, when the zoom
4422            // finishes.  We also do not need to do this unless the WebTextView
4423            // is showing.
4424            if (!animateZoom && inEditingMode()) {
4425                didUpdateWebTextViewDimensions(ANYWHERE);
4426            }
4427        }
4428    }
4429
4430    // draw history
4431    private boolean mDrawHistory = false;
4432    private Picture mHistoryPicture = null;
4433    private int mHistoryWidth = 0;
4434    private int mHistoryHeight = 0;
4435
4436    // Only check the flag, can be called from WebCore thread
4437    boolean drawHistory() {
4438        return mDrawHistory;
4439    }
4440
4441    int getHistoryPictureWidth() {
4442        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
4443    }
4444
4445    // Should only be called in UI thread
4446    void switchOutDrawHistory() {
4447        if (null == mWebViewCore) return; // CallbackProxy may trigger this
4448        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
4449            mDrawHistory = false;
4450            mHistoryPicture = null;
4451            invalidate();
4452            int oldScrollX = mScrollX;
4453            int oldScrollY = mScrollY;
4454            mScrollX = pinLocX(mScrollX);
4455            mScrollY = pinLocY(mScrollY);
4456            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
4457                onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY);
4458            } else {
4459                sendOurVisibleRect();
4460            }
4461        }
4462    }
4463
4464    WebViewCore.CursorData cursorData() {
4465        WebViewCore.CursorData result = cursorDataNoPosition();
4466        Point position = nativeCursorPosition();
4467        result.mX = position.x;
4468        result.mY = position.y;
4469        return result;
4470    }
4471
4472    WebViewCore.CursorData cursorDataNoPosition() {
4473        WebViewCore.CursorData result = new WebViewCore.CursorData();
4474        result.mMoveGeneration = nativeMoveGeneration();
4475        result.mFrame = nativeCursorFramePointer();
4476        return result;
4477    }
4478
4479    /**
4480     *  Delete text from start to end in the focused textfield. If there is no
4481     *  focus, or if start == end, silently fail.  If start and end are out of
4482     *  order, swap them.
4483     *  @param  start   Beginning of selection to delete.
4484     *  @param  end     End of selection to delete.
4485     */
4486    /* package */ void deleteSelection(int start, int end) {
4487        mTextGeneration++;
4488        WebViewCore.TextSelectionData data
4489                = new WebViewCore.TextSelectionData(start, end);
4490        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
4491                data);
4492    }
4493
4494    /**
4495     *  Set the selection to (start, end) in the focused textfield. If start and
4496     *  end are out of order, swap them.
4497     *  @param  start   Beginning of selection.
4498     *  @param  end     End of selection.
4499     */
4500    /* package */ void setSelection(int start, int end) {
4501        if (mWebViewCore != null) {
4502            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
4503        }
4504    }
4505
4506    @Override
4507    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4508      InputConnection connection = super.onCreateInputConnection(outAttrs);
4509      outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN;
4510      return connection;
4511    }
4512
4513    /**
4514     * Called in response to a message from webkit telling us that the soft
4515     * keyboard should be launched.
4516     */
4517    private void displaySoftKeyboard(boolean isTextView) {
4518        InputMethodManager imm = (InputMethodManager)
4519                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
4520
4521        // bring it back to the default level scale so that user can enter text
4522        boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
4523        if (zoom) {
4524            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
4525            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
4526        }
4527        if (isTextView) {
4528            rebuildWebTextView();
4529            if (inEditingMode()) {
4530                imm.showSoftInput(mWebTextView, 0, mWebTextView.getResultReceiver());
4531                if (zoom) {
4532                    didUpdateWebTextViewDimensions(INTERSECTS_SCREEN);
4533                }
4534                return;
4535            }
4536        }
4537        // Used by plugins and contentEditable.
4538        // Also used if the navigation cache is out of date, and
4539        // does not recognize that a textfield is in focus.  In that
4540        // case, use WebView as the targeted view.
4541        // see http://b/issue?id=2457459
4542        imm.showSoftInput(this, 0);
4543    }
4544
4545    // Called by WebKit to instruct the UI to hide the keyboard
4546    private void hideSoftKeyboard() {
4547        InputMethodManager imm = InputMethodManager.peekInstance();
4548        if (imm != null && (imm.isActive(this)
4549                || (inEditingMode() && imm.isActive(mWebTextView)))) {
4550            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
4551        }
4552    }
4553
4554    /*
4555     * This method checks the current focus and cursor and potentially rebuilds
4556     * mWebTextView to have the appropriate properties, such as password,
4557     * multiline, and what text it contains.  It also removes it if necessary.
4558     */
4559    /* package */ void rebuildWebTextView() {
4560        // If the WebView does not have focus, do nothing until it gains focus.
4561        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
4562            return;
4563        }
4564        boolean alreadyThere = inEditingMode();
4565        // inEditingMode can only return true if mWebTextView is non-null,
4566        // so we can safely call remove() if (alreadyThere)
4567        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
4568            if (alreadyThere) {
4569                mWebTextView.remove();
4570            }
4571            return;
4572        }
4573        // At this point, we know we have found an input field, so go ahead
4574        // and create the WebTextView if necessary.
4575        if (mWebTextView == null) {
4576            mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId());
4577            // Initialize our generation number.
4578            mTextGeneration = 0;
4579        }
4580        mWebTextView.updateTextSize();
4581        Rect visibleRect = new Rect();
4582        calcOurContentVisibleRect(visibleRect);
4583        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
4584        // should be in content coordinates.
4585        Rect bounds = nativeFocusCandidateNodeBounds();
4586        Rect vBox = contentToViewRect(bounds);
4587        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
4588        if (!Rect.intersects(bounds, visibleRect)) {
4589            revealSelection();
4590        }
4591        String text = nativeFocusCandidateText();
4592        int nodePointer = nativeFocusCandidatePointer();
4593        mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
4594                Gravity.RIGHT : Gravity.NO_GRAVITY);
4595        // This needs to be called before setType, which may call
4596        // requestFormData, and it needs to have the correct nodePointer.
4597        mWebTextView.setNodePointer(nodePointer);
4598        mWebTextView.setType(nativeFocusCandidateType());
4599        updateWebTextViewPadding();
4600        if (null == text) {
4601            if (DebugFlags.WEB_VIEW) {
4602                Log.v(LOGTAG, "rebuildWebTextView null == text");
4603            }
4604            text = "";
4605        }
4606        mWebTextView.setTextAndKeepSelection(text);
4607        InputMethodManager imm = InputMethodManager.peekInstance();
4608        if (imm != null && imm.isActive(mWebTextView)) {
4609            imm.restartInput(mWebTextView);
4610        }
4611        if (isFocused()) {
4612            mWebTextView.requestFocus();
4613        }
4614    }
4615
4616    /**
4617     * Update the padding of mWebTextView based on the native textfield/textarea
4618     */
4619    void updateWebTextViewPadding() {
4620        Rect paddingRect = nativeFocusCandidatePaddingRect();
4621        if (paddingRect != null) {
4622            // Use contentToViewDimension since these are the dimensions of
4623            // the padding.
4624            mWebTextView.setPadding(
4625                    contentToViewDimension(paddingRect.left),
4626                    contentToViewDimension(paddingRect.top),
4627                    contentToViewDimension(paddingRect.right),
4628                    contentToViewDimension(paddingRect.bottom));
4629        }
4630    }
4631
4632    /**
4633     * Tell webkit to put the cursor on screen.
4634     */
4635    /* package */ void revealSelection() {
4636        if (mWebViewCore != null) {
4637            mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION);
4638        }
4639    }
4640
4641    /**
4642     * Called by WebTextView to find saved form data associated with the
4643     * textfield
4644     * @param name Name of the textfield.
4645     * @param nodePointer Pointer to the node of the textfield, so it can be
4646     *          compared to the currently focused textfield when the data is
4647     *          retrieved.
4648     * @param autoFillable true if WebKit has determined this field is part of
4649     *          a form that can be auto filled.
4650     * @param autoComplete true if the attribute "autocomplete" is set to true
4651     *          on the textfield.
4652     */
4653    /* package */ void requestFormData(String name, int nodePointer,
4654            boolean autoFillable, boolean autoComplete) {
4655        if (mWebViewCore.getSettings().getSaveFormData()) {
4656            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
4657            update.arg1 = nodePointer;
4658            RequestFormData updater = new RequestFormData(name, getUrl(),
4659                    update, autoFillable, autoComplete);
4660            Thread t = new Thread(updater);
4661            t.start();
4662        }
4663    }
4664
4665    /**
4666     * Pass a message to find out the <label> associated with the <input>
4667     * identified by nodePointer
4668     * @param framePointer Pointer to the frame containing the <input> node
4669     * @param nodePointer Pointer to the node for which a <label> is desired.
4670     */
4671    /* package */ void requestLabel(int framePointer, int nodePointer) {
4672        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
4673                nodePointer);
4674    }
4675
4676    /*
4677     * This class requests an Adapter for the WebTextView which shows past
4678     * entries stored in the database.  It is a Runnable so that it can be done
4679     * in its own thread, without slowing down the UI.
4680     */
4681    private class RequestFormData implements Runnable {
4682        private String mName;
4683        private String mUrl;
4684        private Message mUpdateMessage;
4685        private boolean mAutoFillable;
4686        private boolean mAutoComplete;
4687        private WebSettings mWebSettings;
4688
4689        public RequestFormData(String name, String url, Message msg,
4690                boolean autoFillable, boolean autoComplete) {
4691            mName = name;
4692            mUrl = url;
4693            mUpdateMessage = msg;
4694            mAutoFillable = autoFillable;
4695            mAutoComplete = autoComplete;
4696            mWebSettings = getSettings();
4697        }
4698
4699        public void run() {
4700            ArrayList<String> pastEntries = new ArrayList<String>();
4701
4702            if (mAutoFillable) {
4703                // Note that code inside the adapter click handler in WebTextView depends
4704                // on the AutoFill item being at the top of the drop down list. If you change
4705                // the order, make sure to do it there too!
4706                if (mWebSettings != null && mWebSettings.getAutoFillProfile() != null) {
4707                    pastEntries.add(getResources().getText(
4708                            com.android.internal.R.string.autofill_this_form).toString() +
4709                            " " +
4710                            mAutoFillData.getPreviewString());
4711                    mWebTextView.setAutoFillProfileIsSet(true);
4712                } else {
4713                    // There is no autofill profile set up yet, so add an option that
4714                    // will invite the user to set their profile up.
4715                    pastEntries.add(getResources().getText(
4716                            com.android.internal.R.string.setup_autofill).toString());
4717                    mWebTextView.setAutoFillProfileIsSet(false);
4718                }
4719            }
4720
4721            if (mAutoComplete) {
4722                pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
4723            }
4724
4725            if (pastEntries.size() > 0) {
4726                AutoCompleteAdapter adapter = new
4727                        AutoCompleteAdapter(mContext, pastEntries);
4728                mUpdateMessage.obj = adapter;
4729                mUpdateMessage.sendToTarget();
4730            }
4731        }
4732    }
4733
4734    /**
4735     * Dump the display tree to "/sdcard/displayTree.txt"
4736     *
4737     * @hide debug only
4738     */
4739    public void dumpDisplayTree() {
4740        nativeDumpDisplayTree(getUrl());
4741    }
4742
4743    /**
4744     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
4745     * "/sdcard/domTree.txt"
4746     *
4747     * @hide debug only
4748     */
4749    public void dumpDomTree(boolean toFile) {
4750        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
4751    }
4752
4753    /**
4754     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
4755     * to "/sdcard/renderTree.txt"
4756     *
4757     * @hide debug only
4758     */
4759    public void dumpRenderTree(boolean toFile) {
4760        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
4761    }
4762
4763    /**
4764     * Called by DRT on UI thread, need to proxy to WebCore thread.
4765     *
4766     * @hide debug only
4767     */
4768    public void useMockDeviceOrientation() {
4769        mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
4770    }
4771
4772    /**
4773     * Called by DRT on WebCore thread.
4774     *
4775     * @hide debug only
4776     */
4777    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
4778            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
4779        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
4780                canProvideGamma, gamma);
4781    }
4782
4783    /**
4784     * Dump the V8 counters to standard output.
4785     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
4786     * true. Otherwise, this will do nothing.
4787     *
4788     * @hide debug only
4789     */
4790    public void dumpV8Counters() {
4791        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
4792    }
4793
4794    // This is used to determine long press with the center key.  Does not
4795    // affect long press with the trackball/touch.
4796    private boolean mGotCenterDown = false;
4797
4798    @Override
4799    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4800        if (mBlockWebkitViewMessages) {
4801            return false;
4802        }
4803        // send complex characters to webkit for use by JS and plugins
4804        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
4805            // pass the key to DOM
4806            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4807            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4808            // return true as DOM handles the key
4809            return true;
4810        }
4811        return false;
4812    }
4813
4814    private boolean isEnterActionKey(int keyCode) {
4815        return keyCode == KeyEvent.KEYCODE_DPAD_CENTER
4816                || keyCode == KeyEvent.KEYCODE_ENTER
4817                || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER;
4818    }
4819
4820    @Override
4821    public boolean onKeyDown(int keyCode, KeyEvent event) {
4822        if (DebugFlags.WEB_VIEW) {
4823            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
4824                    + "keyCode=" + keyCode
4825                    + ", " + event + ", unicode=" + event.getUnicodeChar());
4826        }
4827        if (mBlockWebkitViewMessages) {
4828            return false;
4829        }
4830
4831        // don't implement accelerator keys here; defer to host application
4832        if (event.isCtrlPressed()) {
4833            return false;
4834        }
4835
4836        if (mNativeClass == 0) {
4837            return false;
4838        }
4839
4840        // do this hack up front, so it always works, regardless of touch-mode
4841        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
4842            mAutoRedraw = !mAutoRedraw;
4843            if (mAutoRedraw) {
4844                invalidate();
4845            }
4846            return true;
4847        }
4848
4849        // Bubble up the key event if
4850        // 1. it is a system key; or
4851        // 2. the host application wants to handle it;
4852        if (event.isSystem()
4853                || mCallbackProxy.uiOverrideKeyEvent(event)) {
4854            return false;
4855        }
4856
4857        // accessibility support
4858        if (accessibilityScriptInjected()) {
4859            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4860                // if an accessibility script is injected we delegate to it the key handling.
4861                // this script is a screen reader which is a fully fledged solution for blind
4862                // users to navigate in and interact with web pages.
4863                mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4864                return true;
4865            } else {
4866                // Clean up if accessibility was disabled after loading the current URL.
4867                mAccessibilityScriptInjected = false;
4868            }
4869        } else if (mAccessibilityInjector != null) {
4870            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4871                if (mAccessibilityInjector.onKeyEvent(event)) {
4872                    // if an accessibility injector is present (no JavaScript enabled or the site
4873                    // opts out injecting our JavaScript screen reader) we let it decide whether
4874                    // to act on and consume the event.
4875                    return true;
4876                }
4877            } else {
4878                // Clean up if accessibility was disabled after loading the current URL.
4879                mAccessibilityInjector = null;
4880            }
4881        }
4882
4883        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
4884            if (event.hasNoModifiers()) {
4885                pageUp(false);
4886                return true;
4887            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4888                pageUp(true);
4889                return true;
4890            }
4891        }
4892
4893        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
4894            if (event.hasNoModifiers()) {
4895                pageDown(false);
4896                return true;
4897            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4898                pageDown(true);
4899                return true;
4900            }
4901        }
4902
4903        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) {
4904            pageUp(true);
4905            return true;
4906        }
4907
4908        if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) {
4909            pageDown(true);
4910            return true;
4911        }
4912
4913        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4914                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
4915            switchOutDrawHistory();
4916            if (nativePageShouldHandleShiftAndArrows()) {
4917                letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState());
4918                return true;
4919            }
4920            if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4921                switch (keyCode) {
4922                    case KeyEvent.KEYCODE_DPAD_UP:
4923                        pageUp(true);
4924                        return true;
4925                    case KeyEvent.KEYCODE_DPAD_DOWN:
4926                        pageDown(true);
4927                        return true;
4928                    case KeyEvent.KEYCODE_DPAD_LEFT:
4929                        nativeClearCursor(); // start next trackball movement from page edge
4930                        return pinScrollTo(0, mScrollY, true, 0);
4931                    case KeyEvent.KEYCODE_DPAD_RIGHT:
4932                        nativeClearCursor(); // start next trackball movement from page edge
4933                        return pinScrollTo(mContentWidth, mScrollY, true, 0);
4934                }
4935            }
4936            if (mSelectingText) {
4937                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
4938                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
4939                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
4940                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
4941                int multiplier = event.getRepeatCount() + 1;
4942                moveSelection(xRate * multiplier, yRate * multiplier);
4943                return true;
4944            }
4945            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
4946                playSoundEffect(keyCodeToSoundsEffect(keyCode));
4947                return true;
4948            }
4949            // Bubble up the key event as WebView doesn't handle it
4950            return false;
4951        }
4952
4953        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
4954            switchOutDrawHistory();
4955            boolean wantsKeyEvents = nativeCursorNodePointer() == 0
4956                || nativeCursorWantsKeyEvents();
4957            if (event.getRepeatCount() == 0) {
4958                if (mSelectingText) {
4959                    return true; // discard press if copy in progress
4960                }
4961                mGotCenterDown = true;
4962                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4963                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
4964                // Already checked mNativeClass, so we do not need to check it
4965                // again.
4966                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4967                if (!wantsKeyEvents) return true;
4968            }
4969            // Bubble up the key event as WebView doesn't handle it
4970            if (!wantsKeyEvents) return false;
4971        }
4972
4973        if (getSettings().getNavDump()) {
4974            switch (keyCode) {
4975                case KeyEvent.KEYCODE_4:
4976                    dumpDisplayTree();
4977                    break;
4978                case KeyEvent.KEYCODE_5:
4979                case KeyEvent.KEYCODE_6:
4980                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
4981                    break;
4982                case KeyEvent.KEYCODE_7:
4983                case KeyEvent.KEYCODE_8:
4984                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
4985                    break;
4986                case KeyEvent.KEYCODE_9:
4987                    nativeInstrumentReport();
4988                    return true;
4989            }
4990        }
4991
4992        if (nativeCursorIsTextInput()) {
4993            // This message will put the node in focus, for the DOM's notion
4994            // of focus.
4995            mWebViewCore.sendMessage(EventHub.FAKE_CLICK, nativeCursorFramePointer(),
4996                    nativeCursorNodePointer());
4997            // This will bring up the WebTextView and put it in focus, for
4998            // our view system's notion of focus
4999            rebuildWebTextView();
5000            // Now we need to pass the event to it
5001            if (inEditingMode()) {
5002                mWebTextView.setDefaultSelection();
5003                return mWebTextView.dispatchKeyEvent(event);
5004            }
5005        } else if (nativeHasFocusNode()) {
5006            // In this case, the cursor is not on a text input, but the focus
5007            // might be.  Check it, and if so, hand over to the WebTextView.
5008            rebuildWebTextView();
5009            if (inEditingMode()) {
5010                mWebTextView.setDefaultSelection();
5011                return mWebTextView.dispatchKeyEvent(event);
5012            }
5013        }
5014
5015        // TODO: should we pass all the keys to DOM or check the meta tag
5016        if (nativeCursorWantsKeyEvents() || true) {
5017            // pass the key to DOM
5018            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5019            // return true as DOM handles the key
5020            return true;
5021        }
5022
5023        // Bubble up the key event as WebView doesn't handle it
5024        return false;
5025    }
5026
5027    @Override
5028    public boolean onKeyUp(int keyCode, KeyEvent event) {
5029        if (DebugFlags.WEB_VIEW) {
5030            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
5031                    + ", " + event + ", unicode=" + event.getUnicodeChar());
5032        }
5033        if (mBlockWebkitViewMessages) {
5034            return false;
5035        }
5036
5037        if (mNativeClass == 0) {
5038            return false;
5039        }
5040
5041        // special CALL handling when cursor node's href is "tel:XXX"
5042        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
5043            String text = nativeCursorText();
5044            if (!nativeCursorIsTextInput() && text != null
5045                    && text.startsWith(SCHEME_TEL)) {
5046                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
5047                getContext().startActivity(intent);
5048                return true;
5049            }
5050        }
5051
5052        // Bubble up the key event if
5053        // 1. it is a system key; or
5054        // 2. the host application wants to handle it;
5055        if (event.isSystem()
5056                || mCallbackProxy.uiOverrideKeyEvent(event)) {
5057            return false;
5058        }
5059
5060        // accessibility support
5061        if (accessibilityScriptInjected()) {
5062            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5063                // if an accessibility script is injected we delegate to it the key handling.
5064                // this script is a screen reader which is a fully fledged solution for blind
5065                // users to navigate in and interact with web pages.
5066                mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5067                return true;
5068            } else {
5069                // Clean up if accessibility was disabled after loading the current URL.
5070                mAccessibilityScriptInjected = false;
5071            }
5072        } else if (mAccessibilityInjector != null) {
5073            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5074                if (mAccessibilityInjector.onKeyEvent(event)) {
5075                    // if an accessibility injector is present (no JavaScript enabled or the site
5076                    // opts out injecting our JavaScript screen reader) we let it decide whether to
5077                    // act on and consume the event.
5078                    return true;
5079                }
5080            } else {
5081                // Clean up if accessibility was disabled after loading the current URL.
5082                mAccessibilityInjector = null;
5083            }
5084        }
5085
5086        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
5087                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
5088            if (nativePageShouldHandleShiftAndArrows()) {
5089                letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState());
5090                return true;
5091            }
5092            // always handle the navigation keys in the UI thread
5093            // Bubble up the key event as WebView doesn't handle it
5094            return false;
5095        }
5096
5097        if (isEnterActionKey(keyCode)) {
5098            // remove the long press message first
5099            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5100            mGotCenterDown = false;
5101
5102            if (mSelectingText) {
5103                if (mExtendSelection) {
5104                    copySelection();
5105                    selectionDone();
5106                } else {
5107                    mExtendSelection = true;
5108                    nativeSetExtendSelection();
5109                    invalidate(); // draw the i-beam instead of the arrow
5110                }
5111                return true; // discard press if copy in progress
5112            }
5113
5114            // perform the single click
5115            Rect visibleRect = sendOurVisibleRect();
5116            // Note that sendOurVisibleRect calls viewToContent, so the
5117            // coordinates should be in content coordinates.
5118            if (!nativeCursorIntersects(visibleRect)) {
5119                return false;
5120            }
5121            WebViewCore.CursorData data = cursorData();
5122            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
5123            playSoundEffect(SoundEffectConstants.CLICK);
5124            if (nativeCursorIsTextInput()) {
5125                rebuildWebTextView();
5126                centerKeyPressOnTextField();
5127                if (inEditingMode()) {
5128                    mWebTextView.setDefaultSelection();
5129                }
5130                return true;
5131            }
5132            clearTextEntry();
5133            nativeShowCursorTimed();
5134            if (mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
5135                return true;
5136            }
5137            if (nativeCursorNodePointer() != 0 && !nativeCursorWantsKeyEvents()) {
5138                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
5139                        nativeCursorNodePointer());
5140                return true;
5141            }
5142        }
5143
5144        // TODO: should we pass all the keys to DOM or check the meta tag
5145        if (nativeCursorWantsKeyEvents() || true) {
5146            // pass the key to DOM
5147            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5148            // return true as DOM handles the key
5149            return true;
5150        }
5151
5152        // Bubble up the key event as WebView doesn't handle it
5153        return false;
5154    }
5155
5156    /*
5157     * Enter selecting text mode, and see if CAB should be shown.
5158     * Returns true if the WebView is now in
5159     * selecting text mode (including if it was already in that mode, and this
5160     * method did nothing).
5161     */
5162    private boolean setUpSelect(boolean selectWord, int x, int y) {
5163        if (0 == mNativeClass) return false; // client isn't initialized
5164        if (inFullScreenMode()) return false;
5165        if (mSelectingText) return true;
5166        nativeResetSelection();
5167        if (selectWord && !nativeWordSelection(x, y)) {
5168            selectionDone();
5169            return false;
5170        }
5171        mSelectCallback = new SelectActionModeCallback();
5172        mSelectCallback.setWebView(this);
5173        if (startActionMode(mSelectCallback) == null) {
5174            // There is no ActionMode, so do not allow the user to modify a
5175            // selection.
5176            selectionDone();
5177            return false;
5178        }
5179        mExtendSelection = false;
5180        mSelectingText = mDrawSelectionPointer = true;
5181        // don't let the picture change during text selection
5182        WebViewCore.pauseUpdatePicture(mWebViewCore);
5183        if (nativeHasCursorNode()) {
5184            Rect rect = nativeCursorNodeBounds();
5185            mSelectX = contentToViewX(rect.left);
5186            mSelectY = contentToViewY(rect.top);
5187        } else if (mLastTouchY > getVisibleTitleHeightImpl()) {
5188            mSelectX = mScrollX + mLastTouchX;
5189            mSelectY = mScrollY + mLastTouchY;
5190        } else {
5191            mSelectX = mScrollX + getViewWidth() / 2;
5192            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
5193        }
5194        nativeHideCursor();
5195        mMinAutoScrollX = 0;
5196        mMaxAutoScrollX = getViewWidth();
5197        mMinAutoScrollY = 0;
5198        mMaxAutoScrollY = getViewHeightWithTitle();
5199        mScrollingLayer = nativeScrollableLayer(viewToContentX(mSelectX),
5200                viewToContentY(mSelectY), mScrollingLayerRect,
5201                mScrollingLayerBounds);
5202        if (mScrollingLayer != 0) {
5203            if (mScrollingLayerRect.left != mScrollingLayerRect.right) {
5204                mMinAutoScrollX = Math.max(mMinAutoScrollX,
5205                        contentToViewX(mScrollingLayerBounds.left));
5206                mMaxAutoScrollX = Math.min(mMaxAutoScrollX,
5207                        contentToViewX(mScrollingLayerBounds.right));
5208            }
5209            if (mScrollingLayerRect.top != mScrollingLayerRect.bottom) {
5210                mMinAutoScrollY = Math.max(mMinAutoScrollY,
5211                        contentToViewY(mScrollingLayerBounds.top));
5212                mMaxAutoScrollY = Math.min(mMaxAutoScrollY,
5213                        contentToViewY(mScrollingLayerBounds.bottom));
5214            }
5215        }
5216        mMinAutoScrollX += SELECT_SCROLL;
5217        mMaxAutoScrollX -= SELECT_SCROLL;
5218        mMinAutoScrollY += SELECT_SCROLL;
5219        mMaxAutoScrollY -= SELECT_SCROLL;
5220        return true;
5221    }
5222
5223    /**
5224     * Use this method to put the WebView into text selection mode.
5225     * Do not rely on this functionality; it will be deprecated in the future.
5226     * @deprecated This method is now obsolete.
5227     */
5228    @Deprecated
5229    public void emulateShiftHeld() {
5230        checkThread();
5231        setUpSelect(false, 0, 0);
5232    }
5233
5234    /**
5235     * Select all of the text in this WebView.
5236     *
5237     * @hide pending API council approval.
5238     */
5239    public void selectAll() {
5240        if (0 == mNativeClass) return; // client isn't initialized
5241        if (inFullScreenMode()) return;
5242        if (!mSelectingText) {
5243            // retrieve a point somewhere within the text
5244            Point select = nativeSelectableText();
5245            if (!selectText(select.x, select.y)) return;
5246        }
5247        nativeSelectAll();
5248        mDrawSelectionPointer = false;
5249        mExtendSelection = true;
5250        invalidate();
5251    }
5252
5253    /**
5254     * Called when the selection has been removed.
5255     */
5256    void selectionDone() {
5257        if (mSelectingText) {
5258            mSelectingText = false;
5259            // finish is idempotent, so this is fine even if selectionDone was
5260            // called by mSelectCallback.onDestroyActionMode
5261            mSelectCallback.finish();
5262            mSelectCallback = null;
5263            WebViewCore.resumePriority();
5264            WebViewCore.resumeUpdatePicture(mWebViewCore);
5265            invalidate(); // redraw without selection
5266            mAutoScrollX = 0;
5267            mAutoScrollY = 0;
5268            mSentAutoScrollMessage = false;
5269        }
5270    }
5271
5272    /**
5273     * Copy the selection to the clipboard
5274     *
5275     * @hide pending API council approval.
5276     */
5277    public boolean copySelection() {
5278        boolean copiedSomething = false;
5279        String selection = getSelection();
5280        if (selection != null && selection != "") {
5281            if (DebugFlags.WEB_VIEW) {
5282                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
5283            }
5284            Toast.makeText(mContext
5285                    , com.android.internal.R.string.text_copied
5286                    , Toast.LENGTH_SHORT).show();
5287            copiedSomething = true;
5288            ClipboardManager cm = (ClipboardManager)getContext()
5289                    .getSystemService(Context.CLIPBOARD_SERVICE);
5290            cm.setText(selection);
5291        }
5292        invalidate(); // remove selection region and pointer
5293        return copiedSomething;
5294    }
5295
5296    /**
5297     * @hide pending API Council approval.
5298     */
5299    public SearchBox getSearchBox() {
5300        if ((mWebViewCore == null) || (mWebViewCore.getBrowserFrame() == null)) {
5301            return null;
5302        }
5303        return mWebViewCore.getBrowserFrame().getSearchBox();
5304    }
5305
5306    /**
5307     * Returns the currently highlighted text as a string.
5308     */
5309    String getSelection() {
5310        if (mNativeClass == 0) return "";
5311        return nativeGetSelection();
5312    }
5313
5314    @Override
5315    protected void onAttachedToWindow() {
5316        super.onAttachedToWindow();
5317        if (hasWindowFocus()) setActive(true);
5318        final ViewTreeObserver treeObserver = getViewTreeObserver();
5319        if (mGlobalLayoutListener == null) {
5320            mGlobalLayoutListener = new InnerGlobalLayoutListener();
5321            treeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);
5322        }
5323        if (mScrollChangedListener == null) {
5324            mScrollChangedListener = new InnerScrollChangedListener();
5325            treeObserver.addOnScrollChangedListener(mScrollChangedListener);
5326        }
5327
5328        addAccessibilityApisToJavaScript();
5329
5330        mTouchEventQueue.reset();
5331    }
5332
5333    @Override
5334    protected void onDetachedFromWindow() {
5335        clearHelpers();
5336        mZoomManager.dismissZoomPicker();
5337        if (hasWindowFocus()) setActive(false);
5338
5339        final ViewTreeObserver treeObserver = getViewTreeObserver();
5340        if (mGlobalLayoutListener != null) {
5341            treeObserver.removeGlobalOnLayoutListener(mGlobalLayoutListener);
5342            mGlobalLayoutListener = null;
5343        }
5344        if (mScrollChangedListener != null) {
5345            treeObserver.removeOnScrollChangedListener(mScrollChangedListener);
5346            mScrollChangedListener = null;
5347        }
5348
5349        removeAccessibilityApisFromJavaScript();
5350
5351        super.onDetachedFromWindow();
5352    }
5353
5354    @Override
5355    protected void onVisibilityChanged(View changedView, int visibility) {
5356        super.onVisibilityChanged(changedView, visibility);
5357        // The zoomManager may be null if the webview is created from XML that
5358        // specifies the view's visibility param as not visible (see http://b/2794841)
5359        if (visibility != View.VISIBLE && mZoomManager != null) {
5360            mZoomManager.dismissZoomPicker();
5361        }
5362    }
5363
5364    /**
5365     * @deprecated WebView no longer needs to implement
5366     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5367     */
5368    @Deprecated
5369    public void onChildViewAdded(View parent, View child) {}
5370
5371    /**
5372     * @deprecated WebView no longer needs to implement
5373     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5374     */
5375    @Deprecated
5376    public void onChildViewRemoved(View p, View child) {}
5377
5378    /**
5379     * @deprecated WebView should not have implemented
5380     * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
5381     */
5382    @Deprecated
5383    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
5384    }
5385
5386    void setActive(boolean active) {
5387        if (active) {
5388            if (hasFocus()) {
5389                // If our window regained focus, and we have focus, then begin
5390                // drawing the cursor ring
5391                mDrawCursorRing = true;
5392                setFocusControllerActive(true);
5393                if (mNativeClass != 0) {
5394                    nativeRecordButtons(true, false, true);
5395                }
5396            } else {
5397                if (!inEditingMode()) {
5398                    // If our window gained focus, but we do not have it, do not
5399                    // draw the cursor ring.
5400                    mDrawCursorRing = false;
5401                    setFocusControllerActive(false);
5402                }
5403                // We do not call nativeRecordButtons here because we assume
5404                // that when we lost focus, or window focus, it got called with
5405                // false for the first parameter
5406            }
5407        } else {
5408            if (!mZoomManager.isZoomPickerVisible()) {
5409                /*
5410                 * The external zoom controls come in their own window, so our
5411                 * window loses focus. Our policy is to not draw the cursor ring
5412                 * if our window is not focused, but this is an exception since
5413                 * the user can still navigate the web page with the zoom
5414                 * controls showing.
5415                 */
5416                mDrawCursorRing = false;
5417            }
5418            mKeysPressed.clear();
5419            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5420            mTouchMode = TOUCH_DONE_MODE;
5421            if (mNativeClass != 0) {
5422                nativeRecordButtons(false, false, true);
5423            }
5424            setFocusControllerActive(false);
5425        }
5426        invalidate();
5427    }
5428
5429    // To avoid drawing the cursor ring, and remove the TextView when our window
5430    // loses focus.
5431    @Override
5432    public void onWindowFocusChanged(boolean hasWindowFocus) {
5433        setActive(hasWindowFocus);
5434        if (hasWindowFocus) {
5435            JWebCoreJavaBridge.setActiveWebView(this);
5436        } else {
5437            JWebCoreJavaBridge.removeActiveWebView(this);
5438        }
5439        super.onWindowFocusChanged(hasWindowFocus);
5440    }
5441
5442    /*
5443     * Pass a message to WebCore Thread, telling the WebCore::Page's
5444     * FocusController to be  "inactive" so that it will
5445     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
5446     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
5447     */
5448    /* package */ void setFocusControllerActive(boolean active) {
5449        if (mWebViewCore == null) return;
5450        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
5451        // Need to send this message after the document regains focus.
5452        if (active && mListBoxMessage != null) {
5453            mWebViewCore.sendMessage(mListBoxMessage);
5454            mListBoxMessage = null;
5455        }
5456    }
5457
5458    @Override
5459    protected void onFocusChanged(boolean focused, int direction,
5460            Rect previouslyFocusedRect) {
5461        if (DebugFlags.WEB_VIEW) {
5462            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
5463        }
5464        if (focused) {
5465            // When we regain focus, if we have window focus, resume drawing
5466            // the cursor ring
5467            if (hasWindowFocus()) {
5468                mDrawCursorRing = true;
5469                if (mNativeClass != 0) {
5470                    nativeRecordButtons(true, false, true);
5471                }
5472                setFocusControllerActive(true);
5473            //} else {
5474                // The WebView has gained focus while we do not have
5475                // windowfocus.  When our window lost focus, we should have
5476                // called nativeRecordButtons(false...)
5477            }
5478        } else {
5479            // When we lost focus, unless focus went to the TextView (which is
5480            // true if we are in editing mode), stop drawing the cursor ring.
5481            if (!inEditingMode()) {
5482                mDrawCursorRing = false;
5483                if (mNativeClass != 0) {
5484                    nativeRecordButtons(false, false, true);
5485                }
5486                setFocusControllerActive(false);
5487            }
5488            mKeysPressed.clear();
5489        }
5490
5491        super.onFocusChanged(focused, direction, previouslyFocusedRect);
5492    }
5493
5494    void setGLRectViewport() {
5495        // Use the getGlobalVisibleRect() to get the intersection among the parents
5496        // visible == false means we're clipped - send a null rect down to indicate that
5497        // we should not draw
5498        boolean visible = getGlobalVisibleRect(mGLRectViewport);
5499        if (visible) {
5500            // Then need to invert the Y axis, just for GL
5501            View rootView = getRootView();
5502            int rootViewHeight = rootView.getHeight();
5503            mViewRectViewport.set(mGLRectViewport);
5504            int savedWebViewBottom = mGLRectViewport.bottom;
5505            mGLRectViewport.bottom = rootViewHeight - mGLRectViewport.top - getVisibleTitleHeightImpl();
5506            mGLRectViewport.top = rootViewHeight - savedWebViewBottom;
5507            mGLViewportEmpty = false;
5508        } else {
5509            mGLViewportEmpty = true;
5510        }
5511        nativeUpdateDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport,
5512                mGLViewportEmpty ? null : mViewRectViewport);
5513    }
5514
5515    /**
5516     * @hide
5517     */
5518    @Override
5519    protected boolean setFrame(int left, int top, int right, int bottom) {
5520        boolean changed = super.setFrame(left, top, right, bottom);
5521        if (!changed && mHeightCanMeasure) {
5522            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
5523            // in WebViewCore after we get the first layout. We do call
5524            // requestLayout() when we get contentSizeChanged(). But the View
5525            // system won't call onSizeChanged if the dimension is not changed.
5526            // In this case, we need to call sendViewSizeZoom() explicitly to
5527            // notify the WebKit about the new dimensions.
5528            sendViewSizeZoom(false);
5529        }
5530        setGLRectViewport();
5531        return changed;
5532    }
5533
5534    @Override
5535    protected void onSizeChanged(int w, int h, int ow, int oh) {
5536        super.onSizeChanged(w, h, ow, oh);
5537
5538        // adjust the max viewport width depending on the view dimensions. This
5539        // is to ensure the scaling is not going insane. So do not shrink it if
5540        // the view size is temporarily smaller, e.g. when soft keyboard is up.
5541        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
5542        if (newMaxViewportWidth > sMaxViewportWidth) {
5543            sMaxViewportWidth = newMaxViewportWidth;
5544        }
5545
5546        mZoomManager.onSizeChanged(w, h, ow, oh);
5547
5548        if (mLoadedPicture != null && mDelaySetPicture == null) {
5549            // Size changes normally result in a new picture
5550            // Re-set the loaded picture to simulate that
5551            // However, do not update the base layer as that hasn't changed
5552            setNewPicture(mLoadedPicture, false);
5553        }
5554    }
5555
5556    @Override
5557    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5558        super.onScrollChanged(l, t, oldl, oldt);
5559        if (!mInOverScrollMode) {
5560            sendOurVisibleRect();
5561            // update WebKit if visible title bar height changed. The logic is same
5562            // as getVisibleTitleHeightImpl.
5563            int titleHeight = getTitleHeight();
5564            if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
5565                sendViewSizeZoom(false);
5566            }
5567        }
5568    }
5569
5570    @Override
5571    public boolean dispatchKeyEvent(KeyEvent event) {
5572        switch (event.getAction()) {
5573            case KeyEvent.ACTION_DOWN:
5574                mKeysPressed.add(Integer.valueOf(event.getKeyCode()));
5575                break;
5576            case KeyEvent.ACTION_MULTIPLE:
5577                // Always accept the action.
5578                break;
5579            case KeyEvent.ACTION_UP:
5580                int location = mKeysPressed.indexOf(Integer.valueOf(event.getKeyCode()));
5581                if (location == -1) {
5582                    // We did not receive the key down for this key, so do not
5583                    // handle the key up.
5584                    return false;
5585                } else {
5586                    // We did receive the key down.  Handle the key up, and
5587                    // remove it from our pressed keys.
5588                    mKeysPressed.remove(location);
5589                }
5590                break;
5591            default:
5592                // Accept the action.  This should not happen, unless a new
5593                // action is added to KeyEvent.
5594                break;
5595        }
5596        if (inEditingMode() && mWebTextView.isFocused()) {
5597            // Ensure that the WebTextView gets the event, even if it does
5598            // not currently have a bounds.
5599            return mWebTextView.dispatchKeyEvent(event);
5600        } else {
5601            return super.dispatchKeyEvent(event);
5602        }
5603    }
5604
5605    /*
5606     * Here is the snap align logic:
5607     * 1. If it starts nearly horizontally or vertically, snap align;
5608     * 2. If there is a dramitic direction change, let it go;
5609     *
5610     * Adjustable parameters. Angle is the radians on a unit circle, limited
5611     * to quadrant 1. Values range from 0f (horizontal) to PI/2 (vertical)
5612     */
5613    private static final float HSLOPE_TO_START_SNAP = .25f;
5614    private static final float HSLOPE_TO_BREAK_SNAP = .4f;
5615    private static final float VSLOPE_TO_START_SNAP = 1.25f;
5616    private static final float VSLOPE_TO_BREAK_SNAP = .95f;
5617    /*
5618     *  These values are used to influence the average angle when entering
5619     *  snap mode. If is is the first movement entering snap, we set the average
5620     *  to the appropriate ideal. If the user is entering into snap after the
5621     *  first movement, then we average the average angle with these values.
5622     */
5623    private static final float ANGLE_VERT = 2f;
5624    private static final float ANGLE_HORIZ = 0f;
5625    /*
5626     *  The modified moving average weight.
5627     *  Formula: MAV[t]=MAV[t-1] + (P[t]-MAV[t-1])/n
5628     */
5629    private static final float MMA_WEIGHT_N = 5;
5630
5631    private boolean hitFocusedPlugin(int contentX, int contentY) {
5632        if (DebugFlags.WEB_VIEW) {
5633            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
5634            Rect r = nativeFocusNodeBounds();
5635            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
5636                    + ", " + r.right + ", " + r.bottom + ")");
5637        }
5638        return nativeFocusIsPlugin()
5639                && nativeFocusNodeBounds().contains(contentX, contentY);
5640    }
5641
5642    private boolean shouldForwardTouchEvent() {
5643        if (mFullScreenHolder != null) return true;
5644        if (mBlockWebkitViewMessages) return false;
5645        return mForwardTouchEvents
5646                && !mSelectingText
5647                && mPreventDefault != PREVENT_DEFAULT_IGNORE
5648                && mPreventDefault != PREVENT_DEFAULT_NO;
5649    }
5650
5651    private boolean inFullScreenMode() {
5652        return mFullScreenHolder != null;
5653    }
5654
5655    private void dismissFullScreenMode() {
5656        if (inFullScreenMode()) {
5657            mFullScreenHolder.hide();
5658            mFullScreenHolder = null;
5659        }
5660    }
5661
5662    void onPinchToZoomAnimationStart() {
5663        // cancel the single touch handling
5664        cancelTouch();
5665        onZoomAnimationStart();
5666    }
5667
5668    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
5669        onZoomAnimationEnd();
5670        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
5671        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
5672        // as it may trigger the unwanted fling.
5673        mTouchMode = TOUCH_PINCH_DRAG;
5674        mConfirmMove = true;
5675        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
5676    }
5677
5678    // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a
5679    // layer is found.
5680    private void startScrollingLayer(float x, float y) {
5681        int contentX = viewToContentX((int) x + mScrollX);
5682        int contentY = viewToContentY((int) y + mScrollY);
5683        mScrollingLayer = nativeScrollableLayer(contentX, contentY,
5684                mScrollingLayerRect, mScrollingLayerBounds);
5685        if (mScrollingLayer != 0) {
5686            mTouchMode = TOUCH_DRAG_LAYER_MODE;
5687        }
5688    }
5689
5690    // 1/(density * density) used to compute the distance between points.
5691    // Computed in init().
5692    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
5693
5694    // The distance between two points reported in onTouchEvent scaled by the
5695    // density of the screen.
5696    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
5697
5698    @Override
5699    public boolean onHoverEvent(MotionEvent event) {
5700        if (mNativeClass == 0) {
5701            return false;
5702        }
5703        WebViewCore.CursorData data = cursorDataNoPosition();
5704        data.mX = viewToContentX((int) event.getX() + mScrollX);
5705        data.mY = viewToContentY((int) event.getY() + mScrollY);
5706        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
5707        return true;
5708    }
5709
5710    @Override
5711    public boolean onTouchEvent(MotionEvent ev) {
5712        if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) {
5713            return false;
5714        }
5715
5716        if (DebugFlags.WEB_VIEW) {
5717            Log.v(LOGTAG, ev + " at " + ev.getEventTime()
5718                + " mTouchMode=" + mTouchMode
5719                + " numPointers=" + ev.getPointerCount());
5720        }
5721
5722        // If WebKit wasn't interested in this multitouch gesture, enqueue
5723        // the event for handling directly rather than making the round trip
5724        // to WebKit and back.
5725        if (ev.getPointerCount() > 1 && mPreventDefault != PREVENT_DEFAULT_NO) {
5726            passMultiTouchToWebKit(ev, mTouchEventQueue.nextTouchSequence());
5727        } else {
5728            mTouchEventQueue.enqueueTouchEvent(ev);
5729        }
5730
5731        // Since all events are handled asynchronously, we always want the gesture stream.
5732        return true;
5733    }
5734
5735    private float calculateDragAngle(int dx, int dy) {
5736        dx = Math.abs(dx);
5737        dy = Math.abs(dy);
5738        return (float) Math.atan2(dy, dx);
5739    }
5740
5741    /*
5742     * Common code for single touch and multi-touch.
5743     * (x, y) denotes current focus point, which is the touch point for single touch
5744     * and the middle point for multi-touch.
5745     */
5746    private boolean handleTouchEventCommon(MotionEvent ev, int action, int x, int y) {
5747        long eventTime = ev.getEventTime();
5748
5749        // Due to the touch screen edge effect, a touch closer to the edge
5750        // always snapped to the edge. As getViewWidth() can be different from
5751        // getWidth() due to the scrollbar, adjusting the point to match
5752        // getViewWidth(). Same applied to the height.
5753        x = Math.min(x, getViewWidth() - 1);
5754        y = Math.min(y, getViewHeightWithTitle() - 1);
5755
5756        int deltaX = mLastTouchX - x;
5757        int deltaY = mLastTouchY - y;
5758        int contentX = viewToContentX(x + mScrollX);
5759        int contentY = viewToContentY(y + mScrollY);
5760
5761        switch (action) {
5762            case MotionEvent.ACTION_DOWN: {
5763                mPreventDefault = PREVENT_DEFAULT_NO;
5764                mConfirmMove = false;
5765                mInitialHitTestResult = null;
5766                if (!mScroller.isFinished()) {
5767                    // stop the current scroll animation, but if this is
5768                    // the start of a fling, allow it to add to the current
5769                    // fling's velocity
5770                    mScroller.abortAnimation();
5771                    mTouchMode = TOUCH_DRAG_START_MODE;
5772                    mConfirmMove = true;
5773                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5774                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
5775                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
5776                    if (getSettings().supportTouchOnly()) {
5777                        removeTouchHighlight(true);
5778                    }
5779                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
5780                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
5781                    } else {
5782                        // commit the short press action for the previous tap
5783                        doShortPress();
5784                        mTouchMode = TOUCH_INIT_MODE;
5785                        mDeferTouchProcess = !mBlockWebkitViewMessages
5786                                && (!inFullScreenMode() && mForwardTouchEvents)
5787                                ? hitFocusedPlugin(contentX, contentY)
5788                                : false;
5789                    }
5790                } else { // the normal case
5791                    mTouchMode = TOUCH_INIT_MODE;
5792                    mDeferTouchProcess = !mBlockWebkitViewMessages
5793                            && (!inFullScreenMode() && mForwardTouchEvents)
5794                            ? hitFocusedPlugin(contentX, contentY)
5795                            : false;
5796                    if (!mBlockWebkitViewMessages) {
5797                        mWebViewCore.sendMessage(
5798                                EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
5799                    }
5800                    if (getSettings().supportTouchOnly()) {
5801                        TouchHighlightData data = new TouchHighlightData();
5802                        data.mX = contentX;
5803                        data.mY = contentY;
5804                        data.mSlop = viewToContentDimension(mNavSlop);
5805                        if (!mBlockWebkitViewMessages) {
5806                            mWebViewCore.sendMessageDelayed(
5807                                    EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
5808                                    ViewConfiguration.getTapTimeout());
5809                        }
5810                        if (DEBUG_TOUCH_HIGHLIGHT) {
5811                            if (getSettings().getNavDump()) {
5812                                mTouchHighlightX = (int) x + mScrollX;
5813                                mTouchHighlightY = (int) y + mScrollY;
5814                                mPrivateHandler.postDelayed(new Runnable() {
5815                                    public void run() {
5816                                        mTouchHighlightX = mTouchHighlightY = 0;
5817                                        invalidate();
5818                                    }
5819                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
5820                            }
5821                        }
5822                    }
5823                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
5824                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
5825                                (eventTime - mLastTouchUpTime), eventTime);
5826                    }
5827                    if (mSelectingText) {
5828                        mDrawSelectionPointer = false;
5829                        mSelectionStarted = nativeStartSelection(contentX, contentY);
5830                        if (DebugFlags.WEB_VIEW) {
5831                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
5832                        }
5833                        invalidate();
5834                    }
5835                }
5836                // Trigger the link
5837                if (!mSelectingText && (mTouchMode == TOUCH_INIT_MODE
5838                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE)) {
5839                    mPrivateHandler.sendEmptyMessageDelayed(
5840                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
5841                    mPrivateHandler.sendEmptyMessageDelayed(
5842                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
5843                    if (inFullScreenMode() || mDeferTouchProcess) {
5844                        mPreventDefault = PREVENT_DEFAULT_YES;
5845                    } else if (!mBlockWebkitViewMessages && mForwardTouchEvents) {
5846                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
5847                    } else {
5848                        mPreventDefault = PREVENT_DEFAULT_NO;
5849                    }
5850                    // pass the touch events from UI thread to WebCore thread
5851                    if (shouldForwardTouchEvent()) {
5852                        TouchEventData ted = new TouchEventData();
5853                        ted.mAction = action;
5854                        ted.mIds = new int[1];
5855                        ted.mIds[0] = ev.getPointerId(0);
5856                        ted.mPoints = new Point[1];
5857                        ted.mPoints[0] = new Point(contentX, contentY);
5858                        ted.mPointsInView = new Point[1];
5859                        ted.mPointsInView[0] = new Point(x, y);
5860                        ted.mMetaState = ev.getMetaState();
5861                        ted.mReprocess = mDeferTouchProcess;
5862                        ted.mNativeLayer = nativeScrollableLayer(
5863                                contentX, contentY, ted.mNativeLayerRect, null);
5864                        ted.mSequence = mTouchEventQueue.nextTouchSequence();
5865                        mTouchEventQueue.preQueueTouchEventData(ted);
5866                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5867                        if (mDeferTouchProcess) {
5868                            // still needs to set them for compute deltaX/Y
5869                            mLastTouchX = x;
5870                            mLastTouchY = y;
5871                            break;
5872                        }
5873                        if (!inFullScreenMode()) {
5874                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
5875                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
5876                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5877                                            action, 0), TAP_TIMEOUT);
5878                        }
5879                    }
5880                }
5881                startTouch(x, y, eventTime);
5882                break;
5883            }
5884            case MotionEvent.ACTION_MOVE: {
5885                boolean firstMove = false;
5886                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
5887                        >= mTouchSlopSquare) {
5888                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5889                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5890                    mConfirmMove = true;
5891                    firstMove = true;
5892                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5893                        mTouchMode = TOUCH_INIT_MODE;
5894                    }
5895                    if (getSettings().supportTouchOnly()) {
5896                        removeTouchHighlight(true);
5897                    }
5898                }
5899                // pass the touch events from UI thread to WebCore thread
5900                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
5901                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
5902                    TouchEventData ted = new TouchEventData();
5903                    ted.mAction = action;
5904                    ted.mIds = new int[1];
5905                    ted.mIds[0] = ev.getPointerId(0);
5906                    ted.mPoints = new Point[1];
5907                    ted.mPoints[0] = new Point(contentX, contentY);
5908                    ted.mPointsInView = new Point[1];
5909                    ted.mPointsInView[0] = new Point(x, y);
5910                    ted.mMetaState = ev.getMetaState();
5911                    ted.mReprocess = mDeferTouchProcess;
5912                    ted.mNativeLayer = mScrollingLayer;
5913                    ted.mNativeLayerRect.set(mScrollingLayerRect);
5914                    ted.mSequence = mTouchEventQueue.nextTouchSequence();
5915                    mTouchEventQueue.preQueueTouchEventData(ted);
5916                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5917                    mLastSentTouchTime = eventTime;
5918                    if (mDeferTouchProcess) {
5919                        break;
5920                    }
5921                    if (firstMove && !inFullScreenMode()) {
5922                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
5923                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5924                                        action, 0), TAP_TIMEOUT);
5925                    }
5926                }
5927                if (mTouchMode == TOUCH_DONE_MODE
5928                        || mPreventDefault == PREVENT_DEFAULT_YES) {
5929                    // no dragging during scroll zoom animation, or when prevent
5930                    // default is yes
5931                    break;
5932                }
5933                if (mVelocityTracker == null) {
5934                    Log.e(LOGTAG, "Got null mVelocityTracker when "
5935                            + "mPreventDefault = " + mPreventDefault
5936                            + " mDeferTouchProcess = " + mDeferTouchProcess
5937                            + " mTouchMode = " + mTouchMode);
5938                } else {
5939                    mVelocityTracker.addMovement(ev);
5940                }
5941                if (mSelectingText && mSelectionStarted) {
5942                    if (DebugFlags.WEB_VIEW) {
5943                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
5944                    }
5945                    ViewParent parent = getParent();
5946                    if (parent != null) {
5947                        parent.requestDisallowInterceptTouchEvent(true);
5948                    }
5949                    mAutoScrollX = x <= mMinAutoScrollX ? -SELECT_SCROLL
5950                            : x >= mMaxAutoScrollX ? SELECT_SCROLL : 0;
5951                    mAutoScrollY = y <= mMinAutoScrollY ? -SELECT_SCROLL
5952                            : y >= mMaxAutoScrollY ? SELECT_SCROLL : 0;
5953                    if ((mAutoScrollX != 0 || mAutoScrollY != 0)
5954                            && !mSentAutoScrollMessage) {
5955                        mSentAutoScrollMessage = true;
5956                        mPrivateHandler.sendEmptyMessageDelayed(
5957                                SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
5958                    }
5959                    if (deltaX != 0 || deltaY != 0) {
5960                        nativeExtendSelection(contentX, contentY);
5961                        invalidate();
5962                    }
5963                    break;
5964                }
5965
5966                if (mTouchMode != TOUCH_DRAG_MODE &&
5967                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5968
5969                    if (!mConfirmMove) {
5970                        break;
5971                    }
5972
5973                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
5974                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
5975                        // track mLastTouchTime as we may need to do fling at
5976                        // ACTION_UP
5977                        mLastTouchTime = eventTime;
5978                        break;
5979                    }
5980
5981                    // Only lock dragging to one axis if we don't have a scale in progress.
5982                    // Scaling implies free-roaming movement. Note this is only ever a question
5983                    // if mZoomManager.supportsPanDuringZoom() is true.
5984                    final ScaleGestureDetector detector =
5985                      mZoomManager.getMultiTouchGestureDetector();
5986                    mAverageAngle = calculateDragAngle(deltaX, deltaY);
5987                    if (detector == null || !detector.isInProgress()) {
5988                        // if it starts nearly horizontal or vertical, enforce it
5989                        if (mAverageAngle < HSLOPE_TO_START_SNAP) {
5990                            mSnapScrollMode = SNAP_X;
5991                            mSnapPositive = deltaX > 0;
5992                            mAverageAngle = ANGLE_HORIZ;
5993                        } else if (mAverageAngle > VSLOPE_TO_START_SNAP) {
5994                            mSnapScrollMode = SNAP_Y;
5995                            mSnapPositive = deltaY > 0;
5996                            mAverageAngle = ANGLE_VERT;
5997                        }
5998                    }
5999
6000                    mTouchMode = TOUCH_DRAG_MODE;
6001                    mLastTouchX = x;
6002                    mLastTouchY = y;
6003                    deltaX = 0;
6004                    deltaY = 0;
6005
6006                    startScrollingLayer(x, y);
6007                    startDrag();
6008                }
6009
6010                // do pan
6011                boolean done = false;
6012                boolean keepScrollBarsVisible = false;
6013                if (deltaX == 0 && deltaY == 0) {
6014                    keepScrollBarsVisible = done = true;
6015                } else {
6016                    mAverageAngle +=
6017                        (calculateDragAngle(deltaX, deltaY) - mAverageAngle)
6018                        / MMA_WEIGHT_N;
6019                    if (mSnapScrollMode != SNAP_NONE) {
6020                        if (mSnapScrollMode == SNAP_Y) {
6021                            // radical change means getting out of snap mode
6022                            if (mAverageAngle < VSLOPE_TO_BREAK_SNAP) {
6023                                mSnapScrollMode = SNAP_NONE;
6024                            }
6025                        }
6026                        if (mSnapScrollMode == SNAP_X) {
6027                            // radical change means getting out of snap mode
6028                            if (mAverageAngle > HSLOPE_TO_BREAK_SNAP) {
6029                                mSnapScrollMode = SNAP_NONE;
6030                            }
6031                        }
6032                    } else {
6033                        if (mAverageAngle < HSLOPE_TO_START_SNAP) {
6034                            mSnapScrollMode = SNAP_X;
6035                            mSnapPositive = deltaX > 0;
6036                            mAverageAngle = (mAverageAngle + ANGLE_HORIZ) / 2;
6037                        } else if (mAverageAngle > VSLOPE_TO_START_SNAP) {
6038                            mSnapScrollMode = SNAP_Y;
6039                            mSnapPositive = deltaY > 0;
6040                            mAverageAngle = (mAverageAngle + ANGLE_VERT) / 2;
6041                        }
6042                    }
6043                    if (mSnapScrollMode != SNAP_NONE) {
6044                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6045                            deltaY = 0;
6046                        } else {
6047                            deltaX = 0;
6048                        }
6049                    }
6050                    mLastTouchX = x;
6051                    mLastTouchY = y;
6052                    if ((deltaX | deltaY) != 0) {
6053                        mHeldMotionless = MOTIONLESS_FALSE;
6054                    }
6055                    mLastTouchTime = eventTime;
6056                }
6057
6058                doDrag(deltaX, deltaY);
6059
6060                // Turn off scrollbars when dragging a layer.
6061                if (keepScrollBarsVisible &&
6062                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6063                    if (mHeldMotionless != MOTIONLESS_TRUE) {
6064                        mHeldMotionless = MOTIONLESS_TRUE;
6065                        invalidate();
6066                    }
6067                    // keep the scrollbar on the screen even there is no scroll
6068                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
6069                            false);
6070                    // return false to indicate that we can't pan out of the
6071                    // view space
6072                    return !done;
6073                }
6074                break;
6075            }
6076            case MotionEvent.ACTION_UP: {
6077                if (!isFocused()) requestFocus();
6078                // pass the touch events from UI thread to WebCore thread
6079                if (shouldForwardTouchEvent()) {
6080                    TouchEventData ted = new TouchEventData();
6081                    ted.mIds = new int[1];
6082                    ted.mIds[0] = ev.getPointerId(0);
6083                    ted.mAction = action;
6084                    ted.mPoints = new Point[1];
6085                    ted.mPoints[0] = new Point(contentX, contentY);
6086                    ted.mPointsInView = new Point[1];
6087                    ted.mPointsInView[0] = new Point(x, y);
6088                    ted.mMetaState = ev.getMetaState();
6089                    ted.mReprocess = mDeferTouchProcess;
6090                    ted.mNativeLayer = mScrollingLayer;
6091                    ted.mNativeLayerRect.set(mScrollingLayerRect);
6092                    ted.mSequence = mTouchEventQueue.nextTouchSequence();
6093                    mTouchEventQueue.preQueueTouchEventData(ted);
6094                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6095                }
6096                mLastTouchUpTime = eventTime;
6097                if (mSentAutoScrollMessage) {
6098                    mAutoScrollX = mAutoScrollY = 0;
6099                }
6100                switch (mTouchMode) {
6101                    case TOUCH_DOUBLE_TAP_MODE: // double tap
6102                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6103                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6104                        if (inFullScreenMode() || mDeferTouchProcess) {
6105                            TouchEventData ted = new TouchEventData();
6106                            ted.mIds = new int[1];
6107                            ted.mIds[0] = ev.getPointerId(0);
6108                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
6109                            ted.mPoints = new Point[1];
6110                            ted.mPoints[0] = new Point(contentX, contentY);
6111                            ted.mPointsInView = new Point[1];
6112                            ted.mPointsInView[0] = new Point(x, y);
6113                            ted.mMetaState = ev.getMetaState();
6114                            ted.mReprocess = mDeferTouchProcess;
6115                            ted.mNativeLayer = nativeScrollableLayer(
6116                                    contentX, contentY,
6117                                    ted.mNativeLayerRect, null);
6118                            ted.mSequence = mTouchEventQueue.nextTouchSequence();
6119                            mTouchEventQueue.preQueueTouchEventData(ted);
6120                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6121                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
6122                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
6123                            mTouchMode = TOUCH_DONE_MODE;
6124                        }
6125                        break;
6126                    case TOUCH_INIT_MODE: // tap
6127                    case TOUCH_SHORTPRESS_START_MODE:
6128                    case TOUCH_SHORTPRESS_MODE:
6129                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6130                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6131                        if (mConfirmMove) {
6132                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
6133                                    " WebCore's response for touch down.");
6134                            if (mPreventDefault != PREVENT_DEFAULT_YES
6135                                    && (computeMaxScrollX() > 0
6136                                            || computeMaxScrollY() > 0)) {
6137                                // If the user has performed a very quick touch
6138                                // sequence it is possible that we may get here
6139                                // before WebCore has had a chance to process the events.
6140                                // In this case, any call to preventDefault in the
6141                                // JS touch handler will not have been executed yet.
6142                                // Hence we will see both the UI (now) and WebCore
6143                                // (when context switches) handling the event,
6144                                // regardless of whether the web developer actually
6145                                // doeses preventDefault in their touch handler. This
6146                                // is the nature of our asynchronous touch model.
6147
6148                                // we will not rewrite drag code here, but we
6149                                // will try fling if it applies.
6150                                WebViewCore.reducePriority();
6151                                // to get better performance, pause updating the
6152                                // picture
6153                                WebViewCore.pauseUpdatePicture(mWebViewCore);
6154                                // fall through to TOUCH_DRAG_MODE
6155                            } else {
6156                                // WebKit may consume the touch event and modify
6157                                // DOM. drawContentPicture() will be called with
6158                                // animateSroll as true for better performance.
6159                                // Force redraw in high-quality.
6160                                invalidate();
6161                                break;
6162                            }
6163                        } else {
6164                            if (mSelectingText) {
6165                                // tapping on selection or controls does nothing
6166                                if (!nativeHitSelection(contentX, contentY)) {
6167                                    selectionDone();
6168                                }
6169                                break;
6170                            }
6171                            // only trigger double tap if the WebView is
6172                            // scalable
6173                            if (mTouchMode == TOUCH_INIT_MODE
6174                                    && (canZoomIn() || canZoomOut())) {
6175                                mPrivateHandler.sendEmptyMessageDelayed(
6176                                        RELEASE_SINGLE_TAP, ViewConfiguration
6177                                                .getDoubleTapTimeout());
6178                            } else {
6179                                doShortPress();
6180                            }
6181                            break;
6182                        }
6183                    case TOUCH_DRAG_MODE:
6184                    case TOUCH_DRAG_LAYER_MODE:
6185                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6186                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6187                        // if the user waits a while w/o moving before the
6188                        // up, we don't want to do a fling
6189                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
6190                            if (mVelocityTracker == null) {
6191                                Log.e(LOGTAG, "Got null mVelocityTracker when "
6192                                        + "mPreventDefault = "
6193                                        + mPreventDefault
6194                                        + " mDeferTouchProcess = "
6195                                        + mDeferTouchProcess);
6196                            } else {
6197                                mVelocityTracker.addMovement(ev);
6198                            }
6199                            // set to MOTIONLESS_IGNORE so that it won't keep
6200                            // removing and sending message in
6201                            // drawCoreAndCursorRing()
6202                            mHeldMotionless = MOTIONLESS_IGNORE;
6203                            doFling();
6204                            break;
6205                        } else {
6206                            if (mScroller.springBack(mScrollX, mScrollY, 0,
6207                                    computeMaxScrollX(), 0,
6208                                    computeMaxScrollY())) {
6209                                invalidate();
6210                            }
6211                        }
6212                        // redraw in high-quality, as we're done dragging
6213                        mHeldMotionless = MOTIONLESS_TRUE;
6214                        invalidate();
6215                        // fall through
6216                    case TOUCH_DRAG_START_MODE:
6217                        // TOUCH_DRAG_START_MODE should not happen for the real
6218                        // device as we almost certain will get a MOVE. But this
6219                        // is possible on emulator.
6220                        mLastVelocity = 0;
6221                        WebViewCore.resumePriority();
6222                        if (!mSelectingText) {
6223                            WebViewCore.resumeUpdatePicture(mWebViewCore);
6224                        }
6225                        break;
6226                }
6227                stopTouch();
6228                break;
6229            }
6230            case MotionEvent.ACTION_CANCEL: {
6231                if (mTouchMode == TOUCH_DRAG_MODE) {
6232                    mScroller.springBack(mScrollX, mScrollY, 0,
6233                            computeMaxScrollX(), 0, computeMaxScrollY());
6234                    invalidate();
6235                }
6236                cancelWebCoreTouchEvent(contentX, contentY, false);
6237                cancelTouch();
6238                break;
6239            }
6240        }
6241        return true;
6242    }
6243
6244    private void passMultiTouchToWebKit(MotionEvent ev, long sequence) {
6245        TouchEventData ted = new TouchEventData();
6246        ted.mAction = ev.getActionMasked();
6247        final int count = ev.getPointerCount();
6248        ted.mIds = new int[count];
6249        ted.mPoints = new Point[count];
6250        ted.mPointsInView = new Point[count];
6251        for (int c = 0; c < count; c++) {
6252            ted.mIds[c] = ev.getPointerId(c);
6253            int x = viewToContentX((int) ev.getX(c) + mScrollX);
6254            int y = viewToContentY((int) ev.getY(c) + mScrollY);
6255            ted.mPoints[c] = new Point(x, y);
6256            ted.mPointsInView[c] = new Point((int) ev.getX(c), (int) ev.getY(c));
6257        }
6258        if (ted.mAction == MotionEvent.ACTION_POINTER_DOWN
6259            || ted.mAction == MotionEvent.ACTION_POINTER_UP) {
6260            ted.mActionIndex = ev.getActionIndex();
6261        }
6262        ted.mMetaState = ev.getMetaState();
6263        ted.mReprocess = true;
6264        ted.mMotionEvent = MotionEvent.obtain(ev);
6265        ted.mSequence = sequence;
6266        mTouchEventQueue.preQueueTouchEventData(ted);
6267        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6268        cancelLongPress();
6269        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6270    }
6271
6272    void handleMultiTouchInWebView(MotionEvent ev) {
6273        if (DebugFlags.WEB_VIEW) {
6274            Log.v(LOGTAG, "multi-touch: " + ev + " at " + ev.getEventTime()
6275                + " mTouchMode=" + mTouchMode
6276                + " numPointers=" + ev.getPointerCount()
6277                + " scrolloffset=(" + mScrollX + "," + mScrollY + ")");
6278        }
6279
6280        final ScaleGestureDetector detector =
6281            mZoomManager.getMultiTouchGestureDetector();
6282
6283        // A few apps use WebView but don't instantiate gesture detector.
6284        // We don't need to support multi touch for them.
6285        if (detector == null) return;
6286
6287        float x = ev.getX();
6288        float y = ev.getY();
6289
6290        if (mPreventDefault != PREVENT_DEFAULT_YES) {
6291            detector.onTouchEvent(ev);
6292
6293            if (detector.isInProgress()) {
6294                if (DebugFlags.WEB_VIEW) {
6295                    Log.v(LOGTAG, "detector is in progress");
6296                }
6297                mLastTouchTime = ev.getEventTime();
6298                x = detector.getFocusX();
6299                y = detector.getFocusY();
6300
6301                cancelLongPress();
6302                mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6303                if (!mZoomManager.supportsPanDuringZoom()) {
6304                    return;
6305                }
6306                mTouchMode = TOUCH_DRAG_MODE;
6307                if (mVelocityTracker == null) {
6308                    mVelocityTracker = VelocityTracker.obtain();
6309                }
6310            }
6311        }
6312
6313        int action = ev.getActionMasked();
6314        if (action == MotionEvent.ACTION_POINTER_DOWN) {
6315            cancelTouch();
6316            action = MotionEvent.ACTION_DOWN;
6317        } else if (action == MotionEvent.ACTION_POINTER_UP && ev.getPointerCount() >= 2) {
6318            // set mLastTouchX/Y to the remaining points for multi-touch.
6319            mLastTouchX = Math.round(x);
6320            mLastTouchY = Math.round(y);
6321        } else if (action == MotionEvent.ACTION_MOVE) {
6322            // negative x or y indicate it is on the edge, skip it.
6323            if (x < 0 || y < 0) {
6324                return;
6325            }
6326        }
6327
6328        handleTouchEventCommon(ev, action, Math.round(x), Math.round(y));
6329    }
6330
6331    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
6332        if (shouldForwardTouchEvent()) {
6333            if (removeEvents) {
6334                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
6335            }
6336            TouchEventData ted = new TouchEventData();
6337            ted.mIds = new int[1];
6338            ted.mIds[0] = 0;
6339            ted.mPoints = new Point[1];
6340            ted.mPoints[0] = new Point(x, y);
6341            ted.mPointsInView = new Point[1];
6342            int viewX = contentToViewX(x) - mScrollX;
6343            int viewY = contentToViewY(y) - mScrollY;
6344            ted.mPointsInView[0] = new Point(viewX, viewY);
6345            ted.mAction = MotionEvent.ACTION_CANCEL;
6346            ted.mNativeLayer = nativeScrollableLayer(
6347                    x, y, ted.mNativeLayerRect, null);
6348            ted.mSequence = mTouchEventQueue.nextTouchSequence();
6349            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6350            mPreventDefault = PREVENT_DEFAULT_IGNORE;
6351
6352            if (removeEvents) {
6353                // Mark this after sending the message above; we should
6354                // be willing to ignore the cancel event that we just sent.
6355                mTouchEventQueue.ignoreCurrentlyMissingEvents();
6356            }
6357        }
6358    }
6359
6360    private void startTouch(float x, float y, long eventTime) {
6361        // Remember where the motion event started
6362        mStartTouchX = mLastTouchX = Math.round(x);
6363        mStartTouchY = mLastTouchY = Math.round(y);
6364        mLastTouchTime = eventTime;
6365        mVelocityTracker = VelocityTracker.obtain();
6366        mSnapScrollMode = SNAP_NONE;
6367    }
6368
6369    private void startDrag() {
6370        WebViewCore.reducePriority();
6371        // to get better performance, pause updating the picture
6372        WebViewCore.pauseUpdatePicture(mWebViewCore);
6373        if (!mDragFromTextInput) {
6374            nativeHideCursor();
6375        }
6376
6377        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
6378                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
6379            mZoomManager.invokeZoomPicker();
6380        }
6381    }
6382
6383    private void doDrag(int deltaX, int deltaY) {
6384        if ((deltaX | deltaY) != 0) {
6385            int oldX = mScrollX;
6386            int oldY = mScrollY;
6387            int rangeX = computeMaxScrollX();
6388            int rangeY = computeMaxScrollY();
6389            int overscrollDistance = mOverscrollDistance;
6390
6391            // Check for the original scrolling layer in case we change
6392            // directions.  mTouchMode might be TOUCH_DRAG_MODE if we have
6393            // reached the edge of a layer but mScrollingLayer will be non-zero
6394            // if we initiated the drag on a layer.
6395            if (mScrollingLayer != 0) {
6396                final int contentX = viewToContentDimension(deltaX);
6397                final int contentY = viewToContentDimension(deltaY);
6398
6399                // Check the scrolling bounds to see if we will actually do any
6400                // scrolling.  The rectangle is in document coordinates.
6401                final int maxX = mScrollingLayerRect.right;
6402                final int maxY = mScrollingLayerRect.bottom;
6403                final int resultX = Math.max(0,
6404                        Math.min(mScrollingLayerRect.left + contentX, maxX));
6405                final int resultY = Math.max(0,
6406                        Math.min(mScrollingLayerRect.top + contentY, maxY));
6407
6408                if (resultX != mScrollingLayerRect.left ||
6409                        resultY != mScrollingLayerRect.top) {
6410                    // In case we switched to dragging the page.
6411                    mTouchMode = TOUCH_DRAG_LAYER_MODE;
6412                    deltaX = contentX;
6413                    deltaY = contentY;
6414                    oldX = mScrollingLayerRect.left;
6415                    oldY = mScrollingLayerRect.top;
6416                    rangeX = maxX;
6417                    rangeY = maxY;
6418                } else {
6419                    // Scroll the main page if we are not going to scroll the
6420                    // layer.  This does not reset mScrollingLayer in case the
6421                    // user changes directions and the layer can scroll the
6422                    // other way.
6423                    mTouchMode = TOUCH_DRAG_MODE;
6424                }
6425            }
6426
6427            if (mOverScrollGlow != null) {
6428                mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
6429            }
6430
6431            overScrollBy(deltaX, deltaY, oldX, oldY,
6432                    rangeX, rangeY,
6433                    mOverscrollDistance, mOverscrollDistance, true);
6434            if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
6435                invalidate();
6436            }
6437        }
6438        mZoomManager.keepZoomPickerVisible();
6439    }
6440
6441    private void stopTouch() {
6442        // we also use mVelocityTracker == null to tell us that we are
6443        // not "moving around", so we can take the slower/prettier
6444        // mode in the drawing code
6445        if (mVelocityTracker != null) {
6446            mVelocityTracker.recycle();
6447            mVelocityTracker = null;
6448        }
6449
6450        // Release any pulled glows
6451        if (mOverScrollGlow != null) {
6452            mOverScrollGlow.releaseAll();
6453        }
6454    }
6455
6456    private void cancelTouch() {
6457        // we also use mVelocityTracker == null to tell us that we are
6458        // not "moving around", so we can take the slower/prettier
6459        // mode in the drawing code
6460        if (mVelocityTracker != null) {
6461            mVelocityTracker.recycle();
6462            mVelocityTracker = null;
6463        }
6464
6465        if ((mTouchMode == TOUCH_DRAG_MODE
6466                || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
6467            WebViewCore.resumePriority();
6468            WebViewCore.resumeUpdatePicture(mWebViewCore);
6469        }
6470        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6471        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6472        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6473        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6474        if (getSettings().supportTouchOnly()) {
6475            removeTouchHighlight(true);
6476        }
6477        mHeldMotionless = MOTIONLESS_TRUE;
6478        mTouchMode = TOUCH_DONE_MODE;
6479        nativeHideCursor();
6480    }
6481
6482    @Override
6483    public boolean onGenericMotionEvent(MotionEvent event) {
6484        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6485            switch (event.getAction()) {
6486                case MotionEvent.ACTION_SCROLL: {
6487                    final float vscroll;
6488                    final float hscroll;
6489                    if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
6490                        vscroll = 0;
6491                        hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6492                    } else {
6493                        vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6494                        hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
6495                    }
6496                    if (hscroll != 0 || vscroll != 0) {
6497                        final int vdelta = (int) (vscroll * getVerticalScrollFactor());
6498                        final int hdelta = (int) (hscroll * getHorizontalScrollFactor());
6499                        if (pinScrollBy(hdelta, vdelta, false, 0)) {
6500                            return true;
6501                        }
6502                    }
6503                }
6504            }
6505        }
6506        return super.onGenericMotionEvent(event);
6507    }
6508
6509    private long mTrackballFirstTime = 0;
6510    private long mTrackballLastTime = 0;
6511    private float mTrackballRemainsX = 0.0f;
6512    private float mTrackballRemainsY = 0.0f;
6513    private int mTrackballXMove = 0;
6514    private int mTrackballYMove = 0;
6515    private boolean mSelectingText = false;
6516    private boolean mSelectionStarted = false;
6517    private boolean mExtendSelection = false;
6518    private boolean mDrawSelectionPointer = false;
6519    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
6520    private static final int TRACKBALL_TIMEOUT = 200;
6521    private static final int TRACKBALL_WAIT = 100;
6522    private static final int TRACKBALL_SCALE = 400;
6523    private static final int TRACKBALL_SCROLL_COUNT = 5;
6524    private static final int TRACKBALL_MOVE_COUNT = 10;
6525    private static final int TRACKBALL_MULTIPLIER = 3;
6526    private static final int SELECT_CURSOR_OFFSET = 16;
6527    private static final int SELECT_SCROLL = 5;
6528    private int mSelectX = 0;
6529    private int mSelectY = 0;
6530    private boolean mFocusSizeChanged = false;
6531    private boolean mTrackballDown = false;
6532    private long mTrackballUpTime = 0;
6533    private long mLastCursorTime = 0;
6534    private Rect mLastCursorBounds;
6535
6536    // Set by default; BrowserActivity clears to interpret trackball data
6537    // directly for movement. Currently, the framework only passes
6538    // arrow key events, not trackball events, from one child to the next
6539    private boolean mMapTrackballToArrowKeys = true;
6540
6541    private DrawData mDelaySetPicture;
6542    private DrawData mLoadedPicture;
6543
6544    public void setMapTrackballToArrowKeys(boolean setMap) {
6545        checkThread();
6546        mMapTrackballToArrowKeys = setMap;
6547    }
6548
6549    void resetTrackballTime() {
6550        mTrackballLastTime = 0;
6551    }
6552
6553    @Override
6554    public boolean onTrackballEvent(MotionEvent ev) {
6555        long time = ev.getEventTime();
6556        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
6557            if (ev.getY() > 0) pageDown(true);
6558            if (ev.getY() < 0) pageUp(true);
6559            return true;
6560        }
6561        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
6562            if (mSelectingText) {
6563                return true; // discard press if copy in progress
6564            }
6565            mTrackballDown = true;
6566            if (mNativeClass == 0) {
6567                return false;
6568            }
6569            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
6570            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
6571                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
6572                nativeSelectBestAt(mLastCursorBounds);
6573            }
6574            if (DebugFlags.WEB_VIEW) {
6575                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
6576                        + " time=" + time
6577                        + " mLastCursorTime=" + mLastCursorTime);
6578            }
6579            if (isInTouchMode()) requestFocusFromTouch();
6580            return false; // let common code in onKeyDown at it
6581        }
6582        if (ev.getAction() == MotionEvent.ACTION_UP) {
6583            // LONG_PRESS_CENTER is set in common onKeyDown
6584            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
6585            mTrackballDown = false;
6586            mTrackballUpTime = time;
6587            if (mSelectingText) {
6588                if (mExtendSelection) {
6589                    copySelection();
6590                    selectionDone();
6591                } else {
6592                    mExtendSelection = true;
6593                    nativeSetExtendSelection();
6594                    invalidate(); // draw the i-beam instead of the arrow
6595                }
6596                return true; // discard press if copy in progress
6597            }
6598            if (DebugFlags.WEB_VIEW) {
6599                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
6600                        + " time=" + time
6601                );
6602            }
6603            return false; // let common code in onKeyUp at it
6604        }
6605        if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
6606                AccessibilityManager.getInstance(mContext).isEnabled()) {
6607            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
6608            return false;
6609        }
6610        if (mTrackballDown) {
6611            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
6612            return true; // discard move if trackball is down
6613        }
6614        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
6615            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
6616            return true;
6617        }
6618        // TODO: alternatively we can do panning as touch does
6619        switchOutDrawHistory();
6620        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
6621            if (DebugFlags.WEB_VIEW) {
6622                Log.v(LOGTAG, "onTrackballEvent time="
6623                        + time + " last=" + mTrackballLastTime);
6624            }
6625            mTrackballFirstTime = time;
6626            mTrackballXMove = mTrackballYMove = 0;
6627        }
6628        mTrackballLastTime = time;
6629        if (DebugFlags.WEB_VIEW) {
6630            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
6631        }
6632        mTrackballRemainsX += ev.getX();
6633        mTrackballRemainsY += ev.getY();
6634        doTrackball(time, ev.getMetaState());
6635        return true;
6636    }
6637
6638    void moveSelection(float xRate, float yRate) {
6639        if (mNativeClass == 0)
6640            return;
6641        int width = getViewWidth();
6642        int height = getViewHeight();
6643        mSelectX += xRate;
6644        mSelectY += yRate;
6645        int maxX = width + mScrollX;
6646        int maxY = height + mScrollY;
6647        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
6648                , mSelectX));
6649        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
6650                , mSelectY));
6651        if (DebugFlags.WEB_VIEW) {
6652            Log.v(LOGTAG, "moveSelection"
6653                    + " mSelectX=" + mSelectX
6654                    + " mSelectY=" + mSelectY
6655                    + " mScrollX=" + mScrollX
6656                    + " mScrollY=" + mScrollY
6657                    + " xRate=" + xRate
6658                    + " yRate=" + yRate
6659                    );
6660        }
6661        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
6662        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
6663                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6664                : 0;
6665        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
6666                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6667                : 0;
6668        pinScrollBy(scrollX, scrollY, true, 0);
6669        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
6670        requestRectangleOnScreen(select);
6671        invalidate();
6672   }
6673
6674    private int scaleTrackballX(float xRate, int width) {
6675        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
6676        int nextXMove = xMove;
6677        if (xMove > 0) {
6678            if (xMove > mTrackballXMove) {
6679                xMove -= mTrackballXMove;
6680            }
6681        } else if (xMove < mTrackballXMove) {
6682            xMove -= mTrackballXMove;
6683        }
6684        mTrackballXMove = nextXMove;
6685        return xMove;
6686    }
6687
6688    private int scaleTrackballY(float yRate, int height) {
6689        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
6690        int nextYMove = yMove;
6691        if (yMove > 0) {
6692            if (yMove > mTrackballYMove) {
6693                yMove -= mTrackballYMove;
6694            }
6695        } else if (yMove < mTrackballYMove) {
6696            yMove -= mTrackballYMove;
6697        }
6698        mTrackballYMove = nextYMove;
6699        return yMove;
6700    }
6701
6702    private int keyCodeToSoundsEffect(int keyCode) {
6703        switch(keyCode) {
6704            case KeyEvent.KEYCODE_DPAD_UP:
6705                return SoundEffectConstants.NAVIGATION_UP;
6706            case KeyEvent.KEYCODE_DPAD_RIGHT:
6707                return SoundEffectConstants.NAVIGATION_RIGHT;
6708            case KeyEvent.KEYCODE_DPAD_DOWN:
6709                return SoundEffectConstants.NAVIGATION_DOWN;
6710            case KeyEvent.KEYCODE_DPAD_LEFT:
6711                return SoundEffectConstants.NAVIGATION_LEFT;
6712        }
6713        throw new IllegalArgumentException("keyCode must be one of " +
6714                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
6715                "KEYCODE_DPAD_LEFT}.");
6716    }
6717
6718    private void doTrackball(long time, int metaState) {
6719        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
6720        if (elapsed == 0) {
6721            elapsed = TRACKBALL_TIMEOUT;
6722        }
6723        float xRate = mTrackballRemainsX * 1000 / elapsed;
6724        float yRate = mTrackballRemainsY * 1000 / elapsed;
6725        int viewWidth = getViewWidth();
6726        int viewHeight = getViewHeight();
6727        if (mSelectingText) {
6728            if (!mDrawSelectionPointer) {
6729                // The last selection was made by touch, disabling drawing the
6730                // selection pointer. Allow the trackball to adjust the
6731                // position of the touch control.
6732                mSelectX = contentToViewX(nativeSelectionX());
6733                mSelectY = contentToViewY(nativeSelectionY());
6734                mDrawSelectionPointer = mExtendSelection = true;
6735                nativeSetExtendSelection();
6736            }
6737            moveSelection(scaleTrackballX(xRate, viewWidth),
6738                    scaleTrackballY(yRate, viewHeight));
6739            mTrackballRemainsX = mTrackballRemainsY = 0;
6740            return;
6741        }
6742        float ax = Math.abs(xRate);
6743        float ay = Math.abs(yRate);
6744        float maxA = Math.max(ax, ay);
6745        if (DebugFlags.WEB_VIEW) {
6746            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
6747                    + " xRate=" + xRate
6748                    + " yRate=" + yRate
6749                    + " mTrackballRemainsX=" + mTrackballRemainsX
6750                    + " mTrackballRemainsY=" + mTrackballRemainsY);
6751        }
6752        int width = mContentWidth - viewWidth;
6753        int height = mContentHeight - viewHeight;
6754        if (width < 0) width = 0;
6755        if (height < 0) height = 0;
6756        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
6757        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
6758        maxA = Math.max(ax, ay);
6759        int count = Math.max(0, (int) maxA);
6760        int oldScrollX = mScrollX;
6761        int oldScrollY = mScrollY;
6762        if (count > 0) {
6763            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
6764                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
6765                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
6766                    KeyEvent.KEYCODE_DPAD_RIGHT;
6767            count = Math.min(count, TRACKBALL_MOVE_COUNT);
6768            if (DebugFlags.WEB_VIEW) {
6769                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
6770                        + " count=" + count
6771                        + " mTrackballRemainsX=" + mTrackballRemainsX
6772                        + " mTrackballRemainsY=" + mTrackballRemainsY);
6773            }
6774            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
6775                for (int i = 0; i < count; i++) {
6776                    letPageHandleNavKey(selectKeyCode, time, true, metaState);
6777                }
6778                letPageHandleNavKey(selectKeyCode, time, false, metaState);
6779            } else if (navHandledKey(selectKeyCode, count, false, time)) {
6780                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
6781            }
6782            mTrackballRemainsX = mTrackballRemainsY = 0;
6783        }
6784        if (count >= TRACKBALL_SCROLL_COUNT) {
6785            int xMove = scaleTrackballX(xRate, width);
6786            int yMove = scaleTrackballY(yRate, height);
6787            if (DebugFlags.WEB_VIEW) {
6788                Log.v(LOGTAG, "doTrackball pinScrollBy"
6789                        + " count=" + count
6790                        + " xMove=" + xMove + " yMove=" + yMove
6791                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
6792                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
6793                        );
6794            }
6795            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
6796                xMove = 0;
6797            }
6798            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
6799                yMove = 0;
6800            }
6801            if (xMove != 0 || yMove != 0) {
6802                pinScrollBy(xMove, yMove, true, 0);
6803            }
6804        }
6805    }
6806
6807    /**
6808     * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
6809     * @return Maximum horizontal scroll position within real content
6810     */
6811    int computeMaxScrollX() {
6812        return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
6813    }
6814
6815    /**
6816     * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
6817     * @return Maximum vertical scroll position within real content
6818     */
6819    int computeMaxScrollY() {
6820        return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
6821                - getViewHeightWithTitle(), 0);
6822    }
6823
6824    boolean updateScrollCoordinates(int x, int y) {
6825        int oldX = mScrollX;
6826        int oldY = mScrollY;
6827        mScrollX = x;
6828        mScrollY = y;
6829        if (oldX != mScrollX || oldY != mScrollY) {
6830            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
6831            return true;
6832        } else {
6833            return false;
6834        }
6835    }
6836
6837    public void flingScroll(int vx, int vy) {
6838        checkThread();
6839        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
6840                computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
6841        invalidate();
6842    }
6843
6844    private void doFling() {
6845        if (mVelocityTracker == null) {
6846            return;
6847        }
6848        int maxX = computeMaxScrollX();
6849        int maxY = computeMaxScrollY();
6850
6851        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
6852        int vx = (int) mVelocityTracker.getXVelocity();
6853        int vy = (int) mVelocityTracker.getYVelocity();
6854
6855        int scrollX = mScrollX;
6856        int scrollY = mScrollY;
6857        int overscrollDistance = mOverscrollDistance;
6858        int overflingDistance = mOverflingDistance;
6859
6860        // Use the layer's scroll data if applicable.
6861        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
6862            scrollX = mScrollingLayerRect.left;
6863            scrollY = mScrollingLayerRect.top;
6864            maxX = mScrollingLayerRect.right;
6865            maxY = mScrollingLayerRect.bottom;
6866            // No overscrolling for layers.
6867            overscrollDistance = overflingDistance = 0;
6868        }
6869
6870        if (mSnapScrollMode != SNAP_NONE) {
6871            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6872                vy = 0;
6873            } else {
6874                vx = 0;
6875            }
6876        }
6877        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
6878            WebViewCore.resumePriority();
6879            if (!mSelectingText) {
6880                WebViewCore.resumeUpdatePicture(mWebViewCore);
6881            }
6882            if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) {
6883                invalidate();
6884            }
6885            return;
6886        }
6887        float currentVelocity = mScroller.getCurrVelocity();
6888        float velocity = (float) Math.hypot(vx, vy);
6889        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
6890                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
6891            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
6892                    - Math.atan2(vy, vx)));
6893            final float circle = (float) (Math.PI) * 2.0f;
6894            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
6895                vx += currentVelocity * mLastVelX / mLastVelocity;
6896                vy += currentVelocity * mLastVelY / mLastVelocity;
6897                velocity = (float) Math.hypot(vx, vy);
6898                if (DebugFlags.WEB_VIEW) {
6899                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
6900                }
6901            } else if (DebugFlags.WEB_VIEW) {
6902                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
6903            }
6904        } else if (DebugFlags.WEB_VIEW) {
6905            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
6906                    + " current=" + currentVelocity
6907                    + " vx=" + vx + " vy=" + vy
6908                    + " maxX=" + maxX + " maxY=" + maxY
6909                    + " scrollX=" + scrollX + " scrollY=" + scrollY
6910                    + " layer=" + mScrollingLayer);
6911        }
6912
6913        // Allow sloppy flings without overscrolling at the edges.
6914        if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
6915            vx = 0;
6916        }
6917        if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
6918            vy = 0;
6919        }
6920
6921        if (overscrollDistance < overflingDistance) {
6922            if ((vx > 0 && scrollX == -overscrollDistance) ||
6923                    (vx < 0 && scrollX == maxX + overscrollDistance)) {
6924                vx = 0;
6925            }
6926            if ((vy > 0 && scrollY == -overscrollDistance) ||
6927                    (vy < 0 && scrollY == maxY + overscrollDistance)) {
6928                vy = 0;
6929            }
6930        }
6931
6932        mLastVelX = vx;
6933        mLastVelY = vy;
6934        mLastVelocity = velocity;
6935
6936        // no horizontal overscroll if the content just fits
6937        mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY,
6938                maxX == 0 ? 0 : overflingDistance, overflingDistance);
6939        // Duration is calculated based on velocity. With range boundaries and overscroll
6940        // we may not know how long the final animation will take. (Hence the deprecation
6941        // warning on the call below.) It's not a big deal for scroll bars but if webcore
6942        // resumes during this effect we will take a performance hit. See computeScroll;
6943        // we resume webcore there when the animation is finished.
6944        final int time = mScroller.getDuration();
6945
6946        // Suppress scrollbars for layer scrolling.
6947        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6948            awakenScrollBars(time);
6949        }
6950
6951        invalidate();
6952    }
6953
6954    /**
6955     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
6956     * in charge of installing this view to the view hierarchy. This view will
6957     * become visible when the user starts scrolling via touch and fade away if
6958     * the user does not interact with it.
6959     * <p/>
6960     * API version 3 introduces a built-in zoom mechanism that is shown
6961     * automatically by the MapView. This is the preferred approach for
6962     * showing the zoom UI.
6963     *
6964     * @deprecated The built-in zoom mechanism is preferred, see
6965     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
6966     */
6967    @Deprecated
6968    public View getZoomControls() {
6969        checkThread();
6970        if (!getSettings().supportZoom()) {
6971            Log.w(LOGTAG, "This WebView doesn't support zoom.");
6972            return null;
6973        }
6974        return mZoomManager.getExternalZoomPicker();
6975    }
6976
6977    void dismissZoomControl() {
6978        mZoomManager.dismissZoomPicker();
6979    }
6980
6981    float getDefaultZoomScale() {
6982        return mZoomManager.getDefaultScale();
6983    }
6984
6985    /**
6986     * @return TRUE if the WebView can be zoomed in.
6987     */
6988    public boolean canZoomIn() {
6989        checkThread();
6990        return mZoomManager.canZoomIn();
6991    }
6992
6993    /**
6994     * @return TRUE if the WebView can be zoomed out.
6995     */
6996    public boolean canZoomOut() {
6997        checkThread();
6998        return mZoomManager.canZoomOut();
6999    }
7000
7001    /**
7002     * Perform zoom in in the webview
7003     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
7004     */
7005    public boolean zoomIn() {
7006        checkThread();
7007        return mZoomManager.zoomIn();
7008    }
7009
7010    /**
7011     * Perform zoom out in the webview
7012     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
7013     */
7014    public boolean zoomOut() {
7015        checkThread();
7016        return mZoomManager.zoomOut();
7017    }
7018
7019    private void updateSelection() {
7020        if (mNativeClass == 0) {
7021            return;
7022        }
7023        // mLastTouchX and mLastTouchY are the point in the current viewport
7024        int contentX = viewToContentX(mLastTouchX + mScrollX);
7025        int contentY = viewToContentY(mLastTouchY + mScrollY);
7026        int slop = viewToContentDimension(mNavSlop);
7027        Rect rect = new Rect(contentX - slop, contentY - slop,
7028                contentX + slop, contentY + slop);
7029        nativeSelectBestAt(rect);
7030        mInitialHitTestResult = hitTestResult(null);
7031    }
7032
7033    /**
7034     * Scroll the focused text field to match the WebTextView
7035     * @param xPercent New x position of the WebTextView from 0 to 1.
7036     */
7037    /*package*/ void scrollFocusedTextInputX(float xPercent) {
7038        if (!inEditingMode() || mWebViewCore == null) {
7039            return;
7040        }
7041        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0,
7042                new Float(xPercent));
7043    }
7044
7045    /**
7046     * Scroll the focused textarea vertically to match the WebTextView
7047     * @param y New y position of the WebTextView in view coordinates
7048     */
7049    /* package */ void scrollFocusedTextInputY(int y) {
7050        if (!inEditingMode() || mWebViewCore == null) {
7051            return;
7052        }
7053        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0, viewToContentDimension(y));
7054    }
7055
7056    /**
7057     * Set our starting point and time for a drag from the WebTextView.
7058     */
7059    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
7060        if (!inEditingMode()) {
7061            return;
7062        }
7063        mLastTouchX = Math.round(x + mWebTextView.getLeft() - mScrollX);
7064        mLastTouchY = Math.round(y + mWebTextView.getTop() - mScrollY);
7065        mLastTouchTime = eventTime;
7066        if (!mScroller.isFinished()) {
7067            abortAnimation();
7068            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
7069        }
7070        mSnapScrollMode = SNAP_NONE;
7071        mVelocityTracker = VelocityTracker.obtain();
7072        mTouchMode = TOUCH_DRAG_START_MODE;
7073    }
7074
7075    /**
7076     * Given a motion event from the WebTextView, set its location to our
7077     * coordinates, and handle the event.
7078     */
7079    /*package*/ boolean textFieldDrag(MotionEvent event) {
7080        if (!inEditingMode()) {
7081            return false;
7082        }
7083        mDragFromTextInput = true;
7084        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
7085                (float) (mWebTextView.getTop() - mScrollY));
7086        boolean result = onTouchEvent(event);
7087        mDragFromTextInput = false;
7088        return result;
7089    }
7090
7091    /**
7092     * Due a touch up from a WebTextView.  This will be handled by webkit to
7093     * change the selection.
7094     * @param event MotionEvent in the WebTextView's coordinates.
7095     */
7096    /*package*/ void touchUpOnTextField(MotionEvent event) {
7097        if (!inEditingMode()) {
7098            return;
7099        }
7100        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
7101        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
7102        int slop = viewToContentDimension(mNavSlop);
7103        nativeMotionUp(x, y, slop);
7104    }
7105
7106    /**
7107     * Called when pressing the center key or trackball on a textfield.
7108     */
7109    /*package*/ void centerKeyPressOnTextField() {
7110        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
7111                    nativeCursorNodePointer());
7112    }
7113
7114    private void doShortPress() {
7115        if (mNativeClass == 0) {
7116            return;
7117        }
7118        if (mPreventDefault == PREVENT_DEFAULT_YES) {
7119            return;
7120        }
7121        mTouchMode = TOUCH_DONE_MODE;
7122        switchOutDrawHistory();
7123        // mLastTouchX and mLastTouchY are the point in the current viewport
7124        int contentX = viewToContentX(mLastTouchX + mScrollX);
7125        int contentY = viewToContentY(mLastTouchY + mScrollY);
7126        int slop = viewToContentDimension(mNavSlop);
7127        if (getSettings().supportTouchOnly()) {
7128            removeTouchHighlight(false);
7129            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7130            // use "0" as generation id to inform WebKit to use the same x/y as
7131            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
7132            touchUpData.mMoveGeneration = 0;
7133            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7134        } else if (nativePointInNavCache(contentX, contentY, slop)) {
7135            WebViewCore.MotionUpData motionUpData = new WebViewCore
7136                    .MotionUpData();
7137            motionUpData.mFrame = nativeCacheHitFramePointer();
7138            motionUpData.mNode = nativeCacheHitNodePointer();
7139            motionUpData.mBounds = nativeCacheHitNodeBounds();
7140            motionUpData.mX = contentX;
7141            motionUpData.mY = contentY;
7142            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
7143                    motionUpData);
7144        } else {
7145            doMotionUp(contentX, contentY);
7146        }
7147    }
7148
7149    private void doMotionUp(int contentX, int contentY) {
7150        int slop = viewToContentDimension(mNavSlop);
7151        if (nativeMotionUp(contentX, contentY, slop) && mLogEvent) {
7152            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
7153        }
7154        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
7155            playSoundEffect(SoundEffectConstants.CLICK);
7156        }
7157    }
7158
7159    /**
7160     * Returns plugin bounds if x/y in content coordinates corresponds to a
7161     * plugin. Otherwise a NULL rectangle is returned.
7162     */
7163    Rect getPluginBounds(int x, int y) {
7164        int slop = viewToContentDimension(mNavSlop);
7165        if (nativePointInNavCache(x, y, slop) && nativeCacheHitIsPlugin()) {
7166            return nativeCacheHitNodeBounds();
7167        } else {
7168            return null;
7169        }
7170    }
7171
7172    /*
7173     * Return true if the rect (e.g. plugin) is fully visible and maximized
7174     * inside the WebView.
7175     */
7176    boolean isRectFitOnScreen(Rect rect) {
7177        final int rectWidth = rect.width();
7178        final int rectHeight = rect.height();
7179        final int viewWidth = getViewWidth();
7180        final int viewHeight = getViewHeightWithTitle();
7181        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight);
7182        scale = mZoomManager.computeScaleWithLimits(scale);
7183        return !mZoomManager.willScaleTriggerZoom(scale)
7184                && contentToViewX(rect.left) >= mScrollX
7185                && contentToViewX(rect.right) <= mScrollX + viewWidth
7186                && contentToViewY(rect.top) >= mScrollY
7187                && contentToViewY(rect.bottom) <= mScrollY + viewHeight;
7188    }
7189
7190    /*
7191     * Maximize and center the rectangle, specified in the document coordinate
7192     * space, inside the WebView. If the zoom doesn't need to be changed, do an
7193     * animated scroll to center it. If the zoom needs to be changed, find the
7194     * zoom center and do a smooth zoom transition. The rect is in document
7195     * coordinates
7196     */
7197    void centerFitRect(Rect rect) {
7198        final int rectWidth = rect.width();
7199        final int rectHeight = rect.height();
7200        final int viewWidth = getViewWidth();
7201        final int viewHeight = getViewHeightWithTitle();
7202        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight
7203                / rectHeight);
7204        scale = mZoomManager.computeScaleWithLimits(scale);
7205        if (!mZoomManager.willScaleTriggerZoom(scale)) {
7206            pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2,
7207                    contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2,
7208                    true, 0);
7209        } else {
7210            float actualScale = mZoomManager.getScale();
7211            float oldScreenX = rect.left * actualScale - mScrollX;
7212            float rectViewX = rect.left * scale;
7213            float rectViewWidth = rectWidth * scale;
7214            float newMaxWidth = mContentWidth * scale;
7215            float newScreenX = (viewWidth - rectViewWidth) / 2;
7216            // pin the newX to the WebView
7217            if (newScreenX > rectViewX) {
7218                newScreenX = rectViewX;
7219            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
7220                newScreenX = viewWidth - (newMaxWidth - rectViewX);
7221            }
7222            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
7223                    / (scale - actualScale);
7224            float oldScreenY = rect.top * actualScale + getTitleHeight()
7225                    - mScrollY;
7226            float rectViewY = rect.top * scale + getTitleHeight();
7227            float rectViewHeight = rectHeight * scale;
7228            float newMaxHeight = mContentHeight * scale + getTitleHeight();
7229            float newScreenY = (viewHeight - rectViewHeight) / 2;
7230            // pin the newY to the WebView
7231            if (newScreenY > rectViewY) {
7232                newScreenY = rectViewY;
7233            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
7234                newScreenY = viewHeight - (newMaxHeight - rectViewY);
7235            }
7236            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
7237                    / (scale - actualScale);
7238            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
7239            mZoomManager.startZoomAnimation(scale, false);
7240        }
7241    }
7242
7243    // Called by JNI to handle a touch on a node representing an email address,
7244    // address, or phone number
7245    private void overrideLoading(String url) {
7246        mCallbackProxy.uiOverrideUrlLoading(url);
7247    }
7248
7249    @Override
7250    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7251        // FIXME: If a subwindow is showing find, and the user touches the
7252        // background window, it can steal focus.
7253        if (mFindIsUp) return false;
7254        boolean result = false;
7255        if (inEditingMode()) {
7256            result = mWebTextView.requestFocus(direction,
7257                    previouslyFocusedRect);
7258        } else {
7259            result = super.requestFocus(direction, previouslyFocusedRect);
7260            if (mWebViewCore.getSettings().getNeedInitialFocus() && !isInTouchMode()) {
7261                // For cases such as GMail, where we gain focus from a direction,
7262                // we want to move to the first available link.
7263                // FIXME: If there are no visible links, we may not want to
7264                int fakeKeyDirection = 0;
7265                switch(direction) {
7266                    case View.FOCUS_UP:
7267                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
7268                        break;
7269                    case View.FOCUS_DOWN:
7270                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
7271                        break;
7272                    case View.FOCUS_LEFT:
7273                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
7274                        break;
7275                    case View.FOCUS_RIGHT:
7276                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
7277                        break;
7278                    default:
7279                        return result;
7280                }
7281                if (mNativeClass != 0 && !nativeHasCursorNode()) {
7282                    navHandledKey(fakeKeyDirection, 1, true, 0);
7283                }
7284            }
7285        }
7286        return result;
7287    }
7288
7289    @Override
7290    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7291        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
7292
7293        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
7294        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
7295        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
7296        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
7297
7298        int measuredHeight = heightSize;
7299        int measuredWidth = widthSize;
7300
7301        // Grab the content size from WebViewCore.
7302        int contentHeight = contentToViewDimension(mContentHeight);
7303        int contentWidth = contentToViewDimension(mContentWidth);
7304
7305//        Log.d(LOGTAG, "------- measure " + heightMode);
7306
7307        if (heightMode != MeasureSpec.EXACTLY) {
7308            mHeightCanMeasure = true;
7309            measuredHeight = contentHeight;
7310            if (heightMode == MeasureSpec.AT_MOST) {
7311                // If we are larger than the AT_MOST height, then our height can
7312                // no longer be measured and we should scroll internally.
7313                if (measuredHeight > heightSize) {
7314                    measuredHeight = heightSize;
7315                    mHeightCanMeasure = false;
7316                    measuredHeight |= MEASURED_STATE_TOO_SMALL;
7317                }
7318            }
7319        } else {
7320            mHeightCanMeasure = false;
7321        }
7322        if (mNativeClass != 0) {
7323            nativeSetHeightCanMeasure(mHeightCanMeasure);
7324        }
7325        // For the width, always use the given size unless unspecified.
7326        if (widthMode == MeasureSpec.UNSPECIFIED) {
7327            mWidthCanMeasure = true;
7328            measuredWidth = contentWidth;
7329        } else {
7330            if (measuredWidth < contentWidth) {
7331                measuredWidth |= MEASURED_STATE_TOO_SMALL;
7332            }
7333            mWidthCanMeasure = false;
7334        }
7335
7336        synchronized (this) {
7337            setMeasuredDimension(measuredWidth, measuredHeight);
7338        }
7339    }
7340
7341    @Override
7342    public boolean requestChildRectangleOnScreen(View child,
7343                                                 Rect rect,
7344                                                 boolean immediate) {
7345        if (mNativeClass == 0) {
7346            return false;
7347        }
7348        // don't scroll while in zoom animation. When it is done, we will adjust
7349        // the necessary components (e.g., WebTextView if it is in editing mode)
7350        if (mZoomManager.isFixedLengthAnimationInProgress()) {
7351            return false;
7352        }
7353
7354        rect.offset(child.getLeft() - child.getScrollX(),
7355                child.getTop() - child.getScrollY());
7356
7357        Rect content = new Rect(viewToContentX(mScrollX),
7358                viewToContentY(mScrollY),
7359                viewToContentX(mScrollX + getWidth()
7360                - getVerticalScrollbarWidth()),
7361                viewToContentY(mScrollY + getViewHeightWithTitle()));
7362        content = nativeSubtractLayers(content);
7363        int screenTop = contentToViewY(content.top);
7364        int screenBottom = contentToViewY(content.bottom);
7365        int height = screenBottom - screenTop;
7366        int scrollYDelta = 0;
7367
7368        if (rect.bottom > screenBottom) {
7369            int oneThirdOfScreenHeight = height / 3;
7370            if (rect.height() > 2 * oneThirdOfScreenHeight) {
7371                // If the rectangle is too tall to fit in the bottom two thirds
7372                // of the screen, place it at the top.
7373                scrollYDelta = rect.top - screenTop;
7374            } else {
7375                // If the rectangle will still fit on screen, we want its
7376                // top to be in the top third of the screen.
7377                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
7378            }
7379        } else if (rect.top < screenTop) {
7380            scrollYDelta = rect.top - screenTop;
7381        }
7382
7383        int screenLeft = contentToViewX(content.left);
7384        int screenRight = contentToViewX(content.right);
7385        int width = screenRight - screenLeft;
7386        int scrollXDelta = 0;
7387
7388        if (rect.right > screenRight && rect.left > screenLeft) {
7389            if (rect.width() > width) {
7390                scrollXDelta += (rect.left - screenLeft);
7391            } else {
7392                scrollXDelta += (rect.right - screenRight);
7393            }
7394        } else if (rect.left < screenLeft) {
7395            scrollXDelta -= (screenLeft - rect.left);
7396        }
7397
7398        if ((scrollYDelta | scrollXDelta) != 0) {
7399            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
7400        }
7401
7402        return false;
7403    }
7404
7405    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
7406            String replace, int newStart, int newEnd) {
7407        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
7408        arg.mReplace = replace;
7409        arg.mNewStart = newStart;
7410        arg.mNewEnd = newEnd;
7411        mTextGeneration++;
7412        arg.mTextGeneration = mTextGeneration;
7413        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
7414    }
7415
7416    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
7417        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
7418        arg.mEvent = event;
7419        arg.mCurrentText = currentText;
7420        // Increase our text generation number, and pass it to webcore thread
7421        mTextGeneration++;
7422        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
7423        // WebKit's document state is not saved until about to leave the page.
7424        // To make sure the host application, like Browser, has the up to date
7425        // document state when it goes to background, we force to save the
7426        // document state.
7427        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
7428        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
7429                cursorData(), 1000);
7430    }
7431
7432    /**
7433     * @hide
7434     */
7435    public synchronized WebViewCore getWebViewCore() {
7436        return mWebViewCore;
7437    }
7438
7439    /**
7440     * Used only by TouchEventQueue to store pending touch events.
7441     */
7442    private static class QueuedTouch {
7443        long mSequence;
7444        MotionEvent mEvent; // Optional
7445        TouchEventData mTed; // Optional
7446
7447        QueuedTouch mNext;
7448
7449        public QueuedTouch set(TouchEventData ted) {
7450            mSequence = ted.mSequence;
7451            mTed = ted;
7452            mEvent = null;
7453            mNext = null;
7454            return this;
7455        }
7456
7457        public QueuedTouch set(MotionEvent ev, long sequence) {
7458            mEvent = MotionEvent.obtain(ev);
7459            mSequence = sequence;
7460            mTed = null;
7461            mNext = null;
7462            return this;
7463        }
7464
7465        public QueuedTouch add(QueuedTouch other) {
7466            if (other.mSequence < mSequence) {
7467                other.mNext = this;
7468                return other;
7469            }
7470
7471            QueuedTouch insertAt = this;
7472            while (insertAt.mNext != null && insertAt.mNext.mSequence < other.mSequence) {
7473                insertAt = insertAt.mNext;
7474            }
7475            other.mNext = insertAt.mNext;
7476            insertAt.mNext = other;
7477            return this;
7478        }
7479    }
7480
7481    /**
7482     * WebView handles touch events asynchronously since some events must be passed to WebKit
7483     * for potentially slower processing. TouchEventQueue serializes touch events regardless
7484     * of which path they take to ensure that no events are ever processed out of order
7485     * by WebView.
7486     */
7487    private class TouchEventQueue {
7488        private long mNextTouchSequence = Long.MIN_VALUE + 1;
7489        private long mLastHandledTouchSequence = Long.MIN_VALUE;
7490        private long mIgnoreUntilSequence = Long.MIN_VALUE + 1;
7491
7492        // Events waiting to be processed.
7493        private QueuedTouch mTouchEventQueue;
7494
7495        // Known events that are waiting on a response before being enqueued.
7496        private QueuedTouch mPreQueue;
7497
7498        // Pool of QueuedTouch objects saved for later use.
7499        private QueuedTouch mQueuedTouchRecycleBin;
7500        private int mQueuedTouchRecycleCount;
7501
7502        private long mLastEventTime = Long.MAX_VALUE;
7503        private static final int MAX_RECYCLED_QUEUED_TOUCH = 15;
7504
7505        // milliseconds until we abandon hope of getting all of a previous gesture
7506        private static final int QUEUED_GESTURE_TIMEOUT = 1000;
7507
7508        private QueuedTouch obtainQueuedTouch() {
7509            if (mQueuedTouchRecycleBin != null) {
7510                QueuedTouch result = mQueuedTouchRecycleBin;
7511                mQueuedTouchRecycleBin = result.mNext;
7512                mQueuedTouchRecycleCount--;
7513                return result;
7514            }
7515            return new QueuedTouch();
7516        }
7517
7518        /**
7519         * Allow events with any currently missing sequence numbers to be skipped in processing.
7520         */
7521        public void ignoreCurrentlyMissingEvents() {
7522            mIgnoreUntilSequence = mNextTouchSequence;
7523
7524            // Run any events we have available and complete, pre-queued or otherwise.
7525            runQueuedAndPreQueuedEvents();
7526        }
7527
7528        private void runQueuedAndPreQueuedEvents() {
7529            QueuedTouch qd = mPreQueue;
7530            boolean fromPreQueue = true;
7531            while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) {
7532                handleQueuedTouch(qd);
7533                QueuedTouch recycleMe = qd;
7534                if (fromPreQueue) {
7535                    mPreQueue = qd.mNext;
7536                } else {
7537                    mTouchEventQueue = qd.mNext;
7538                }
7539                recycleQueuedTouch(recycleMe);
7540                mLastHandledTouchSequence++;
7541
7542                long nextPre = mPreQueue != null ? mPreQueue.mSequence : Long.MAX_VALUE;
7543                long nextQueued = mTouchEventQueue != null ?
7544                        mTouchEventQueue.mSequence : Long.MAX_VALUE;
7545                fromPreQueue = nextPre < nextQueued;
7546                qd = fromPreQueue ? mPreQueue : mTouchEventQueue;
7547            }
7548        }
7549
7550        /**
7551         * Add a TouchEventData to the pre-queue.
7552         *
7553         * An event in the pre-queue is an event that we know about that
7554         * has been sent to webkit, but that we haven't received back and
7555         * enqueued into the normal touch queue yet. If webkit ever times
7556         * out and we need to ignore currently missing events, we'll run
7557         * events from the pre-queue to patch the holes.
7558         *
7559         * @param ted TouchEventData to pre-queue
7560         */
7561        public void preQueueTouchEventData(TouchEventData ted) {
7562            QueuedTouch newTouch = obtainQueuedTouch().set(ted);
7563            if (mPreQueue == null) {
7564                mPreQueue = newTouch;
7565            } else {
7566                QueuedTouch insertionPoint = mPreQueue;
7567                while (insertionPoint.mNext != null &&
7568                        insertionPoint.mNext.mSequence < newTouch.mSequence) {
7569                    insertionPoint = insertionPoint.mNext;
7570                }
7571                newTouch.mNext = insertionPoint.mNext;
7572                insertionPoint.mNext = newTouch;
7573            }
7574        }
7575
7576        private void recycleQueuedTouch(QueuedTouch qd) {
7577            if (mQueuedTouchRecycleCount < MAX_RECYCLED_QUEUED_TOUCH) {
7578                qd.mNext = mQueuedTouchRecycleBin;
7579                mQueuedTouchRecycleBin = qd;
7580                mQueuedTouchRecycleCount++;
7581            }
7582        }
7583
7584        /**
7585         * Reset the touch event queue. This will dump any pending events
7586         * and reset the sequence numbering.
7587         */
7588        public void reset() {
7589            mNextTouchSequence = Long.MIN_VALUE + 1;
7590            mLastHandledTouchSequence = Long.MIN_VALUE;
7591            mIgnoreUntilSequence = Long.MIN_VALUE + 1;
7592            while (mTouchEventQueue != null) {
7593                QueuedTouch recycleMe = mTouchEventQueue;
7594                mTouchEventQueue = mTouchEventQueue.mNext;
7595                recycleQueuedTouch(recycleMe);
7596            }
7597            while (mPreQueue != null) {
7598                QueuedTouch recycleMe = mPreQueue;
7599                mPreQueue = mPreQueue.mNext;
7600                recycleQueuedTouch(recycleMe);
7601            }
7602        }
7603
7604        /**
7605         * Return the next valid sequence number for tagging incoming touch events.
7606         * @return The next touch event sequence number
7607         */
7608        public long nextTouchSequence() {
7609            return mNextTouchSequence++;
7610        }
7611
7612        /**
7613         * Enqueue a touch event in the form of TouchEventData.
7614         * The sequence number will be read from the mSequence field of the argument.
7615         *
7616         * If the touch event's sequence number is the next in line to be processed, it will
7617         * be handled before this method returns. Any subsequent events that have already
7618         * been queued will also be processed in their proper order.
7619         *
7620         * @param ted Touch data to be processed in order.
7621         * @return true if the event was processed before returning, false if it was just enqueued.
7622         */
7623        public boolean enqueueTouchEvent(TouchEventData ted) {
7624            // Remove from the pre-queue if present
7625            QueuedTouch preQueue = mPreQueue;
7626            if (preQueue != null) {
7627                // On exiting this block, preQueue is set to the pre-queued QueuedTouch object
7628                // if it was present in the pre-queue, and removed from the pre-queue itself.
7629                if (preQueue.mSequence == ted.mSequence) {
7630                    mPreQueue = preQueue.mNext;
7631                } else {
7632                    QueuedTouch prev = preQueue;
7633                    preQueue = null;
7634                    while (prev.mNext != null) {
7635                        if (prev.mNext.mSequence == ted.mSequence) {
7636                            preQueue = prev.mNext;
7637                            prev.mNext = preQueue.mNext;
7638                            break;
7639                        } else {
7640                            prev = prev.mNext;
7641                        }
7642                    }
7643                }
7644            }
7645
7646            if (ted.mSequence < mLastHandledTouchSequence) {
7647                // Stale event and we already moved on; drop it. (Should not be common.)
7648                Log.w(LOGTAG, "Stale touch event " + MotionEvent.actionToString(ted.mAction) +
7649                        " received from webcore; ignoring");
7650                return false;
7651            }
7652
7653            if (dropStaleGestures(ted.mMotionEvent, ted.mSequence)) {
7654                return false;
7655            }
7656
7657            // dropStaleGestures above might have fast-forwarded us to
7658            // an event we have already.
7659            runNextQueuedEvents();
7660
7661            if (mLastHandledTouchSequence + 1 == ted.mSequence) {
7662                if (preQueue != null) {
7663                    recycleQueuedTouch(preQueue);
7664                    preQueue = null;
7665                }
7666                handleQueuedTouchEventData(ted);
7667
7668                mLastHandledTouchSequence++;
7669
7670                // Do we have any more? Run them if so.
7671                runNextQueuedEvents();
7672            } else {
7673                // Reuse the pre-queued object if we had it.
7674                QueuedTouch qd = preQueue != null ? preQueue : obtainQueuedTouch().set(ted);
7675                mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd);
7676            }
7677            return true;
7678        }
7679
7680        /**
7681         * Enqueue a touch event in the form of a MotionEvent from the framework.
7682         *
7683         * If the touch event's sequence number is the next in line to be processed, it will
7684         * be handled before this method returns. Any subsequent events that have already
7685         * been queued will also be processed in their proper order.
7686         *
7687         * @param ev MotionEvent to be processed in order
7688         */
7689        public void enqueueTouchEvent(MotionEvent ev) {
7690            final long sequence = nextTouchSequence();
7691
7692            if (dropStaleGestures(ev, sequence)) {
7693                return;
7694            }
7695
7696            // dropStaleGestures above might have fast-forwarded us to
7697            // an event we have already.
7698            runNextQueuedEvents();
7699
7700            if (mLastHandledTouchSequence + 1 == sequence) {
7701                handleQueuedMotionEvent(ev);
7702
7703                mLastHandledTouchSequence++;
7704
7705                // Do we have any more? Run them if so.
7706                runNextQueuedEvents();
7707            } else {
7708                QueuedTouch qd = obtainQueuedTouch().set(ev, sequence);
7709                mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd);
7710            }
7711        }
7712
7713        private void runNextQueuedEvents() {
7714            QueuedTouch qd = mTouchEventQueue;
7715            while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) {
7716                handleQueuedTouch(qd);
7717                QueuedTouch recycleMe = qd;
7718                qd = qd.mNext;
7719                recycleQueuedTouch(recycleMe);
7720                mLastHandledTouchSequence++;
7721            }
7722            mTouchEventQueue = qd;
7723        }
7724
7725        private boolean dropStaleGestures(MotionEvent ev, long sequence) {
7726            if (ev != null && ev.getAction() == MotionEvent.ACTION_MOVE && !mConfirmMove) {
7727                // This is to make sure that we don't attempt to process a tap
7728                // or long press when webkit takes too long to get back to us.
7729                // The movement will be properly confirmed when we process the
7730                // enqueued event later.
7731                final int dx = Math.round(ev.getX()) - mLastTouchX;
7732                final int dy = Math.round(ev.getY()) - mLastTouchY;
7733                if (dx * dx + dy * dy > mTouchSlopSquare) {
7734                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
7735                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
7736                }
7737            }
7738
7739            if (mTouchEventQueue == null) {
7740                return sequence <= mLastHandledTouchSequence;
7741            }
7742
7743            // If we have a new down event and it's been a while since the last event
7744            // we saw, catch up as best we can and keep going.
7745            if (ev != null && ev.getAction() == MotionEvent.ACTION_DOWN) {
7746                long eventTime = ev.getEventTime();
7747                long lastHandledEventTime = mLastEventTime;
7748                if (eventTime > lastHandledEventTime + QUEUED_GESTURE_TIMEOUT) {
7749                    Log.w(LOGTAG, "Got ACTION_DOWN but still waiting on stale event. " +
7750                            "Catching up.");
7751                    runQueuedAndPreQueuedEvents();
7752
7753                    // Drop leftovers that we truly don't have.
7754                    QueuedTouch qd = mTouchEventQueue;
7755                    while (qd != null && qd.mSequence < sequence) {
7756                        QueuedTouch recycleMe = qd;
7757                        qd = qd.mNext;
7758                        recycleQueuedTouch(recycleMe);
7759                    }
7760                    mTouchEventQueue = qd;
7761                    mLastHandledTouchSequence = sequence - 1;
7762                }
7763            }
7764
7765            if (mIgnoreUntilSequence - 1 > mLastHandledTouchSequence) {
7766                QueuedTouch qd = mTouchEventQueue;
7767                while (qd != null && qd.mSequence < mIgnoreUntilSequence) {
7768                    QueuedTouch recycleMe = qd;
7769                    qd = qd.mNext;
7770                    recycleQueuedTouch(recycleMe);
7771                }
7772                mTouchEventQueue = qd;
7773                mLastHandledTouchSequence = mIgnoreUntilSequence - 1;
7774            }
7775
7776            if (mPreQueue != null) {
7777                // Drop stale prequeued events
7778                QueuedTouch qd = mPreQueue;
7779                while (qd != null && qd.mSequence < mIgnoreUntilSequence) {
7780                    QueuedTouch recycleMe = qd;
7781                    qd = qd.mNext;
7782                    recycleQueuedTouch(recycleMe);
7783                }
7784                mPreQueue = qd;
7785            }
7786
7787            return sequence <= mLastHandledTouchSequence;
7788        }
7789
7790        private void handleQueuedTouch(QueuedTouch qt) {
7791            if (qt.mTed != null) {
7792                handleQueuedTouchEventData(qt.mTed);
7793            } else {
7794                handleQueuedMotionEvent(qt.mEvent);
7795                qt.mEvent.recycle();
7796            }
7797        }
7798
7799        private void handleQueuedMotionEvent(MotionEvent ev) {
7800            mLastEventTime = ev.getEventTime();
7801            int action = ev.getActionMasked();
7802            if (ev.getPointerCount() > 1) {  // Multi-touch
7803                handleMultiTouchInWebView(ev);
7804            } else {
7805                final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
7806                if (detector != null && mPreventDefault != PREVENT_DEFAULT_YES) {
7807                    // ScaleGestureDetector needs a consistent event stream to operate properly.
7808                    // It won't take any action with fewer than two pointers, but it needs to
7809                    // update internal bookkeeping state.
7810                    detector.onTouchEvent(ev);
7811                }
7812
7813                handleTouchEventCommon(ev, action, Math.round(ev.getX()), Math.round(ev.getY()));
7814            }
7815        }
7816
7817        private void handleQueuedTouchEventData(TouchEventData ted) {
7818            if (ted.mMotionEvent != null) {
7819                mLastEventTime = ted.mMotionEvent.getEventTime();
7820            }
7821            if (!ted.mReprocess) {
7822                if (ted.mAction == MotionEvent.ACTION_DOWN
7823                        && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
7824                    // if prevent default is called from WebCore, UI
7825                    // will not handle the rest of the touch events any
7826                    // more.
7827                    mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES
7828                            : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
7829                } else if (ted.mAction == MotionEvent.ACTION_MOVE
7830                        && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
7831                    // the return for the first ACTION_MOVE will decide
7832                    // whether UI will handle touch or not. Currently no
7833                    // support for alternating prevent default
7834                    mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES
7835                            : PREVENT_DEFAULT_NO;
7836                }
7837                if (mPreventDefault == PREVENT_DEFAULT_YES) {
7838                    mTouchHighlightRegion.setEmpty();
7839                }
7840            } else {
7841                if (ted.mPoints.length > 1) {  // multi-touch
7842                    if (!ted.mNativeResult && mPreventDefault != PREVENT_DEFAULT_YES) {
7843                        mPreventDefault = PREVENT_DEFAULT_NO;
7844                        handleMultiTouchInWebView(ted.mMotionEvent);
7845                    } else {
7846                        mPreventDefault = PREVENT_DEFAULT_YES;
7847                    }
7848                    return;
7849                }
7850
7851                // prevent default is not called in WebCore, so the
7852                // message needs to be reprocessed in UI
7853                if (!ted.mNativeResult) {
7854                    // Following is for single touch.
7855                    switch (ted.mAction) {
7856                        case MotionEvent.ACTION_DOWN:
7857                            mLastDeferTouchX = ted.mPointsInView[0].x;
7858                            mLastDeferTouchY = ted.mPointsInView[0].y;
7859                            mDeferTouchMode = TOUCH_INIT_MODE;
7860                            break;
7861                        case MotionEvent.ACTION_MOVE: {
7862                            // no snapping in defer process
7863                            int x = ted.mPointsInView[0].x;
7864                            int y = ted.mPointsInView[0].y;
7865
7866                            if (mDeferTouchMode != TOUCH_DRAG_MODE) {
7867                                mDeferTouchMode = TOUCH_DRAG_MODE;
7868                                mLastDeferTouchX = x;
7869                                mLastDeferTouchY = y;
7870                                startScrollingLayer(x, y);
7871                                startDrag();
7872                            }
7873                            int deltaX = pinLocX((int) (mScrollX
7874                                    + mLastDeferTouchX - x))
7875                                    - mScrollX;
7876                            int deltaY = pinLocY((int) (mScrollY
7877                                    + mLastDeferTouchY - y))
7878                                    - mScrollY;
7879                            doDrag(deltaX, deltaY);
7880                            if (deltaX != 0) mLastDeferTouchX = x;
7881                            if (deltaY != 0) mLastDeferTouchY = y;
7882                            break;
7883                        }
7884                        case MotionEvent.ACTION_UP:
7885                        case MotionEvent.ACTION_CANCEL:
7886                            if (mDeferTouchMode == TOUCH_DRAG_MODE) {
7887                                // no fling in defer process
7888                                mScroller.springBack(mScrollX, mScrollY, 0,
7889                                        computeMaxScrollX(), 0,
7890                                        computeMaxScrollY());
7891                                invalidate();
7892                                WebViewCore.resumePriority();
7893                                WebViewCore.resumeUpdatePicture(mWebViewCore);
7894                            }
7895                            mDeferTouchMode = TOUCH_DONE_MODE;
7896                            break;
7897                        case WebViewCore.ACTION_DOUBLETAP:
7898                            // doDoubleTap() needs mLastTouchX/Y as anchor
7899                            mLastDeferTouchX = ted.mPointsInView[0].x;
7900                            mLastDeferTouchY = ted.mPointsInView[0].y;
7901                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
7902                            mDeferTouchMode = TOUCH_DONE_MODE;
7903                            break;
7904                        case WebViewCore.ACTION_LONGPRESS:
7905                            HitTestResult hitTest = getHitTestResult();
7906                            if (hitTest != null && hitTest.mType
7907                                    != HitTestResult.UNKNOWN_TYPE) {
7908                                performLongClick();
7909                            }
7910                            mDeferTouchMode = TOUCH_DONE_MODE;
7911                            break;
7912                    }
7913                }
7914            }
7915        }
7916    }
7917
7918    //-------------------------------------------------------------------------
7919    // Methods can be called from a separate thread, like WebViewCore
7920    // If it needs to call the View system, it has to send message.
7921    //-------------------------------------------------------------------------
7922
7923    /**
7924     * General handler to receive message coming from webkit thread
7925     */
7926    class PrivateHandler extends Handler {
7927        @Override
7928        public void handleMessage(Message msg) {
7929            // exclude INVAL_RECT_MSG_ID since it is frequently output
7930            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
7931                if (msg.what >= FIRST_PRIVATE_MSG_ID
7932                        && msg.what <= LAST_PRIVATE_MSG_ID) {
7933                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
7934                            - FIRST_PRIVATE_MSG_ID]);
7935                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
7936                        && msg.what <= LAST_PACKAGE_MSG_ID) {
7937                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
7938                            - FIRST_PACKAGE_MSG_ID]);
7939                } else {
7940                    Log.v(LOGTAG, Integer.toString(msg.what));
7941                }
7942            }
7943            if (mWebViewCore == null) {
7944                // after WebView's destroy() is called, skip handling messages.
7945                return;
7946            }
7947            if (mBlockWebkitViewMessages
7948                    && msg.what != WEBCORE_INITIALIZED_MSG_ID) {
7949                // Blocking messages from webkit
7950                return;
7951            }
7952            switch (msg.what) {
7953                case REMEMBER_PASSWORD: {
7954                    mDatabase.setUsernamePassword(
7955                            msg.getData().getString("host"),
7956                            msg.getData().getString("username"),
7957                            msg.getData().getString("password"));
7958                    ((Message) msg.obj).sendToTarget();
7959                    break;
7960                }
7961                case NEVER_REMEMBER_PASSWORD: {
7962                    mDatabase.setUsernamePassword(
7963                            msg.getData().getString("host"), null, null);
7964                    ((Message) msg.obj).sendToTarget();
7965                    break;
7966                }
7967                case PREVENT_DEFAULT_TIMEOUT: {
7968                    // if timeout happens, cancel it so that it won't block UI
7969                    // to continue handling touch events
7970                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
7971                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
7972                            || (msg.arg1 == MotionEvent.ACTION_MOVE
7973                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
7974                        cancelWebCoreTouchEvent(
7975                                viewToContentX(mLastTouchX + mScrollX),
7976                                viewToContentY(mLastTouchY + mScrollY),
7977                                true);
7978                    }
7979                    break;
7980                }
7981                case SCROLL_SELECT_TEXT: {
7982                    if (mAutoScrollX == 0 && mAutoScrollY == 0) {
7983                        mSentAutoScrollMessage = false;
7984                        break;
7985                    }
7986                    if (mScrollingLayer == 0) {
7987                        pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
7988                    } else {
7989                        mScrollingLayerRect.left += mAutoScrollX;
7990                        mScrollingLayerRect.top += mAutoScrollY;
7991                        nativeScrollLayer(mScrollingLayer,
7992                                mScrollingLayerRect.left,
7993                                mScrollingLayerRect.top);
7994                        invalidate();
7995                    }
7996                    sendEmptyMessageDelayed(
7997                            SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
7998                    break;
7999                }
8000                case SWITCH_TO_SHORTPRESS: {
8001                    mInitialHitTestResult = null; // set by updateSelection()
8002                    if (mTouchMode == TOUCH_INIT_MODE) {
8003                        if (!getSettings().supportTouchOnly()
8004                                && mPreventDefault != PREVENT_DEFAULT_YES) {
8005                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
8006                            updateSelection();
8007                        } else {
8008                            // set to TOUCH_SHORTPRESS_MODE so that it won't
8009                            // trigger double tap any more
8010                            mTouchMode = TOUCH_SHORTPRESS_MODE;
8011                        }
8012                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
8013                        mTouchMode = TOUCH_DONE_MODE;
8014                    }
8015                    break;
8016                }
8017                case SWITCH_TO_LONGPRESS: {
8018                    if (getSettings().supportTouchOnly()) {
8019                        removeTouchHighlight(false);
8020                    }
8021                    if (inFullScreenMode() || mDeferTouchProcess) {
8022                        TouchEventData ted = new TouchEventData();
8023                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
8024                        ted.mIds = new int[1];
8025                        ted.mIds[0] = 0;
8026                        ted.mPoints = new Point[1];
8027                        ted.mPoints[0] = new Point(viewToContentX(mLastTouchX + mScrollX),
8028                                                   viewToContentY(mLastTouchY + mScrollY));
8029                        ted.mPointsInView = new Point[1];
8030                        ted.mPointsInView[0] = new Point(mLastTouchX, mLastTouchY);
8031                        // metaState for long press is tricky. Should it be the
8032                        // state when the press started or when the press was
8033                        // released? Or some intermediary key state? For
8034                        // simplicity for now, we don't set it.
8035                        ted.mMetaState = 0;
8036                        ted.mReprocess = mDeferTouchProcess;
8037                        ted.mNativeLayer = nativeScrollableLayer(
8038                                ted.mPoints[0].x, ted.mPoints[0].y,
8039                                ted.mNativeLayerRect, null);
8040                        ted.mSequence = mTouchEventQueue.nextTouchSequence();
8041                        mTouchEventQueue.preQueueTouchEventData(ted);
8042                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
8043                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
8044                        mTouchMode = TOUCH_DONE_MODE;
8045                        performLongClick();
8046                    }
8047                    break;
8048                }
8049                case RELEASE_SINGLE_TAP: {
8050                    doShortPress();
8051                    break;
8052                }
8053                case SCROLL_TO_MSG_ID: {
8054                    // arg1 = animate, arg2 = onlyIfImeIsShowing
8055                    // obj = Point(x, y)
8056                    if (msg.arg2 == 1) {
8057                        // This scroll is intended to bring the textfield into
8058                        // view, but is only necessary if the IME is showing
8059                        InputMethodManager imm = InputMethodManager.peekInstance();
8060                        if (imm == null || !imm.isAcceptingText()
8061                                || (!imm.isActive(WebView.this) && (!inEditingMode()
8062                                || !imm.isActive(mWebTextView)))) {
8063                            break;
8064                        }
8065                    }
8066                    final Point p = (Point) msg.obj;
8067                    if (msg.arg1 == 1) {
8068                        spawnContentScrollTo(p.x, p.y);
8069                    } else {
8070                        setContentScrollTo(p.x, p.y);
8071                    }
8072                    break;
8073                }
8074                case UPDATE_ZOOM_RANGE: {
8075                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
8076                    // mScrollX contains the new minPrefWidth
8077                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
8078                    break;
8079                }
8080                case REPLACE_BASE_CONTENT: {
8081                    nativeReplaceBaseContent(msg.arg1);
8082                    break;
8083                }
8084                case NEW_PICTURE_MSG_ID: {
8085                    // called for new content
8086                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
8087                    setNewPicture(draw, true);
8088                    break;
8089                }
8090                case WEBCORE_INITIALIZED_MSG_ID:
8091                    // nativeCreate sets mNativeClass to a non-zero value
8092                    String drawableDir = BrowserFrame.getRawResFilename(
8093                            BrowserFrame.DRAWABLEDIR, mContext);
8094                    AssetManager am = mContext.getAssets();
8095                    nativeCreate(msg.arg1, drawableDir, am);
8096                    if (mDelaySetPicture != null) {
8097                        setNewPicture(mDelaySetPicture, true);
8098                        mDelaySetPicture = null;
8099                    }
8100                    break;
8101                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
8102                    // Make sure that the textfield is currently focused
8103                    // and representing the same node as the pointer.
8104                    if (inEditingMode() &&
8105                            mWebTextView.isSameTextField(msg.arg1)) {
8106                        if (msg.arg2 == mTextGeneration) {
8107                            String text = (String) msg.obj;
8108                            if (null == text) {
8109                                text = "";
8110                            }
8111                            mWebTextView.setTextAndKeepSelection(text);
8112                        }
8113                    }
8114                    break;
8115                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
8116                    displaySoftKeyboard(true);
8117                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
8118                case UPDATE_TEXT_SELECTION_MSG_ID:
8119                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
8120                            (WebViewCore.TextSelectionData) msg.obj);
8121                    break;
8122                case FORM_DID_BLUR:
8123                    if (inEditingMode()
8124                            && mWebTextView.isSameTextField(msg.arg1)) {
8125                        hideSoftKeyboard();
8126                    }
8127                    break;
8128                case RETURN_LABEL:
8129                    if (inEditingMode()
8130                            && mWebTextView.isSameTextField(msg.arg1)) {
8131                        mWebTextView.setHint((String) msg.obj);
8132                        InputMethodManager imm
8133                                = InputMethodManager.peekInstance();
8134                        // The hint is propagated to the IME in
8135                        // onCreateInputConnection.  If the IME is already
8136                        // active, restart it so that its hint text is updated.
8137                        if (imm != null && imm.isActive(mWebTextView)) {
8138                            imm.restartInput(mWebTextView);
8139                        }
8140                    }
8141                    break;
8142                case UNHANDLED_NAV_KEY:
8143                    navHandledKey(msg.arg1, 1, false, 0);
8144                    break;
8145                case UPDATE_TEXT_ENTRY_MSG_ID:
8146                    // this is sent after finishing resize in WebViewCore. Make
8147                    // sure the text edit box is still on the  screen.
8148                    if (inEditingMode() && nativeCursorIsTextInput()) {
8149                        rebuildWebTextView();
8150                    }
8151                    break;
8152                case CLEAR_TEXT_ENTRY:
8153                    clearTextEntry();
8154                    break;
8155                case INVAL_RECT_MSG_ID: {
8156                    Rect r = (Rect)msg.obj;
8157                    if (r == null) {
8158                        invalidate();
8159                    } else {
8160                        // we need to scale r from content into view coords,
8161                        // which viewInvalidate() does for us
8162                        viewInvalidate(r.left, r.top, r.right, r.bottom);
8163                    }
8164                    break;
8165                }
8166                case REQUEST_FORM_DATA:
8167                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
8168                    if (mWebTextView.isSameTextField(msg.arg1)) {
8169                        mWebTextView.setAdapterCustom(adapter);
8170                    }
8171                    break;
8172                case RESUME_WEBCORE_PRIORITY:
8173                    WebViewCore.resumePriority();
8174                    WebViewCore.resumeUpdatePicture(mWebViewCore);
8175                    break;
8176
8177                case LONG_PRESS_CENTER:
8178                    // as this is shared by keydown and trackballdown, reset all
8179                    // the states
8180                    mGotCenterDown = false;
8181                    mTrackballDown = false;
8182                    performLongClick();
8183                    break;
8184
8185                case WEBCORE_NEED_TOUCH_EVENTS:
8186                    mForwardTouchEvents = (msg.arg1 != 0);
8187                    break;
8188
8189                case PREVENT_TOUCH_ID:
8190                    if (inFullScreenMode()) {
8191                        break;
8192                    }
8193                    TouchEventData ted = (TouchEventData) msg.obj;
8194
8195                    if (mTouchEventQueue.enqueueTouchEvent(ted)) {
8196                        // WebCore is responding to us; remove pending timeout.
8197                        // It will be re-posted when needed.
8198                        removeMessages(PREVENT_DEFAULT_TIMEOUT);
8199                    }
8200                    break;
8201
8202                case REQUEST_KEYBOARD:
8203                    if (msg.arg1 == 0) {
8204                        hideSoftKeyboard();
8205                    } else {
8206                        displaySoftKeyboard(false);
8207                    }
8208                    break;
8209
8210                case FIND_AGAIN:
8211                    // Ignore if find has been dismissed.
8212                    if (mFindIsUp && mFindCallback != null) {
8213                        mFindCallback.findAll();
8214                    }
8215                    break;
8216
8217                case DRAG_HELD_MOTIONLESS:
8218                    mHeldMotionless = MOTIONLESS_TRUE;
8219                    invalidate();
8220                    // fall through to keep scrollbars awake
8221
8222                case AWAKEN_SCROLL_BARS:
8223                    if (mTouchMode == TOUCH_DRAG_MODE
8224                            && mHeldMotionless == MOTIONLESS_TRUE) {
8225                        awakenScrollBars(ViewConfiguration
8226                                .getScrollDefaultDelay(), false);
8227                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
8228                                .obtainMessage(AWAKEN_SCROLL_BARS),
8229                                ViewConfiguration.getScrollDefaultDelay());
8230                    }
8231                    break;
8232
8233                case DO_MOTION_UP:
8234                    doMotionUp(msg.arg1, msg.arg2);
8235                    break;
8236
8237                case SCREEN_ON:
8238                    setKeepScreenOn(msg.arg1 == 1);
8239                    break;
8240
8241                case ENTER_FULLSCREEN_VIDEO:
8242                    int layerId = msg.arg1;
8243
8244                    String url = (String) msg.obj;
8245                    if (mHTML5VideoViewProxy != null) {
8246                        mHTML5VideoViewProxy.enterFullScreenVideo(layerId, url);
8247                    }
8248                    break;
8249
8250                case SHOW_FULLSCREEN: {
8251                    View view = (View) msg.obj;
8252                    int orientation = msg.arg1;
8253                    int npp = msg.arg2;
8254
8255                    if (inFullScreenMode()) {
8256                        Log.w(LOGTAG, "Should not have another full screen.");
8257                        dismissFullScreenMode();
8258                    }
8259                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, orientation, npp);
8260                    mFullScreenHolder.setContentView(view);
8261                    mFullScreenHolder.show();
8262
8263                    break;
8264                }
8265                case HIDE_FULLSCREEN:
8266                    dismissFullScreenMode();
8267                    break;
8268
8269                case DOM_FOCUS_CHANGED:
8270                    if (inEditingMode()) {
8271                        nativeClearCursor();
8272                        rebuildWebTextView();
8273                    }
8274                    break;
8275
8276                case SHOW_RECT_MSG_ID: {
8277                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
8278                    int x = mScrollX;
8279                    int left = contentToViewX(data.mLeft);
8280                    int width = contentToViewDimension(data.mWidth);
8281                    int maxWidth = contentToViewDimension(data.mContentWidth);
8282                    int viewWidth = getViewWidth();
8283                    if (width < viewWidth) {
8284                        // center align
8285                        x += left + width / 2 - mScrollX - viewWidth / 2;
8286                    } else {
8287                        x += (int) (left + data.mXPercentInDoc * width
8288                                - mScrollX - data.mXPercentInView * viewWidth);
8289                    }
8290                    if (DebugFlags.WEB_VIEW) {
8291                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
8292                              width + ",maxWidth=" + maxWidth +
8293                              ",viewWidth=" + viewWidth + ",x="
8294                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
8295                              ",xPercentInView=" + data.mXPercentInView+ ")");
8296                    }
8297                    // use the passing content width to cap x as the current
8298                    // mContentWidth may not be updated yet
8299                    x = Math.max(0,
8300                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
8301                    int top = contentToViewY(data.mTop);
8302                    int height = contentToViewDimension(data.mHeight);
8303                    int maxHeight = contentToViewDimension(data.mContentHeight);
8304                    int viewHeight = getViewHeight();
8305                    int y = (int) (top + data.mYPercentInDoc * height -
8306                                   data.mYPercentInView * viewHeight);
8307                    if (DebugFlags.WEB_VIEW) {
8308                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
8309                              height + ",maxHeight=" + maxHeight +
8310                              ",viewHeight=" + viewHeight + ",y="
8311                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
8312                              ",yPercentInView=" + data.mYPercentInView+ ")");
8313                    }
8314                    // use the passing content height to cap y as the current
8315                    // mContentHeight may not be updated yet
8316                    y = Math.max(0,
8317                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
8318                    // We need to take into account the visible title height
8319                    // when scrolling since y is an absolute view position.
8320                    y = Math.max(0, y - getVisibleTitleHeightImpl());
8321                    scrollTo(x, y);
8322                    }
8323                    break;
8324
8325                case CENTER_FIT_RECT:
8326                    centerFitRect((Rect)msg.obj);
8327                    break;
8328
8329                case SET_SCROLLBAR_MODES:
8330                    mHorizontalScrollBarMode = msg.arg1;
8331                    mVerticalScrollBarMode = msg.arg2;
8332                    break;
8333
8334                case SELECTION_STRING_CHANGED:
8335                    if (mAccessibilityInjector != null) {
8336                        String selectionString = (String) msg.obj;
8337                        mAccessibilityInjector.onSelectionStringChange(selectionString);
8338                    }
8339                    break;
8340
8341                case SET_TOUCH_HIGHLIGHT_RECTS:
8342                    invalidate(mTouchHighlightRegion.getBounds());
8343                    mTouchHighlightRegion.setEmpty();
8344                    if (msg.obj != null) {
8345                        ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
8346                        for (Rect rect : rects) {
8347                            Rect viewRect = contentToViewRect(rect);
8348                            // some sites, like stories in nytimes.com, set
8349                            // mouse event handler in the top div. It is not
8350                            // user friendly to highlight the div if it covers
8351                            // more than half of the screen.
8352                            if (viewRect.width() < getWidth() >> 1
8353                                    || viewRect.height() < getHeight() >> 1) {
8354                                mTouchHighlightRegion.union(viewRect);
8355                                invalidate(viewRect);
8356                            } else {
8357                                Log.w(LOGTAG, "Skip the huge selection rect:"
8358                                        + viewRect);
8359                            }
8360                        }
8361                    }
8362                    break;
8363
8364                case SAVE_WEBARCHIVE_FINISHED:
8365                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
8366                    if (saveMessage.mCallback != null) {
8367                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
8368                    }
8369                    break;
8370
8371                case SET_AUTOFILLABLE:
8372                    mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
8373                    if (mWebTextView != null) {
8374                        mWebTextView.setAutoFillable(mAutoFillData.getQueryId());
8375                        rebuildWebTextView();
8376                    }
8377                    break;
8378
8379                case AUTOFILL_COMPLETE:
8380                    if (mWebTextView != null) {
8381                        // Clear the WebTextView adapter when AutoFill finishes
8382                        // so that the drop down gets cleared.
8383                        mWebTextView.setAdapterCustom(null);
8384                    }
8385                    break;
8386
8387                case SELECT_AT:
8388                    nativeSelectAt(msg.arg1, msg.arg2);
8389                    break;
8390
8391                default:
8392                    super.handleMessage(msg);
8393                    break;
8394            }
8395        }
8396    }
8397
8398    void setNewPicture(final WebViewCore.DrawData draw, boolean updateBaseLayer) {
8399        if (mNativeClass == 0) {
8400            if (mDelaySetPicture != null) {
8401                throw new IllegalStateException("Tried to setNewPicture with"
8402                        + " a delay picture already set! (memory leak)");
8403            }
8404            // Not initialized yet, delay set
8405            mDelaySetPicture = draw;
8406            return;
8407        }
8408        WebViewCore.ViewState viewState = draw.mViewState;
8409        boolean isPictureAfterFirstLayout = viewState != null;
8410        if (updateBaseLayer) {
8411            setBaseLayer(draw.mBaseLayer, draw.mInvalRegion,
8412                    getSettings().getShowVisualIndicator(),
8413                    isPictureAfterFirstLayout);
8414        }
8415        final Point viewSize = draw.mViewSize;
8416        if (isPictureAfterFirstLayout) {
8417            // Reset the last sent data here since dealing with new page.
8418            mLastWidthSent = 0;
8419            mZoomManager.onFirstLayout(draw);
8420            if (!mDrawHistory) {
8421                // Do not send the scroll event for this particular
8422                // scroll message.  Note that a scroll event may
8423                // still be fired if the user scrolls before the
8424                // message can be handled.
8425                mSendScrollEvent = false;
8426                setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
8427                mSendScrollEvent = true;
8428
8429                // As we are on a new page, remove the WebTextView. This
8430                // is necessary for page loads driven by webkit, and in
8431                // particular when the user was on a password field, so
8432                // the WebTextView was visible.
8433                clearTextEntry();
8434            }
8435        }
8436
8437        // We update the layout (i.e. request a layout from the
8438        // view system) if the last view size that we sent to
8439        // WebCore matches the view size of the picture we just
8440        // received in the fixed dimension.
8441        final boolean updateLayout = viewSize.x == mLastWidthSent
8442                && viewSize.y == mLastHeightSent;
8443        // Don't send scroll event for picture coming from webkit,
8444        // since the new picture may cause a scroll event to override
8445        // the saved history scroll position.
8446        mSendScrollEvent = false;
8447        recordNewContentSize(draw.mContentSize.x,
8448                draw.mContentSize.y, updateLayout);
8449        mSendScrollEvent = true;
8450        if (DebugFlags.WEB_VIEW) {
8451            Rect b = draw.mInvalRegion.getBounds();
8452            Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
8453                    b.left+","+b.top+","+b.right+","+b.bottom+"}");
8454        }
8455        invalidateContentRect(draw.mInvalRegion.getBounds());
8456
8457        if (mPictureListener != null) {
8458            mPictureListener.onNewPicture(WebView.this, capturePicture());
8459        }
8460
8461        // update the zoom information based on the new picture
8462        mZoomManager.onNewPicture(draw);
8463
8464        if (draw.mFocusSizeChanged && inEditingMode()) {
8465            mFocusSizeChanged = true;
8466        }
8467        if (isPictureAfterFirstLayout) {
8468            mViewManager.postReadyToDrawAll();
8469        }
8470    }
8471
8472    /**
8473     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
8474     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
8475     */
8476    private void updateTextSelectionFromMessage(int nodePointer,
8477            int textGeneration, WebViewCore.TextSelectionData data) {
8478        if (inEditingMode()
8479                && mWebTextView.isSameTextField(nodePointer)
8480                && textGeneration == mTextGeneration) {
8481            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
8482        }
8483    }
8484
8485    // Class used to use a dropdown for a <select> element
8486    private class InvokeListBox implements Runnable {
8487        // Whether the listbox allows multiple selection.
8488        private boolean     mMultiple;
8489        // Passed in to a list with multiple selection to tell
8490        // which items are selected.
8491        private int[]       mSelectedArray;
8492        // Passed in to a list with single selection to tell
8493        // where the initial selection is.
8494        private int         mSelection;
8495
8496        private Container[] mContainers;
8497
8498        // Need these to provide stable ids to my ArrayAdapter,
8499        // which normally does not have stable ids. (Bug 1250098)
8500        private class Container extends Object {
8501            /**
8502             * Possible values for mEnabled.  Keep in sync with OptionStatus in
8503             * WebViewCore.cpp
8504             */
8505            final static int OPTGROUP = -1;
8506            final static int OPTION_DISABLED = 0;
8507            final static int OPTION_ENABLED = 1;
8508
8509            String  mString;
8510            int     mEnabled;
8511            int     mId;
8512
8513            @Override
8514            public String toString() {
8515                return mString;
8516            }
8517        }
8518
8519        /**
8520         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
8521         *  and allow filtering.
8522         */
8523        private class MyArrayListAdapter extends ArrayAdapter<Container> {
8524            public MyArrayListAdapter() {
8525                super(mContext,
8526                        mMultiple ? com.android.internal.R.layout.select_dialog_multichoice :
8527                        com.android.internal.R.layout.webview_select_singlechoice,
8528                        mContainers);
8529            }
8530
8531            @Override
8532            public View getView(int position, View convertView,
8533                    ViewGroup parent) {
8534                // Always pass in null so that we will get a new CheckedTextView
8535                // Otherwise, an item which was previously used as an <optgroup>
8536                // element (i.e. has no check), could get used as an <option>
8537                // element, which needs a checkbox/radio, but it would not have
8538                // one.
8539                convertView = super.getView(position, null, parent);
8540                Container c = item(position);
8541                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
8542                    // ListView does not draw dividers between disabled and
8543                    // enabled elements.  Use a LinearLayout to provide dividers
8544                    LinearLayout layout = new LinearLayout(mContext);
8545                    layout.setOrientation(LinearLayout.VERTICAL);
8546                    if (position > 0) {
8547                        View dividerTop = new View(mContext);
8548                        dividerTop.setBackgroundResource(
8549                                android.R.drawable.divider_horizontal_bright);
8550                        layout.addView(dividerTop);
8551                    }
8552
8553                    if (Container.OPTGROUP == c.mEnabled) {
8554                        // Currently select_dialog_multichoice uses CheckedTextViews.
8555                        // If that changes, the class cast will no longer be valid.
8556                        if (mMultiple) {
8557                            Assert.assertTrue(convertView instanceof CheckedTextView);
8558                            ((CheckedTextView) convertView).setCheckMarkDrawable(null);
8559                        }
8560                    } else {
8561                        // c.mEnabled == Container.OPTION_DISABLED
8562                        // Draw the disabled element in a disabled state.
8563                        convertView.setEnabled(false);
8564                    }
8565
8566                    layout.addView(convertView);
8567                    if (position < getCount() - 1) {
8568                        View dividerBottom = new View(mContext);
8569                        dividerBottom.setBackgroundResource(
8570                                android.R.drawable.divider_horizontal_bright);
8571                        layout.addView(dividerBottom);
8572                    }
8573                    return layout;
8574                }
8575                return convertView;
8576            }
8577
8578            @Override
8579            public boolean hasStableIds() {
8580                // AdapterView's onChanged method uses this to determine whether
8581                // to restore the old state.  Return false so that the old (out
8582                // of date) state does not replace the new, valid state.
8583                return false;
8584            }
8585
8586            private Container item(int position) {
8587                if (position < 0 || position >= getCount()) {
8588                    return null;
8589                }
8590                return (Container) getItem(position);
8591            }
8592
8593            @Override
8594            public long getItemId(int position) {
8595                Container item = item(position);
8596                if (item == null) {
8597                    return -1;
8598                }
8599                return item.mId;
8600            }
8601
8602            @Override
8603            public boolean areAllItemsEnabled() {
8604                return false;
8605            }
8606
8607            @Override
8608            public boolean isEnabled(int position) {
8609                Container item = item(position);
8610                if (item == null) {
8611                    return false;
8612                }
8613                return Container.OPTION_ENABLED == item.mEnabled;
8614            }
8615        }
8616
8617        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
8618            mMultiple = true;
8619            mSelectedArray = selected;
8620
8621            int length = array.length;
8622            mContainers = new Container[length];
8623            for (int i = 0; i < length; i++) {
8624                mContainers[i] = new Container();
8625                mContainers[i].mString = array[i];
8626                mContainers[i].mEnabled = enabled[i];
8627                mContainers[i].mId = i;
8628            }
8629        }
8630
8631        private InvokeListBox(String[] array, int[] enabled, int selection) {
8632            mSelection = selection;
8633            mMultiple = false;
8634
8635            int length = array.length;
8636            mContainers = new Container[length];
8637            for (int i = 0; i < length; i++) {
8638                mContainers[i] = new Container();
8639                mContainers[i].mString = array[i];
8640                mContainers[i].mEnabled = enabled[i];
8641                mContainers[i].mId = i;
8642            }
8643        }
8644
8645        /*
8646         * Whenever the data set changes due to filtering, this class ensures
8647         * that the checked item remains checked.
8648         */
8649        private class SingleDataSetObserver extends DataSetObserver {
8650            private long        mCheckedId;
8651            private ListView    mListView;
8652            private Adapter     mAdapter;
8653
8654            /*
8655             * Create a new observer.
8656             * @param id The ID of the item to keep checked.
8657             * @param l ListView for getting and clearing the checked states
8658             * @param a Adapter for getting the IDs
8659             */
8660            public SingleDataSetObserver(long id, ListView l, Adapter a) {
8661                mCheckedId = id;
8662                mListView = l;
8663                mAdapter = a;
8664            }
8665
8666            @Override
8667            public void onChanged() {
8668                // The filter may have changed which item is checked.  Find the
8669                // item that the ListView thinks is checked.
8670                int position = mListView.getCheckedItemPosition();
8671                long id = mAdapter.getItemId(position);
8672                if (mCheckedId != id) {
8673                    // Clear the ListView's idea of the checked item, since
8674                    // it is incorrect
8675                    mListView.clearChoices();
8676                    // Search for mCheckedId.  If it is in the filtered list,
8677                    // mark it as checked
8678                    int count = mAdapter.getCount();
8679                    for (int i = 0; i < count; i++) {
8680                        if (mAdapter.getItemId(i) == mCheckedId) {
8681                            mListView.setItemChecked(i, true);
8682                            break;
8683                        }
8684                    }
8685                }
8686            }
8687        }
8688
8689        public void run() {
8690            final ListView listView = (ListView) LayoutInflater.from(mContext)
8691                    .inflate(com.android.internal.R.layout.select_dialog, null);
8692            final MyArrayListAdapter adapter = new MyArrayListAdapter();
8693            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
8694                    .setView(listView).setCancelable(true)
8695                    .setInverseBackgroundForced(true);
8696
8697            if (mMultiple) {
8698                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
8699                    public void onClick(DialogInterface dialog, int which) {
8700                        mWebViewCore.sendMessage(
8701                                EventHub.LISTBOX_CHOICES,
8702                                adapter.getCount(), 0,
8703                                listView.getCheckedItemPositions());
8704                    }});
8705                b.setNegativeButton(android.R.string.cancel,
8706                        new DialogInterface.OnClickListener() {
8707                    public void onClick(DialogInterface dialog, int which) {
8708                        mWebViewCore.sendMessage(
8709                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
8710                }});
8711            }
8712            mListBoxDialog = b.create();
8713            listView.setAdapter(adapter);
8714            listView.setFocusableInTouchMode(true);
8715            // There is a bug (1250103) where the checks in a ListView with
8716            // multiple items selected are associated with the positions, not
8717            // the ids, so the items do not properly retain their checks when
8718            // filtered.  Do not allow filtering on multiple lists until
8719            // that bug is fixed.
8720
8721            listView.setTextFilterEnabled(!mMultiple);
8722            if (mMultiple) {
8723                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
8724                int length = mSelectedArray.length;
8725                for (int i = 0; i < length; i++) {
8726                    listView.setItemChecked(mSelectedArray[i], true);
8727                }
8728            } else {
8729                listView.setOnItemClickListener(new OnItemClickListener() {
8730                    public void onItemClick(AdapterView<?> parent, View v,
8731                            int position, long id) {
8732                        // Rather than sending the message right away, send it
8733                        // after the page regains focus.
8734                        mListBoxMessage = Message.obtain(null,
8735                                EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0);
8736                        mListBoxDialog.dismiss();
8737                        mListBoxDialog = null;
8738                    }
8739                });
8740                if (mSelection != -1) {
8741                    listView.setSelection(mSelection);
8742                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
8743                    listView.setItemChecked(mSelection, true);
8744                    DataSetObserver observer = new SingleDataSetObserver(
8745                            adapter.getItemId(mSelection), listView, adapter);
8746                    adapter.registerDataSetObserver(observer);
8747                }
8748            }
8749            mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
8750                public void onCancel(DialogInterface dialog) {
8751                    mWebViewCore.sendMessage(
8752                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
8753                    mListBoxDialog = null;
8754                }
8755            });
8756            mListBoxDialog.show();
8757        }
8758    }
8759
8760    private Message mListBoxMessage;
8761
8762    /*
8763     * Request a dropdown menu for a listbox with multiple selection.
8764     *
8765     * @param array Labels for the listbox.
8766     * @param enabledArray  State for each element in the list.  See static
8767     *      integers in Container class.
8768     * @param selectedArray Which positions are initally selected.
8769     */
8770    void requestListBox(String[] array, int[] enabledArray, int[]
8771            selectedArray) {
8772        mPrivateHandler.post(
8773                new InvokeListBox(array, enabledArray, selectedArray));
8774    }
8775
8776    /*
8777     * Request a dropdown menu for a listbox with single selection or a single
8778     * <select> element.
8779     *
8780     * @param array Labels for the listbox.
8781     * @param enabledArray  State for each element in the list.  See static
8782     *      integers in Container class.
8783     * @param selection Which position is initally selected.
8784     */
8785    void requestListBox(String[] array, int[] enabledArray, int selection) {
8786        mPrivateHandler.post(
8787                new InvokeListBox(array, enabledArray, selection));
8788    }
8789
8790    // called by JNI
8791    private void sendMoveFocus(int frame, int node) {
8792        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
8793                new WebViewCore.CursorData(frame, node, 0, 0));
8794    }
8795
8796    // called by JNI
8797    private void sendMoveMouse(int frame, int node, int x, int y) {
8798        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
8799                new WebViewCore.CursorData(frame, node, x, y));
8800    }
8801
8802    /*
8803     * Send a mouse move event to the webcore thread.
8804     *
8805     * @param removeFocus Pass true to remove the WebTextView, if present.
8806     * @param stopPaintingCaret Stop drawing the blinking caret if true.
8807     * called by JNI
8808     */
8809    @SuppressWarnings("unused")
8810    private void sendMoveMouseIfLatest(boolean removeFocus, boolean stopPaintingCaret) {
8811        if (removeFocus) {
8812            clearTextEntry();
8813        }
8814        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
8815                stopPaintingCaret ? 1 : 0, 0,
8816                cursorData());
8817    }
8818
8819    /**
8820     * Called by JNI to send a message to the webcore thread that the user
8821     * touched the webpage.
8822     * @param touchGeneration Generation number of the touch, to ignore touches
8823     *      after a new one has been generated.
8824     * @param frame Pointer to the frame holding the node that was touched.
8825     * @param node Pointer to the node touched.
8826     * @param x x-position of the touch.
8827     * @param y y-position of the touch.
8828     */
8829    private void sendMotionUp(int touchGeneration,
8830            int frame, int node, int x, int y) {
8831        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
8832        touchUpData.mMoveGeneration = touchGeneration;
8833        touchUpData.mFrame = frame;
8834        touchUpData.mNode = node;
8835        touchUpData.mX = x;
8836        touchUpData.mY = y;
8837        touchUpData.mNativeLayer = nativeScrollableLayer(
8838                x, y, touchUpData.mNativeLayerRect, null);
8839        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
8840    }
8841
8842
8843    private int getScaledMaxXScroll() {
8844        int width;
8845        if (mHeightCanMeasure == false) {
8846            width = getViewWidth() / 4;
8847        } else {
8848            Rect visRect = new Rect();
8849            calcOurVisibleRect(visRect);
8850            width = visRect.width() / 2;
8851        }
8852        // FIXME the divisor should be retrieved from somewhere
8853        return viewToContentX(width);
8854    }
8855
8856    private int getScaledMaxYScroll() {
8857        int height;
8858        if (mHeightCanMeasure == false) {
8859            height = getViewHeight() / 4;
8860        } else {
8861            Rect visRect = new Rect();
8862            calcOurVisibleRect(visRect);
8863            height = visRect.height() / 2;
8864        }
8865        // FIXME the divisor should be retrieved from somewhere
8866        // the closest thing today is hard-coded into ScrollView.java
8867        // (from ScrollView.java, line 363)   int maxJump = height/2;
8868        return Math.round(height * mZoomManager.getInvScale());
8869    }
8870
8871    /**
8872     * Called by JNI to invalidate view
8873     */
8874    private void viewInvalidate() {
8875        invalidate();
8876    }
8877
8878    /**
8879     * Pass the key directly to the page.  This assumes that
8880     * nativePageShouldHandleShiftAndArrows() returned true.
8881     */
8882    private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
8883        int keyEventAction;
8884        int eventHubAction;
8885        if (down) {
8886            keyEventAction = KeyEvent.ACTION_DOWN;
8887            eventHubAction = EventHub.KEY_DOWN;
8888            playSoundEffect(keyCodeToSoundsEffect(keyCode));
8889        } else {
8890            keyEventAction = KeyEvent.ACTION_UP;
8891            eventHubAction = EventHub.KEY_UP;
8892        }
8893
8894        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
8895                1, (metaState & KeyEvent.META_SHIFT_ON)
8896                | (metaState & KeyEvent.META_ALT_ON)
8897                | (metaState & KeyEvent.META_SYM_ON)
8898                , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
8899        mWebViewCore.sendMessage(eventHubAction, event);
8900    }
8901
8902    // return true if the key was handled
8903    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
8904            long time) {
8905        if (mNativeClass == 0) {
8906            return false;
8907        }
8908        mInitialHitTestResult = null;
8909        mLastCursorTime = time;
8910        mLastCursorBounds = nativeGetCursorRingBounds();
8911        boolean keyHandled
8912                = nativeMoveCursor(keyCode, count, noScroll) == false;
8913        if (DebugFlags.WEB_VIEW) {
8914            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
8915                    + " mLastCursorTime=" + mLastCursorTime
8916                    + " handled=" + keyHandled);
8917        }
8918        if (keyHandled == false) {
8919            return keyHandled;
8920        }
8921        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
8922        if (contentCursorRingBounds.isEmpty()) return keyHandled;
8923        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
8924        // set last touch so that context menu related functions will work
8925        mLastTouchX = (viewCursorRingBounds.left + viewCursorRingBounds.right) / 2;
8926        mLastTouchY = (viewCursorRingBounds.top + viewCursorRingBounds.bottom) / 2;
8927        if (mHeightCanMeasure == false) {
8928            return keyHandled;
8929        }
8930        Rect visRect = new Rect();
8931        calcOurVisibleRect(visRect);
8932        Rect outset = new Rect(visRect);
8933        int maxXScroll = visRect.width() / 2;
8934        int maxYScroll = visRect.height() / 2;
8935        outset.inset(-maxXScroll, -maxYScroll);
8936        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
8937            return keyHandled;
8938        }
8939        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
8940        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
8941                maxXScroll);
8942        if (maxH > 0) {
8943            pinScrollBy(maxH, 0, true, 0);
8944        } else {
8945            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
8946                    -maxXScroll);
8947            if (maxH < 0) {
8948                pinScrollBy(maxH, 0, true, 0);
8949            }
8950        }
8951        if (mLastCursorBounds.isEmpty()) return keyHandled;
8952        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
8953            return keyHandled;
8954        }
8955        if (DebugFlags.WEB_VIEW) {
8956            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
8957                    + contentCursorRingBounds);
8958        }
8959        requestRectangleOnScreen(viewCursorRingBounds);
8960        return keyHandled;
8961    }
8962
8963    /**
8964     * @return Whether accessibility script has been injected.
8965     */
8966    private boolean accessibilityScriptInjected() {
8967        // TODO: Maybe the injected script should announce its presence in
8968        // the page meta-tag so the nativePageShouldHandleShiftAndArrows
8969        // will check that as one of the conditions it looks for
8970        return mAccessibilityScriptInjected;
8971    }
8972
8973    /**
8974     * Set the background color. It's white by default. Pass
8975     * zero to make the view transparent.
8976     * @param color   the ARGB color described by Color.java
8977     */
8978    @Override
8979    public void setBackgroundColor(int color) {
8980        mBackgroundColor = color;
8981        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
8982    }
8983
8984    /**
8985     * @deprecated This method is now obsolete.
8986     */
8987    @Deprecated
8988    public void debugDump() {
8989        checkThread();
8990        nativeDebugDump();
8991        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
8992    }
8993
8994    /**
8995     * Draw the HTML page into the specified canvas. This call ignores any
8996     * view-specific zoom, scroll offset, or other changes. It does not draw
8997     * any view-specific chrome, such as progress or URL bars.
8998     *
8999     * @hide only needs to be accessible to Browser and testing
9000     */
9001    public void drawPage(Canvas canvas) {
9002        nativeDraw(canvas, 0, 0, false);
9003    }
9004
9005    /**
9006     * Enable the communication b/t the webView and VideoViewProxy
9007     *
9008     * @hide only used by the Browser
9009     */
9010    public void setHTML5VideoViewProxy(HTML5VideoViewProxy proxy) {
9011        mHTML5VideoViewProxy = proxy;
9012    }
9013
9014    /**
9015     * Enable expanded tiles bound for smoother scrolling.
9016     *
9017     * @hide only used by the Browser
9018     */
9019    public void setExpandedTileBounds(boolean enabled) {
9020        nativeSetExpandedTileBounds(enabled);
9021    }
9022
9023    /**
9024     * Set the time to wait between passing touches to WebCore. See also the
9025     * TOUCH_SENT_INTERVAL member for further discussion.
9026     *
9027     * @hide This is only used by the DRT test application.
9028     */
9029    public void setTouchInterval(int interval) {
9030        mCurrentTouchInterval = interval;
9031    }
9032
9033    /**
9034     *  Update our cache with updatedText.
9035     *  @param updatedText  The new text to put in our cache.
9036     *  @hide
9037     */
9038    protected void updateCachedTextfield(String updatedText) {
9039        // Also place our generation number so that when we look at the cache
9040        // we recognize that it is up to date.
9041        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
9042    }
9043
9044    /*package*/ void autoFillForm(int autoFillQueryId) {
9045        mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0);
9046    }
9047
9048    /* package */ ViewManager getViewManager() {
9049        return mViewManager;
9050    }
9051
9052    private static void checkThread() {
9053        if (Looper.myLooper() != Looper.getMainLooper()) {
9054            RuntimeException exception = new RuntimeException(
9055                    "A WebView method was called on thread '" +
9056                    Thread.currentThread().getName() + "'. " +
9057                    "All WebView methods must be called on the UI thread. " +
9058                    "Future versions of WebView may not support use on other threads.");
9059            Log.e(LOGTAG, Log.getStackTraceString(exception));
9060            StrictMode.onWebViewMethodCalledOnWrongThread(exception);
9061        }
9062    }
9063
9064    /**
9065     * Begin collecting per-tile profiling data
9066     *
9067     * @hide only used by profiling tests
9068     */
9069    public void tileProfilingStart() {
9070        nativeTileProfilingStart();
9071    }
9072    /**
9073     * Return per-tile profiling data
9074     *
9075     * @hide only used by profiling tests
9076     */
9077    public float tileProfilingStop() {
9078        return nativeTileProfilingStop();
9079    }
9080
9081    /** @hide only used by profiling tests */
9082    public void tileProfilingClear() {
9083        nativeTileProfilingClear();
9084    }
9085    /** @hide only used by profiling tests */
9086    public int tileProfilingNumFrames() {
9087        return nativeTileProfilingNumFrames();
9088    }
9089    /** @hide only used by profiling tests */
9090    public int tileProfilingNumTilesInFrame(int frame) {
9091        return nativeTileProfilingNumTilesInFrame(frame);
9092    }
9093    /** @hide only used by profiling tests */
9094    public int tileProfilingGetInt(int frame, int tile, String key) {
9095        return nativeTileProfilingGetInt(frame, tile, key);
9096    }
9097    /** @hide only used by profiling tests */
9098    public float tileProfilingGetFloat(int frame, int tile, String key) {
9099        return nativeTileProfilingGetFloat(frame, tile, key);
9100    }
9101
9102    private native int nativeCacheHitFramePointer();
9103    private native boolean  nativeCacheHitIsPlugin();
9104    private native Rect nativeCacheHitNodeBounds();
9105    private native int nativeCacheHitNodePointer();
9106    /* package */ native void nativeClearCursor();
9107    private native void     nativeCreate(int ptr, String drawableDir, AssetManager am);
9108    private native int      nativeCursorFramePointer();
9109    private native Rect     nativeCursorNodeBounds();
9110    private native int nativeCursorNodePointer();
9111    private native boolean  nativeCursorIntersects(Rect visibleRect);
9112    private native boolean  nativeCursorIsAnchor();
9113    private native boolean  nativeCursorIsTextInput();
9114    private native Point    nativeCursorPosition();
9115    private native String   nativeCursorText();
9116    /**
9117     * Returns true if the native cursor node says it wants to handle key events
9118     * (ala plugins). This can only be called if mNativeClass is non-zero!
9119     */
9120    private native boolean  nativeCursorWantsKeyEvents();
9121    private native void     nativeDebugDump();
9122    private native void     nativeDestroy();
9123
9124    /**
9125     * Draw the picture set with a background color and extra. If
9126     * "splitIfNeeded" is true and the return value is not 0, the return value
9127     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
9128     * native allocation can be freed.
9129     */
9130    private native int nativeDraw(Canvas canvas, int color, int extra,
9131            boolean splitIfNeeded);
9132    private native void     nativeDumpDisplayTree(String urlOrNull);
9133    private native boolean  nativeEvaluateLayersAnimations();
9134    private native int      nativeGetDrawGLFunction(Rect rect, Rect viewRect,
9135            float scale, int extras);
9136    private native void     nativeUpdateDrawGLFunction(Rect rect, Rect viewRect);
9137    private native void     nativeExtendSelection(int x, int y);
9138    private native int      nativeFindAll(String findLower, String findUpper,
9139            boolean sameAsLastSearch);
9140    private native void     nativeFindNext(boolean forward);
9141    /* package */ native int      nativeFocusCandidateFramePointer();
9142    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
9143    /* package */ native boolean  nativeFocusCandidateIsPassword();
9144    private native boolean  nativeFocusCandidateIsRtlText();
9145    private native boolean  nativeFocusCandidateIsTextInput();
9146    /* package */ native int      nativeFocusCandidateMaxLength();
9147    /* package */ native boolean  nativeFocusCandidateIsAutoComplete();
9148    /* package */ native String   nativeFocusCandidateName();
9149    private native Rect     nativeFocusCandidateNodeBounds();
9150    /**
9151     * @return A Rect with left, top, right, bottom set to the corresponding
9152     * padding values in the focus candidate, if it is a textfield/textarea with
9153     * a style.  Otherwise return null.  This is not actually a rectangle; Rect
9154     * is being used to pass four integers.
9155     */
9156    private native Rect     nativeFocusCandidatePaddingRect();
9157    /* package */ native int      nativeFocusCandidatePointer();
9158    private native String   nativeFocusCandidateText();
9159    /* package */ native float    nativeFocusCandidateTextSize();
9160    /* package */ native int nativeFocusCandidateLineHeight();
9161    /**
9162     * Returns an integer corresponding to WebView.cpp::type.
9163     * See WebTextView.setType()
9164     */
9165    private native int      nativeFocusCandidateType();
9166    private native boolean  nativeFocusIsPlugin();
9167    private native Rect     nativeFocusNodeBounds();
9168    /* package */ native int nativeFocusNodePointer();
9169    private native Rect     nativeGetCursorRingBounds();
9170    private native String   nativeGetSelection();
9171    private native boolean  nativeHasCursorNode();
9172    private native boolean  nativeHasFocusNode();
9173    private native void     nativeHideCursor();
9174    private native boolean  nativeHitSelection(int x, int y);
9175    private native String   nativeImageURI(int x, int y);
9176    private native void     nativeInstrumentReport();
9177    private native Rect     nativeLayerBounds(int layer);
9178    /* package */ native boolean nativeMoveCursorToNextTextInput();
9179    // return true if the page has been scrolled
9180    private native boolean  nativeMotionUp(int x, int y, int slop);
9181    // returns false if it handled the key
9182    private native boolean  nativeMoveCursor(int keyCode, int count,
9183            boolean noScroll);
9184    private native int      nativeMoveGeneration();
9185    private native void     nativeMoveSelection(int x, int y);
9186    /**
9187     * @return true if the page should get the shift and arrow keys, rather
9188     * than select text/navigation.
9189     *
9190     * If the focus is a plugin, or if the focus and cursor match and are
9191     * a contentEditable element, then the page should handle these keys.
9192     */
9193    private native boolean  nativePageShouldHandleShiftAndArrows();
9194    private native boolean  nativePointInNavCache(int x, int y, int slop);
9195    // Like many other of our native methods, you must make sure that
9196    // mNativeClass is not null before calling this method.
9197    private native void     nativeRecordButtons(boolean focused,
9198            boolean pressed, boolean invalidate);
9199    private native void     nativeResetSelection();
9200    private native Point    nativeSelectableText();
9201    private native void     nativeSelectAll();
9202    private native void     nativeSelectBestAt(Rect rect);
9203    private native void     nativeSelectAt(int x, int y);
9204    private native int      nativeSelectionX();
9205    private native int      nativeSelectionY();
9206    private native int      nativeFindIndex();
9207    private native void     nativeSetExtendSelection();
9208    private native void     nativeSetFindIsEmpty();
9209    private native void     nativeSetFindIsUp(boolean isUp);
9210    private native void     nativeSetHeightCanMeasure(boolean measure);
9211    private native void     nativeSetBaseLayer(int layer, Region invalRegion,
9212            boolean showVisualIndicator, boolean isPictureAfterFirstLayout);
9213    private native int      nativeGetBaseLayer();
9214    private native void     nativeShowCursorTimed();
9215    private native void     nativeReplaceBaseContent(int content);
9216    private native void     nativeCopyBaseContentToPicture(Picture pict);
9217    private native boolean  nativeHasContent();
9218    private native void     nativeSetSelectionPointer(boolean set,
9219            float scale, int x, int y);
9220    private native boolean  nativeStartSelection(int x, int y);
9221    private native void     nativeStopGL();
9222    private native Rect     nativeSubtractLayers(Rect content);
9223    private native int      nativeTextGeneration();
9224    private native void     nativeTileProfilingStart();
9225    private native float    nativeTileProfilingStop();
9226    private native void     nativeTileProfilingClear();
9227    private native int      nativeTileProfilingNumFrames();
9228    private native int      nativeTileProfilingNumTilesInFrame(int frame);
9229    private native int      nativeTileProfilingGetInt(int frame, int tile, String key);
9230    private native float    nativeTileProfilingGetFloat(int frame, int tile, String key);
9231    // Never call this version except by updateCachedTextfield(String) -
9232    // we always want to pass in our generation number.
9233    private native void     nativeUpdateCachedTextfield(String updatedText,
9234            int generation);
9235    private native boolean  nativeWordSelection(int x, int y);
9236    // return NO_LEFTEDGE means failure.
9237    static final int NO_LEFTEDGE = -1;
9238    native int nativeGetBlockLeftEdge(int x, int y, float scale);
9239
9240    private native void nativeSetExpandedTileBounds(boolean enabled);
9241
9242    // Returns a pointer to the scrollable LayerAndroid at the given point.
9243    private native int      nativeScrollableLayer(int x, int y, Rect scrollRect,
9244            Rect scrollBounds);
9245    /**
9246     * Scroll the specified layer.
9247     * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer.
9248     * @param newX Destination x position to which to scroll.
9249     * @param newY Destination y position to which to scroll.
9250     * @return True if the layer is successfully scrolled.
9251     */
9252    private native boolean  nativeScrollLayer(int layer, int newX, int newY);
9253    private native int      nativeGetBackgroundColor();
9254    native void     nativeSetProperty(String key, String value);
9255    native String   nativeGetProperty(String key);
9256}
9257