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