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