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