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