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