WebView.java revision 91fc3cf3b62833515a48ceb59546200994c6af5c
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        int saveCount = canvas.save();
3739        if (mInOverScrollMode && !getSettings()
3740                .getUseWebViewBackgroundForOverscrollBackground()) {
3741            drawOverScrollBackground(canvas);
3742        }
3743        if (mTitleBar != null) {
3744            canvas.translate(0, (int) mTitleBar.getHeight());
3745        }
3746        drawContent(canvas);
3747        canvas.restoreToCount(saveCount);
3748
3749        if (AUTO_REDRAW_HACK && mAutoRedraw) {
3750            invalidate();
3751        }
3752        if (inEditingMode()) {
3753            mWebTextView.onDrawSubstitute();
3754        }
3755        mWebViewCore.signalRepaintDone();
3756
3757        if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
3758            invalidate();
3759        }
3760
3761        // paint the highlight in the end
3762        if (!mTouchHighlightRegion.isEmpty()) {
3763            if (mTouchHightlightPaint == null) {
3764                mTouchHightlightPaint = new Paint();
3765                mTouchHightlightPaint.setColor(mHightlightColor);
3766                mTouchHightlightPaint.setAntiAlias(true);
3767                mTouchHightlightPaint.setPathEffect(new CornerPathEffect(
3768                        TOUCH_HIGHLIGHT_ARC));
3769            }
3770            canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(),
3771                    mTouchHightlightPaint);
3772        }
3773        if (DEBUG_TOUCH_HIGHLIGHT) {
3774            if (getSettings().getNavDump()) {
3775                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
3776                    if (mTouchCrossHairColor == null) {
3777                        mTouchCrossHairColor = new Paint();
3778                        mTouchCrossHairColor.setColor(Color.RED);
3779                    }
3780                    canvas.drawLine(mTouchHighlightX - mNavSlop,
3781                            mTouchHighlightY - mNavSlop, mTouchHighlightX
3782                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
3783                                    + 1, mTouchCrossHairColor);
3784                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
3785                            mTouchHighlightY - mNavSlop, mTouchHighlightX
3786                                    - mNavSlop,
3787                            mTouchHighlightY + mNavSlop + 1,
3788                            mTouchCrossHairColor);
3789                }
3790            }
3791        }
3792    }
3793
3794    private void removeTouchHighlight(boolean removePendingMessage) {
3795        if (removePendingMessage) {
3796            mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS);
3797        }
3798        mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS);
3799    }
3800
3801    @Override
3802    public void setLayoutParams(ViewGroup.LayoutParams params) {
3803        if (params.height == LayoutParams.WRAP_CONTENT) {
3804            mWrapContent = true;
3805        }
3806        super.setLayoutParams(params);
3807    }
3808
3809    @Override
3810    public boolean performLongClick() {
3811        // performLongClick() is the result of a delayed message. If we switch
3812        // to windows overview, the WebView will be temporarily removed from the
3813        // view system. In that case, do nothing.
3814        if (getParent() == null) return false;
3815
3816        // A multi-finger gesture can look like a long press; make sure we don't take
3817        // long press actions if we're scaling.
3818        final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
3819        if (detector != null && detector.isInProgress()) {
3820            return false;
3821        }
3822
3823        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
3824            // Send the click so that the textfield is in focus
3825            centerKeyPressOnTextField();
3826            rebuildWebTextView();
3827        } else {
3828            clearTextEntry();
3829        }
3830        if (inEditingMode()) {
3831            // Since we just called rebuildWebTextView, the layout is not set
3832            // properly.  Update it so it can correctly find the word to select.
3833            mWebTextView.ensureLayout();
3834            // Provide a touch down event to WebTextView, which will allow it
3835            // to store the location to use in performLongClick.
3836            AbsoluteLayout.LayoutParams params
3837                    = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams();
3838            MotionEvent fake = MotionEvent.obtain(mLastTouchTime,
3839                    mLastTouchTime, MotionEvent.ACTION_DOWN,
3840                    mLastTouchX - params.x + mScrollX,
3841                    mLastTouchY - params.y + mScrollY, 0);
3842            mWebTextView.dispatchTouchEvent(fake);
3843            return mWebTextView.performLongClick();
3844        }
3845        if (mSelectingText) return false; // long click does nothing on selection
3846        /* if long click brings up a context menu, the super function
3847         * returns true and we're done. Otherwise, nothing happened when
3848         * the user clicked. */
3849        if (super.performLongClick()) {
3850            return true;
3851        }
3852        /* In the case where the application hasn't already handled the long
3853         * click action, look for a word under the  click. If one is found,
3854         * animate the text selection into view.
3855         * FIXME: no animation code yet */
3856        return selectText();
3857    }
3858
3859    /**
3860     * Select the word at the last click point.
3861     *
3862     * @hide pending API council approval
3863     */
3864    public boolean selectText() {
3865        int x = viewToContentX(mLastTouchX + mScrollX);
3866        int y = viewToContentY(mLastTouchY + mScrollY);
3867        return selectText(x, y);
3868    }
3869
3870    /**
3871     * Select the word at the indicated content coordinates.
3872     */
3873    boolean selectText(int x, int y) {
3874        if (!setUpSelect()) {
3875            return false;
3876        }
3877        if (mNativeClass != 0 && nativeWordSelection(x, y)) {
3878            nativeSetExtendSelection();
3879            mDrawSelectionPointer = false;
3880            mSelectionStarted = true;
3881            mTouchMode = TOUCH_DRAG_MODE;
3882            return true;
3883        }
3884        selectionDone();
3885        return false;
3886    }
3887
3888    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
3889
3890    @Override
3891    protected void onConfigurationChanged(Configuration newConfig) {
3892        if (mSelectingText && mOrientation != newConfig.orientation) {
3893            selectionDone();
3894        }
3895        mOrientation = newConfig.orientation;
3896    }
3897
3898    /**
3899     * Keep track of the Callback so we can end its ActionMode or remove its
3900     * titlebar.
3901     */
3902    private SelectActionModeCallback mSelectCallback;
3903
3904    // These values are possible options for didUpdateWebTextViewDimensions.
3905    private static final int FULLY_ON_SCREEN = 0;
3906    private static final int INTERSECTS_SCREEN = 1;
3907    private static final int ANYWHERE = 2;
3908
3909    /**
3910     * Check to see if the focused textfield/textarea is still on screen.  If it
3911     * is, update the the dimensions and location of WebTextView.  Otherwise,
3912     * remove the WebTextView.  Should be called when the zoom level changes.
3913     * @param intersection How to determine whether the textfield/textarea is
3914     *        still on screen.
3915     * @return boolean True if the textfield/textarea is still on screen and the
3916     *         dimensions/location of WebTextView have been updated.
3917     */
3918    private boolean didUpdateWebTextViewDimensions(int intersection) {
3919        Rect contentBounds = nativeFocusCandidateNodeBounds();
3920        Rect vBox = contentToViewRect(contentBounds);
3921        Rect visibleRect = new Rect();
3922        calcOurVisibleRect(visibleRect);
3923        // If the textfield is on screen, place the WebTextView in
3924        // its new place, accounting for our new scroll/zoom values,
3925        // and adjust its textsize.
3926        boolean onScreen;
3927        switch (intersection) {
3928            case FULLY_ON_SCREEN:
3929                onScreen = visibleRect.contains(vBox);
3930                break;
3931            case INTERSECTS_SCREEN:
3932                onScreen = Rect.intersects(visibleRect, vBox);
3933                break;
3934            case ANYWHERE:
3935                onScreen = true;
3936                break;
3937            default:
3938                throw new AssertionError(
3939                        "invalid parameter passed to didUpdateWebTextViewDimensions");
3940        }
3941        if (onScreen) {
3942            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3943                    vBox.height());
3944            mWebTextView.updateTextSize();
3945            updateWebTextViewPadding();
3946            return true;
3947        } else {
3948            // The textfield is now off screen.  The user probably
3949            // was not zooming to see the textfield better.  Remove
3950            // the WebTextView.  If the user types a key, and the
3951            // textfield is still in focus, we will reconstruct
3952            // the WebTextView and scroll it back on screen.
3953            mWebTextView.remove();
3954            return false;
3955        }
3956    }
3957
3958    void setBaseLayer(int layer, Rect invalRect) {
3959        if (mNativeClass == 0)
3960            return;
3961        if (invalRect == null) {
3962            Rect rect = new Rect(0, 0, mContentWidth, mContentHeight);
3963            nativeSetBaseLayer(layer, rect);
3964        } else {
3965            nativeSetBaseLayer(layer, invalRect);
3966        }
3967    }
3968
3969    private void onZoomAnimationStart() {
3970        // If it is in password mode, turn it off so it does not draw misplaced.
3971        if (inEditingMode() && nativeFocusCandidateIsPassword()) {
3972            mWebTextView.setInPassword(false);
3973        }
3974    }
3975
3976    private void onZoomAnimationEnd() {
3977        // adjust the edit text view if needed
3978        if (inEditingMode() && didUpdateWebTextViewDimensions(FULLY_ON_SCREEN)
3979                && nativeFocusCandidateIsPassword()) {
3980            // If it is a password field, start drawing the WebTextView once
3981            // again.
3982            mWebTextView.setInPassword(true);
3983        }
3984    }
3985
3986    void onFixedLengthZoomAnimationStart() {
3987        WebViewCore.pauseUpdatePicture(getWebViewCore());
3988        onZoomAnimationStart();
3989    }
3990
3991    void onFixedLengthZoomAnimationEnd() {
3992        if (!mSelectingText) {
3993            WebViewCore.resumeUpdatePicture(mWebViewCore);
3994        }
3995        onZoomAnimationEnd();
3996    }
3997
3998    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
3999                                         Paint.DITHER_FLAG |
4000                                         Paint.SUBPIXEL_TEXT_FLAG;
4001    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
4002                                           Paint.DITHER_FLAG;
4003
4004    private final DrawFilter mZoomFilter =
4005            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4006    // If we need to trade better quality for speed, set mScrollFilter to null
4007    private final DrawFilter mScrollFilter =
4008            new PaintFlagsDrawFilter(SCROLL_BITS, 0);
4009
4010    private void drawCoreAndCursorRing(Canvas canvas, int color,
4011        boolean drawCursorRing) {
4012        if (mDrawHistory) {
4013            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4014            canvas.drawPicture(mHistoryPicture);
4015            return;
4016        }
4017        if (mNativeClass == 0) return;
4018
4019        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
4020        boolean animateScroll = ((!mScroller.isFinished()
4021                || mVelocityTracker != null)
4022                && (mTouchMode != TOUCH_DRAG_MODE ||
4023                mHeldMotionless != MOTIONLESS_TRUE))
4024                || mDeferTouchMode == TOUCH_DRAG_MODE;
4025        if (mTouchMode == TOUCH_DRAG_MODE) {
4026            if (mHeldMotionless == MOTIONLESS_PENDING) {
4027                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4028                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4029                mHeldMotionless = MOTIONLESS_FALSE;
4030            }
4031            if (mHeldMotionless == MOTIONLESS_FALSE) {
4032                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4033                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
4034                mHeldMotionless = MOTIONLESS_PENDING;
4035            }
4036        }
4037        if (animateZoom) {
4038            mZoomManager.animateZoom(canvas);
4039        } else {
4040            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4041        }
4042
4043        boolean UIAnimationsRunning = false;
4044        // Currently for each draw we compute the animation values;
4045        // We may in the future decide to do that independently.
4046        if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) {
4047            UIAnimationsRunning = true;
4048            // If we have unfinished (or unstarted) animations,
4049            // we ask for a repaint.
4050            invalidate();
4051        }
4052
4053        // decide which adornments to draw
4054        int extras = DRAW_EXTRAS_NONE;
4055        if (mFindIsUp) {
4056            extras = DRAW_EXTRAS_FIND;
4057        } else if (mSelectingText) {
4058            extras = DRAW_EXTRAS_SELECTION;
4059            nativeSetSelectionPointer(mDrawSelectionPointer,
4060                    mZoomManager.getInvScale(),
4061                    mSelectX, mSelectY - getTitleHeight());
4062        } else if (drawCursorRing) {
4063            extras = DRAW_EXTRAS_CURSOR_RING;
4064        }
4065        if (DebugFlags.WEB_VIEW) {
4066            Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp
4067                    + " mSelectingText=" + mSelectingText
4068                    + " nativePageShouldHandleShiftAndArrows()="
4069                    + nativePageShouldHandleShiftAndArrows()
4070                    + " animateZoom=" + animateZoom
4071                    + " extras=" + extras);
4072        }
4073
4074        if (canvas.isHardwareAccelerated()) {
4075            int functor = nativeGetDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport,
4076                    getScale(), extras);
4077            ((HardwareCanvas) canvas).callDrawGLFunction(functor);
4078        } else {
4079            DrawFilter df = null;
4080            if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
4081                df = mZoomFilter;
4082            } else if (animateScroll) {
4083                df = mScrollFilter;
4084            }
4085            canvas.setDrawFilter(df);
4086            // XXX: Revisit splitting content.  Right now it causes a
4087            // synchronization problem with layers.
4088            int content = nativeDraw(canvas, color, extras, false);
4089            canvas.setDrawFilter(null);
4090            if (content != 0) {
4091                mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
4092            }
4093        }
4094
4095        if (extras == DRAW_EXTRAS_CURSOR_RING) {
4096            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
4097                mTouchMode = TOUCH_SHORTPRESS_MODE;
4098            }
4099        }
4100        if (mFocusSizeChanged) {
4101            mFocusSizeChanged = false;
4102            // If we are zooming, this will get handled above, when the zoom
4103            // finishes.  We also do not need to do this unless the WebTextView
4104            // is showing.
4105            if (!animateZoom && inEditingMode()) {
4106                didUpdateWebTextViewDimensions(ANYWHERE);
4107            }
4108        }
4109    }
4110
4111    // draw history
4112    private boolean mDrawHistory = false;
4113    private Picture mHistoryPicture = null;
4114    private int mHistoryWidth = 0;
4115    private int mHistoryHeight = 0;
4116
4117    // Only check the flag, can be called from WebCore thread
4118    boolean drawHistory() {
4119        return mDrawHistory;
4120    }
4121
4122    int getHistoryPictureWidth() {
4123        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
4124    }
4125
4126    // Should only be called in UI thread
4127    void switchOutDrawHistory() {
4128        if (null == mWebViewCore) return; // CallbackProxy may trigger this
4129        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
4130            mDrawHistory = false;
4131            mHistoryPicture = null;
4132            invalidate();
4133            int oldScrollX = mScrollX;
4134            int oldScrollY = mScrollY;
4135            mScrollX = pinLocX(mScrollX);
4136            mScrollY = pinLocY(mScrollY);
4137            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
4138                mUserScroll = false;
4139                mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
4140                        oldScrollY);
4141                onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY);
4142            } else {
4143                sendOurVisibleRect();
4144            }
4145        }
4146    }
4147
4148    WebViewCore.CursorData cursorData() {
4149        WebViewCore.CursorData result = new WebViewCore.CursorData();
4150        result.mMoveGeneration = nativeMoveGeneration();
4151        result.mFrame = nativeCursorFramePointer();
4152        Point position = nativeCursorPosition();
4153        result.mX = position.x;
4154        result.mY = position.y;
4155        return result;
4156    }
4157
4158    /**
4159     *  Delete text from start to end in the focused textfield. If there is no
4160     *  focus, or if start == end, silently fail.  If start and end are out of
4161     *  order, swap them.
4162     *  @param  start   Beginning of selection to delete.
4163     *  @param  end     End of selection to delete.
4164     */
4165    /* package */ void deleteSelection(int start, int end) {
4166        mTextGeneration++;
4167        WebViewCore.TextSelectionData data
4168                = new WebViewCore.TextSelectionData(start, end);
4169        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
4170                data);
4171    }
4172
4173    /**
4174     *  Set the selection to (start, end) in the focused textfield. If start and
4175     *  end are out of order, swap them.
4176     *  @param  start   Beginning of selection.
4177     *  @param  end     End of selection.
4178     */
4179    /* package */ void setSelection(int start, int end) {
4180        if (mWebViewCore != null) {
4181            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
4182        }
4183    }
4184
4185    @Override
4186    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4187      InputConnection connection = super.onCreateInputConnection(outAttrs);
4188      outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN;
4189      return connection;
4190    }
4191
4192    /**
4193     * Called in response to a message from webkit telling us that the soft
4194     * keyboard should be launched.
4195     */
4196    private void displaySoftKeyboard(boolean isTextView) {
4197        InputMethodManager imm = (InputMethodManager)
4198                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
4199
4200        // bring it back to the default level scale so that user can enter text
4201        boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
4202        if (zoom) {
4203            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
4204            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
4205        }
4206        if (isTextView) {
4207            rebuildWebTextView();
4208            if (inEditingMode()) {
4209                imm.showSoftInput(mWebTextView, 0);
4210                if (zoom) {
4211                    didUpdateWebTextViewDimensions(INTERSECTS_SCREEN);
4212                }
4213                return;
4214            }
4215        }
4216        // Used by plugins and contentEditable.
4217        // Also used if the navigation cache is out of date, and
4218        // does not recognize that a textfield is in focus.  In that
4219        // case, use WebView as the targeted view.
4220        // see http://b/issue?id=2457459
4221        imm.showSoftInput(this, 0);
4222    }
4223
4224    // Called by WebKit to instruct the UI to hide the keyboard
4225    private void hideSoftKeyboard() {
4226        InputMethodManager imm = InputMethodManager.peekInstance();
4227        if (imm != null && (imm.isActive(this)
4228                || (inEditingMode() && imm.isActive(mWebTextView)))) {
4229            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
4230        }
4231    }
4232
4233    /*
4234     * This method checks the current focus and cursor and potentially rebuilds
4235     * mWebTextView to have the appropriate properties, such as password,
4236     * multiline, and what text it contains.  It also removes it if necessary.
4237     */
4238    /* package */ void rebuildWebTextView() {
4239        // If the WebView does not have focus, do nothing until it gains focus.
4240        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
4241            return;
4242        }
4243        boolean alreadyThere = inEditingMode();
4244        // inEditingMode can only return true if mWebTextView is non-null,
4245        // so we can safely call remove() if (alreadyThere)
4246        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
4247            if (alreadyThere) {
4248                mWebTextView.remove();
4249            }
4250            return;
4251        }
4252        // At this point, we know we have found an input field, so go ahead
4253        // and create the WebTextView if necessary.
4254        if (mWebTextView == null) {
4255            mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId());
4256            // Initialize our generation number.
4257            mTextGeneration = 0;
4258        }
4259        mWebTextView.updateTextSize();
4260        Rect visibleRect = new Rect();
4261        calcOurContentVisibleRect(visibleRect);
4262        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
4263        // should be in content coordinates.
4264        Rect bounds = nativeFocusCandidateNodeBounds();
4265        Rect vBox = contentToViewRect(bounds);
4266        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
4267        if (!Rect.intersects(bounds, visibleRect)) {
4268            revealSelection();
4269        }
4270        String text = nativeFocusCandidateText();
4271        int nodePointer = nativeFocusCandidatePointer();
4272        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
4273            // It is possible that we have the same textfield, but it has moved,
4274            // i.e. In the case of opening/closing the screen.
4275            // In that case, we need to set the dimensions, but not the other
4276            // aspects.
4277            // If the text has been changed by webkit, update it.  However, if
4278            // there has been more UI text input, ignore it.  We will receive
4279            // another update when that text is recognized.
4280            if (text != null && !text.equals(mWebTextView.getText().toString())
4281                    && nativeTextGeneration() == mTextGeneration) {
4282                mWebTextView.setTextAndKeepSelection(text);
4283            }
4284        } else {
4285            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
4286                    Gravity.RIGHT : Gravity.NO_GRAVITY);
4287            // This needs to be called before setType, which may call
4288            // requestFormData, and it needs to have the correct nodePointer.
4289            mWebTextView.setNodePointer(nodePointer);
4290            mWebTextView.setType(nativeFocusCandidateType());
4291            updateWebTextViewPadding();
4292            if (null == text) {
4293                if (DebugFlags.WEB_VIEW) {
4294                    Log.v(LOGTAG, "rebuildWebTextView null == text");
4295                }
4296                text = "";
4297            }
4298            mWebTextView.setTextAndKeepSelection(text);
4299            InputMethodManager imm = InputMethodManager.peekInstance();
4300            if (imm != null && imm.isActive(mWebTextView)) {
4301                imm.restartInput(mWebTextView);
4302            }
4303        }
4304        if (isFocused()) {
4305            mWebTextView.requestFocus();
4306        }
4307    }
4308
4309    /**
4310     * Update the padding of mWebTextView based on the native textfield/textarea
4311     */
4312    void updateWebTextViewPadding() {
4313        Rect paddingRect = nativeFocusCandidatePaddingRect();
4314        if (paddingRect != null) {
4315            // Use contentToViewDimension since these are the dimensions of
4316            // the padding.
4317            mWebTextView.setPadding(
4318                    contentToViewDimension(paddingRect.left),
4319                    contentToViewDimension(paddingRect.top),
4320                    contentToViewDimension(paddingRect.right),
4321                    contentToViewDimension(paddingRect.bottom));
4322        }
4323    }
4324
4325    /**
4326     * Tell webkit to put the cursor on screen.
4327     */
4328    /* package */ void revealSelection() {
4329        if (mWebViewCore != null) {
4330            mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION);
4331        }
4332    }
4333
4334    /**
4335     * Called by WebTextView to find saved form data associated with the
4336     * textfield
4337     * @param name Name of the textfield.
4338     * @param nodePointer Pointer to the node of the textfield, so it can be
4339     *          compared to the currently focused textfield when the data is
4340     *          retrieved.
4341     * @param autoFillable true if WebKit has determined this field is part of
4342     *          a form that can be auto filled.
4343     * @param autoComplete true if the attribute "autocomplete" is set to true
4344     *          on the textfield.
4345     */
4346    /* package */ void requestFormData(String name, int nodePointer,
4347            boolean autoFillable, boolean autoComplete) {
4348        if (mWebViewCore.getSettings().getSaveFormData()) {
4349            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
4350            update.arg1 = nodePointer;
4351            RequestFormData updater = new RequestFormData(name, getUrl(),
4352                    update, autoFillable, autoComplete);
4353            Thread t = new Thread(updater);
4354            t.start();
4355        }
4356    }
4357
4358    /**
4359     * Pass a message to find out the <label> associated with the <input>
4360     * identified by nodePointer
4361     * @param framePointer Pointer to the frame containing the <input> node
4362     * @param nodePointer Pointer to the node for which a <label> is desired.
4363     */
4364    /* package */ void requestLabel(int framePointer, int nodePointer) {
4365        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
4366                nodePointer);
4367    }
4368
4369    /*
4370     * This class requests an Adapter for the WebTextView which shows past
4371     * entries stored in the database.  It is a Runnable so that it can be done
4372     * in its own thread, without slowing down the UI.
4373     */
4374    private class RequestFormData implements Runnable {
4375        private String mName;
4376        private String mUrl;
4377        private Message mUpdateMessage;
4378        private boolean mAutoFillable;
4379        private boolean mAutoComplete;
4380
4381        public RequestFormData(String name, String url, Message msg,
4382                boolean autoFillable, boolean autoComplete) {
4383            mName = name;
4384            mUrl = url;
4385            mUpdateMessage = msg;
4386            mAutoFillable = autoFillable;
4387            mAutoComplete = autoComplete;
4388        }
4389
4390        public void run() {
4391            ArrayList<String> pastEntries = new ArrayList<String>();
4392
4393            if (mAutoFillable) {
4394                // Note that code inside the adapter click handler in WebTextView depends
4395                // on the AutoFill item being at the top of the drop down list. If you change
4396                // the order, make sure to do it there too!
4397                WebSettings settings = getSettings();
4398                if (settings != null && settings.getAutoFillProfile() != null) {
4399                    pastEntries.add(getResources().getText(
4400                            com.android.internal.R.string.autofill_this_form).toString() +
4401                            " " +
4402                            mAutoFillData.getPreviewString());
4403                    mWebTextView.setAutoFillProfileIsSet(true);
4404                } else {
4405                    // There is no autofill profile set up yet, so add an option that
4406                    // will invite the user to set their profile up.
4407                    pastEntries.add(getResources().getText(
4408                            com.android.internal.R.string.setup_autofill).toString());
4409                    mWebTextView.setAutoFillProfileIsSet(false);
4410                }
4411            }
4412
4413            if (mAutoComplete) {
4414                pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
4415            }
4416
4417            if (pastEntries.size() > 0) {
4418                AutoCompleteAdapter adapter = new
4419                        AutoCompleteAdapter(mContext, pastEntries);
4420                mUpdateMessage.obj = adapter;
4421                mUpdateMessage.sendToTarget();
4422            }
4423        }
4424    }
4425
4426    /**
4427     * Dump the display tree to "/sdcard/displayTree.txt"
4428     *
4429     * @hide debug only
4430     */
4431    public void dumpDisplayTree() {
4432        nativeDumpDisplayTree(getUrl());
4433    }
4434
4435    /**
4436     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
4437     * "/sdcard/domTree.txt"
4438     *
4439     * @hide debug only
4440     */
4441    public void dumpDomTree(boolean toFile) {
4442        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
4443    }
4444
4445    /**
4446     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
4447     * to "/sdcard/renderTree.txt"
4448     *
4449     * @hide debug only
4450     */
4451    public void dumpRenderTree(boolean toFile) {
4452        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
4453    }
4454
4455    /**
4456     * Called by DRT on UI thread, need to proxy to WebCore thread.
4457     *
4458     * @hide debug only
4459     */
4460    public void useMockDeviceOrientation() {
4461        mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
4462    }
4463
4464    /**
4465     * Called by DRT on WebCore thread.
4466     *
4467     * @hide debug only
4468     */
4469    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
4470            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
4471        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
4472                canProvideGamma, gamma);
4473    }
4474
4475    /**
4476     * Dump the V8 counters to standard output.
4477     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
4478     * true. Otherwise, this will do nothing.
4479     *
4480     * @hide debug only
4481     */
4482    public void dumpV8Counters() {
4483        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
4484    }
4485
4486    // This is used to determine long press with the center key.  Does not
4487    // affect long press with the trackball/touch.
4488    private boolean mGotCenterDown = false;
4489
4490    @Override
4491    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4492        // send complex characters to webkit for use by JS and plugins
4493        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
4494            // pass the key to DOM
4495            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4496            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4497            // return true as DOM handles the key
4498            return true;
4499        }
4500        return false;
4501    }
4502
4503    private boolean isEnterActionKey(int keyCode) {
4504        return keyCode == KeyEvent.KEYCODE_DPAD_CENTER
4505                || keyCode == KeyEvent.KEYCODE_ENTER
4506                || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER;
4507    }
4508
4509    @Override
4510    public boolean onKeyDown(int keyCode, KeyEvent event) {
4511        if (DebugFlags.WEB_VIEW) {
4512            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
4513                    + "keyCode=" + keyCode
4514                    + ", " + event + ", unicode=" + event.getUnicodeChar());
4515        }
4516
4517        // don't implement accelerator keys here; defer to host application
4518        if (event.isCtrlPressed()) {
4519            return false;
4520        }
4521
4522        if (mNativeClass == 0) {
4523            return false;
4524        }
4525
4526        // do this hack up front, so it always works, regardless of touch-mode
4527        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
4528            mAutoRedraw = !mAutoRedraw;
4529            if (mAutoRedraw) {
4530                invalidate();
4531            }
4532            return true;
4533        }
4534
4535        // Bubble up the key event if
4536        // 1. it is a system key; or
4537        // 2. the host application wants to handle it;
4538        if (event.isSystem()
4539                || mCallbackProxy.uiOverrideKeyEvent(event)) {
4540            return false;
4541        }
4542
4543        // accessibility support
4544        if (accessibilityScriptInjected()) {
4545            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4546                // if an accessibility script is injected we delegate to it the key handling.
4547                // this script is a screen reader which is a fully fledged solution for blind
4548                // users to navigate in and interact with web pages.
4549                mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4550                return true;
4551            } else {
4552                // Clean up if accessibility was disabled after loading the current URL.
4553                mAccessibilityScriptInjected = false;
4554            }
4555        } else if (mAccessibilityInjector != null) {
4556            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4557                if (mAccessibilityInjector.onKeyEvent(event)) {
4558                    // if an accessibility injector is present (no JavaScript enabled or the site
4559                    // opts out injecting our JavaScript screen reader) we let it decide whether
4560                    // to act on and consume the event.
4561                    return true;
4562                }
4563            } else {
4564                // Clean up if accessibility was disabled after loading the current URL.
4565                mAccessibilityInjector = null;
4566            }
4567        }
4568
4569        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
4570            if (event.hasNoModifiers()) {
4571                pageUp(false);
4572                return true;
4573            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4574                pageUp(true);
4575                return true;
4576            }
4577        }
4578
4579        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
4580            if (event.hasNoModifiers()) {
4581                pageDown(false);
4582                return true;
4583            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4584                pageDown(true);
4585                return true;
4586            }
4587        }
4588
4589        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) {
4590            pageUp(true);
4591            return true;
4592        }
4593
4594        if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) {
4595            pageDown(true);
4596            return true;
4597        }
4598
4599        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4600                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
4601            switchOutDrawHistory();
4602            if (nativePageShouldHandleShiftAndArrows()) {
4603                letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState());
4604                return true;
4605            }
4606            if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
4607                switch (keyCode) {
4608                    case KeyEvent.KEYCODE_DPAD_UP:
4609                        pageUp(true);
4610                        return true;
4611                    case KeyEvent.KEYCODE_DPAD_DOWN:
4612                        pageDown(true);
4613                        return true;
4614                    case KeyEvent.KEYCODE_DPAD_LEFT:
4615                        nativeClearCursor(); // start next trackball movement from page edge
4616                        return pinScrollTo(0, mScrollY, true, 0);
4617                    case KeyEvent.KEYCODE_DPAD_RIGHT:
4618                        nativeClearCursor(); // start next trackball movement from page edge
4619                        return pinScrollTo(mContentWidth, mScrollY, true, 0);
4620                }
4621            }
4622            if (mSelectingText) {
4623                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
4624                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
4625                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
4626                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
4627                int multiplier = event.getRepeatCount() + 1;
4628                moveSelection(xRate * multiplier, yRate * multiplier);
4629                return true;
4630            }
4631            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
4632                playSoundEffect(keyCodeToSoundsEffect(keyCode));
4633                return true;
4634            }
4635            // Bubble up the key event as WebView doesn't handle it
4636            return false;
4637        }
4638
4639        if (isEnterActionKey(keyCode)) {
4640            switchOutDrawHistory();
4641            boolean wantsKeyEvents = nativeCursorNodePointer() == 0
4642                || nativeCursorWantsKeyEvents();
4643            if (event.getRepeatCount() == 0) {
4644                if (mSelectingText) {
4645                    return true; // discard press if copy in progress
4646                }
4647                mGotCenterDown = true;
4648                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4649                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
4650                // Already checked mNativeClass, so we do not need to check it
4651                // again.
4652                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4653                if (!wantsKeyEvents) return true;
4654            }
4655            // Bubble up the key event as WebView doesn't handle it
4656            if (!wantsKeyEvents) return false;
4657        }
4658
4659        if (getSettings().getNavDump()) {
4660            switch (keyCode) {
4661                case KeyEvent.KEYCODE_4:
4662                    dumpDisplayTree();
4663                    break;
4664                case KeyEvent.KEYCODE_5:
4665                case KeyEvent.KEYCODE_6:
4666                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
4667                    break;
4668                case KeyEvent.KEYCODE_7:
4669                case KeyEvent.KEYCODE_8:
4670                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
4671                    break;
4672                case KeyEvent.KEYCODE_9:
4673                    nativeInstrumentReport();
4674                    return true;
4675            }
4676        }
4677
4678        if (nativeCursorIsTextInput()) {
4679            // This message will put the node in focus, for the DOM's notion
4680            // of focus.
4681            mWebViewCore.sendMessage(EventHub.FAKE_CLICK, nativeCursorFramePointer(),
4682                    nativeCursorNodePointer());
4683            // This will bring up the WebTextView and put it in focus, for
4684            // our view system's notion of focus
4685            rebuildWebTextView();
4686            // Now we need to pass the event to it
4687            if (inEditingMode()) {
4688                mWebTextView.setDefaultSelection();
4689                return mWebTextView.dispatchKeyEvent(event);
4690            }
4691        } else if (nativeHasFocusNode()) {
4692            // In this case, the cursor is not on a text input, but the focus
4693            // might be.  Check it, and if so, hand over to the WebTextView.
4694            rebuildWebTextView();
4695            if (inEditingMode()) {
4696                mWebTextView.setDefaultSelection();
4697                return mWebTextView.dispatchKeyEvent(event);
4698            }
4699        }
4700
4701        // TODO: should we pass all the keys to DOM or check the meta tag
4702        if (nativeCursorWantsKeyEvents() || true) {
4703            // pass the key to DOM
4704            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4705            // return true as DOM handles the key
4706            return true;
4707        }
4708
4709        // Bubble up the key event as WebView doesn't handle it
4710        return false;
4711    }
4712
4713    @Override
4714    public boolean onKeyUp(int keyCode, KeyEvent event) {
4715        if (DebugFlags.WEB_VIEW) {
4716            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
4717                    + ", " + event + ", unicode=" + event.getUnicodeChar());
4718        }
4719
4720        if (mNativeClass == 0) {
4721            return false;
4722        }
4723
4724        // special CALL handling when cursor node's href is "tel:XXX"
4725        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
4726            String text = nativeCursorText();
4727            if (!nativeCursorIsTextInput() && text != null
4728                    && text.startsWith(SCHEME_TEL)) {
4729                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
4730                getContext().startActivity(intent);
4731                return true;
4732            }
4733        }
4734
4735        // Bubble up the key event if
4736        // 1. it is a system key; or
4737        // 2. the host application wants to handle it;
4738        if (event.isSystem()
4739                || mCallbackProxy.uiOverrideKeyEvent(event)) {
4740            return false;
4741        }
4742
4743        // accessibility support
4744        if (accessibilityScriptInjected()) {
4745            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4746                // if an accessibility script is injected we delegate to it the key handling.
4747                // this script is a screen reader which is a fully fledged solution for blind
4748                // users to navigate in and interact with web pages.
4749                mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4750                return true;
4751            } else {
4752                // Clean up if accessibility was disabled after loading the current URL.
4753                mAccessibilityScriptInjected = false;
4754            }
4755        } else if (mAccessibilityInjector != null) {
4756            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4757                if (mAccessibilityInjector.onKeyEvent(event)) {
4758                    // if an accessibility injector is present (no JavaScript enabled or the site
4759                    // opts out injecting our JavaScript screen reader) we let it decide whether to
4760                    // act on and consume the event.
4761                    return true;
4762                }
4763            } else {
4764                // Clean up if accessibility was disabled after loading the current URL.
4765                mAccessibilityInjector = null;
4766            }
4767        }
4768
4769        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4770                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
4771            if (nativePageShouldHandleShiftAndArrows()) {
4772                letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState());
4773                return true;
4774            }
4775            // always handle the navigation keys in the UI thread
4776            // Bubble up the key event as WebView doesn't handle it
4777            return false;
4778        }
4779
4780        if (isEnterActionKey(keyCode)) {
4781            // remove the long press message first
4782            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4783            mGotCenterDown = false;
4784
4785            if (mSelectingText) {
4786                if (mExtendSelection) {
4787                    copySelection();
4788                    selectionDone();
4789                } else {
4790                    mExtendSelection = true;
4791                    nativeSetExtendSelection();
4792                    invalidate(); // draw the i-beam instead of the arrow
4793                }
4794                return true; // discard press if copy in progress
4795            }
4796
4797            // perform the single click
4798            Rect visibleRect = sendOurVisibleRect();
4799            // Note that sendOurVisibleRect calls viewToContent, so the
4800            // coordinates should be in content coordinates.
4801            if (!nativeCursorIntersects(visibleRect)) {
4802                return false;
4803            }
4804            WebViewCore.CursorData data = cursorData();
4805            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
4806            playSoundEffect(SoundEffectConstants.CLICK);
4807            if (nativeCursorIsTextInput()) {
4808                rebuildWebTextView();
4809                centerKeyPressOnTextField();
4810                if (inEditingMode()) {
4811                    mWebTextView.setDefaultSelection();
4812                }
4813                return true;
4814            }
4815            clearTextEntry();
4816            nativeShowCursorTimed();
4817            if (mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
4818                return true;
4819            }
4820            if (nativeCursorNodePointer() != 0 && !nativeCursorWantsKeyEvents()) {
4821                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
4822                        nativeCursorNodePointer());
4823                return true;
4824            }
4825        }
4826
4827        // TODO: should we pass all the keys to DOM or check the meta tag
4828        if (nativeCursorWantsKeyEvents() || true) {
4829            // pass the key to DOM
4830            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4831            // return true as DOM handles the key
4832            return true;
4833        }
4834
4835        // Bubble up the key event as WebView doesn't handle it
4836        return false;
4837    }
4838
4839    /*
4840     * Enter selecting text mode.  Returns true if the WebView is now in
4841     * selecting text mode (including if it was already in that mode, and this
4842     * method did nothing).
4843     */
4844    private boolean setUpSelect() {
4845        if (0 == mNativeClass) return false; // client isn't initialized
4846        if (inFullScreenMode()) return false;
4847        if (mSelectingText) return true;
4848        mExtendSelection = false;
4849        mSelectingText = mDrawSelectionPointer = true;
4850        // don't let the picture change during text selection
4851        WebViewCore.pauseUpdatePicture(mWebViewCore);
4852        nativeResetSelection();
4853        if (nativeHasCursorNode()) {
4854            Rect rect = nativeCursorNodeBounds();
4855            mSelectX = contentToViewX(rect.left);
4856            mSelectY = contentToViewY(rect.top);
4857        } else if (mLastTouchY > getVisibleTitleHeight()) {
4858            mSelectX = mScrollX + mLastTouchX;
4859            mSelectY = mScrollY + mLastTouchY;
4860        } else {
4861            mSelectX = mScrollX + getViewWidth() / 2;
4862            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
4863        }
4864        nativeHideCursor();
4865        mSelectCallback = new SelectActionModeCallback();
4866        mSelectCallback.setWebView(this);
4867        if (startActionMode(mSelectCallback) == null) {
4868            // There is no ActionMode, so do not allow the user to modify a
4869            // selection.
4870            selectionDone();
4871            return false;
4872        }
4873        mMinAutoScrollX = 0;
4874        mMaxAutoScrollX = getViewWidth();
4875        mMinAutoScrollY = 0;
4876        mMaxAutoScrollY = getViewHeightWithTitle();
4877        mScrollingLayer = nativeScrollableLayer(viewToContentX(mSelectX),
4878                viewToContentY(mSelectY), mScrollingLayerRect,
4879                mScrollingLayerBounds);
4880        if (mScrollingLayer != 0) {
4881            if (mScrollingLayerRect.left != mScrollingLayerRect.right) {
4882                mMinAutoScrollX = Math.max(mMinAutoScrollX,
4883                        contentToViewX(mScrollingLayerBounds.left));
4884                mMaxAutoScrollX = Math.min(mMaxAutoScrollX,
4885                        contentToViewX(mScrollingLayerBounds.right));
4886            }
4887            if (mScrollingLayerRect.top != mScrollingLayerRect.bottom) {
4888                mMinAutoScrollY = Math.max(mMinAutoScrollY,
4889                        contentToViewY(mScrollingLayerBounds.top));
4890                mMaxAutoScrollY = Math.min(mMaxAutoScrollY,
4891                        contentToViewY(mScrollingLayerBounds.bottom));
4892            }
4893        }
4894        mMinAutoScrollX += SELECT_SCROLL;
4895        mMaxAutoScrollX -= SELECT_SCROLL;
4896        mMinAutoScrollY += SELECT_SCROLL;
4897        mMaxAutoScrollY -= SELECT_SCROLL;
4898        return true;
4899    }
4900
4901    /**
4902     * Use this method to put the WebView into text selection mode.
4903     * Do not rely on this functionality; it will be deprecated in the future.
4904     */
4905    public void emulateShiftHeld() {
4906        setUpSelect();
4907    }
4908
4909    /**
4910     * Select all of the text in this WebView.
4911     *
4912     * @hide pending API council approval.
4913     */
4914    public void selectAll() {
4915        if (0 == mNativeClass) return; // client isn't initialized
4916        if (inFullScreenMode()) return;
4917        if (!mSelectingText) {
4918            // retrieve a point somewhere within the text
4919            Point select = nativeSelectableText();
4920            if (!selectText(select.x, select.y)) return;
4921        }
4922        nativeSelectAll();
4923        mDrawSelectionPointer = false;
4924        mExtendSelection = true;
4925        invalidate();
4926    }
4927
4928    /**
4929     * Called when the selection has been removed.
4930     */
4931    void selectionDone() {
4932        if (mSelectingText) {
4933            mSelectingText = false;
4934            // finish is idempotent, so this is fine even if selectionDone was
4935            // called by mSelectCallback.onDestroyActionMode
4936            mSelectCallback.finish();
4937            mSelectCallback = null;
4938            WebViewCore.resumePriority();
4939            WebViewCore.resumeUpdatePicture(mWebViewCore);
4940            invalidate(); // redraw without selection
4941            mAutoScrollX = 0;
4942            mAutoScrollY = 0;
4943            mSentAutoScrollMessage = false;
4944        }
4945    }
4946
4947    /**
4948     * Copy the selection to the clipboard
4949     *
4950     * @hide pending API council approval.
4951     */
4952    public boolean copySelection() {
4953        boolean copiedSomething = false;
4954        String selection = getSelection();
4955        if (selection != null && selection != "") {
4956            if (DebugFlags.WEB_VIEW) {
4957                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
4958            }
4959            Toast.makeText(mContext
4960                    , com.android.internal.R.string.text_copied
4961                    , Toast.LENGTH_SHORT).show();
4962            copiedSomething = true;
4963            ClipboardManager cm = (ClipboardManager)getContext()
4964                    .getSystemService(Context.CLIPBOARD_SERVICE);
4965            cm.setText(selection);
4966        }
4967        invalidate(); // remove selection region and pointer
4968        return copiedSomething;
4969    }
4970
4971    /**
4972     * Returns the currently highlighted text as a string.
4973     */
4974    String getSelection() {
4975        if (mNativeClass == 0) return "";
4976        return nativeGetSelection();
4977    }
4978
4979    @Override
4980    protected void onAttachedToWindow() {
4981        super.onAttachedToWindow();
4982        if (hasWindowFocus()) setActive(true);
4983        final ViewTreeObserver treeObserver = getViewTreeObserver();
4984        if (treeObserver != null) {
4985            if (mGlobalLayoutListener == null) {
4986                mGlobalLayoutListener = new InnerGlobalLayoutListener();
4987                treeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);
4988            }
4989            if (mScrollChangedListener == null) {
4990                mScrollChangedListener = new InnerScrollChangedListener();
4991                treeObserver.addOnScrollChangedListener(mScrollChangedListener);
4992            }
4993        }
4994    }
4995
4996    @Override
4997    protected void onDetachedFromWindow() {
4998        clearHelpers();
4999        mZoomManager.dismissZoomPicker();
5000        if (hasWindowFocus()) setActive(false);
5001
5002        final ViewTreeObserver treeObserver = getViewTreeObserver();
5003        if (treeObserver != null) {
5004            if (mGlobalLayoutListener != null) {
5005                treeObserver.removeGlobalOnLayoutListener(mGlobalLayoutListener);
5006                mGlobalLayoutListener = null;
5007            }
5008            if (mScrollChangedListener != null) {
5009                treeObserver.removeOnScrollChangedListener(mScrollChangedListener);
5010                mScrollChangedListener = null;
5011            }
5012        }
5013
5014        super.onDetachedFromWindow();
5015    }
5016
5017    @Override
5018    protected void onVisibilityChanged(View changedView, int visibility) {
5019        super.onVisibilityChanged(changedView, visibility);
5020        // The zoomManager may be null if the webview is created from XML that
5021        // specifies the view's visibility param as not visible (see http://b/2794841)
5022        if (visibility != View.VISIBLE && mZoomManager != null) {
5023            mZoomManager.dismissZoomPicker();
5024        }
5025    }
5026
5027    /**
5028     * @deprecated WebView no longer needs to implement
5029     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5030     */
5031    @Deprecated
5032    public void onChildViewAdded(View parent, View child) {}
5033
5034    /**
5035     * @deprecated WebView no longer needs to implement
5036     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
5037     */
5038    @Deprecated
5039    public void onChildViewRemoved(View p, View child) {}
5040
5041    /**
5042     * @deprecated WebView should not have implemented
5043     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
5044     * does nothing now.
5045     */
5046    @Deprecated
5047    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
5048    }
5049
5050    void setActive(boolean active) {
5051        if (active) {
5052            if (hasFocus()) {
5053                // If our window regained focus, and we have focus, then begin
5054                // drawing the cursor ring
5055                mDrawCursorRing = true;
5056                setFocusControllerActive(true);
5057                if (mNativeClass != 0) {
5058                    nativeRecordButtons(true, false, true);
5059                }
5060            } else {
5061                if (!inEditingMode()) {
5062                    // If our window gained focus, but we do not have it, do not
5063                    // draw the cursor ring.
5064                    mDrawCursorRing = false;
5065                    setFocusControllerActive(false);
5066                }
5067                // We do not call nativeRecordButtons here because we assume
5068                // that when we lost focus, or window focus, it got called with
5069                // false for the first parameter
5070            }
5071        } else {
5072            if (!mZoomManager.isZoomPickerVisible()) {
5073                /*
5074                 * The external zoom controls come in their own window, so our
5075                 * window loses focus. Our policy is to not draw the cursor ring
5076                 * if our window is not focused, but this is an exception since
5077                 * the user can still navigate the web page with the zoom
5078                 * controls showing.
5079                 */
5080                mDrawCursorRing = false;
5081            }
5082            mGotKeyDown = false;
5083            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5084            mTouchMode = TOUCH_DONE_MODE;
5085            if (mNativeClass != 0) {
5086                nativeRecordButtons(false, false, true);
5087            }
5088            setFocusControllerActive(false);
5089        }
5090        invalidate();
5091    }
5092
5093    // To avoid drawing the cursor ring, and remove the TextView when our window
5094    // loses focus.
5095    @Override
5096    public void onWindowFocusChanged(boolean hasWindowFocus) {
5097        setActive(hasWindowFocus);
5098        if (hasWindowFocus) {
5099            JWebCoreJavaBridge.setActiveWebView(this);
5100        } else {
5101            JWebCoreJavaBridge.removeActiveWebView(this);
5102        }
5103        super.onWindowFocusChanged(hasWindowFocus);
5104    }
5105
5106    /*
5107     * Pass a message to WebCore Thread, telling the WebCore::Page's
5108     * FocusController to be  "inactive" so that it will
5109     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
5110     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
5111     */
5112    /* package */ void setFocusControllerActive(boolean active) {
5113        if (mWebViewCore == null) return;
5114        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
5115        // Need to send this message after the document regains focus.
5116        if (active && mListBoxMessage != null) {
5117            mWebViewCore.sendMessage(mListBoxMessage);
5118            mListBoxMessage = null;
5119        }
5120    }
5121
5122    @Override
5123    protected void onFocusChanged(boolean focused, int direction,
5124            Rect previouslyFocusedRect) {
5125        if (DebugFlags.WEB_VIEW) {
5126            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
5127        }
5128        if (focused) {
5129            // When we regain focus, if we have window focus, resume drawing
5130            // the cursor ring
5131            if (hasWindowFocus()) {
5132                mDrawCursorRing = true;
5133                if (mNativeClass != 0) {
5134                    nativeRecordButtons(true, false, true);
5135                }
5136                setFocusControllerActive(true);
5137            //} else {
5138                // The WebView has gained focus while we do not have
5139                // windowfocus.  When our window lost focus, we should have
5140                // called nativeRecordButtons(false...)
5141            }
5142        } else {
5143            // When we lost focus, unless focus went to the TextView (which is
5144            // true if we are in editing mode), stop drawing the cursor ring.
5145            if (!inEditingMode()) {
5146                mDrawCursorRing = false;
5147                if (mNativeClass != 0) {
5148                    nativeRecordButtons(false, false, true);
5149                }
5150                setFocusControllerActive(false);
5151            }
5152            mGotKeyDown = false;
5153        }
5154
5155        super.onFocusChanged(focused, direction, previouslyFocusedRect);
5156    }
5157
5158    void setGLRectViewport() {
5159        // Use the getGlobalVisibleRect() to get the intersection among the parents
5160        // visible == false means we're clipped - send a null rect down to indicate that
5161        // we should not draw
5162        boolean visible = getGlobalVisibleRect(mGLRectViewport);
5163        if (visible) {
5164            // Then need to invert the Y axis, just for GL
5165            View rootView = getRootView();
5166            int rootViewHeight = rootView.getHeight();
5167            int savedWebViewBottom = mGLRectViewport.bottom;
5168            mGLRectViewport.bottom = rootViewHeight - mGLRectViewport.top - getVisibleTitleHeight();
5169            mGLRectViewport.top = rootViewHeight - savedWebViewBottom;
5170            mGLViewportEmpty = false;
5171        } else {
5172            mGLViewportEmpty = true;
5173        }
5174        nativeUpdateDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport);
5175    }
5176
5177    /**
5178     * @hide
5179     */
5180    @Override
5181    protected boolean setFrame(int left, int top, int right, int bottom) {
5182        boolean changed = super.setFrame(left, top, right, bottom);
5183        if (!changed && mHeightCanMeasure) {
5184            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
5185            // in WebViewCore after we get the first layout. We do call
5186            // requestLayout() when we get contentSizeChanged(). But the View
5187            // system won't call onSizeChanged if the dimension is not changed.
5188            // In this case, we need to call sendViewSizeZoom() explicitly to
5189            // notify the WebKit about the new dimensions.
5190            sendViewSizeZoom(false);
5191        }
5192        setGLRectViewport();
5193        return changed;
5194    }
5195
5196    @Override
5197    protected void onSizeChanged(int w, int h, int ow, int oh) {
5198        super.onSizeChanged(w, h, ow, oh);
5199
5200        // adjust the max viewport width depending on the view dimensions. This
5201        // is to ensure the scaling is not going insane. So do not shrink it if
5202        // the view size is temporarily smaller, e.g. when soft keyboard is up.
5203        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
5204        if (newMaxViewportWidth > sMaxViewportWidth) {
5205            sMaxViewportWidth = newMaxViewportWidth;
5206        }
5207
5208        mZoomManager.onSizeChanged(w, h, ow, oh);
5209    }
5210
5211    @Override
5212    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5213        super.onScrollChanged(l, t, oldl, oldt);
5214        if (!mInOverScrollMode) {
5215            sendOurVisibleRect();
5216            // update WebKit if visible title bar height changed. The logic is same
5217            // as getVisibleTitleHeight.
5218            int titleHeight = getTitleHeight();
5219            if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
5220                sendViewSizeZoom(false);
5221            }
5222        }
5223    }
5224
5225    @Override
5226    public boolean dispatchKeyEvent(KeyEvent event) {
5227        boolean dispatch = true;
5228
5229        // Textfields, plugins, and contentEditable nodes need to receive the
5230        // shift up key even if another key was released while the shift key
5231        // was held down.
5232        boolean inEditingMode = inEditingMode();
5233        if (!inEditingMode && (mNativeClass == 0
5234                || !nativePageShouldHandleShiftAndArrows())) {
5235            if (event.getAction() == KeyEvent.ACTION_DOWN) {
5236                mGotKeyDown = true;
5237            } else {
5238                if (!mGotKeyDown && event.getAction() != KeyEvent.ACTION_MULTIPLE) {
5239                    /*
5240                     * We got a key up for which we were not the recipient of
5241                     * the original key down. Don't give it to the view.
5242                     */
5243                    dispatch = false;
5244                }
5245                mGotKeyDown = false;
5246            }
5247        }
5248
5249        if (dispatch) {
5250            if (inEditingMode) {
5251                // Ensure that the WebTextView gets the event, even if it does
5252                // not currently have a bounds.
5253                return mWebTextView.dispatchKeyEvent(event);
5254            } else {
5255                return super.dispatchKeyEvent(event);
5256            }
5257        } else {
5258            // We didn't dispatch, so let something else handle the key
5259            return false;
5260        }
5261    }
5262
5263    // Here are the snap align logic:
5264    // 1. If it starts nearly horizontally or vertically, snap align;
5265    // 2. If there is a dramitic direction change, let it go;
5266    // 3. If there is a same direction back and forth, lock it.
5267
5268    // adjustable parameters
5269    private int mMinLockSnapReverseDistance;
5270    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
5271    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
5272
5273    private boolean hitFocusedPlugin(int contentX, int contentY) {
5274        if (DebugFlags.WEB_VIEW) {
5275            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
5276            Rect r = nativeFocusNodeBounds();
5277            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
5278                    + ", " + r.right + ", " + r.bottom + ")");
5279        }
5280        return nativeFocusIsPlugin()
5281                && nativeFocusNodeBounds().contains(contentX, contentY);
5282    }
5283
5284    private boolean shouldForwardTouchEvent() {
5285        return mFullScreenHolder != null || (mForwardTouchEvents
5286                && !mSelectingText
5287                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
5288    }
5289
5290    private boolean inFullScreenMode() {
5291        return mFullScreenHolder != null;
5292    }
5293
5294    private void dismissFullScreenMode() {
5295        if (inFullScreenMode()) {
5296            mFullScreenHolder.dismiss();
5297            mFullScreenHolder = null;
5298        }
5299    }
5300
5301    void onPinchToZoomAnimationStart() {
5302        // cancel the single touch handling
5303        cancelTouch();
5304        onZoomAnimationStart();
5305    }
5306
5307    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
5308        onZoomAnimationEnd();
5309        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
5310        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
5311        // as it may trigger the unwanted fling.
5312        mTouchMode = TOUCH_PINCH_DRAG;
5313        mConfirmMove = true;
5314        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
5315    }
5316
5317    // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a
5318    // layer is found.
5319    private void startScrollingLayer(float x, float y) {
5320        int contentX = viewToContentX((int) x + mScrollX);
5321        int contentY = viewToContentY((int) y + mScrollY);
5322        mScrollingLayer = nativeScrollableLayer(contentX, contentY,
5323                mScrollingLayerRect, mScrollingLayerBounds);
5324        if (mScrollingLayer != 0) {
5325            mTouchMode = TOUCH_DRAG_LAYER_MODE;
5326        }
5327    }
5328
5329    // 1/(density * density) used to compute the distance between points.
5330    // Computed in init().
5331    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
5332
5333    // The distance between two points reported in onTouchEvent scaled by the
5334    // density of the screen.
5335    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
5336
5337    @Override
5338    public boolean onTouchEvent(MotionEvent ev) {
5339        if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) {
5340            return false;
5341        }
5342
5343        if (DebugFlags.WEB_VIEW) {
5344            Log.v(LOGTAG, ev + " at " + ev.getEventTime()
5345                + " mTouchMode=" + mTouchMode
5346                + " numPointers=" + ev.getPointerCount());
5347        }
5348
5349        int action = ev.getActionMasked();
5350        if (ev.getPointerCount() > 1) {  // Multi-touch
5351            mIsHandlingMultiTouch = true;
5352
5353            // If WebKit already showed no interests in this sequence of events,
5354            // WebView handles them directly.
5355            if (mPreventDefault == PREVENT_DEFAULT_NO && action == MotionEvent.ACTION_MOVE) {
5356                handleMultiTouchInWebView(ev);
5357            } else {
5358                passMultiTouchToWebKit(ev);
5359            }
5360            return true;
5361        }
5362
5363        // Skip ACTION_MOVE for single touch if it's still handling multi-touch.
5364        if (mIsHandlingMultiTouch && action == MotionEvent.ACTION_MOVE) {
5365            return false;
5366        }
5367
5368        return handleTouchEventCommon(ev, action, Math.round(ev.getX()), Math.round(ev.getY()));
5369    }
5370
5371    /*
5372     * Common code for single touch and multi-touch.
5373     * (x, y) denotes current focus point, which is the touch point for single touch
5374     * and the middle point for multi-touch.
5375     */
5376    private boolean handleTouchEventCommon(MotionEvent ev, int action, int x, int y) {
5377        long eventTime = ev.getEventTime();
5378
5379
5380        // Due to the touch screen edge effect, a touch closer to the edge
5381        // always snapped to the edge. As getViewWidth() can be different from
5382        // getWidth() due to the scrollbar, adjusting the point to match
5383        // getViewWidth(). Same applied to the height.
5384        x = Math.min(x, getViewWidth() - 1);
5385        y = Math.min(y, getViewHeightWithTitle() - 1);
5386
5387        int deltaX = mLastTouchX - x;
5388        int deltaY = mLastTouchY - y;
5389        int contentX = viewToContentX(x + mScrollX);
5390        int contentY = viewToContentY(y + mScrollY);
5391
5392        switch (action) {
5393            case MotionEvent.ACTION_DOWN: {
5394                mPreventDefault = PREVENT_DEFAULT_NO;
5395                mConfirmMove = false;
5396                mIsHandlingMultiTouch = false;
5397                mInitialHitTestResult = null;
5398                if (!mScroller.isFinished()) {
5399                    // stop the current scroll animation, but if this is
5400                    // the start of a fling, allow it to add to the current
5401                    // fling's velocity
5402                    mScroller.abortAnimation();
5403                    mTouchMode = TOUCH_DRAG_START_MODE;
5404                    mConfirmMove = true;
5405                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5406                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
5407                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
5408                    if (getSettings().supportTouchOnly()) {
5409                        removeTouchHighlight(true);
5410                    }
5411                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
5412                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
5413                    } else {
5414                        // commit the short press action for the previous tap
5415                        doShortPress();
5416                        mTouchMode = TOUCH_INIT_MODE;
5417                        mDeferTouchProcess = (!inFullScreenMode()
5418                                && mForwardTouchEvents) ? hitFocusedPlugin(
5419                                contentX, contentY) : false;
5420                    }
5421                } else { // the normal case
5422                    mTouchMode = TOUCH_INIT_MODE;
5423                    mDeferTouchProcess = (!inFullScreenMode()
5424                            && mForwardTouchEvents) ? hitFocusedPlugin(
5425                            contentX, contentY) : false;
5426                    mWebViewCore.sendMessage(
5427                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
5428                    if (getSettings().supportTouchOnly()) {
5429                        TouchHighlightData data = new TouchHighlightData();
5430                        data.mX = contentX;
5431                        data.mY = contentY;
5432                        data.mSlop = viewToContentDimension(mNavSlop);
5433                        mWebViewCore.sendMessageDelayed(
5434                                EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
5435                                ViewConfiguration.getTapTimeout());
5436                        if (DEBUG_TOUCH_HIGHLIGHT) {
5437                            if (getSettings().getNavDump()) {
5438                                mTouchHighlightX = (int) x + mScrollX;
5439                                mTouchHighlightY = (int) y + mScrollY;
5440                                mPrivateHandler.postDelayed(new Runnable() {
5441                                    public void run() {
5442                                        mTouchHighlightX = mTouchHighlightY = 0;
5443                                        invalidate();
5444                                    }
5445                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
5446                            }
5447                        }
5448                    }
5449                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
5450                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
5451                                (eventTime - mLastTouchUpTime), eventTime);
5452                    }
5453                    if (mSelectingText) {
5454                        mDrawSelectionPointer = false;
5455                        mSelectionStarted = nativeStartSelection(contentX, contentY);
5456                        if (DebugFlags.WEB_VIEW) {
5457                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
5458                        }
5459                        invalidate();
5460                    }
5461                }
5462                // Trigger the link
5463                if (mTouchMode == TOUCH_INIT_MODE
5464                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5465                    mPrivateHandler.sendEmptyMessageDelayed(
5466                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
5467                    mPrivateHandler.sendEmptyMessageDelayed(
5468                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
5469                    if (inFullScreenMode() || mDeferTouchProcess) {
5470                        mPreventDefault = PREVENT_DEFAULT_YES;
5471                    } else if (mForwardTouchEvents) {
5472                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
5473                    } else {
5474                        mPreventDefault = PREVENT_DEFAULT_NO;
5475                    }
5476                    // pass the touch events from UI thread to WebCore thread
5477                    if (shouldForwardTouchEvent()) {
5478                        TouchEventData ted = new TouchEventData();
5479                        ted.mAction = action;
5480                        ted.mIds = new int[1];
5481                        ted.mIds[0] = ev.getPointerId(0);
5482                        ted.mPoints = new Point[1];
5483                        ted.mPoints[0] = new Point(contentX, contentY);
5484                        ted.mMetaState = ev.getMetaState();
5485                        ted.mReprocess = mDeferTouchProcess;
5486                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5487                        if (mDeferTouchProcess) {
5488                            // still needs to set them for compute deltaX/Y
5489                            mLastTouchX = x;
5490                            mLastTouchY = y;
5491                            break;
5492                        }
5493                        if (!inFullScreenMode()) {
5494                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
5495                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
5496                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5497                                            action, 0), TAP_TIMEOUT);
5498                        }
5499                    }
5500                }
5501                startTouch(x, y, eventTime);
5502                break;
5503            }
5504            case MotionEvent.ACTION_MOVE: {
5505                boolean firstMove = false;
5506                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
5507                        >= mTouchSlopSquare) {
5508                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5509                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5510                    mConfirmMove = true;
5511                    firstMove = true;
5512                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5513                        mTouchMode = TOUCH_INIT_MODE;
5514                    }
5515                    if (getSettings().supportTouchOnly()) {
5516                        removeTouchHighlight(true);
5517                    }
5518                }
5519                // pass the touch events from UI thread to WebCore thread
5520                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
5521                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
5522                    TouchEventData ted = new TouchEventData();
5523                    ted.mAction = action;
5524                    ted.mIds = new int[1];
5525                    ted.mIds[0] = ev.getPointerId(0);
5526                    ted.mPoints = new Point[1];
5527                    ted.mPoints[0] = new Point(contentX, contentY);
5528                    ted.mMetaState = ev.getMetaState();
5529                    ted.mReprocess = mDeferTouchProcess;
5530                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5531                    mLastSentTouchTime = eventTime;
5532                    if (mDeferTouchProcess) {
5533                        break;
5534                    }
5535                    if (firstMove && !inFullScreenMode()) {
5536                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
5537                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5538                                        action, 0), TAP_TIMEOUT);
5539                    }
5540                }
5541                if (mTouchMode == TOUCH_DONE_MODE
5542                        || mPreventDefault == PREVENT_DEFAULT_YES) {
5543                    // no dragging during scroll zoom animation, or when prevent
5544                    // default is yes
5545                    break;
5546                }
5547                if (mVelocityTracker == null) {
5548                    Log.e(LOGTAG, "Got null mVelocityTracker when "
5549                            + "mPreventDefault = " + mPreventDefault
5550                            + " mDeferTouchProcess = " + mDeferTouchProcess
5551                            + " mTouchMode = " + mTouchMode);
5552                } else {
5553                    mVelocityTracker.addMovement(ev);
5554                }
5555                if (mSelectingText && mSelectionStarted) {
5556                    if (DebugFlags.WEB_VIEW) {
5557                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
5558                    }
5559                    ViewParent parent = getParent();
5560                    if (parent != null) {
5561                        parent.requestDisallowInterceptTouchEvent(true);
5562                    }
5563                    mAutoScrollX = x <= mMinAutoScrollX ? -SELECT_SCROLL
5564                            : x >= mMaxAutoScrollX ? SELECT_SCROLL : 0;
5565                    mAutoScrollY = y <= mMinAutoScrollY ? -SELECT_SCROLL
5566                            : y >= mMaxAutoScrollY ? SELECT_SCROLL : 0;
5567                    if ((mAutoScrollX != 0 || mAutoScrollY != 0)
5568                            && !mSentAutoScrollMessage) {
5569                        mSentAutoScrollMessage = true;
5570                        mPrivateHandler.sendEmptyMessageDelayed(
5571                                SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
5572                    }
5573                    if (deltaX != 0 || deltaY != 0) {
5574                        nativeExtendSelection(contentX, contentY);
5575                        invalidate();
5576                    }
5577                    break;
5578                }
5579
5580                if (mTouchMode != TOUCH_DRAG_MODE &&
5581                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5582
5583                    if (!mConfirmMove) {
5584                        break;
5585                    }
5586
5587                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
5588                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
5589                        // track mLastTouchTime as we may need to do fling at
5590                        // ACTION_UP
5591                        mLastTouchTime = eventTime;
5592                        break;
5593                    }
5594
5595                    // Only lock dragging to one axis if we don't have a scale in progress.
5596                    // Scaling implies free-roaming movement. Note this is only ever a question
5597                    // if mZoomManager.supportsPanDuringZoom() is true.
5598                    final ScaleGestureDetector detector =
5599                      mZoomManager.getMultiTouchGestureDetector();
5600                    if (detector == null || !detector.isInProgress()) {
5601                        // if it starts nearly horizontal or vertical, enforce it
5602                        int ax = Math.abs(deltaX);
5603                        int ay = Math.abs(deltaY);
5604                        if (ax > MAX_SLOPE_FOR_DIAG * ay) {
5605                            mSnapScrollMode = SNAP_X;
5606                            mSnapPositive = deltaX > 0;
5607                        } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
5608                            mSnapScrollMode = SNAP_Y;
5609                            mSnapPositive = deltaY > 0;
5610                        }
5611                    }
5612
5613                    mTouchMode = TOUCH_DRAG_MODE;
5614                    mLastTouchX = x;
5615                    mLastTouchY = y;
5616                    deltaX = 0;
5617                    deltaY = 0;
5618
5619                    startScrollingLayer(x, y);
5620                    startDrag();
5621                }
5622
5623                // do pan
5624                boolean done = false;
5625                boolean keepScrollBarsVisible = false;
5626                if (deltaX == 0 && deltaY == 0) {
5627                    keepScrollBarsVisible = done = true;
5628                } else {
5629                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
5630                        int ax = Math.abs(deltaX);
5631                        int ay = Math.abs(deltaY);
5632                        if (mSnapScrollMode == SNAP_X) {
5633                            // radical change means getting out of snap mode
5634                            if (ay > MAX_SLOPE_FOR_DIAG * ax
5635                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5636                                mSnapScrollMode = SNAP_NONE;
5637                            }
5638                            // reverse direction means lock in the snap mode
5639                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
5640                                    (mSnapPositive
5641                                    ? deltaX < -mMinLockSnapReverseDistance
5642                                    : deltaX > mMinLockSnapReverseDistance)) {
5643                                mSnapScrollMode |= SNAP_LOCK;
5644                            }
5645                        } else {
5646                            // radical change means getting out of snap mode
5647                            if (ax > MAX_SLOPE_FOR_DIAG * ay
5648                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5649                                mSnapScrollMode = SNAP_NONE;
5650                            }
5651                            // reverse direction means lock in the snap mode
5652                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
5653                                    (mSnapPositive
5654                                    ? deltaY < -mMinLockSnapReverseDistance
5655                                    : deltaY > mMinLockSnapReverseDistance)) {
5656                                mSnapScrollMode |= SNAP_LOCK;
5657                            }
5658                        }
5659                    }
5660                    if (mSnapScrollMode != SNAP_NONE) {
5661                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5662                            deltaY = 0;
5663                        } else {
5664                            deltaX = 0;
5665                        }
5666                    }
5667                    if ((deltaX | deltaY) != 0) {
5668                        if (deltaX != 0) {
5669                            mLastTouchX = x;
5670                        }
5671                        if (deltaY != 0) {
5672                            mLastTouchY = y;
5673                        }
5674                        mHeldMotionless = MOTIONLESS_FALSE;
5675                    }
5676                    mLastTouchTime = eventTime;
5677                    mUserScroll = true;
5678                }
5679
5680                doDrag(deltaX, deltaY);
5681
5682                // Turn off scrollbars when dragging a layer.
5683                if (keepScrollBarsVisible &&
5684                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5685                    if (mHeldMotionless != MOTIONLESS_TRUE) {
5686                        mHeldMotionless = MOTIONLESS_TRUE;
5687                        invalidate();
5688                    }
5689                    // keep the scrollbar on the screen even there is no scroll
5690                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
5691                            false);
5692                    // return false to indicate that we can't pan out of the
5693                    // view space
5694                    return !done;
5695                }
5696                break;
5697            }
5698            case MotionEvent.ACTION_UP: {
5699                if (!isFocused()) requestFocus();
5700                // pass the touch events from UI thread to WebCore thread
5701                if (shouldForwardTouchEvent()) {
5702                    TouchEventData ted = new TouchEventData();
5703                    ted.mIds = new int[1];
5704                    ted.mIds[0] = ev.getPointerId(0);
5705                    ted.mAction = action;
5706                    ted.mPoints = new Point[1];
5707                    ted.mPoints[0] = new Point(contentX, contentY);
5708                    ted.mMetaState = ev.getMetaState();
5709                    ted.mReprocess = mDeferTouchProcess;
5710                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5711                }
5712                mLastTouchUpTime = eventTime;
5713                if (mSentAutoScrollMessage) {
5714                    mAutoScrollX = mAutoScrollY = 0;
5715                }
5716                switch (mTouchMode) {
5717                    case TOUCH_DOUBLE_TAP_MODE: // double tap
5718                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5719                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5720                        if (inFullScreenMode() || mDeferTouchProcess) {
5721                            TouchEventData ted = new TouchEventData();
5722                            ted.mIds = new int[1];
5723                            ted.mIds[0] = ev.getPointerId(0);
5724                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
5725                            ted.mPoints = new Point[1];
5726                            ted.mPoints[0] = new Point(contentX, contentY);
5727                            ted.mMetaState = ev.getMetaState();
5728                            ted.mReprocess = mDeferTouchProcess;
5729                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5730                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
5731                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
5732                            mTouchMode = TOUCH_DONE_MODE;
5733                        }
5734                        break;
5735                    case TOUCH_INIT_MODE: // tap
5736                    case TOUCH_SHORTPRESS_START_MODE:
5737                    case TOUCH_SHORTPRESS_MODE:
5738                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5739                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5740                        if (mConfirmMove) {
5741                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
5742                                    " WebCore's response for touch down.");
5743                            if (mPreventDefault != PREVENT_DEFAULT_YES
5744                                    && (computeMaxScrollX() > 0
5745                                            || computeMaxScrollY() > 0)) {
5746                                // If the user has performed a very quick touch
5747                                // sequence it is possible that we may get here
5748                                // before WebCore has had a chance to process the events.
5749                                // In this case, any call to preventDefault in the
5750                                // JS touch handler will not have been executed yet.
5751                                // Hence we will see both the UI (now) and WebCore
5752                                // (when context switches) handling the event,
5753                                // regardless of whether the web developer actually
5754                                // doeses preventDefault in their touch handler. This
5755                                // is the nature of our asynchronous touch model.
5756
5757                                // we will not rewrite drag code here, but we
5758                                // will try fling if it applies.
5759                                WebViewCore.reducePriority();
5760                                // to get better performance, pause updating the
5761                                // picture
5762                                WebViewCore.pauseUpdatePicture(mWebViewCore);
5763                                // fall through to TOUCH_DRAG_MODE
5764                            } else {
5765                                // WebKit may consume the touch event and modify
5766                                // DOM. drawContentPicture() will be called with
5767                                // animateSroll as true for better performance.
5768                                // Force redraw in high-quality.
5769                                invalidate();
5770                                break;
5771                            }
5772                        } else {
5773                            if (mSelectingText) {
5774                                // tapping on selection or controls does nothing
5775                                if (!nativeHitSelection(contentX, contentY)) {
5776                                    selectionDone();
5777                                }
5778                                break;
5779                            }
5780                            // only trigger double tap if the WebView is
5781                            // scalable
5782                            if (mTouchMode == TOUCH_INIT_MODE
5783                                    && (canZoomIn() || canZoomOut())) {
5784                                mPrivateHandler.sendEmptyMessageDelayed(
5785                                        RELEASE_SINGLE_TAP, ViewConfiguration
5786                                                .getDoubleTapTimeout());
5787                            } else {
5788                                doShortPress();
5789                            }
5790                            break;
5791                        }
5792                    case TOUCH_DRAG_MODE:
5793                    case TOUCH_DRAG_LAYER_MODE:
5794                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5795                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5796                        // if the user waits a while w/o moving before the
5797                        // up, we don't want to do a fling
5798                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
5799                            if (mVelocityTracker == null) {
5800                                Log.e(LOGTAG, "Got null mVelocityTracker when "
5801                                        + "mPreventDefault = "
5802                                        + mPreventDefault
5803                                        + " mDeferTouchProcess = "
5804                                        + mDeferTouchProcess);
5805                            } else {
5806                                mVelocityTracker.addMovement(ev);
5807                            }
5808                            // set to MOTIONLESS_IGNORE so that it won't keep
5809                            // removing and sending message in
5810                            // drawCoreAndCursorRing()
5811                            mHeldMotionless = MOTIONLESS_IGNORE;
5812                            doFling();
5813                            break;
5814                        } else {
5815                            if (mScroller.springBack(mScrollX, mScrollY, 0,
5816                                    computeMaxScrollX(), 0,
5817                                    computeMaxScrollY())) {
5818                                invalidate();
5819                            }
5820                        }
5821                        // redraw in high-quality, as we're done dragging
5822                        mHeldMotionless = MOTIONLESS_TRUE;
5823                        invalidate();
5824                        // fall through
5825                    case TOUCH_DRAG_START_MODE:
5826                        // TOUCH_DRAG_START_MODE should not happen for the real
5827                        // device as we almost certain will get a MOVE. But this
5828                        // is possible on emulator.
5829                        mLastVelocity = 0;
5830                        WebViewCore.resumePriority();
5831                        if (!mSelectingText) {
5832                            WebViewCore.resumeUpdatePicture(mWebViewCore);
5833                        }
5834                        break;
5835                }
5836                stopTouch();
5837                break;
5838            }
5839            case MotionEvent.ACTION_CANCEL: {
5840                if (mTouchMode == TOUCH_DRAG_MODE) {
5841                    mScroller.springBack(mScrollX, mScrollY, 0,
5842                            computeMaxScrollX(), 0, computeMaxScrollY());
5843                    invalidate();
5844                }
5845                cancelWebCoreTouchEvent(contentX, contentY, false);
5846                cancelTouch();
5847                break;
5848            }
5849        }
5850        return true;
5851    }
5852
5853    private void passMultiTouchToWebKit(MotionEvent ev) {
5854        TouchEventData ted = new TouchEventData();
5855        ted.mAction = ev.getActionMasked();
5856        final int count = ev.getPointerCount();
5857        ted.mIds = new int[count];
5858        ted.mPoints = new Point[count];
5859        for (int c = 0; c < count; c++) {
5860            ted.mIds[c] = ev.getPointerId(c);
5861            int x = viewToContentX((int) ev.getX(c) + mScrollX);
5862            int y = viewToContentY((int) ev.getY(c) + mScrollY);
5863            ted.mPoints[c] = new Point(x, y);
5864        }
5865        ted.mMetaState = ev.getMetaState();
5866        ted.mReprocess = true;
5867        ted.mMotionEvent = MotionEvent.obtain(ev);
5868        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5869        cancelLongPress();
5870        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5871        mPreventDefault = PREVENT_DEFAULT_IGNORE;
5872    }
5873
5874    private void handleMultiTouchInWebView(MotionEvent ev) {
5875        if (DebugFlags.WEB_VIEW) {
5876            Log.v(LOGTAG, "multi-touch: " + ev + " at " + ev.getEventTime()
5877                + " mTouchMode=" + mTouchMode
5878                + " numPointers=" + ev.getPointerCount()
5879                + " scrolloffset=(" + mScrollX + "," + mScrollY + ")");
5880        }
5881
5882        final ScaleGestureDetector detector =
5883            mZoomManager.getMultiTouchGestureDetector();
5884
5885        // A few apps use WebView but don't instantiate gesture detector.
5886        // We don't need to support multi touch for them.
5887        if (detector == null) return;
5888
5889        float x = ev.getX();
5890        float y = ev.getY();
5891
5892        if (!detector.isInProgress() &&
5893            ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
5894            // Insert a fake pointer down event in order to start
5895            // the zoom scale detector.
5896            MotionEvent temp = MotionEvent.obtain(ev);
5897            // Clear the original event and set it to
5898            // ACTION_POINTER_DOWN.
5899            try {
5900                temp.setAction(temp.getAction() &
5901                ~MotionEvent.ACTION_MASK |
5902                MotionEvent.ACTION_POINTER_DOWN);
5903                detector.onTouchEvent(temp);
5904            } finally {
5905                temp.recycle();
5906            }
5907        }
5908
5909        detector.onTouchEvent(ev);
5910
5911        if (detector.isInProgress()) {
5912            if (DebugFlags.WEB_VIEW) {
5913                Log.v(LOGTAG, "detector is in progress");
5914            }
5915            mLastTouchTime = ev.getEventTime();
5916            x = detector.getFocusX();
5917            y = detector.getFocusY();
5918
5919            cancelLongPress();
5920            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5921            if (!mZoomManager.supportsPanDuringZoom()) {
5922                return;
5923            }
5924            mTouchMode = TOUCH_DRAG_MODE;
5925            if (mVelocityTracker == null) {
5926                mVelocityTracker = VelocityTracker.obtain();
5927            }
5928        }
5929
5930        int action = ev.getActionMasked();
5931        if (action == MotionEvent.ACTION_POINTER_DOWN) {
5932            cancelTouch();
5933            action = MotionEvent.ACTION_DOWN;
5934        } else if (action == MotionEvent.ACTION_POINTER_UP) {
5935            // set mLastTouchX/Y to the remaining point
5936            mLastTouchX = Math.round(x);
5937            mLastTouchY = Math.round(y);
5938            mIsHandlingMultiTouch = false;
5939        } else if (action == MotionEvent.ACTION_MOVE) {
5940            // negative x or y indicate it is on the edge, skip it.
5941            if (x < 0 || y < 0) {
5942                return;
5943            }
5944        }
5945
5946        handleTouchEventCommon(ev, action, Math.round(x), Math.round(y));
5947    }
5948
5949    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
5950        if (shouldForwardTouchEvent()) {
5951            if (removeEvents) {
5952                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5953            }
5954            TouchEventData ted = new TouchEventData();
5955            ted.mIds = new int[1];
5956            ted.mIds[0] = 0;
5957            ted.mPoints = new Point[1];
5958            ted.mPoints[0] = new Point(x, y);
5959            ted.mAction = MotionEvent.ACTION_CANCEL;
5960            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5961            mPreventDefault = PREVENT_DEFAULT_IGNORE;
5962        }
5963    }
5964
5965    private void startTouch(float x, float y, long eventTime) {
5966        // Remember where the motion event started
5967        mLastTouchX = Math.round(x);
5968        mLastTouchY = Math.round(y);
5969        mLastTouchTime = eventTime;
5970        mVelocityTracker = VelocityTracker.obtain();
5971        mSnapScrollMode = SNAP_NONE;
5972    }
5973
5974    private void startDrag() {
5975        WebViewCore.reducePriority();
5976        // to get better performance, pause updating the picture
5977        WebViewCore.pauseUpdatePicture(mWebViewCore);
5978        if (!mDragFromTextInput) {
5979            nativeHideCursor();
5980        }
5981
5982        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
5983                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
5984            mZoomManager.invokeZoomPicker();
5985        }
5986    }
5987
5988    private void doDrag(int deltaX, int deltaY) {
5989        if ((deltaX | deltaY) != 0) {
5990            int oldX = mScrollX;
5991            int oldY = mScrollY;
5992            int rangeX = computeMaxScrollX();
5993            int rangeY = computeMaxScrollY();
5994            int overscrollDistance = mOverscrollDistance;
5995
5996            // Check for the original scrolling layer in case we change
5997            // directions.  mTouchMode might be TOUCH_DRAG_MODE if we have
5998            // reached the edge of a layer but mScrollingLayer will be non-zero
5999            // if we initiated the drag on a layer.
6000            if (mScrollingLayer != 0) {
6001                final int contentX = viewToContentDimension(deltaX);
6002                final int contentY = viewToContentDimension(deltaY);
6003
6004                // Check the scrolling bounds to see if we will actually do any
6005                // scrolling.  The rectangle is in document coordinates.
6006                final int maxX = mScrollingLayerRect.right;
6007                final int maxY = mScrollingLayerRect.bottom;
6008                final int resultX = Math.max(0,
6009                        Math.min(mScrollingLayerRect.left + contentX, maxX));
6010                final int resultY = Math.max(0,
6011                        Math.min(mScrollingLayerRect.top + contentY, maxY));
6012
6013                if (resultX != mScrollingLayerRect.left ||
6014                        resultY != mScrollingLayerRect.top) {
6015                    // In case we switched to dragging the page.
6016                    mTouchMode = TOUCH_DRAG_LAYER_MODE;
6017                    deltaX = contentX;
6018                    deltaY = contentY;
6019                    oldX = mScrollingLayerRect.left;
6020                    oldY = mScrollingLayerRect.top;
6021                    rangeX = maxX;
6022                    rangeY = maxY;
6023                } else {
6024                    // Scroll the main page if we are not going to scroll the
6025                    // layer.  This does not reset mScrollingLayer in case the
6026                    // user changes directions and the layer can scroll the
6027                    // other way.
6028                    mTouchMode = TOUCH_DRAG_MODE;
6029                }
6030            }
6031
6032            if (mOverScrollGlow != null) {
6033                mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
6034            }
6035
6036            overScrollBy(deltaX, deltaY, oldX, oldY,
6037                    rangeX, rangeY,
6038                    mOverscrollDistance, mOverscrollDistance, true);
6039            if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
6040                invalidate();
6041            }
6042        }
6043        mZoomManager.keepZoomPickerVisible();
6044    }
6045
6046    private void stopTouch() {
6047        // we also use mVelocityTracker == null to tell us that we are
6048        // not "moving around", so we can take the slower/prettier
6049        // mode in the drawing code
6050        if (mVelocityTracker != null) {
6051            mVelocityTracker.recycle();
6052            mVelocityTracker = null;
6053        }
6054
6055        // Release any pulled glows
6056        if (mOverScrollGlow != null) {
6057            mOverScrollGlow.releaseAll();
6058        }
6059    }
6060
6061    private void cancelTouch() {
6062        // we also use mVelocityTracker == null to tell us that we are
6063        // not "moving around", so we can take the slower/prettier
6064        // mode in the drawing code
6065        if (mVelocityTracker != null) {
6066            mVelocityTracker.recycle();
6067            mVelocityTracker = null;
6068        }
6069
6070        if ((mTouchMode == TOUCH_DRAG_MODE
6071                || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
6072            WebViewCore.resumePriority();
6073            WebViewCore.resumeUpdatePicture(mWebViewCore);
6074        }
6075        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6076        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6077        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6078        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
6079        if (getSettings().supportTouchOnly()) {
6080            removeTouchHighlight(true);
6081        }
6082        mHeldMotionless = MOTIONLESS_TRUE;
6083        mTouchMode = TOUCH_DONE_MODE;
6084        nativeHideCursor();
6085    }
6086
6087    private long mTrackballFirstTime = 0;
6088    private long mTrackballLastTime = 0;
6089    private float mTrackballRemainsX = 0.0f;
6090    private float mTrackballRemainsY = 0.0f;
6091    private int mTrackballXMove = 0;
6092    private int mTrackballYMove = 0;
6093    private boolean mSelectingText = false;
6094    private boolean mSelectionStarted = false;
6095    private boolean mExtendSelection = false;
6096    private boolean mDrawSelectionPointer = false;
6097    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
6098    private static final int TRACKBALL_TIMEOUT = 200;
6099    private static final int TRACKBALL_WAIT = 100;
6100    private static final int TRACKBALL_SCALE = 400;
6101    private static final int TRACKBALL_SCROLL_COUNT = 5;
6102    private static final int TRACKBALL_MOVE_COUNT = 10;
6103    private static final int TRACKBALL_MULTIPLIER = 3;
6104    private static final int SELECT_CURSOR_OFFSET = 16;
6105    private static final int SELECT_SCROLL = 5;
6106    private int mSelectX = 0;
6107    private int mSelectY = 0;
6108    private boolean mFocusSizeChanged = false;
6109    private boolean mTrackballDown = false;
6110    private long mTrackballUpTime = 0;
6111    private long mLastCursorTime = 0;
6112    private Rect mLastCursorBounds;
6113
6114    // Set by default; BrowserActivity clears to interpret trackball data
6115    // directly for movement. Currently, the framework only passes
6116    // arrow key events, not trackball events, from one child to the next
6117    private boolean mMapTrackballToArrowKeys = true;
6118
6119    public void setMapTrackballToArrowKeys(boolean setMap) {
6120        mMapTrackballToArrowKeys = setMap;
6121    }
6122
6123    void resetTrackballTime() {
6124        mTrackballLastTime = 0;
6125    }
6126
6127    @Override
6128    public boolean onTrackballEvent(MotionEvent ev) {
6129        long time = ev.getEventTime();
6130        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
6131            if (ev.getY() > 0) pageDown(true);
6132            if (ev.getY() < 0) pageUp(true);
6133            return true;
6134        }
6135        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
6136            if (mSelectingText) {
6137                return true; // discard press if copy in progress
6138            }
6139            mTrackballDown = true;
6140            if (mNativeClass == 0) {
6141                return false;
6142            }
6143            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
6144            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
6145                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
6146                nativeSelectBestAt(mLastCursorBounds);
6147            }
6148            if (DebugFlags.WEB_VIEW) {
6149                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
6150                        + " time=" + time
6151                        + " mLastCursorTime=" + mLastCursorTime);
6152            }
6153            if (isInTouchMode()) requestFocusFromTouch();
6154            return false; // let common code in onKeyDown at it
6155        }
6156        if (ev.getAction() == MotionEvent.ACTION_UP) {
6157            // LONG_PRESS_CENTER is set in common onKeyDown
6158            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
6159            mTrackballDown = false;
6160            mTrackballUpTime = time;
6161            if (mSelectingText) {
6162                if (mExtendSelection) {
6163                    copySelection();
6164                    selectionDone();
6165                } else {
6166                    mExtendSelection = true;
6167                    nativeSetExtendSelection();
6168                    invalidate(); // draw the i-beam instead of the arrow
6169                }
6170                return true; // discard press if copy in progress
6171            }
6172            if (DebugFlags.WEB_VIEW) {
6173                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
6174                        + " time=" + time
6175                );
6176            }
6177            return false; // let common code in onKeyUp at it
6178        }
6179        if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
6180                AccessibilityManager.getInstance(mContext).isEnabled()) {
6181            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
6182            return false;
6183        }
6184        if (mTrackballDown) {
6185            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
6186            return true; // discard move if trackball is down
6187        }
6188        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
6189            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
6190            return true;
6191        }
6192        // TODO: alternatively we can do panning as touch does
6193        switchOutDrawHistory();
6194        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
6195            if (DebugFlags.WEB_VIEW) {
6196                Log.v(LOGTAG, "onTrackballEvent time="
6197                        + time + " last=" + mTrackballLastTime);
6198            }
6199            mTrackballFirstTime = time;
6200            mTrackballXMove = mTrackballYMove = 0;
6201        }
6202        mTrackballLastTime = time;
6203        if (DebugFlags.WEB_VIEW) {
6204            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
6205        }
6206        mTrackballRemainsX += ev.getX();
6207        mTrackballRemainsY += ev.getY();
6208        doTrackball(time, ev.getMetaState());
6209        return true;
6210    }
6211
6212    void moveSelection(float xRate, float yRate) {
6213        if (mNativeClass == 0)
6214            return;
6215        int width = getViewWidth();
6216        int height = getViewHeight();
6217        mSelectX += xRate;
6218        mSelectY += yRate;
6219        int maxX = width + mScrollX;
6220        int maxY = height + mScrollY;
6221        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
6222                , mSelectX));
6223        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
6224                , mSelectY));
6225        if (DebugFlags.WEB_VIEW) {
6226            Log.v(LOGTAG, "moveSelection"
6227                    + " mSelectX=" + mSelectX
6228                    + " mSelectY=" + mSelectY
6229                    + " mScrollX=" + mScrollX
6230                    + " mScrollY=" + mScrollY
6231                    + " xRate=" + xRate
6232                    + " yRate=" + yRate
6233                    );
6234        }
6235        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
6236        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
6237                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6238                : 0;
6239        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
6240                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
6241                : 0;
6242        pinScrollBy(scrollX, scrollY, true, 0);
6243        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
6244        requestRectangleOnScreen(select);
6245        invalidate();
6246   }
6247
6248    private int scaleTrackballX(float xRate, int width) {
6249        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
6250        int nextXMove = xMove;
6251        if (xMove > 0) {
6252            if (xMove > mTrackballXMove) {
6253                xMove -= mTrackballXMove;
6254            }
6255        } else if (xMove < mTrackballXMove) {
6256            xMove -= mTrackballXMove;
6257        }
6258        mTrackballXMove = nextXMove;
6259        return xMove;
6260    }
6261
6262    private int scaleTrackballY(float yRate, int height) {
6263        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
6264        int nextYMove = yMove;
6265        if (yMove > 0) {
6266            if (yMove > mTrackballYMove) {
6267                yMove -= mTrackballYMove;
6268            }
6269        } else if (yMove < mTrackballYMove) {
6270            yMove -= mTrackballYMove;
6271        }
6272        mTrackballYMove = nextYMove;
6273        return yMove;
6274    }
6275
6276    private int keyCodeToSoundsEffect(int keyCode) {
6277        switch(keyCode) {
6278            case KeyEvent.KEYCODE_DPAD_UP:
6279                return SoundEffectConstants.NAVIGATION_UP;
6280            case KeyEvent.KEYCODE_DPAD_RIGHT:
6281                return SoundEffectConstants.NAVIGATION_RIGHT;
6282            case KeyEvent.KEYCODE_DPAD_DOWN:
6283                return SoundEffectConstants.NAVIGATION_DOWN;
6284            case KeyEvent.KEYCODE_DPAD_LEFT:
6285                return SoundEffectConstants.NAVIGATION_LEFT;
6286        }
6287        throw new IllegalArgumentException("keyCode must be one of " +
6288                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
6289                "KEYCODE_DPAD_LEFT}.");
6290    }
6291
6292    private void doTrackball(long time, int metaState) {
6293        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
6294        if (elapsed == 0) {
6295            elapsed = TRACKBALL_TIMEOUT;
6296        }
6297        float xRate = mTrackballRemainsX * 1000 / elapsed;
6298        float yRate = mTrackballRemainsY * 1000 / elapsed;
6299        int viewWidth = getViewWidth();
6300        int viewHeight = getViewHeight();
6301        if (mSelectingText) {
6302            if (!mDrawSelectionPointer) {
6303                // The last selection was made by touch, disabling drawing the
6304                // selection pointer. Allow the trackball to adjust the
6305                // position of the touch control.
6306                mSelectX = contentToViewX(nativeSelectionX());
6307                mSelectY = contentToViewY(nativeSelectionY());
6308                mDrawSelectionPointer = mExtendSelection = true;
6309                nativeSetExtendSelection();
6310            }
6311            moveSelection(scaleTrackballX(xRate, viewWidth),
6312                    scaleTrackballY(yRate, viewHeight));
6313            mTrackballRemainsX = mTrackballRemainsY = 0;
6314            return;
6315        }
6316        float ax = Math.abs(xRate);
6317        float ay = Math.abs(yRate);
6318        float maxA = Math.max(ax, ay);
6319        if (DebugFlags.WEB_VIEW) {
6320            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
6321                    + " xRate=" + xRate
6322                    + " yRate=" + yRate
6323                    + " mTrackballRemainsX=" + mTrackballRemainsX
6324                    + " mTrackballRemainsY=" + mTrackballRemainsY);
6325        }
6326        int width = mContentWidth - viewWidth;
6327        int height = mContentHeight - viewHeight;
6328        if (width < 0) width = 0;
6329        if (height < 0) height = 0;
6330        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
6331        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
6332        maxA = Math.max(ax, ay);
6333        int count = Math.max(0, (int) maxA);
6334        int oldScrollX = mScrollX;
6335        int oldScrollY = mScrollY;
6336        if (count > 0) {
6337            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
6338                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
6339                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
6340                    KeyEvent.KEYCODE_DPAD_RIGHT;
6341            count = Math.min(count, TRACKBALL_MOVE_COUNT);
6342            if (DebugFlags.WEB_VIEW) {
6343                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
6344                        + " count=" + count
6345                        + " mTrackballRemainsX=" + mTrackballRemainsX
6346                        + " mTrackballRemainsY=" + mTrackballRemainsY);
6347            }
6348            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
6349                for (int i = 0; i < count; i++) {
6350                    letPageHandleNavKey(selectKeyCode, time, true, metaState);
6351                }
6352                letPageHandleNavKey(selectKeyCode, time, false, metaState);
6353            } else if (navHandledKey(selectKeyCode, count, false, time)) {
6354                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
6355            }
6356            mTrackballRemainsX = mTrackballRemainsY = 0;
6357        }
6358        if (count >= TRACKBALL_SCROLL_COUNT) {
6359            int xMove = scaleTrackballX(xRate, width);
6360            int yMove = scaleTrackballY(yRate, height);
6361            if (DebugFlags.WEB_VIEW) {
6362                Log.v(LOGTAG, "doTrackball pinScrollBy"
6363                        + " count=" + count
6364                        + " xMove=" + xMove + " yMove=" + yMove
6365                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
6366                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
6367                        );
6368            }
6369            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
6370                xMove = 0;
6371            }
6372            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
6373                yMove = 0;
6374            }
6375            if (xMove != 0 || yMove != 0) {
6376                pinScrollBy(xMove, yMove, true, 0);
6377            }
6378            mUserScroll = true;
6379        }
6380    }
6381
6382    /**
6383     * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
6384     * @return Maximum horizontal scroll position within real content
6385     */
6386    int computeMaxScrollX() {
6387        return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
6388    }
6389
6390    /**
6391     * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
6392     * @return Maximum vertical scroll position within real content
6393     */
6394    int computeMaxScrollY() {
6395        return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
6396                - getViewHeightWithTitle(), 0);
6397    }
6398
6399    boolean updateScrollCoordinates(int x, int y) {
6400        int oldX = mScrollX;
6401        int oldY = mScrollY;
6402        mScrollX = x;
6403        mScrollY = y;
6404        if (oldX != mScrollX || oldY != mScrollY) {
6405            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
6406            return true;
6407        } else {
6408            return false;
6409        }
6410    }
6411
6412    public void flingScroll(int vx, int vy) {
6413        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
6414                computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
6415        invalidate();
6416    }
6417
6418    private void doFling() {
6419        if (mVelocityTracker == null) {
6420            return;
6421        }
6422        int maxX = computeMaxScrollX();
6423        int maxY = computeMaxScrollY();
6424
6425        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
6426        int vx = (int) mVelocityTracker.getXVelocity();
6427        int vy = (int) mVelocityTracker.getYVelocity();
6428
6429        int scrollX = mScrollX;
6430        int scrollY = mScrollY;
6431        int overscrollDistance = mOverscrollDistance;
6432        int overflingDistance = mOverflingDistance;
6433
6434        // Use the layer's scroll data if applicable.
6435        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
6436            scrollX = mScrollingLayerRect.left;
6437            scrollY = mScrollingLayerRect.top;
6438            maxX = mScrollingLayerRect.right;
6439            maxY = mScrollingLayerRect.bottom;
6440            // No overscrolling for layers.
6441            overscrollDistance = overflingDistance = 0;
6442        }
6443
6444        if (mSnapScrollMode != SNAP_NONE) {
6445            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6446                vy = 0;
6447            } else {
6448                vx = 0;
6449            }
6450        }
6451        if (true /* EMG release: make our fling more like Maps' */) {
6452            // maps cuts their velocity in half
6453            vx = vx * 3 / 4;
6454            vy = vy * 3 / 4;
6455        }
6456        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
6457            WebViewCore.resumePriority();
6458            if (!mSelectingText) {
6459                WebViewCore.resumeUpdatePicture(mWebViewCore);
6460            }
6461            if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) {
6462                invalidate();
6463            }
6464            return;
6465        }
6466        float currentVelocity = mScroller.getCurrVelocity();
6467        float velocity = (float) Math.hypot(vx, vy);
6468        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
6469                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
6470            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
6471                    - Math.atan2(vy, vx)));
6472            final float circle = (float) (Math.PI) * 2.0f;
6473            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
6474                vx += currentVelocity * mLastVelX / mLastVelocity;
6475                vy += currentVelocity * mLastVelY / mLastVelocity;
6476                velocity = (float) Math.hypot(vx, vy);
6477                if (DebugFlags.WEB_VIEW) {
6478                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
6479                }
6480            } else if (DebugFlags.WEB_VIEW) {
6481                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
6482            }
6483        } else if (DebugFlags.WEB_VIEW) {
6484            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
6485                    + " current=" + currentVelocity
6486                    + " vx=" + vx + " vy=" + vy
6487                    + " maxX=" + maxX + " maxY=" + maxY
6488                    + " scrollX=" + scrollX + " scrollY=" + scrollY
6489                    + " layer=" + mScrollingLayer);
6490        }
6491
6492        // Allow sloppy flings without overscrolling at the edges.
6493        if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
6494            vx = 0;
6495        }
6496        if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
6497            vy = 0;
6498        }
6499
6500        if (overscrollDistance < overflingDistance) {
6501            if ((vx > 0 && scrollX == -overscrollDistance) ||
6502                    (vx < 0 && scrollX == maxX + overscrollDistance)) {
6503                vx = 0;
6504            }
6505            if ((vy > 0 && scrollY == -overscrollDistance) ||
6506                    (vy < 0 && scrollY == maxY + overscrollDistance)) {
6507                vy = 0;
6508            }
6509        }
6510
6511        mLastVelX = vx;
6512        mLastVelY = vy;
6513        mLastVelocity = velocity;
6514
6515        // no horizontal overscroll if the content just fits
6516        mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY,
6517                maxX == 0 ? 0 : overflingDistance, overflingDistance);
6518        // Duration is calculated based on velocity. With range boundaries and overscroll
6519        // we may not know how long the final animation will take. (Hence the deprecation
6520        // warning on the call below.) It's not a big deal for scroll bars but if webcore
6521        // resumes during this effect we will take a performance hit. See computeScroll;
6522        // we resume webcore there when the animation is finished.
6523        final int time = mScroller.getDuration();
6524
6525        // Suppress scrollbars for layer scrolling.
6526        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6527            awakenScrollBars(time);
6528        }
6529
6530        invalidate();
6531    }
6532
6533    /**
6534     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
6535     * in charge of installing this view to the view hierarchy. This view will
6536     * become visible when the user starts scrolling via touch and fade away if
6537     * the user does not interact with it.
6538     * <p/>
6539     * API version 3 introduces a built-in zoom mechanism that is shown
6540     * automatically by the MapView. This is the preferred approach for
6541     * showing the zoom UI.
6542     *
6543     * @deprecated The built-in zoom mechanism is preferred, see
6544     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
6545     */
6546    @Deprecated
6547    public View getZoomControls() {
6548        if (!getSettings().supportZoom()) {
6549            Log.w(LOGTAG, "This WebView doesn't support zoom.");
6550            return null;
6551        }
6552        return mZoomManager.getExternalZoomPicker();
6553    }
6554
6555    void dismissZoomControl() {
6556        mZoomManager.dismissZoomPicker();
6557    }
6558
6559    float getDefaultZoomScale() {
6560        return mZoomManager.getDefaultScale();
6561    }
6562
6563    /**
6564     * @return TRUE if the WebView can be zoomed in.
6565     */
6566    public boolean canZoomIn() {
6567        return mZoomManager.canZoomIn();
6568    }
6569
6570    /**
6571     * @return TRUE if the WebView can be zoomed out.
6572     */
6573    public boolean canZoomOut() {
6574        return mZoomManager.canZoomOut();
6575    }
6576
6577    /**
6578     * Perform zoom in in the webview
6579     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
6580     */
6581    public boolean zoomIn() {
6582        return mZoomManager.zoomIn();
6583    }
6584
6585    /**
6586     * Perform zoom out in the webview
6587     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
6588     */
6589    public boolean zoomOut() {
6590        return mZoomManager.zoomOut();
6591    }
6592
6593    private void updateSelection() {
6594        if (mNativeClass == 0) {
6595            return;
6596        }
6597        // mLastTouchX and mLastTouchY are the point in the current viewport
6598        int contentX = viewToContentX(mLastTouchX + mScrollX);
6599        int contentY = viewToContentY(mLastTouchY + mScrollY);
6600        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
6601                contentX + mNavSlop, contentY + mNavSlop);
6602        nativeSelectBestAt(rect);
6603        mInitialHitTestResult = hitTestResult(null);
6604    }
6605
6606    /**
6607     * Scroll the focused text field to match the WebTextView
6608     * @param xPercent New x position of the WebTextView from 0 to 1.
6609     */
6610    /*package*/ void scrollFocusedTextInputX(float xPercent) {
6611        if (!inEditingMode() || mWebViewCore == null) {
6612            return;
6613        }
6614        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0,
6615                new Float(xPercent));
6616    }
6617
6618    /**
6619     * Scroll the focused textarea vertically to match the WebTextView
6620     * @param y New y position of the WebTextView in view coordinates
6621     */
6622    /* package */ void scrollFocusedTextInputY(int y) {
6623        if (!inEditingMode()) {
6624            return;
6625        }
6626        int xPos = viewToContentX((mWebTextView.getLeft() + mWebTextView.getRight()) / 2);
6627        int yPos = viewToContentY((mWebTextView.getTop() + mWebTextView.getBottom()) / 2);
6628        int layer = nativeScrollableLayer(xPos, yPos, null, null);
6629        if (layer != 0) {
6630            nativeScrollLayer(layer, 0, viewToContentDimension(y));
6631        }
6632    }
6633
6634    /**
6635     * Set our starting point and time for a drag from the WebTextView.
6636     */
6637    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
6638        if (!inEditingMode()) {
6639            return;
6640        }
6641        mLastTouchX = Math.round(x + mWebTextView.getLeft() - mScrollX);
6642        mLastTouchY = Math.round(y + mWebTextView.getTop() - mScrollY);
6643        mLastTouchTime = eventTime;
6644        if (!mScroller.isFinished()) {
6645            abortAnimation();
6646            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
6647        }
6648        mSnapScrollMode = SNAP_NONE;
6649        mVelocityTracker = VelocityTracker.obtain();
6650        mTouchMode = TOUCH_DRAG_START_MODE;
6651    }
6652
6653    /**
6654     * Given a motion event from the WebTextView, set its location to our
6655     * coordinates, and handle the event.
6656     */
6657    /*package*/ boolean textFieldDrag(MotionEvent event) {
6658        if (!inEditingMode()) {
6659            return false;
6660        }
6661        mDragFromTextInput = true;
6662        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
6663                (float) (mWebTextView.getTop() - mScrollY));
6664        boolean result = onTouchEvent(event);
6665        mDragFromTextInput = false;
6666        return result;
6667    }
6668
6669    /**
6670     * Due a touch up from a WebTextView.  This will be handled by webkit to
6671     * change the selection.
6672     * @param event MotionEvent in the WebTextView's coordinates.
6673     */
6674    /*package*/ void touchUpOnTextField(MotionEvent event) {
6675        if (!inEditingMode()) {
6676            return;
6677        }
6678        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
6679        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
6680        nativeMotionUp(x, y, mNavSlop);
6681    }
6682
6683    /**
6684     * Called when pressing the center key or trackball on a textfield.
6685     */
6686    /*package*/ void centerKeyPressOnTextField() {
6687        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
6688                    nativeCursorNodePointer());
6689    }
6690
6691    private void doShortPress() {
6692        if (mNativeClass == 0) {
6693            return;
6694        }
6695        if (mPreventDefault == PREVENT_DEFAULT_YES) {
6696            return;
6697        }
6698        mTouchMode = TOUCH_DONE_MODE;
6699        switchOutDrawHistory();
6700        // mLastTouchX and mLastTouchY are the point in the current viewport
6701        int contentX = viewToContentX(mLastTouchX + mScrollX);
6702        int contentY = viewToContentY(mLastTouchY + mScrollY);
6703        if (getSettings().supportTouchOnly()) {
6704            removeTouchHighlight(false);
6705            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
6706            // use "0" as generation id to inform WebKit to use the same x/y as
6707            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
6708            touchUpData.mMoveGeneration = 0;
6709            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
6710        } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
6711            WebViewCore.MotionUpData motionUpData = new WebViewCore
6712                    .MotionUpData();
6713            motionUpData.mFrame = nativeCacheHitFramePointer();
6714            motionUpData.mNode = nativeCacheHitNodePointer();
6715            motionUpData.mBounds = nativeCacheHitNodeBounds();
6716            motionUpData.mX = contentX;
6717            motionUpData.mY = contentY;
6718            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
6719                    motionUpData);
6720        } else {
6721            doMotionUp(contentX, contentY);
6722        }
6723    }
6724
6725    private void doMotionUp(int contentX, int contentY) {
6726        if (nativeMotionUp(contentX, contentY, mNavSlop) && mLogEvent) {
6727            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
6728        }
6729        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
6730            playSoundEffect(SoundEffectConstants.CLICK);
6731        }
6732    }
6733
6734    /**
6735     * Returns plugin bounds if x/y in content coordinates corresponds to a
6736     * plugin. Otherwise a NULL rectangle is returned.
6737     */
6738    Rect getPluginBounds(int x, int y) {
6739        if (nativePointInNavCache(x, y, mNavSlop) && nativeCacheHitIsPlugin()) {
6740            return nativeCacheHitNodeBounds();
6741        } else {
6742            return null;
6743        }
6744    }
6745
6746    /*
6747     * Return true if the rect (e.g. plugin) is fully visible and maximized
6748     * inside the WebView.
6749     */
6750    boolean isRectFitOnScreen(Rect rect) {
6751        final int rectWidth = rect.width();
6752        final int rectHeight = rect.height();
6753        final int viewWidth = getViewWidth();
6754        final int viewHeight = getViewHeightWithTitle();
6755        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight);
6756        scale = mZoomManager.computeScaleWithLimits(scale);
6757        return !mZoomManager.willScaleTriggerZoom(scale)
6758                && contentToViewX(rect.left) >= mScrollX
6759                && contentToViewX(rect.right) <= mScrollX + viewWidth
6760                && contentToViewY(rect.top) >= mScrollY
6761                && contentToViewY(rect.bottom) <= mScrollY + viewHeight;
6762    }
6763
6764    /*
6765     * Maximize and center the rectangle, specified in the document coordinate
6766     * space, inside the WebView. If the zoom doesn't need to be changed, do an
6767     * animated scroll to center it. If the zoom needs to be changed, find the
6768     * zoom center and do a smooth zoom transition. The rect is in document
6769     * coordinates
6770     */
6771    void centerFitRect(Rect rect) {
6772        final int rectWidth = rect.width();
6773        final int rectHeight = rect.height();
6774        final int viewWidth = getViewWidth();
6775        final int viewHeight = getViewHeightWithTitle();
6776        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight
6777                / rectHeight);
6778        scale = mZoomManager.computeScaleWithLimits(scale);
6779        if (!mZoomManager.willScaleTriggerZoom(scale)) {
6780            pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2,
6781                    contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2,
6782                    true, 0);
6783        } else {
6784            float actualScale = mZoomManager.getScale();
6785            float oldScreenX = rect.left * actualScale - mScrollX;
6786            float rectViewX = rect.left * scale;
6787            float rectViewWidth = rectWidth * scale;
6788            float newMaxWidth = mContentWidth * scale;
6789            float newScreenX = (viewWidth - rectViewWidth) / 2;
6790            // pin the newX to the WebView
6791            if (newScreenX > rectViewX) {
6792                newScreenX = rectViewX;
6793            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
6794                newScreenX = viewWidth - (newMaxWidth - rectViewX);
6795            }
6796            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
6797                    / (scale - actualScale);
6798            float oldScreenY = rect.top * actualScale + getTitleHeight()
6799                    - mScrollY;
6800            float rectViewY = rect.top * scale + getTitleHeight();
6801            float rectViewHeight = rectHeight * scale;
6802            float newMaxHeight = mContentHeight * scale + getTitleHeight();
6803            float newScreenY = (viewHeight - rectViewHeight) / 2;
6804            // pin the newY to the WebView
6805            if (newScreenY > rectViewY) {
6806                newScreenY = rectViewY;
6807            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
6808                newScreenY = viewHeight - (newMaxHeight - rectViewY);
6809            }
6810            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
6811                    / (scale - actualScale);
6812            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
6813            mZoomManager.startZoomAnimation(scale, false);
6814        }
6815    }
6816
6817    // Called by JNI to handle a touch on a node representing an email address,
6818    // address, or phone number
6819    private void overrideLoading(String url) {
6820        mCallbackProxy.uiOverrideUrlLoading(url);
6821    }
6822
6823    @Override
6824    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6825        // FIXME: If a subwindow is showing find, and the user touches the
6826        // background window, it can steal focus.
6827        if (mFindIsUp) return false;
6828        boolean result = false;
6829        if (inEditingMode()) {
6830            result = mWebTextView.requestFocus(direction,
6831                    previouslyFocusedRect);
6832        } else {
6833            result = super.requestFocus(direction, previouslyFocusedRect);
6834            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
6835                // For cases such as GMail, where we gain focus from a direction,
6836                // we want to move to the first available link.
6837                // FIXME: If there are no visible links, we may not want to
6838                int fakeKeyDirection = 0;
6839                switch(direction) {
6840                    case View.FOCUS_UP:
6841                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
6842                        break;
6843                    case View.FOCUS_DOWN:
6844                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
6845                        break;
6846                    case View.FOCUS_LEFT:
6847                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
6848                        break;
6849                    case View.FOCUS_RIGHT:
6850                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
6851                        break;
6852                    default:
6853                        return result;
6854                }
6855                if (mNativeClass != 0 && !nativeHasCursorNode()) {
6856                    navHandledKey(fakeKeyDirection, 1, true, 0);
6857                }
6858            }
6859        }
6860        return result;
6861    }
6862
6863    @Override
6864    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
6865        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
6866
6867        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
6868        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6869        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6870        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6871
6872        int measuredHeight = heightSize;
6873        int measuredWidth = widthSize;
6874
6875        // Grab the content size from WebViewCore.
6876        int contentHeight = contentToViewDimension(mContentHeight);
6877        int contentWidth = contentToViewDimension(mContentWidth);
6878
6879//        Log.d(LOGTAG, "------- measure " + heightMode);
6880
6881        if (heightMode != MeasureSpec.EXACTLY) {
6882            mHeightCanMeasure = true;
6883            measuredHeight = contentHeight;
6884            if (heightMode == MeasureSpec.AT_MOST) {
6885                // If we are larger than the AT_MOST height, then our height can
6886                // no longer be measured and we should scroll internally.
6887                if (measuredHeight > heightSize) {
6888                    measuredHeight = heightSize;
6889                    mHeightCanMeasure = false;
6890                } else if (measuredHeight < heightSize) {
6891                    measuredHeight |= MEASURED_STATE_TOO_SMALL;
6892                }
6893            }
6894        } else {
6895            mHeightCanMeasure = false;
6896        }
6897        if (mNativeClass != 0) {
6898            nativeSetHeightCanMeasure(mHeightCanMeasure);
6899        }
6900        // For the width, always use the given size unless unspecified.
6901        if (widthMode == MeasureSpec.UNSPECIFIED) {
6902            mWidthCanMeasure = true;
6903            measuredWidth = contentWidth;
6904        } else {
6905            if (measuredWidth < contentWidth) {
6906                measuredWidth |= MEASURED_STATE_TOO_SMALL;
6907            }
6908            mWidthCanMeasure = false;
6909        }
6910
6911        synchronized (this) {
6912            setMeasuredDimension(measuredWidth, measuredHeight);
6913        }
6914    }
6915
6916    @Override
6917    public boolean requestChildRectangleOnScreen(View child,
6918                                                 Rect rect,
6919                                                 boolean immediate) {
6920        if (mNativeClass == 0) {
6921            return false;
6922        }
6923        // don't scroll while in zoom animation. When it is done, we will adjust
6924        // the necessary components (e.g., WebTextView if it is in editing mode)
6925        if (mZoomManager.isFixedLengthAnimationInProgress()) {
6926            return false;
6927        }
6928
6929        rect.offset(child.getLeft() - child.getScrollX(),
6930                child.getTop() - child.getScrollY());
6931
6932        Rect content = new Rect(viewToContentX(mScrollX),
6933                viewToContentY(mScrollY),
6934                viewToContentX(mScrollX + getWidth()
6935                - getVerticalScrollbarWidth()),
6936                viewToContentY(mScrollY + getViewHeightWithTitle()));
6937        content = nativeSubtractLayers(content);
6938        int screenTop = contentToViewY(content.top);
6939        int screenBottom = contentToViewY(content.bottom);
6940        int height = screenBottom - screenTop;
6941        int scrollYDelta = 0;
6942
6943        if (rect.bottom > screenBottom) {
6944            int oneThirdOfScreenHeight = height / 3;
6945            if (rect.height() > 2 * oneThirdOfScreenHeight) {
6946                // If the rectangle is too tall to fit in the bottom two thirds
6947                // of the screen, place it at the top.
6948                scrollYDelta = rect.top - screenTop;
6949            } else {
6950                // If the rectangle will still fit on screen, we want its
6951                // top to be in the top third of the screen.
6952                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
6953            }
6954        } else if (rect.top < screenTop) {
6955            scrollYDelta = rect.top - screenTop;
6956        }
6957
6958        int screenLeft = contentToViewX(content.left);
6959        int screenRight = contentToViewX(content.right);
6960        int width = screenRight - screenLeft;
6961        int scrollXDelta = 0;
6962
6963        if (rect.right > screenRight && rect.left > screenLeft) {
6964            if (rect.width() > width) {
6965                scrollXDelta += (rect.left - screenLeft);
6966            } else {
6967                scrollXDelta += (rect.right - screenRight);
6968            }
6969        } else if (rect.left < screenLeft) {
6970            scrollXDelta -= (screenLeft - rect.left);
6971        }
6972
6973        if ((scrollYDelta | scrollXDelta) != 0) {
6974            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
6975        }
6976
6977        return false;
6978    }
6979
6980    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
6981            String replace, int newStart, int newEnd) {
6982        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
6983        arg.mReplace = replace;
6984        arg.mNewStart = newStart;
6985        arg.mNewEnd = newEnd;
6986        mTextGeneration++;
6987        arg.mTextGeneration = mTextGeneration;
6988        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
6989    }
6990
6991    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
6992        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
6993        arg.mEvent = event;
6994        arg.mCurrentText = currentText;
6995        // Increase our text generation number, and pass it to webcore thread
6996        mTextGeneration++;
6997        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
6998        // WebKit's document state is not saved until about to leave the page.
6999        // To make sure the host application, like Browser, has the up to date
7000        // document state when it goes to background, we force to save the
7001        // document state.
7002        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
7003        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
7004                cursorData(), 1000);
7005    }
7006
7007    /* package */ synchronized WebViewCore getWebViewCore() {
7008        return mWebViewCore;
7009    }
7010
7011    //-------------------------------------------------------------------------
7012    // Methods can be called from a separate thread, like WebViewCore
7013    // If it needs to call the View system, it has to send message.
7014    //-------------------------------------------------------------------------
7015
7016    /**
7017     * General handler to receive message coming from webkit thread
7018     */
7019    class PrivateHandler extends Handler {
7020        @Override
7021        public void handleMessage(Message msg) {
7022            // exclude INVAL_RECT_MSG_ID since it is frequently output
7023            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
7024                if (msg.what >= FIRST_PRIVATE_MSG_ID
7025                        && msg.what <= LAST_PRIVATE_MSG_ID) {
7026                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
7027                            - FIRST_PRIVATE_MSG_ID]);
7028                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
7029                        && msg.what <= LAST_PACKAGE_MSG_ID) {
7030                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
7031                            - FIRST_PACKAGE_MSG_ID]);
7032                } else {
7033                    Log.v(LOGTAG, Integer.toString(msg.what));
7034                }
7035            }
7036            if (mWebViewCore == null) {
7037                // after WebView's destroy() is called, skip handling messages.
7038                return;
7039            }
7040            switch (msg.what) {
7041                case REMEMBER_PASSWORD: {
7042                    mDatabase.setUsernamePassword(
7043                            msg.getData().getString("host"),
7044                            msg.getData().getString("username"),
7045                            msg.getData().getString("password"));
7046                    ((Message) msg.obj).sendToTarget();
7047                    break;
7048                }
7049                case NEVER_REMEMBER_PASSWORD: {
7050                    mDatabase.setUsernamePassword(
7051                            msg.getData().getString("host"), null, null);
7052                    ((Message) msg.obj).sendToTarget();
7053                    break;
7054                }
7055                case PREVENT_DEFAULT_TIMEOUT: {
7056                    // if timeout happens, cancel it so that it won't block UI
7057                    // to continue handling touch events
7058                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
7059                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
7060                            || (msg.arg1 == MotionEvent.ACTION_MOVE
7061                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
7062                        cancelWebCoreTouchEvent(
7063                                viewToContentX(mLastTouchX + mScrollX),
7064                                viewToContentY(mLastTouchY + mScrollY),
7065                                true);
7066                    }
7067                    break;
7068                }
7069                case SCROLL_SELECT_TEXT: {
7070                    if (mAutoScrollX == 0 && mAutoScrollY == 0) {
7071                        mSentAutoScrollMessage = false;
7072                        break;
7073                    }
7074                    if (mScrollingLayer == 0) {
7075                        pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
7076                    } else {
7077                        mScrollingLayerRect.left += mAutoScrollX;
7078                        mScrollingLayerRect.top += mAutoScrollY;
7079                        nativeScrollLayer(mScrollingLayer,
7080                                mScrollingLayerRect.left,
7081                                mScrollingLayerRect.top);
7082                        invalidate();
7083                    }
7084                    sendEmptyMessageDelayed(
7085                            SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
7086                    break;
7087                }
7088                case SWITCH_TO_SHORTPRESS: {
7089                    mInitialHitTestResult = null; // set by updateSelection()
7090                    if (mTouchMode == TOUCH_INIT_MODE) {
7091                        if (!getSettings().supportTouchOnly()
7092                                && mPreventDefault != PREVENT_DEFAULT_YES) {
7093                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
7094                            updateSelection();
7095                        } else {
7096                            // set to TOUCH_SHORTPRESS_MODE so that it won't
7097                            // trigger double tap any more
7098                            mTouchMode = TOUCH_SHORTPRESS_MODE;
7099                        }
7100                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
7101                        mTouchMode = TOUCH_DONE_MODE;
7102                    }
7103                    break;
7104                }
7105                case SWITCH_TO_LONGPRESS: {
7106                    if (getSettings().supportTouchOnly()) {
7107                        removeTouchHighlight(false);
7108                    }
7109                    if (inFullScreenMode() || mDeferTouchProcess) {
7110                        TouchEventData ted = new TouchEventData();
7111                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
7112                        ted.mIds = new int[1];
7113                        ted.mIds[0] = 0;
7114                        ted.mPoints = new Point[1];
7115                        ted.mPoints[0] = new Point(viewToContentX(mLastTouchX + mScrollX),
7116                                                   viewToContentY(mLastTouchY + mScrollY));
7117                        // metaState for long press is tricky. Should it be the
7118                        // state when the press started or when the press was
7119                        // released? Or some intermediary key state? For
7120                        // simplicity for now, we don't set it.
7121                        ted.mMetaState = 0;
7122                        ted.mReprocess = mDeferTouchProcess;
7123                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
7124                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
7125                        mTouchMode = TOUCH_DONE_MODE;
7126                        performLongClick();
7127                    }
7128                    break;
7129                }
7130                case RELEASE_SINGLE_TAP: {
7131                    doShortPress();
7132                    break;
7133                }
7134                case SCROLL_BY_MSG_ID:
7135                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
7136                    break;
7137                case SYNC_SCROLL_TO_MSG_ID:
7138                    if (mUserScroll) {
7139                        // if user has scrolled explicitly, don't sync the
7140                        // scroll position any more
7141                        mUserScroll = false;
7142                        break;
7143                    }
7144                    setContentScrollTo(msg.arg1, msg.arg2);
7145                    break;
7146                case SCROLL_TO_MSG_ID:
7147                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
7148                        // if we can't scroll to the exact position due to pin,
7149                        // send a message to WebCore to re-scroll when we get a
7150                        // new picture
7151                        mUserScroll = false;
7152                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
7153                                msg.arg1, msg.arg2);
7154                    }
7155                    break;
7156                case SPAWN_SCROLL_TO_MSG_ID:
7157                    spawnContentScrollTo(msg.arg1, msg.arg2);
7158                    break;
7159                case UPDATE_ZOOM_RANGE: {
7160                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
7161                    // mScrollX contains the new minPrefWidth
7162                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
7163                    break;
7164                }
7165                case REPLACE_BASE_CONTENT: {
7166                    nativeReplaceBaseContent(msg.arg1);
7167                    break;
7168                }
7169                case NEW_PICTURE_MSG_ID: {
7170                    // called for new content
7171                    mUserScroll = false;
7172                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
7173                    setBaseLayer(draw.mBaseLayer, draw.mInvalRegion.getBounds());
7174                    final Point viewSize = draw.mViewSize;
7175                    WebViewCore.ViewState viewState = draw.mViewState;
7176                    boolean isPictureAfterFirstLayout = viewState != null;
7177                    if (isPictureAfterFirstLayout) {
7178                        // Reset the last sent data here since dealing with new page.
7179                        mLastWidthSent = 0;
7180                        mZoomManager.onFirstLayout(draw);
7181                        if (!mDrawHistory) {
7182                            setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
7183                            // As we are on a new page, remove the WebTextView. This
7184                            // is necessary for page loads driven by webkit, and in
7185                            // particular when the user was on a password field, so
7186                            // the WebTextView was visible.
7187                            clearTextEntry();
7188                        }
7189                    }
7190
7191                    // We update the layout (i.e. request a layout from the
7192                    // view system) if the last view size that we sent to
7193                    // WebCore matches the view size of the picture we just
7194                    // received in the fixed dimension.
7195                    final boolean updateLayout = viewSize.x == mLastWidthSent
7196                            && viewSize.y == mLastHeightSent;
7197                    recordNewContentSize(draw.mContentSize.x,
7198                            draw.mContentSize.y, updateLayout);
7199                    if (DebugFlags.WEB_VIEW) {
7200                        Rect b = draw.mInvalRegion.getBounds();
7201                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
7202                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
7203                    }
7204                    invalidateContentRect(draw.mInvalRegion.getBounds());
7205
7206                    if (mPictureListener != null) {
7207                        mPictureListener.onNewPicture(WebView.this, capturePicture());
7208                    }
7209
7210                    // update the zoom information based on the new picture
7211                    mZoomManager.onNewPicture(draw);
7212
7213                    if (draw.mFocusSizeChanged && inEditingMode()) {
7214                        mFocusSizeChanged = true;
7215                    }
7216                    if (isPictureAfterFirstLayout) {
7217                        mViewManager.postReadyToDrawAll();
7218                    }
7219                    break;
7220                }
7221                case WEBCORE_INITIALIZED_MSG_ID:
7222                    // nativeCreate sets mNativeClass to a non-zero value
7223                    nativeCreate(msg.arg1);
7224                    break;
7225                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
7226                    // Make sure that the textfield is currently focused
7227                    // and representing the same node as the pointer.
7228                    if (inEditingMode() &&
7229                            mWebTextView.isSameTextField(msg.arg1)) {
7230                        if (msg.getData().getBoolean("password")) {
7231                            Spannable text = (Spannable) mWebTextView.getText();
7232                            int start = Selection.getSelectionStart(text);
7233                            int end = Selection.getSelectionEnd(text);
7234                            mWebTextView.setInPassword(true);
7235                            // Restore the selection, which may have been
7236                            // ruined by setInPassword.
7237                            Spannable pword =
7238                                    (Spannable) mWebTextView.getText();
7239                            Selection.setSelection(pword, start, end);
7240                        // If the text entry has created more events, ignore
7241                        // this one.
7242                        } else if (msg.arg2 == mTextGeneration) {
7243                            String text = (String) msg.obj;
7244                            if (null == text) {
7245                                text = "";
7246                            }
7247                            mWebTextView.setTextAndKeepSelection(text);
7248                        }
7249                    }
7250                    break;
7251                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
7252                    displaySoftKeyboard(true);
7253                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
7254                case UPDATE_TEXT_SELECTION_MSG_ID:
7255                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
7256                            (WebViewCore.TextSelectionData) msg.obj);
7257                    break;
7258                case FORM_DID_BLUR:
7259                    if (inEditingMode()
7260                            && mWebTextView.isSameTextField(msg.arg1)) {
7261                        hideSoftKeyboard();
7262                    }
7263                    break;
7264                case RETURN_LABEL:
7265                    if (inEditingMode()
7266                            && mWebTextView.isSameTextField(msg.arg1)) {
7267                        mWebTextView.setHint((String) msg.obj);
7268                        InputMethodManager imm
7269                                = InputMethodManager.peekInstance();
7270                        // The hint is propagated to the IME in
7271                        // onCreateInputConnection.  If the IME is already
7272                        // active, restart it so that its hint text is updated.
7273                        if (imm != null && imm.isActive(mWebTextView)) {
7274                            imm.restartInput(mWebTextView);
7275                        }
7276                    }
7277                    break;
7278                case UNHANDLED_NAV_KEY:
7279                    navHandledKey(msg.arg1, 1, false, 0);
7280                    break;
7281                case UPDATE_TEXT_ENTRY_MSG_ID:
7282                    // this is sent after finishing resize in WebViewCore. Make
7283                    // sure the text edit box is still on the  screen.
7284                    if (inEditingMode() && nativeCursorIsTextInput()) {
7285                        rebuildWebTextView();
7286                    }
7287                    break;
7288                case CLEAR_TEXT_ENTRY:
7289                    clearTextEntry();
7290                    break;
7291                case INVAL_RECT_MSG_ID: {
7292                    Rect r = (Rect)msg.obj;
7293                    if (r == null) {
7294                        invalidate();
7295                    } else {
7296                        // we need to scale r from content into view coords,
7297                        // which viewInvalidate() does for us
7298                        viewInvalidate(r.left, r.top, r.right, r.bottom);
7299                    }
7300                    break;
7301                }
7302                case REQUEST_FORM_DATA:
7303                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
7304                    if (mWebTextView.isSameTextField(msg.arg1)) {
7305                        mWebTextView.setAdapterCustom(adapter);
7306                    }
7307                    break;
7308                case RESUME_WEBCORE_PRIORITY:
7309                    WebViewCore.resumePriority();
7310                    WebViewCore.resumeUpdatePicture(mWebViewCore);
7311                    break;
7312
7313                case LONG_PRESS_CENTER:
7314                    // as this is shared by keydown and trackballdown, reset all
7315                    // the states
7316                    mGotCenterDown = false;
7317                    mTrackballDown = false;
7318                    performLongClick();
7319                    break;
7320
7321                case WEBCORE_NEED_TOUCH_EVENTS:
7322                    mForwardTouchEvents = (msg.arg1 != 0);
7323                    break;
7324
7325                case PREVENT_TOUCH_ID:
7326                    if (inFullScreenMode()) {
7327                        break;
7328                    }
7329                    if (msg.obj == null) {
7330                        if (msg.arg1 == MotionEvent.ACTION_DOWN
7331                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
7332                            // if prevent default is called from WebCore, UI
7333                            // will not handle the rest of the touch events any
7334                            // more.
7335                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
7336                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
7337                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
7338                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
7339                            // the return for the first ACTION_MOVE will decide
7340                            // whether UI will handle touch or not. Currently no
7341                            // support for alternating prevent default
7342                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
7343                                    : PREVENT_DEFAULT_NO;
7344                        }
7345                        if (mPreventDefault == PREVENT_DEFAULT_YES) {
7346                            mTouchHighlightRegion.setEmpty();
7347                        }
7348                    } else {
7349                        TouchEventData ted = (TouchEventData) msg.obj;
7350
7351                        if (ted.mPoints.length > 1) {  // multi-touch
7352                            if (ted.mAction == MotionEvent.ACTION_POINTER_UP) {
7353                                mIsHandlingMultiTouch = false;
7354                            }
7355                            if (msg.arg2 == 0) {
7356                                mPreventDefault = PREVENT_DEFAULT_NO;
7357                                handleMultiTouchInWebView(ted.mMotionEvent);
7358                            } else {
7359                                mPreventDefault = PREVENT_DEFAULT_YES;
7360                            }
7361                            break;
7362                        }
7363
7364                        // prevent default is not called in WebCore, so the
7365                        // message needs to be reprocessed in UI
7366                        if (msg.arg2 == 0) {
7367                            // Following is for single touch.
7368                            switch (ted.mAction) {
7369                                case MotionEvent.ACTION_DOWN:
7370                                    mLastDeferTouchX = contentToViewX(ted.mPoints[0].x)
7371                                            - mScrollX;
7372                                    mLastDeferTouchY = contentToViewY(ted.mPoints[0].y)
7373                                            - mScrollY;
7374                                    mDeferTouchMode = TOUCH_INIT_MODE;
7375                                    break;
7376                                case MotionEvent.ACTION_MOVE: {
7377                                    // no snapping in defer process
7378                                    int x = contentToViewX(ted.mPoints[0].x) - mScrollX;
7379                                    int y = contentToViewY(ted.mPoints[0].y) - mScrollY;
7380                                    if (mDeferTouchMode != TOUCH_DRAG_MODE) {
7381                                        mDeferTouchMode = TOUCH_DRAG_MODE;
7382                                        mLastDeferTouchX = x;
7383                                        mLastDeferTouchY = y;
7384                                        startScrollingLayer(x, y);
7385                                        startDrag();
7386                                    }
7387                                    int deltaX = pinLocX((int) (mScrollX
7388                                            + mLastDeferTouchX - x))
7389                                            - mScrollX;
7390                                    int deltaY = pinLocY((int) (mScrollY
7391                                            + mLastDeferTouchY - y))
7392                                            - mScrollY;
7393                                    doDrag(deltaX, deltaY);
7394                                    if (deltaX != 0) mLastDeferTouchX = x;
7395                                    if (deltaY != 0) mLastDeferTouchY = y;
7396                                    break;
7397                                }
7398                                case MotionEvent.ACTION_UP:
7399                                case MotionEvent.ACTION_CANCEL:
7400                                    if (mDeferTouchMode == TOUCH_DRAG_MODE) {
7401                                        // no fling in defer process
7402                                        mScroller.springBack(mScrollX, mScrollY, 0,
7403                                                computeMaxScrollX(), 0,
7404                                                computeMaxScrollY());
7405                                        invalidate();
7406                                        WebViewCore.resumePriority();
7407                                        WebViewCore.resumeUpdatePicture(mWebViewCore);
7408                                    }
7409                                    mDeferTouchMode = TOUCH_DONE_MODE;
7410                                    break;
7411                                case WebViewCore.ACTION_DOUBLETAP:
7412                                    // doDoubleTap() needs mLastTouchX/Y as anchor
7413                                    mLastTouchX = contentToViewX(ted.mPoints[0].x) - mScrollX;
7414                                    mLastTouchY = contentToViewY(ted.mPoints[0].y) - mScrollY;
7415                                    mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
7416                                    mDeferTouchMode = TOUCH_DONE_MODE;
7417                                    break;
7418                                case WebViewCore.ACTION_LONGPRESS:
7419                                    HitTestResult hitTest = getHitTestResult();
7420                                    if (hitTest != null && hitTest.mType
7421                                            != HitTestResult.UNKNOWN_TYPE) {
7422                                        performLongClick();
7423                                    }
7424                                    mDeferTouchMode = TOUCH_DONE_MODE;
7425                                    break;
7426                            }
7427                        }
7428                    }
7429                    break;
7430
7431                case REQUEST_KEYBOARD:
7432                    if (msg.arg1 == 0) {
7433                        hideSoftKeyboard();
7434                    } else {
7435                        displaySoftKeyboard(false);
7436                    }
7437                    break;
7438
7439                case FIND_AGAIN:
7440                    // Ignore if find has been dismissed.
7441                    if (mFindIsUp && mFindCallback != null) {
7442                        mFindCallback.findAll();
7443                    }
7444                    break;
7445
7446                case DRAG_HELD_MOTIONLESS:
7447                    mHeldMotionless = MOTIONLESS_TRUE;
7448                    invalidate();
7449                    // fall through to keep scrollbars awake
7450
7451                case AWAKEN_SCROLL_BARS:
7452                    if (mTouchMode == TOUCH_DRAG_MODE
7453                            && mHeldMotionless == MOTIONLESS_TRUE) {
7454                        awakenScrollBars(ViewConfiguration
7455                                .getScrollDefaultDelay(), false);
7456                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
7457                                .obtainMessage(AWAKEN_SCROLL_BARS),
7458                                ViewConfiguration.getScrollDefaultDelay());
7459                    }
7460                    break;
7461
7462                case DO_MOTION_UP:
7463                    doMotionUp(msg.arg1, msg.arg2);
7464                    break;
7465
7466                case SCREEN_ON:
7467                    setKeepScreenOn(msg.arg1 == 1);
7468                    break;
7469
7470                case SHOW_FULLSCREEN: {
7471                    View view = (View) msg.obj;
7472                    int npp = msg.arg1;
7473
7474                    if (inFullScreenMode()) {
7475                        Log.w(LOGTAG, "Should not have another full screen.");
7476                        dismissFullScreenMode();
7477                    }
7478                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp);
7479                    mFullScreenHolder.setContentView(view);
7480                    mFullScreenHolder.setCancelable(false);
7481                    mFullScreenHolder.setCanceledOnTouchOutside(false);
7482                    mFullScreenHolder.show();
7483
7484                    break;
7485                }
7486                case HIDE_FULLSCREEN:
7487                    dismissFullScreenMode();
7488                    break;
7489
7490                case DOM_FOCUS_CHANGED:
7491                    if (inEditingMode()) {
7492                        nativeClearCursor();
7493                        rebuildWebTextView();
7494                    }
7495                    break;
7496
7497                case SHOW_RECT_MSG_ID: {
7498                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
7499                    int x = mScrollX;
7500                    int left = contentToViewX(data.mLeft);
7501                    int width = contentToViewDimension(data.mWidth);
7502                    int maxWidth = contentToViewDimension(data.mContentWidth);
7503                    int viewWidth = getViewWidth();
7504                    if (width < viewWidth) {
7505                        // center align
7506                        x += left + width / 2 - mScrollX - viewWidth / 2;
7507                    } else {
7508                        x += (int) (left + data.mXPercentInDoc * width
7509                                - mScrollX - data.mXPercentInView * viewWidth);
7510                    }
7511                    if (DebugFlags.WEB_VIEW) {
7512                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
7513                              width + ",maxWidth=" + maxWidth +
7514                              ",viewWidth=" + viewWidth + ",x="
7515                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
7516                              ",xPercentInView=" + data.mXPercentInView+ ")");
7517                    }
7518                    // use the passing content width to cap x as the current
7519                    // mContentWidth may not be updated yet
7520                    x = Math.max(0,
7521                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
7522                    int top = contentToViewY(data.mTop);
7523                    int height = contentToViewDimension(data.mHeight);
7524                    int maxHeight = contentToViewDimension(data.mContentHeight);
7525                    int viewHeight = getViewHeight();
7526                    int y = (int) (top + data.mYPercentInDoc * height -
7527                                   data.mYPercentInView * viewHeight);
7528                    if (DebugFlags.WEB_VIEW) {
7529                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
7530                              height + ",maxHeight=" + maxHeight +
7531                              ",viewHeight=" + viewHeight + ",y="
7532                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
7533                              ",yPercentInView=" + data.mYPercentInView+ ")");
7534                    }
7535                    // use the passing content height to cap y as the current
7536                    // mContentHeight may not be updated yet
7537                    y = Math.max(0,
7538                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
7539                    // We need to take into account the visible title height
7540                    // when scrolling since y is an absolute view position.
7541                    y = Math.max(0, y - getVisibleTitleHeight());
7542                    scrollTo(x, y);
7543                    }
7544                    break;
7545
7546                case CENTER_FIT_RECT:
7547                    centerFitRect((Rect)msg.obj);
7548                    break;
7549
7550                case SET_SCROLLBAR_MODES:
7551                    mHorizontalScrollBarMode = msg.arg1;
7552                    mVerticalScrollBarMode = msg.arg2;
7553                    break;
7554
7555                case SELECTION_STRING_CHANGED:
7556                    if (mAccessibilityInjector != null) {
7557                        String selectionString = (String) msg.obj;
7558                        mAccessibilityInjector.onSelectionStringChange(selectionString);
7559                    }
7560                    break;
7561
7562                case SET_TOUCH_HIGHLIGHT_RECTS:
7563                    invalidate(mTouchHighlightRegion.getBounds());
7564                    mTouchHighlightRegion.setEmpty();
7565                    if (msg.obj != null) {
7566                        ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
7567                        for (Rect rect : rects) {
7568                            Rect viewRect = contentToViewRect(rect);
7569                            // some sites, like stories in nytimes.com, set
7570                            // mouse event handler in the top div. It is not
7571                            // user friendly to highlight the div if it covers
7572                            // more than half of the screen.
7573                            if (viewRect.width() < getWidth() >> 1
7574                                    || viewRect.height() < getHeight() >> 1) {
7575                                mTouchHighlightRegion.union(viewRect);
7576                                invalidate(viewRect);
7577                            } else {
7578                                Log.w(LOGTAG, "Skip the huge selection rect:"
7579                                        + viewRect);
7580                            }
7581                        }
7582                    }
7583                    break;
7584
7585                case SAVE_WEBARCHIVE_FINISHED:
7586                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
7587                    if (saveMessage.mCallback != null) {
7588                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
7589                    }
7590                    break;
7591
7592                case SET_AUTOFILLABLE:
7593                    mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
7594                    if (mWebTextView != null) {
7595                        mWebTextView.setAutoFillable(mAutoFillData.getQueryId());
7596                        rebuildWebTextView();
7597                    }
7598                    break;
7599
7600                case AUTOFILL_COMPLETE:
7601                    if (mWebTextView != null) {
7602                        // Clear the WebTextView adapter when AutoFill finishes
7603                        // so that the drop down gets cleared.
7604                        mWebTextView.setAdapterCustom(null);
7605                    }
7606                    break;
7607
7608                case SELECT_AT:
7609                    nativeSelectAt(msg.arg1, msg.arg2);
7610                    break;
7611
7612                default:
7613                    super.handleMessage(msg);
7614                    break;
7615            }
7616        }
7617    }
7618
7619    /**
7620     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
7621     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
7622     */
7623    private void updateTextSelectionFromMessage(int nodePointer,
7624            int textGeneration, WebViewCore.TextSelectionData data) {
7625        if (inEditingMode()
7626                && mWebTextView.isSameTextField(nodePointer)
7627                && textGeneration == mTextGeneration) {
7628            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
7629        }
7630    }
7631
7632    // Class used to use a dropdown for a <select> element
7633    private class InvokeListBox implements Runnable {
7634        // Whether the listbox allows multiple selection.
7635        private boolean     mMultiple;
7636        // Passed in to a list with multiple selection to tell
7637        // which items are selected.
7638        private int[]       mSelectedArray;
7639        // Passed in to a list with single selection to tell
7640        // where the initial selection is.
7641        private int         mSelection;
7642
7643        private Container[] mContainers;
7644
7645        // Need these to provide stable ids to my ArrayAdapter,
7646        // which normally does not have stable ids. (Bug 1250098)
7647        private class Container extends Object {
7648            /**
7649             * Possible values for mEnabled.  Keep in sync with OptionStatus in
7650             * WebViewCore.cpp
7651             */
7652            final static int OPTGROUP = -1;
7653            final static int OPTION_DISABLED = 0;
7654            final static int OPTION_ENABLED = 1;
7655
7656            String  mString;
7657            int     mEnabled;
7658            int     mId;
7659
7660            public String toString() {
7661                return mString;
7662            }
7663        }
7664
7665        /**
7666         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
7667         *  and allow filtering.
7668         */
7669        private class MyArrayListAdapter extends ArrayAdapter<Container> {
7670            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
7671                super(context,
7672                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
7673                            com.android.internal.R.layout.select_dialog_singlechoice,
7674                            objects);
7675            }
7676
7677            @Override
7678            public View getView(int position, View convertView,
7679                    ViewGroup parent) {
7680                // Always pass in null so that we will get a new CheckedTextView
7681                // Otherwise, an item which was previously used as an <optgroup>
7682                // element (i.e. has no check), could get used as an <option>
7683                // element, which needs a checkbox/radio, but it would not have
7684                // one.
7685                convertView = super.getView(position, null, parent);
7686                Container c = item(position);
7687                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
7688                    // ListView does not draw dividers between disabled and
7689                    // enabled elements.  Use a LinearLayout to provide dividers
7690                    LinearLayout layout = new LinearLayout(mContext);
7691                    layout.setOrientation(LinearLayout.VERTICAL);
7692                    if (position > 0) {
7693                        View dividerTop = new View(mContext);
7694                        dividerTop.setBackgroundResource(
7695                                android.R.drawable.divider_horizontal_bright);
7696                        layout.addView(dividerTop);
7697                    }
7698
7699                    if (Container.OPTGROUP == c.mEnabled) {
7700                        // Currently select_dialog_multichoice and
7701                        // select_dialog_singlechoice are CheckedTextViews.  If
7702                        // that changes, the class cast will no longer be valid.
7703                        Assert.assertTrue(
7704                                convertView instanceof CheckedTextView);
7705                        ((CheckedTextView) convertView).setCheckMarkDrawable(
7706                                null);
7707                    } else {
7708                        // c.mEnabled == Container.OPTION_DISABLED
7709                        // Draw the disabled element in a disabled state.
7710                        convertView.setEnabled(false);
7711                    }
7712
7713                    layout.addView(convertView);
7714                    if (position < getCount() - 1) {
7715                        View dividerBottom = new View(mContext);
7716                        dividerBottom.setBackgroundResource(
7717                                android.R.drawable.divider_horizontal_bright);
7718                        layout.addView(dividerBottom);
7719                    }
7720                    return layout;
7721                }
7722                return convertView;
7723            }
7724
7725            @Override
7726            public boolean hasStableIds() {
7727                // AdapterView's onChanged method uses this to determine whether
7728                // to restore the old state.  Return false so that the old (out
7729                // of date) state does not replace the new, valid state.
7730                return false;
7731            }
7732
7733            private Container item(int position) {
7734                if (position < 0 || position >= getCount()) {
7735                    return null;
7736                }
7737                return (Container) getItem(position);
7738            }
7739
7740            @Override
7741            public long getItemId(int position) {
7742                Container item = item(position);
7743                if (item == null) {
7744                    return -1;
7745                }
7746                return item.mId;
7747            }
7748
7749            @Override
7750            public boolean areAllItemsEnabled() {
7751                return false;
7752            }
7753
7754            @Override
7755            public boolean isEnabled(int position) {
7756                Container item = item(position);
7757                if (item == null) {
7758                    return false;
7759                }
7760                return Container.OPTION_ENABLED == item.mEnabled;
7761            }
7762        }
7763
7764        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
7765            mMultiple = true;
7766            mSelectedArray = selected;
7767
7768            int length = array.length;
7769            mContainers = new Container[length];
7770            for (int i = 0; i < length; i++) {
7771                mContainers[i] = new Container();
7772                mContainers[i].mString = array[i];
7773                mContainers[i].mEnabled = enabled[i];
7774                mContainers[i].mId = i;
7775            }
7776        }
7777
7778        private InvokeListBox(String[] array, int[] enabled, int selection) {
7779            mSelection = selection;
7780            mMultiple = false;
7781
7782            int length = array.length;
7783            mContainers = new Container[length];
7784            for (int i = 0; i < length; i++) {
7785                mContainers[i] = new Container();
7786                mContainers[i].mString = array[i];
7787                mContainers[i].mEnabled = enabled[i];
7788                mContainers[i].mId = i;
7789            }
7790        }
7791
7792        /*
7793         * Whenever the data set changes due to filtering, this class ensures
7794         * that the checked item remains checked.
7795         */
7796        private class SingleDataSetObserver extends DataSetObserver {
7797            private long        mCheckedId;
7798            private ListView    mListView;
7799            private Adapter     mAdapter;
7800
7801            /*
7802             * Create a new observer.
7803             * @param id The ID of the item to keep checked.
7804             * @param l ListView for getting and clearing the checked states
7805             * @param a Adapter for getting the IDs
7806             */
7807            public SingleDataSetObserver(long id, ListView l, Adapter a) {
7808                mCheckedId = id;
7809                mListView = l;
7810                mAdapter = a;
7811            }
7812
7813            public void onChanged() {
7814                // The filter may have changed which item is checked.  Find the
7815                // item that the ListView thinks is checked.
7816                int position = mListView.getCheckedItemPosition();
7817                long id = mAdapter.getItemId(position);
7818                if (mCheckedId != id) {
7819                    // Clear the ListView's idea of the checked item, since
7820                    // it is incorrect
7821                    mListView.clearChoices();
7822                    // Search for mCheckedId.  If it is in the filtered list,
7823                    // mark it as checked
7824                    int count = mAdapter.getCount();
7825                    for (int i = 0; i < count; i++) {
7826                        if (mAdapter.getItemId(i) == mCheckedId) {
7827                            mListView.setItemChecked(i, true);
7828                            break;
7829                        }
7830                    }
7831                }
7832            }
7833
7834            public void onInvalidate() {}
7835        }
7836
7837        public void run() {
7838            final ListView listView = (ListView) LayoutInflater.from(mContext)
7839                    .inflate(com.android.internal.R.layout.select_dialog, null);
7840            final MyArrayListAdapter adapter = new
7841                    MyArrayListAdapter(mContext, mContainers, mMultiple);
7842            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
7843                    .setView(listView).setCancelable(true)
7844                    .setInverseBackgroundForced(true);
7845
7846            if (mMultiple) {
7847                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
7848                    public void onClick(DialogInterface dialog, int which) {
7849                        mWebViewCore.sendMessage(
7850                                EventHub.LISTBOX_CHOICES,
7851                                adapter.getCount(), 0,
7852                                listView.getCheckedItemPositions());
7853                    }});
7854                b.setNegativeButton(android.R.string.cancel,
7855                        new DialogInterface.OnClickListener() {
7856                    public void onClick(DialogInterface dialog, int which) {
7857                        mWebViewCore.sendMessage(
7858                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
7859                }});
7860            }
7861            mListBoxDialog = b.create();
7862            listView.setAdapter(adapter);
7863            listView.setFocusableInTouchMode(true);
7864            // There is a bug (1250103) where the checks in a ListView with
7865            // multiple items selected are associated with the positions, not
7866            // the ids, so the items do not properly retain their checks when
7867            // filtered.  Do not allow filtering on multiple lists until
7868            // that bug is fixed.
7869
7870            listView.setTextFilterEnabled(!mMultiple);
7871            if (mMultiple) {
7872                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
7873                int length = mSelectedArray.length;
7874                for (int i = 0; i < length; i++) {
7875                    listView.setItemChecked(mSelectedArray[i], true);
7876                }
7877            } else {
7878                listView.setOnItemClickListener(new OnItemClickListener() {
7879                    public void onItemClick(AdapterView parent, View v,
7880                            int position, long id) {
7881                        // Rather than sending the message right away, send it
7882                        // after the page regains focus.
7883                        mListBoxMessage = Message.obtain(null,
7884                                EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0);
7885                        mListBoxDialog.dismiss();
7886                        mListBoxDialog = null;
7887                    }
7888                });
7889                if (mSelection != -1) {
7890                    listView.setSelection(mSelection);
7891                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
7892                    listView.setItemChecked(mSelection, true);
7893                    DataSetObserver observer = new SingleDataSetObserver(
7894                            adapter.getItemId(mSelection), listView, adapter);
7895                    adapter.registerDataSetObserver(observer);
7896                }
7897            }
7898            mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
7899                public void onCancel(DialogInterface dialog) {
7900                    mWebViewCore.sendMessage(
7901                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
7902                    mListBoxDialog = null;
7903                }
7904            });
7905            mListBoxDialog.show();
7906        }
7907    }
7908
7909    private Message mListBoxMessage;
7910
7911    /*
7912     * Request a dropdown menu for a listbox with multiple selection.
7913     *
7914     * @param array Labels for the listbox.
7915     * @param enabledArray  State for each element in the list.  See static
7916     *      integers in Container class.
7917     * @param selectedArray Which positions are initally selected.
7918     */
7919    void requestListBox(String[] array, int[] enabledArray, int[]
7920            selectedArray) {
7921        mPrivateHandler.post(
7922                new InvokeListBox(array, enabledArray, selectedArray));
7923    }
7924
7925    /*
7926     * Request a dropdown menu for a listbox with single selection or a single
7927     * <select> element.
7928     *
7929     * @param array Labels for the listbox.
7930     * @param enabledArray  State for each element in the list.  See static
7931     *      integers in Container class.
7932     * @param selection Which position is initally selected.
7933     */
7934    void requestListBox(String[] array, int[] enabledArray, int selection) {
7935        mPrivateHandler.post(
7936                new InvokeListBox(array, enabledArray, selection));
7937    }
7938
7939    // called by JNI
7940    private void sendMoveFocus(int frame, int node) {
7941        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
7942                new WebViewCore.CursorData(frame, node, 0, 0));
7943    }
7944
7945    // called by JNI
7946    private void sendMoveMouse(int frame, int node, int x, int y) {
7947        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
7948                new WebViewCore.CursorData(frame, node, x, y));
7949    }
7950
7951    /*
7952     * Send a mouse move event to the webcore thread.
7953     *
7954     * @param removeFocus Pass true if the "mouse" cursor is now over a node
7955     *                    which wants key events, but it is not the focus. This
7956     *                    will make the visual appear as though nothing is in
7957     *                    focus.  Remove the WebTextView, if present, and stop
7958     *                    drawing the blinking caret.
7959     * called by JNI
7960     */
7961    private void sendMoveMouseIfLatest(boolean removeFocus) {
7962        if (removeFocus) {
7963            clearTextEntry();
7964        }
7965        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
7966                cursorData());
7967    }
7968
7969    /**
7970     * Called by JNI to send a message to the webcore thread that the user
7971     * touched the webpage.
7972     * @param touchGeneration Generation number of the touch, to ignore touches
7973     *      after a new one has been generated.
7974     * @param frame Pointer to the frame holding the node that was touched.
7975     * @param node Pointer to the node touched.
7976     * @param x x-position of the touch.
7977     * @param y y-position of the touch.
7978     * @param scrollY Only used when touching on a textarea.  Otherwise, use -1.
7979     *      Tells how much the textarea is scrolled.
7980     */
7981    private void sendMotionUp(int touchGeneration,
7982            int frame, int node, int x, int y, int scrollY) {
7983        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7984        touchUpData.mMoveGeneration = touchGeneration;
7985        touchUpData.mFrame = frame;
7986        touchUpData.mNode = node;
7987        touchUpData.mX = x;
7988        touchUpData.mY = y;
7989        touchUpData.mScrollY = scrollY;
7990        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7991    }
7992
7993
7994    private int getScaledMaxXScroll() {
7995        int width;
7996        if (mHeightCanMeasure == false) {
7997            width = getViewWidth() / 4;
7998        } else {
7999            Rect visRect = new Rect();
8000            calcOurVisibleRect(visRect);
8001            width = visRect.width() / 2;
8002        }
8003        // FIXME the divisor should be retrieved from somewhere
8004        return viewToContentX(width);
8005    }
8006
8007    private int getScaledMaxYScroll() {
8008        int height;
8009        if (mHeightCanMeasure == false) {
8010            height = getViewHeight() / 4;
8011        } else {
8012            Rect visRect = new Rect();
8013            calcOurVisibleRect(visRect);
8014            height = visRect.height() / 2;
8015        }
8016        // FIXME the divisor should be retrieved from somewhere
8017        // the closest thing today is hard-coded into ScrollView.java
8018        // (from ScrollView.java, line 363)   int maxJump = height/2;
8019        return Math.round(height * mZoomManager.getInvScale());
8020    }
8021
8022    /**
8023     * Called by JNI to invalidate view
8024     */
8025    private void viewInvalidate() {
8026        invalidate();
8027    }
8028
8029    /**
8030     * Pass the key directly to the page.  This assumes that
8031     * nativePageShouldHandleShiftAndArrows() returned true.
8032     */
8033    private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
8034        int keyEventAction;
8035        int eventHubAction;
8036        if (down) {
8037            keyEventAction = KeyEvent.ACTION_DOWN;
8038            eventHubAction = EventHub.KEY_DOWN;
8039            playSoundEffect(keyCodeToSoundsEffect(keyCode));
8040        } else {
8041            keyEventAction = KeyEvent.ACTION_UP;
8042            eventHubAction = EventHub.KEY_UP;
8043        }
8044
8045        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
8046                1, (metaState & KeyEvent.META_SHIFT_ON)
8047                | (metaState & KeyEvent.META_ALT_ON)
8048                | (metaState & KeyEvent.META_SYM_ON)
8049                , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
8050        mWebViewCore.sendMessage(eventHubAction, event);
8051    }
8052
8053    // return true if the key was handled
8054    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
8055            long time) {
8056        if (mNativeClass == 0) {
8057            return false;
8058        }
8059        mInitialHitTestResult = null;
8060        mLastCursorTime = time;
8061        mLastCursorBounds = nativeGetCursorRingBounds();
8062        boolean keyHandled
8063                = nativeMoveCursor(keyCode, count, noScroll) == false;
8064        if (DebugFlags.WEB_VIEW) {
8065            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
8066                    + " mLastCursorTime=" + mLastCursorTime
8067                    + " handled=" + keyHandled);
8068        }
8069        if (keyHandled == false) {
8070            return keyHandled;
8071        }
8072        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
8073        if (contentCursorRingBounds.isEmpty()) return keyHandled;
8074        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
8075        // set last touch so that context menu related functions will work
8076        mLastTouchX = (viewCursorRingBounds.left + viewCursorRingBounds.right) / 2;
8077        mLastTouchY = (viewCursorRingBounds.top + viewCursorRingBounds.bottom) / 2;
8078        if (mHeightCanMeasure == false) {
8079            return keyHandled;
8080        }
8081        Rect visRect = new Rect();
8082        calcOurVisibleRect(visRect);
8083        Rect outset = new Rect(visRect);
8084        int maxXScroll = visRect.width() / 2;
8085        int maxYScroll = visRect.height() / 2;
8086        outset.inset(-maxXScroll, -maxYScroll);
8087        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
8088            return keyHandled;
8089        }
8090        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
8091        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
8092                maxXScroll);
8093        if (maxH > 0) {
8094            pinScrollBy(maxH, 0, true, 0);
8095        } else {
8096            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
8097                    -maxXScroll);
8098            if (maxH < 0) {
8099                pinScrollBy(maxH, 0, true, 0);
8100            }
8101        }
8102        if (mLastCursorBounds.isEmpty()) return keyHandled;
8103        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
8104            return keyHandled;
8105        }
8106        if (DebugFlags.WEB_VIEW) {
8107            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
8108                    + contentCursorRingBounds);
8109        }
8110        requestRectangleOnScreen(viewCursorRingBounds);
8111        mUserScroll = true;
8112        return keyHandled;
8113    }
8114
8115    /**
8116     * @return Whether accessibility script has been injected.
8117     */
8118    private boolean accessibilityScriptInjected() {
8119        // TODO: Maybe the injected script should announce its presence in
8120        // the page meta-tag so the nativePageShouldHandleShiftAndArrows
8121        // will check that as one of the conditions it looks for
8122        return mAccessibilityScriptInjected;
8123    }
8124
8125    /**
8126     * Set the background color. It's white by default. Pass
8127     * zero to make the view transparent.
8128     * @param color   the ARGB color described by Color.java
8129     */
8130    public void setBackgroundColor(int color) {
8131        mBackgroundColor = color;
8132        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
8133    }
8134
8135    public void debugDump() {
8136        nativeDebugDump();
8137        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
8138    }
8139
8140    /**
8141     * Draw the HTML page into the specified canvas. This call ignores any
8142     * view-specific zoom, scroll offset, or other changes. It does not draw
8143     * any view-specific chrome, such as progress or URL bars.
8144     *
8145     * @hide only needs to be accessible to Browser and testing
8146     */
8147    public void drawPage(Canvas canvas) {
8148        nativeDraw(canvas, 0, 0, false);
8149    }
8150
8151    /**
8152     * Set the time to wait between passing touches to WebCore. See also the
8153     * TOUCH_SENT_INTERVAL member for further discussion.
8154     *
8155     * @hide This is only used by the DRT test application.
8156     */
8157    public void setTouchInterval(int interval) {
8158        mCurrentTouchInterval = interval;
8159    }
8160
8161    /**
8162     *  Update our cache with updatedText.
8163     *  @param updatedText  The new text to put in our cache.
8164     */
8165    /* package */ void updateCachedTextfield(String updatedText) {
8166        // Also place our generation number so that when we look at the cache
8167        // we recognize that it is up to date.
8168        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
8169    }
8170
8171    /*package*/ void autoFillForm(int autoFillQueryId) {
8172        mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0);
8173    }
8174
8175    /* package */ ViewManager getViewManager() {
8176        return mViewManager;
8177    }
8178
8179    private native int nativeCacheHitFramePointer();
8180    private native boolean  nativeCacheHitIsPlugin();
8181    private native Rect nativeCacheHitNodeBounds();
8182    private native int nativeCacheHitNodePointer();
8183    /* package */ native void nativeClearCursor();
8184    private native void     nativeCreate(int ptr);
8185    private native int      nativeCursorFramePointer();
8186    private native Rect     nativeCursorNodeBounds();
8187    private native int nativeCursorNodePointer();
8188    private native boolean  nativeCursorIntersects(Rect visibleRect);
8189    private native boolean  nativeCursorIsAnchor();
8190    private native boolean  nativeCursorIsTextInput();
8191    private native Point    nativeCursorPosition();
8192    private native String   nativeCursorText();
8193    /**
8194     * Returns true if the native cursor node says it wants to handle key events
8195     * (ala plugins). This can only be called if mNativeClass is non-zero!
8196     */
8197    private native boolean  nativeCursorWantsKeyEvents();
8198    private native void     nativeDebugDump();
8199    private native void     nativeDestroy();
8200
8201    /**
8202     * Draw the picture set with a background color and extra. If
8203     * "splitIfNeeded" is true and the return value is not 0, the return value
8204     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
8205     * native allocation can be freed.
8206     */
8207    private native int nativeDraw(Canvas canvas, int color, int extra,
8208            boolean splitIfNeeded);
8209    private native void     nativeDumpDisplayTree(String urlOrNull);
8210    private native boolean  nativeEvaluateLayersAnimations();
8211    private native int      nativeGetDrawGLFunction(Rect rect, float scale, int extras);
8212    private native void     nativeUpdateDrawGLFunction(Rect rect);
8213    private native boolean  nativeDrawGL(Rect rect, float scale, int extras);
8214    private native void     nativeExtendSelection(int x, int y);
8215    private native int      nativeFindAll(String findLower, String findUpper,
8216            boolean sameAsLastSearch);
8217    private native void     nativeFindNext(boolean forward);
8218    /* package */ native int      nativeFocusCandidateFramePointer();
8219    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
8220    /* package */ native boolean  nativeFocusCandidateIsPassword();
8221    private native boolean  nativeFocusCandidateIsRtlText();
8222    private native boolean  nativeFocusCandidateIsTextInput();
8223    /* package */ native int      nativeFocusCandidateMaxLength();
8224    /* package */ native boolean  nativeFocusCandidateIsAutoComplete();
8225    /* package */ native String   nativeFocusCandidateName();
8226    private native Rect     nativeFocusCandidateNodeBounds();
8227    /**
8228     * @return A Rect with left, top, right, bottom set to the corresponding
8229     * padding values in the focus candidate, if it is a textfield/textarea with
8230     * a style.  Otherwise return null.  This is not actually a rectangle; Rect
8231     * is being used to pass four integers.
8232     */
8233    private native Rect     nativeFocusCandidatePaddingRect();
8234    /* package */ native int      nativeFocusCandidatePointer();
8235    private native String   nativeFocusCandidateText();
8236    /* package */ native float    nativeFocusCandidateTextSize();
8237    /* package */ native int nativeFocusCandidateLineHeight();
8238    /**
8239     * Returns an integer corresponding to WebView.cpp::type.
8240     * See WebTextView.setType()
8241     */
8242    private native int      nativeFocusCandidateType();
8243    private native boolean  nativeFocusIsPlugin();
8244    private native Rect     nativeFocusNodeBounds();
8245    /* package */ native int nativeFocusNodePointer();
8246    private native Rect     nativeGetCursorRingBounds();
8247    private native String   nativeGetSelection();
8248    private native boolean  nativeHasCursorNode();
8249    private native boolean  nativeHasFocusNode();
8250    private native void     nativeHideCursor();
8251    private native boolean  nativeHitSelection(int x, int y);
8252    private native String   nativeImageURI(int x, int y);
8253    private native void     nativeInstrumentReport();
8254    private native Rect     nativeLayerBounds(int layer);
8255    /* package */ native boolean nativeMoveCursorToNextTextInput();
8256    // return true if the page has been scrolled
8257    private native boolean  nativeMotionUp(int x, int y, int slop);
8258    // returns false if it handled the key
8259    private native boolean  nativeMoveCursor(int keyCode, int count,
8260            boolean noScroll);
8261    private native int      nativeMoveGeneration();
8262    private native void     nativeMoveSelection(int x, int y);
8263    /**
8264     * @return true if the page should get the shift and arrow keys, rather
8265     * than select text/navigation.
8266     *
8267     * If the focus is a plugin, or if the focus and cursor match and are
8268     * a contentEditable element, then the page should handle these keys.
8269     */
8270    private native boolean  nativePageShouldHandleShiftAndArrows();
8271    private native boolean  nativePointInNavCache(int x, int y, int slop);
8272    // Like many other of our native methods, you must make sure that
8273    // mNativeClass is not null before calling this method.
8274    private native void     nativeRecordButtons(boolean focused,
8275            boolean pressed, boolean invalidate);
8276    private native void     nativeResetSelection();
8277    private native Point    nativeSelectableText();
8278    private native void     nativeSelectAll();
8279    private native void     nativeSelectBestAt(Rect rect);
8280    private native void     nativeSelectAt(int x, int y);
8281    private native int      nativeSelectionX();
8282    private native int      nativeSelectionY();
8283    private native int      nativeFindIndex();
8284    private native void     nativeSetExtendSelection();
8285    private native void     nativeSetFindIsEmpty();
8286    private native void     nativeSetFindIsUp(boolean isUp);
8287    private native void     nativeSetHeightCanMeasure(boolean measure);
8288    private native void     nativeSetBaseLayer(int layer, Rect invalRect);
8289    private native void     nativeShowCursorTimed();
8290    private native void     nativeReplaceBaseContent(int content);
8291    private native void     nativeCopyBaseContentToPicture(Picture pict);
8292    private native boolean  nativeHasContent();
8293    private native void     nativeSetSelectionPointer(boolean set,
8294            float scale, int x, int y);
8295    private native boolean  nativeStartSelection(int x, int y);
8296    private native Rect     nativeSubtractLayers(Rect content);
8297    private native int      nativeTextGeneration();
8298    // Never call this version except by updateCachedTextfield(String) -
8299    // we always want to pass in our generation number.
8300    private native void     nativeUpdateCachedTextfield(String updatedText,
8301            int generation);
8302    private native boolean  nativeWordSelection(int x, int y);
8303    // return NO_LEFTEDGE means failure.
8304    static final int NO_LEFTEDGE = -1;
8305    native int nativeGetBlockLeftEdge(int x, int y, float scale);
8306
8307    // Returns a pointer to the scrollable LayerAndroid at the given point.
8308    private native int      nativeScrollableLayer(int x, int y, Rect scrollRect,
8309            Rect scrollBounds);
8310    /**
8311     * Scroll the specified layer.
8312     * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer.
8313     * @param newX Destination x position to which to scroll.
8314     * @param newY Destination y position to which to scroll.
8315     * @return True if the layer is successfully scrolled.
8316     */
8317    private native boolean  nativeScrollLayer(int layer, int newX, int newY);
8318}
8319