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